From 3826dce93b056fb2d6f69abbffaeb66a7fdc67c6 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Wed, 25 Nov 2026 16:24:26 +0000 Subject: [PATCH] Document core operation authoring with a working example --- docs/internal/dnd.md | 17 +- docs/internal/llm.md | 11 +- docs/internal/modules.md | 119 +++++----- docs/internal/overview.md | 4 +- docs/internal/pipeline.md | 19 +- docs/internal/state.md | 2 +- docs/roadmap/implementation.md | 4 + .../framework/pipeline/author_example_test.go | 205 ++++++++++++++++++ 8 files changed, 295 insertions(+), 86 deletions(-) create mode 100644 internal/framework/pipeline/author_example_test.go diff --git a/docs/internal/dnd.md b/docs/internal/dnd.md index 1ee2b886..96fa1d73 100644 --- a/docs/internal/dnd.md +++ b/docs/internal/dnd.md @@ -33,11 +33,10 @@ registry normalizers are model-backed; current mergers and remaining normalizers are deterministic. A model-backed module can still have an ordinary no-model branch. Registration does not construct engines or register prompt/schema assets. -Each model producer receives the shared native engine, prepares fixed operation -inputs, and calls the common producer helper with initial request, interpretation, -correction builder, and supported fallback. Static prompt dependencies match its -request constants. The pipeline supplies complete candidate assessment; returning -from the helper does not trigger a duplicate validator pass. +Each model producer prepares fixed operation inputs and returns an initial request, +interpretation, correction builder, and supported fallback to core. Static prompt +dependencies match its request constants. Core owns the shared engine and complete +candidate assessment; modules do not run another producer loop. Pure codecs, identities, reference resolvers, and deterministic transforms remain separate from execution integration. @@ -137,13 +136,13 @@ The three registry normalizers retain their intentional model-assisted exception [NPC](../../internal/modules/dnd/normalize/npcregistry/normalizer.go), [item](../../internal/modules/dnd/normalize/itemregistry/normalizer.go), and [location](../../internal/modules/dnd/normalize/locationregistry/normalizer.go) -normalization use ordinary functions from -[semanticreconcile](../../internal/framework/semanticreconcile/preparation.go), +normalization use the shared operation facility in +[semanticreconcile](../../internal/framework/semanticreconcile/operation.go), not a separate reconciliation engine/service. The operation retains the incoming merged artifact separately, preprocesses -fixed originals once, and calls `Prepare` once. Preparation filters unusable -candidate evidence, assigns contiguous one-based request-local handles, declares +fixed originals once; the shared facility prepares candidates once. Preparation +filters unusable candidate evidence, assigns contiguous one-based request-local handles, declares their inclusive range, and builds bounded transcript windows/material. Candidate handles are not transcript unit IDs or durable identity. Identical labels/evidence remain separately selectable. diff --git a/docs/internal/llm.md b/docs/internal/llm.md index d80dfda4..bed17178 100644 --- a/docs/internal/llm.md +++ b/docs/internal/llm.md @@ -29,8 +29,7 @@ operation invokes a model. ## Requests And Fixed Operation Inputs -Model modules receive the shared engine during typed preparation. A module -prepares transcript, references, contextual identity projections, and any +Core owns the shared engine. A model module prepares transcript, references, contextual identity projections, and any normalization candidate mapping once. It constructs a `promptkit.RunRequest` with its selected prompt, profile/session, native artifact inputs, and variables. Response interpretation consumes `*promptkit.RunResult` and produces the @@ -49,14 +48,14 @@ acquire authority over durable IDs, citation meaning, or typed artifact shape. recipes. Native request overrides preserve supplied values without rewriting configured -profiles. The producer helper's request composition preserves operation-owned +profiles. Core request composition preserves operation-owned prompt/input/capture fields and existing callbacks; validators pass native execution options explicitly on their own requests. ## Native Production And Application Assessment -[RunProducer](../../internal/framework/pipeline/producer.go) connects ordinary -module interpretation/correction/fallback functions to the pipeline assessor. +[Core native execution](../../internal/framework/pipeline/operation_native.go) +connects prepared interpretation/correction/fallback functions to the pipeline assessor. It uses native `Run`, or retained prepared execution on the cache path, then checks errors and public validation status before interpretation. Failed native validation can accompany nil Go error and is not a usable semantic candidate. @@ -124,7 +123,7 @@ counter around native coordination. ## Prepared Execution And Reuse -For eligible cacheable producers, the helper prepares the initial request once, +For eligible cacheable operations, core prepares the initial request once, retains its details and opaque message-content hash, and either discards the handle on a usable hit or executes that same handle with `RunPrepared`. Unused handles are discarded on exits. Continuation retains the initial key. diff --git a/docs/internal/modules.md b/docs/internal/modules.md index 9e9048c3..9fd9fae9 100644 --- a/docs/internal/modules.md +++ b/docs/internal/modules.md @@ -20,8 +20,9 @@ modules. The resolver applies model-profile selections only to model roles. Static initial/correction dependencies use the same constants as request builders; they are preflight declarations, not asset manifests or execution fingerprints. -[BuildRequest](../../internal/framework/pipeline/construction.go) supplies the -shared native engine, option values, and prepared references. Option-aware +[BuildRequest](../../internal/framework/pipeline/construction.go) supplies +dependencies, option values, and prepared references; one-shot validators may +use the shared native engine. Option-aware modules provide a resolver validator and a builder using the same strict decoder. They do not rediscover configuration or reopen reference files. Generated references arrive through operation requests, not construction-time file reads. @@ -43,66 +44,68 @@ Preparation rejects incompatible types/registrations before parsing source. Projectors do not inspect arbitrary domain JSON or publish files; the [evidence contract](../integrations/evidence-context.md) owns the excerpt. -## Native Producer Recipe +## Preparing Operations -Follow the actual [spell extractor](../../internal/modules/dnd/extract/spells/extractor.go) -alongside [typed requests/results](../../internal/framework/contracts/typed_pipeline.go) -and [operation contracts](../../internal/framework/contracts/producer.go): +The [tested message-topic example](../../internal/framework/pipeline/author_example_test.go) +shows a domain-neutral input, codec, registrar, text chunk, contextual +interpretation, correction binding, and a deterministic branch. For production +adapters see [spell extraction](../../internal/modules/dnd/extract/spells/extractor.go) +and the [item registry normalizer](../../internal/modules/dnd/normalize/itemregistry/normalizer.go). -1. Validate operation input and prepare owned transcript/reference/contextual - projections once. Retain those fixed bytes and resolution mappings locally. -2. Build the initial `promptkit.RunRequest` using the declared prompt ID, - operation profile/session, native artifacts, and variables. -3. Call [RunProducer](../../internal/framework/pipeline/producer.go) with the shared - engine and the supplied typed operation. Supply ordinary interpretation, - correction-request, and supported fallback functions. -4. Interpret `*promptkit.RunResult` into the typed domain candidate. Attach - deterministic identities and canonical source references here, not by asking - the model to reproduce opaque IDs. Return actionable interpretation guidance - separately from operator diagnostics where the module can correct a selection. -5. Build the follow-up request from new findings/assignment only. Preserve - profile/session selections; native coordination carries prior conversation. - Do not rerender source inputs, serialize a domain artifact as a previous - assistant response, or implement another turn loop. -6. Return the helper's value and outcome in the typed operation result. The - runner has already supplied assessment; do not validate again after the helper. +A typed stage implements its `PrepareExtraction`, `PrepareMerge`, +`PrepareNormalize`, or `PrepareChunk` method from +[preparation contracts](../../internal/framework/contracts/preparation.go). +Core invokes that method once with domain inputs, then executes the returned +operation. The stage does not receive or choose an assessor, engine, cache, +capture, or terminal mode. The runner binds those privately; direct callers can +supply a [core execution context](../../internal/framework/pipeline/operation.go) +and preparation function to the same executor. -The helper checks native structural status before interpretation, binds native -execution overrides/observers, assesses every delivered usable candidate, and -handles prepared reuse. Modules do not replace its assessor/cache or infer -acceptance from provider success. [Pipeline Internals](pipeline.md) owns the -complete assessment/disposition algorithm; [LLM Integration](llm.md) owns native -execution and [State Internals](state.md) owns storage/capture lifecycle. +- Return a deterministic operation with one candidate when no model is needed. + Core assesses it once; there is no native request or synthetic cache key. +- Return a native operation containing the selected `promptkit.RunRequest`, + an interpreter, and, when supported, a correction builder and fallback. + Interpret into an evaluation with a candidate and any ordered guidance. + A correctable selection can provide guidance without a candidate. A candidate + is not an approval: core still runs every configured validator. +- Return an ordinary Go error for preparation failures. Use the explicit + preparation-limit operation only for an existing supported limit, not as + generic error recovery. Core selects strict/permissive handling. +- Supply fallback only when the family supports intrinsically usable output. + It receives the final eligible evaluation, or nil when none remains. It must + preserve domain/source/downstream invariants; core does not re-run ordinary + validators or claim acceptance for fallback. -Fallback construction is explicit and family-owned. It must satisfy intrinsic -shape/source/downstream invariants, but does not rerun ordinary validators or -claim semantic approval. Unsupported/invalid construction fails. No earlier -candidate is recovered after an unusable continuation; cancellation produces no -fallback. Modules do not pick a permissive default or hide an ordinary operation -error as recovery. +For the common correction form, `PromptCorrection` binds ordered guidance to +an integration-chosen prompt input; a specialized builder can instead construct +the assignment directly. Native coordination retains the initial profile/session, +resolved options, and conversation history. Modules do not replay source or +implement a continuation loop. See [Pipeline Internals](pipeline.md) for +assessment and terminal behavior and [LLM Integration](llm.md) for native ownership. + +An evaluation and its candidate, diagnostics, guidance, and optional evidence +are one operation-local unit. Core replaces it on each delivered interpretation +and clears it before a selected correction; failed or unusable continuation +cannot restore a prior evaluation. Historical capture may retain prior evidence. +Preparation transfers returned values and callbacks to that operation; a shared +module must not store mutable operation state. Own mutable slices/maps that a +callback might modify and respect the existing detached input boundaries. +Optional evidence projections are lazy and only invoked when capture is enabled. +This does not promise thread safety for caller-supplied writers or observers. ## Validators And Deterministic Work Validators receive native execution options and detached candidate/context views, -not a producer operation or semantic-turn loop. Return approval, or rejection -with separate stable reason and actionable `CorrectionGuidance`. Operator -`Message` is not model feedback. The detecting rule owns guidance about fields -the producer controls, without internal paths/keys/opaque identities. -Invalid rejection guidance is a contract failure. +not an operation executor. Return approval or rejection with separately authored +actionable correction guidance; operator messages are not model feedback. +A model validator calls the shared engine once and checks native result usability +before interpretation. The [combat validator](../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go) +is the one-shot example. It does not own a semantic correction loop or extend +native repair budgets. -A model validator calls the shared native engine directly, checks native errors/ -validation before interpretation, and distinguishes unavailable judgment from -semantic rejection while preserving causes. See the -[combat validator](../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go). -Do not rerun a validator to extend native repair budgets. - -Deterministic modules produce once through ordinary typed interfaces. The runner -assesses the value and can invoke an explicitly supported result fallback after -nonacceptance. Production errors propagate without generic retries. Model-backed -modules with legitimate no-model branches use direct `AssessProducer` on that -value; preparation-limit terminal handling uses `FinishProducerFailure` rather -than synthetic requests. The [noop normalizer](../../internal/modules/generic/normalize/noop/normalizer.go) -and registry normalizers show the distinct paths. +Deterministic modules return prepared candidates through the same core path. +See the [noop normalizer](../../internal/modules/generic/normalize/noop/typed.go) +and the model-backed extractors with no-model branches. ## Prompt And Schema Ownership @@ -121,17 +124,17 @@ See [schema selection](../config.md#prompt-output-contracts-and-schemas) and the ## Semantic Reconciliation -The [shared core](../../internal/framework/semanticreconcile/preparation.go) -offers preparation, native request builders, proposal assessment, and typed -application functions, not a replacement execution service. +The [shared facility](../../internal/framework/semanticreconcile/operation.go) +prepares core operations and provides proposal assessment and typed application, +not a replacement execution service. [Requests](../../internal/framework/semanticreconcile/requests.go) consume one retained preparation. [Proposal safety](../../internal/framework/semanticreconcile/proposal.go) resolves request-local handles; [application](../../internal/framework/semanticreconcile/application.go) clones/preserves originals and applies domain policies. The [item normalizer](../../internal/modules/dnd/normalize/itemregistry/normalizer.go) -preprocesses fixed originals once, prepares bounded windows/handles once, then -uses the same producer helper as extraction. Each complete proposal is assessed +preprocesses fixed originals once and prepares bounded windows/handles once. +Core executes its operation like extraction. Each complete proposal is assessed and applied afresh to originals before pipeline assessment. Domain guards, identity, evidence, diagnostics, and supported final-only fallback remain with the artifact family. Do not union plans across turns, reuse prior mutated output, diff --git a/docs/internal/overview.md b/docs/internal/overview.md index e5efd599..1c83851d 100644 --- a/docs/internal/overview.md +++ b/docs/internal/overview.md @@ -26,9 +26,9 @@ streams or roots. Standard inspection/preflight paths do not become runs. | Executable and native CLI | [cmd/notarius](../../cmd/notarius/), [internal/cli](../../internal/cli/) | Identity, native commands/aliases/suites, invocation-local source/engine selection, registrars, run composition, publication/reporting. | | Application configuration | [internal/core/config](../../internal/core/config/) | Composed ConfigKit/native settings definition, source-aware normalization, detached runtime conversion, application validation, effective domain resolution. | | Generic source and typed contracts | [internal/core/source](../../internal/core/source/), [internal/framework/contracts](../../internal/framework/contracts/) | Documents/units/chunks, typed production/assessment, source references, codecs, native execution selections, and small cache/evidence collaborators. | -| Pipeline framework | [internal/framework/pipeline](../../internal/framework/pipeline/) | Registries, typed resolution/preparation, complete candidate assessment, native producer helper, ready-job workers, ordered handoffs, reuse eligibility, evidence/output assembly. | +| Pipeline framework | [internal/framework/pipeline](../../internal/framework/pipeline/) | Registries, typed resolution, core-invoked preparation and execution, complete candidate assessment, ready-job workers, ordered handoffs, reuse eligibility, evidence/output assembly. | | Offline dependency preflight | [internal/preflight](../../internal/preflight/) | Known native prompt/profile checks on already resolved composition and supplied engine; no synthetic request or execution input reads. | -| Semantic reconciliation | [internal/framework/semanticreconcile](../../internal/framework/semanticreconcile/) | Fixed bounded candidate/window preparation, native request builders, request-local handle/proposal safety, and typed fresh application. | +| Semantic reconciliation | [internal/framework/semanticreconcile](../../internal/framework/semanticreconcile/) | Prepared reconciliation operations, bounded candidate/window inputs, request-local proposal safety, typed fresh application, and evaluation-scoped details. | | Embedded content | [assets](../../assets/) | Content-only native prompt/profile/schema/message files imported with filesystem contexts; no behavioral registry. | | Accepted-result cache | [internal/framework/artifactcache](../../internal/framework/artifactcache/) | Raw accepted artifact/plan bytes under native content keys, confined atomic publication, and deployment-owned creation permissions. | | Capture and file placement | [internal/core/fileio](../../internal/core/fileio/), [internal/core/debugbundle](../../internal/core/debugbundle/), [internal/framework/debug](../../internal/framework/debug/) | Confined writes, run capture allocation/start-time latest link, incremental evidence, one terminalization, and retained causes. | diff --git a/docs/internal/pipeline.md b/docs/internal/pipeline.md index 0bc534d2..8bff74fa 100644 --- a/docs/internal/pipeline.md +++ b/docs/internal/pipeline.md @@ -55,13 +55,12 @@ a separate composition check, not request execution or module construction. ## Typed Operations And Assessment -[Typed contracts](../../internal/framework/contracts/typed_pipeline.go) carry -a `ProducerOperation[T]` with resolved controls, one assessor, native execution -options, incoming reuse eligibility, and an optional typed cache binding. -[Runner operation completion](../../internal/framework/pipeline/runner_operation.go) -assesses deterministic production directly. Model modules use -[RunProducer](../../internal/framework/pipeline/producer.go); the runner consumes -its acceptance/fallback outcome without assessing it again. +[Typed stage contracts](../../internal/framework/contracts/typed_pipeline.go) +expose preparation. The runner binds resolved controls, assessment, native +execution, reuse eligibility, and cache in a private execution context. +[The core executor](../../internal/framework/pipeline/operation.go) invokes +preparation and handles deterministic and model operations alike; modules do +not select execution collaborators or claim acceptance. [Candidate assessment](../../internal/framework/pipeline/candidate_assessment.go) invokes each applicable validator once in configured order. It continues after @@ -83,13 +82,13 @@ on the shared engine and do not own another semantic loop. ## Native Continuation And Terminal Handling -For executed model work, `RunProducer` checks native errors and structural +For executed model work, the [native executor](../../internal/framework/pipeline/operation_native.go) checks native errors and structural validation status before interpretation, including a failed result with no Go error. Module interpretation produces a usable typed candidate and any actionable domain guidance. The assessor runs the complete chain on every delivered usable candidate, including unchanged revisions and the final allowed response. -When correction is possible, the helper starts native `Coordinate` from the +When correction is possible, core starts native `Coordinate` from the captured exchange. Its first callback reuses already-collected initial findings. Native coordination owns turn iteration and growing history; the module builds only new correction material from fixed operation inputs. Successful native @@ -105,7 +104,7 @@ recover an earlier candidate; caller cancellation and undelivered responses produce no acceptance/fallback. Native operational timeouts retain typed causes rather than becoming caller cancellation solely by error spelling. -Deterministic work produces once, then uses direct assessment and any supported +Deterministic work produces once, then uses core assessment and any supported module fallback. An operation/parse/materialization/encoding error remains an error, not a generic rerun or permissive recovery mechanism. diff --git a/docs/internal/state.md b/docs/internal/state.md index f226655b..477adf07 100644 --- a/docs/internal/state.md +++ b/docs/internal/state.md @@ -22,7 +22,7 @@ persisted resume ledger. ## Prepared Result Reuse -[RunProducer](../../internal/framework/pipeline/producer.go) owns native request +[Core native execution](../../internal/framework/pipeline/operation_native.go) owns native request selection and cache interaction for an eligible model operation: 1. Prepare the initial request once with `PrepareExecution`, retain its detached diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 8cff7bd0..cc334839 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -828,6 +828,10 @@ and `go test -race ./internal/framework/pipeline ./internal/framework/semanticre ## Stage 22 — Provide The Working Author Example And Internal Guides +**Status:** Complete. The registered domain-neutral message example exercises +contextual correction and deterministic completion through core. Pipeline tests +pass, and affected internal-guide paths and API references were checked. + **Goal:** Make the new boundary usable without reading producer implementation. **Inspect:** Stage 1's non-D&D sketches, actual finished APIs, and current diff --git a/internal/framework/pipeline/author_example_test.go b/internal/framework/pipeline/author_example_test.go new file mode 100644 index 00000000..31a51017 --- /dev/null +++ b/internal/framework/pipeline/author_example_test.go @@ -0,0 +1,205 @@ +package pipeline_test + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "gitea.maximumdirect.net/eric/notarius/internal/core/source" + "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" + "gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline" + "go.maximumdirect.net/configkit" + "go.maximumdirect.net/promptkit" +) + +// This fixture is a small end-to-end authoring example for generic messages. +// Its domain interpretation uses source metadata and ordinary text chunks. +type messageTopic struct { + Topic string `json:"topic"` +} + +const topicKind contracts.ArtifactKind = "example/message-topic" + +type topicCodec struct{} + +func (topicCodec) Kind() contracts.ArtifactKind { return topicKind } +func (topicCodec) Schema() contracts.ArtifactSchema { + return contracts.ArtifactSchema{ID: "example.message-topic", Name: "example_message_topic", Version: "v1", JSONSchema: []byte(`{"type":"object","properties":{"topic":{"type":"string"}},"required":["topic"]}`)} +} +func (topicCodec) MediaType() string { return "application/json" } +func (topicCodec) Encode(value messageTopic) ([]byte, error) { return json.Marshal(value) } +func (codec topicCodec) EncodeCandidate(value messageTopic) ([]byte, error) { + return codec.Encode(value) +} +func (topicCodec) Decode(content []byte) (messageTopic, error) { + var value messageTopic + err := json.Unmarshal(content, &value) + return value, err +} +func (codec topicCodec) DecodeCandidate(content []byte) (messageTopic, error) { + return codec.Decode(content) +} + +func deterministic[T any](value T) contracts.PreparedOperation[T] { + return contracts.DeterministicOperation[T]{Evaluation: contracts.CandidateEvaluation[T]{Result: contracts.EvaluationView[T]{Candidate: &value}}} +} + +type messageInput struct{ document *source.SourceDocument } + +func (messageInput) Key() string { return "example/input" } +func (input messageInput) Parse(context.Context, contracts.ParseRequest) (*source.SourceDocument, error) { + return input.document, nil +} + +type messageChunker struct{} + +func (messageChunker) Key() string { return "example/chunk" } +func (messageChunker) ReferenceSlots() []contracts.ReferenceSlot { return nil } +func (messageChunker) PrepareChunk(_ context.Context, input contracts.ChunkInput) (contracts.PreparedOperation[source.ChunkPlan], error) { + return deterministic(source.ChunkPlan{SourceDigest: input.Source.Digest, Ranges: []source.ChunkRange{{StartUnitID: input.Source.Units[0].ID, EndUnitID: input.Source.Units[len(input.Source.Units)-1].ID}}}), nil +} + +type topicExtractor struct{} + +func (topicExtractor) Key() string { return "example/topic" } +func (topicExtractor) ReferenceSlots() []contracts.ReferenceSlot { return nil } +func (topicExtractor) PrepareExtraction(_ context.Context, input contracts.ExtractionInput) (contracts.PreparedOperation[messageTopic], error) { + subject, _ := input.Source.Metadata["subject"].(string) + if subject == "automatic notice" { + return deterministic(messageTopic{Topic: "notice"}), nil + } + initial := promptkit.RunRequest{PromptID: "message-topic-initial", ProfileID: input.LLMProfile, SessionID: input.SessionID, Inputs: map[string]promptkit.ArtifactRef{"message": promptkit.Inline(string(input.Chunk.Content)), "subject": promptkit.Inline(subject)}} + return contracts.NativeOperation[messageTopic]{Initial: initial, + Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[messageTopic], error) { + var value messageTopic + if err := json.Unmarshal([]byte(result.RawOutput), &value); err != nil { + return nil, err + } + if value.Topic == "unknown" { + return contracts.CandidateEvaluation[messageTopic]{Result: contracts.EvaluationView[messageTopic]{Guidance: []string{"Use the message subject: " + subject + "."}}}, nil + } + return contracts.CandidateEvaluation[messageTopic]{Result: contracts.EvaluationView[messageTopic]{Candidate: &value}}, nil + }, Correction: contracts.PromptCorrection("message-topic-correction", "assignment", func(guidance []string) promptkit.ArtifactRef { return promptkit.Inline(strings.Join(guidance, "\n")) }), + }, nil +} + +type topicMerge struct{} + +func (topicMerge) Key() string { return "example/merge" } +func (topicMerge) PrepareMerge(_ context.Context, input contracts.MergeInput[messageTopic]) (contracts.PreparedOperation[messageTopic], error) { + return deterministic(input.ExtractOutputs[0].Value), nil +} + +type topicNormalize struct{} + +func (topicNormalize) Key() string { return "example/normalize" } +func (topicNormalize) ReferenceSlots() []contracts.ReferenceSlot { return nil } +func (topicNormalize) PrepareNormalize(_ context.Context, input contracts.NormalizeInput[messageTopic]) (contracts.PreparedOperation[messageTopic], error) { + return deterministic(input.MergeOutput.Value), nil +} + +type topicOutput struct{ values *[]contracts.SerializedOutput } + +func (topicOutput) Key() string { return "example/output" } +func (output topicOutput) Encode(_ context.Context, input contracts.OutputRequest) (contracts.OutputResult, error) { + *output.values = input.NormalizeOutputs + return contracts.OutputResult{}, nil +} + +type topicProvider struct { + calls int + correction string +} + +func (provider *topicProvider) Generate(_ context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) { + provider.calls++ + if provider.calls == 1 { + return &promptkit.GenerateResponse{Content: `{"topic":"unknown"}`}, nil + } + for _, message := range request.Prompt.Messages { + provider.correction += message.Content + } + return &promptkit.GenerateResponse{Content: `{"topic":"weather"}`}, nil +} + +func TestRegisteredMessageTopicExample(t *testing.T) { + settings := `profiles: + - id: example + endpoint: https://example.invalid/v1 + model: local-fake + api_key_required: false +prompts: + - id: message-topic-initial + default_profile: example + inputs: [{name: message, required: true}, {name: subject, required: true}] + messages: + - {role: user, content: '{{input "subject"}}: {{input "message"}}'} + output: {format: json, validation_mode: json, repair_attempts: 0} + - id: message-topic-correction + default_profile: example + inputs: [{name: assignment, required: true}] + messages: + - {role: user, content: '{{input "assignment"}}'} + output: {format: json, validation_mode: json, repair_attempts: 0} +` + provider := &topicProvider{} + engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{promptkit.SettingsInput(configkit.Bytes("example", []byte(settings)))}}}}}, promptkit.WithBundledOpenRouter(false), promptkit.WithLLMClient(provider)) + if err != nil { + var load *configkit.LoadError + if errors.As(err, &load) { + t.Fatalf("%v: %#v", err, load.Diagnostics()) + } + t.Fatal(err) + } + for _, test := range []struct { + subject, want string + calls int + }{{"forecast discussion", "weather", 2}, {"automatic notice", "notice", 0}} { + t.Run(test.subject, func(t *testing.T) { + provider.calls, provider.correction = 0, "" + doc := &source.SourceDocument{ID: "message", Kind: "email", Format: "text/plain", Metadata: map[string]any{"subject": test.subject}, Units: []source.SourceUnit{{ID: 1, Kind: "text", Text: "Rain is expected.", Ref: source.SourceRef{SourceID: "message", StartUnitID: 1, EndUnitID: 1}}}} + doc.Digest, err = source.DigestDocument(doc) + if err != nil { + t.Fatal(err) + } + catalog := pipeline.ModuleCatalog{Inputs: pipeline.NewInputAdapterRegistry(), Chunkers: pipeline.NewChunkerRegistry(), ArtifactCodecs: pipeline.NewArtifactCodecRegistry(), Extractors: pipeline.NewExtractorRegistry(), Mergers: pipeline.NewMergerRegistry(), Normalizers: pipeline.NewNormalizerRegistry(), Validators: pipeline.NewValidatorRegistry(), ValidatorChains: pipeline.NewValidatorChainRegistry(), Outputs: pipeline.NewOutputEncoderRegistry()} + check := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + check(catalog.Inputs.RegisterWithSpec(pipeline.ModuleSpec{Key: "example/input", Stage: pipeline.StageInput, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.InputAdapter, error) { return messageInput{doc}, nil })) + check(catalog.Chunkers.RegisterWithSpec(pipeline.ModuleSpec{Key: "example/chunk", Stage: pipeline.StageChunk, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Chunker, error) { return messageChunker{}, nil })) + check(pipeline.RegisterArtifactCodec(catalog.ArtifactCodecs, topicCodec{})) + check(pipeline.RegisterExtractor(catalog.Extractors, pipeline.ModuleSpec{Key: "example/topic", Stage: pipeline.StageExtract, ArtifactKind: topicKind, ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{"message-topic-initial", "message-topic-correction"}}, func() (contracts.Extractor[messageTopic], error) { return topicExtractor{}, nil })) + check(pipeline.RegisterMerger(catalog.Mergers, pipeline.ModuleSpec{Key: "example/merge", Stage: pipeline.StageMerge, ArtifactKind: topicKind, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Merger[messageTopic], error) { return topicMerge{}, nil })) + check(pipeline.RegisterNormalizer(catalog.Normalizers, pipeline.ModuleSpec{Key: "example/normalize", Stage: pipeline.StageNormalize, ArtifactKind: topicKind, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Normalizer[messageTopic], error) { return topicNormalize{}, nil })) + var output []contracts.SerializedOutput + check(catalog.Outputs.RegisterWithSpec(pipeline.ModuleSpec{Key: "example/output", Stage: pipeline.StageOutput, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.OutputEncoder, error) { return topicOutput{&output}, nil })) + turns := 1 + profile := pipeline.PipelineProfile{ID: "example", Input: pipeline.Binding("example/input"), Chunk: pipeline.Binding("example/chunk"), Output: pipeline.Binding("example/output"), LLMProfile: "example", MaxAdditionalTurns: &turns, Artifacts: map[string]pipeline.ArtifactLaneProfile{"topics": {Extract: pipeline.Binding("example/topic"), Merge: pipeline.Binding("example/merge"), Normalize: pipeline.Binding("example/normalize")}}} + resolved, err := pipeline.ResolvePipeline(profile, pipeline.ResolveOptions{}, catalog) + check(err) + resolved, _, err = pipeline.MaterializeReferences(resolved, catalog, pipeline.ReferenceMaterializationOptions{}) + check(err) + prepared, err := pipeline.Prepare(resolved, pipeline.Registries{Inputs: catalog.Inputs, Chunkers: catalog.Chunkers, ArtifactCodecs: catalog.ArtifactCodecs, Extractors: catalog.Extractors, Mergers: catalog.Mergers, Normalizers: catalog.Normalizers, Validators: catalog.Validators, ValidatorChains: catalog.ValidatorChains, Outputs: catalog.Outputs}, pipeline.ModuleDependencies{Engine: engine}) + check(err) + _, err = pipeline.New().Run(context.Background(), pipeline.RunInput{Prepared: prepared, RawInput: []byte("message"), Workers: 1}) + check(err) + if len(output) != 1 { + t.Fatalf("outputs = %#v", output) + } + value, err := (topicCodec{}).Decode(output[0].Artifact.Content) + check(err) + if value.Topic != test.want || provider.calls != test.calls { + t.Fatalf("topic=%q calls=%d", value.Topic, provider.calls) + } + if test.calls > 0 && !strings.Contains(provider.correction, "Use the message subject") { + t.Fatal("correction assignment did not carry interpretation guidance") + } + }) + } +}