diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index ae4d024b..e1b57a61 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -516,6 +516,10 @@ their domain preparation into one configurable D&D extractor engine. ## Stage 12 — Migrate The Three Occurrence Extractors +**Status:** Complete. Focused occurrence suites pass, including generated +registry handoff through registered typed execution. Remaining unmigrated +integrations and fixtures are addressed in subsequent stages. + **Goal:** Preserve contextual selections and domain feedback at the new boundary. **Inspect:** `dnd/extract/{npcoccurrences,itemoccurrences,locationoccurrences}`, diff --git a/internal/modules/dnd/extract/itemoccurrences/extractor.go b/internal/modules/dnd/extract/itemoccurrences/extractor.go index 7fc4305d..380c70d5 100644 --- a/internal/modules/dnd/extract/itemoccurrences/extractor.go +++ b/internal/modules/dnd/extract/itemoccurrences/extractor.go @@ -61,14 +61,10 @@ var _ contracts.Extractor[dnd.ItemOccurrenceList] = (*Extractor)(nil) type Options struct{} type Extractor struct { - engine *promptkit.Engine itemResolver *itemregistry.Resolver } -func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceSet) (*Extractor, error) { - if engine == nil { - return nil, extractorErrorf("native engine must not be nil") - } +func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) { if len(references) > 1 { return nil, extractorErrorf("at most one reference set may be supplied") } @@ -80,32 +76,29 @@ func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceS if err != nil { return nil, extractorErrorf("prepare item registry prompt input: %w", err) } - return &Extractor{engine: engine, itemResolver: itemResolver}, nil + return &Extractor{itemResolver: itemResolver}, nil } func (e *Extractor) Key() string { return Key } func (e *Extractor) ReferenceSlots() []contracts.ReferenceSlot { return referenceSlots() } -func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRequest[dnd.ItemOccurrenceList]) (contracts.TypedExtractionResult[dnd.ItemOccurrenceList], error) { +func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.ExtractionInput) (contracts.PreparedOperation[dnd.ItemOccurrenceList], error) { if e == nil { - return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("extractor must not be nil") + return nil, extractorErrorf("extractor must not be nil") } - if e.engine == nil { - return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("native engine must not be nil") - } - sourceInput, err := shared.PrepareChunkExtraction(ctx, req) + sourceInput, err := shared.PrepareChunkInput(ctx, req) if err != nil { - return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("%w", err) + return nil, extractorErrorf("%w", err) } order := shared.NewSourceRefOrder(req.Source) registry, err := e.itemResolver.Resolve(req.References) if err != nil { - return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("resolve item registry: %w", err) + return nil, extractorErrorf("resolve item registry: %w", err) } if !registry.Bound() { - return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("item registry reference is required") + return nil, extractorErrorf("item registry reference is required") } sourceID := req.Source.ID @@ -116,29 +109,22 @@ func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRe inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content)) } initial := promptkit.RunRequest{PromptID: PromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, Inputs: inputs} - value, outcome, err := pipeline.RunProducer(ctx, e.engine, req.Operation, initial, - func(_ context.Context, result *promptkit.RunResult) (*dnd.ItemOccurrenceList, []string, error) { + return contracts.NativeOperation[dnd.ItemOccurrenceList]{Initial: initial, + Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[dnd.ItemOccurrenceList], error) { var response extractionResponse if err := json.Unmarshal([]byte(result.RawOutput), &response); err != nil { - return nil, nil, extractorErrorf("decode native output: %w", err) + return nil, extractorErrorf("decode native output: %w", err) } value, err := canonicalItemOccurrenceList(response, order, sourceID, registry) if err != nil { - return nil, []string{"Select the exact canonical item name from the supplied registry for every occurrence. Omit unsupported or ambiguous selections; do not invent an item. Return the complete replacement occurrence list, keeping current-transcript evidence separate from registry context."}, nil + return contracts.CandidateEvaluation[dnd.ItemOccurrenceList]{Result: contracts.EvaluationView[dnd.ItemOccurrenceList]{Guidance: []string{"Select the exact canonical item name from the supplied registry for every occurrence. Omit unsupported or ambiguous selections; do not invent an item. Return the complete replacement occurrence list, keeping current-transcript evidence separate from registry context."}}}, nil } - return &value, nil, nil + return contracts.CandidateEvaluation[dnd.ItemOccurrenceList]{Result: contracts.EvaluationView[dnd.ItemOccurrenceList]{Candidate: &value}}, nil }, - func(_ context.Context, guidance []string) (promptkit.RunRequest, error) { - return promptkit.RunRequest{PromptID: CorrectionPromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, - Inputs: map[string]promptkit.ArtifactRef{"guidance": promptkit.Inline(strings.Join(guidance, "\n\n"))}}, nil - }, - func(context.Context, *dnd.ItemOccurrenceList) (dnd.ItemOccurrenceList, error) { + Correction: contracts.PromptCorrection(CorrectionPromptID, "guidance", func(guidance []string) promptkit.ArtifactRef { return promptkit.Inline(strings.Join(guidance, "\n\n")) }), + Fallback: func(context.Context, contracts.Evaluation[dnd.ItemOccurrenceList]) (dnd.ItemOccurrenceList, error) { return dnd.ItemOccurrenceList{Occurrences: []dnd.ItemOccurrence{}}, nil - }) - if err != nil { - return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("produce occurrences: %w", err) - } - return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{Value: value, Outcome: outcome}, nil + }}, nil } func ModuleSpec() pipeline.ModuleSpec { @@ -160,7 +146,7 @@ func Register(registry *pipeline.ExtractorRegistry) error { if err != nil { return nil, err } - return New(request.Dependencies.Engine, options, request.References) + return New(options, request.References) }) } diff --git a/internal/modules/dnd/extract/itemoccurrences/extractor_test.go b/internal/modules/dnd/extract/itemoccurrences/extractor_test.go index 397092fb..ce7d330c 100644 --- a/internal/modules/dnd/extract/itemoccurrences/extractor_test.go +++ b/internal/modules/dnd/extract/itemoccurrences/extractor_test.go @@ -15,7 +15,7 @@ func TestExtractGroundsOccurrencesInRequiredRegistry(t *testing.T) { client := &fakeItemOccurrencesLLMClient{content: append([]byte(nil), rawResponse...)} req := extractionRequest() req.References = itemRegistryReferences(t) - result, err := newExtractor(t, client, req.References).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req) if err != nil { t.Fatal(err) } @@ -48,7 +48,7 @@ func TestExtractCanonicalizesComparisonEquivalentNames(t *testing.T) { }}} req := extractionRequest() req.References = itemRegistryReferences(t) - result, err := newExtractor(t, client, req.References).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req) if err != nil { t.Fatal(err) } @@ -65,7 +65,7 @@ func TestExtractRejectsUnknownNameAfterValidOccurrence(t *testing.T) { }}} req := extractionRequest() req.References = itemRegistryReferences(t) - result, err := newExtractor(t, client, req.References).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req) if err == nil || result.Outcome.Disposition != "" { t.Fatalf("Extract() error = %v, want atomic unknown-name failure", err) } @@ -75,7 +75,7 @@ func TestExtractRejectsUnknownNameAfterValidOccurrence(t *testing.T) { } func TestExtractRequiresItemRegistry(t *testing.T) { - _, err := newExtractor(t, &fakeItemOccurrencesLLMClient{}).Extract(context.Background(), extractionRequest()) + _, err := runExtraction(context.Background(), newExtractor(t, &fakeItemOccurrencesLLMClient{}), extractionRequest()) if err == nil { t.Fatal("Extract() error = nil, want required registry error") } @@ -95,7 +95,7 @@ func TestExtractAcceptsOnlyEmptyResponseForEmptyRegistry(t *testing.T) { client := &fakeItemOccurrencesLLMClient{response: test.response} req := extractionRequest() req.References = references - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if test.wantErr { if err == nil || result.Outcome.Disposition != "" || len(result.Value.Occurrences) != 0 { t.Fatalf("Extract() = %#v, %v; want no accepted occurrences", result, err) @@ -113,7 +113,7 @@ func TestExtractPreservesNullableFields(t *testing.T) { client := &fakeItemOccurrencesLLMClient{content: []byte(`{"occurrences":[{"name":"Torch","kind":"discovered","quantity":null,"from":null,"to":null,"source_refs":[{"start_unit_id":1,"end_unit_id":1}]}]}`)} req := extractionRequest() req.References = itemRegistryReferences(t) - result, err := newExtractor(t, client, req.References).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req) if err != nil || len(result.Value.Occurrences) != 1 || result.Value.Occurrences[0].Quantity != nil || result.Value.Occurrences[0].From != "" || result.Value.Occurrences[0].To != "" { t.Fatalf("result = %#v, %v", result, err) } @@ -124,7 +124,7 @@ func TestExtractUsesOnlySupportedPromptInputs(t *testing.T) { req := extractionRequest() req.References = itemRegistryReferences(t) req.References.Slots["unrelated"] = contracts.ResolvedReferenceSlot{Slot: contracts.ReferenceSlot{Name: "unrelated"}, Items: []contracts.ReferenceItem{{SlotName: "unrelated", Content: []byte("ignored")}}} - if _, err := newExtractor(t, client, req.References).Extract(context.Background(), req); err != nil { + if _, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req); err != nil { t.Fatal(err) } for _, message := range client.requests[0].Prompt.Messages { diff --git a/internal/modules/dnd/extract/itemoccurrences/native_execution_test.go b/internal/modules/dnd/extract/itemoccurrences/native_execution_test.go index c5416c4c..ac7f45cd 100644 --- a/internal/modules/dnd/extract/itemoccurrences/native_execution_test.go +++ b/internal/modules/dnd/extract/itemoccurrences/native_execution_test.go @@ -68,7 +68,7 @@ func TestExtractCarriesRejectedHolderGuidanceIntoNativeCorrection(t *testing.T) request.Operation.Execution.OnPrepared = func(_ context.Context, run promptkit.PreparedRun) { prepared = append(prepared, run) } calls, guidance := bindAssessment(t, &request) client := &fakeItemOccurrencesLLMClient{responses: []string{rejectedHolder, correctedHolder}} - result, err := newExtractor(t, client, request.References).Extract(context.Background(), request) + result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request) chain := []string{shape.Key, sourcerefs.Key, relatedness.Key, registryvalidator.Key} if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || result.Outcome.ReuseEligible || !reflect.DeepEqual(*calls, append(append([]string(nil), chain...), chain...)) || len(result.Value.Occurrences) != 1 || len(client.requests) != 2 || len(prepared) != 2 || len(*guidance) != 1 { @@ -148,7 +148,7 @@ func TestItemOccurrenceTerminalModesDoNotSynthesizeHolders(t *testing.T) { runs := 0 request.Operation.Execution.OnPrepared = func(context.Context, promptkit.PreparedRun) { runs++ } client := &fakeItemOccurrencesLLMClient{content: []byte(test.response), errors: test.failures} - result, err := newExtractor(t, client, request.References).Extract(context.Background(), request) + result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request) if (err != nil) != test.wantError || len(*calls) != test.assessments*4 || runs != test.runs { t.Fatalf("terminal = %#v %v, validators=%#v runs=%d", result, err, *calls, runs) } @@ -175,7 +175,7 @@ func TestItemOccurrenceCancellationCannotPublishFallback(t *testing.T) { request.References = itemRegistryReferences(t) request.Operation.Controls.Mode = contracts.ModePermissive client := &fakeItemOccurrencesLLMClient{content: []byte(correctedHolder), onGenerate: func(context.Context, promptkit.GenerateRequest) { cancel() }} - result, err := newExtractor(t, client, request.References).Extract(ctx, request) + result, err := runExtraction(ctx, newExtractor(t, client, request.References), request) if !errors.Is(err, context.Canceled) || result.Outcome.Disposition != "" || len(client.requests) != 1 { t.Fatalf("canceled delivery = %#v %v", result, err) } @@ -193,7 +193,7 @@ func TestItemOccurrenceKindsHoldersQuantityAndDocumentOrderSurvive(t *testing.T) request := extractionRequest() request.References = itemRegistryReferences(t) bindAssessment(t, &request) - result, err := newExtractor(t, client).Extract(context.Background(), request) + result, err := runExtraction(context.Background(), newExtractor(t, client), request) if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || len(result.Value.Occurrences) != 5 { t.Fatalf("kinds = %#v %v", result, err) } diff --git a/internal/modules/dnd/extract/itemoccurrences/test_helpers_test.go b/internal/modules/dnd/extract/itemoccurrences/test_helpers_test.go index 05f82722..218f51e8 100644 --- a/internal/modules/dnd/extract/itemoccurrences/test_helpers_test.go +++ b/internal/modules/dnd/extract/itemoccurrences/test_helpers_test.go @@ -13,6 +13,7 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/core/source" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" + "gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline" "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" ) @@ -56,7 +57,12 @@ func responseRefs(start, end int) []itemOccurrenceSourceRefResponse { return []itemOccurrenceSourceRefResponse{{StartUnitID: start, EndUnitID: end}} } -func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *Extractor { +type extractionFixture struct { + *Extractor + engine *promptkit.Engine +} + +func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *extractionFixture { t.Helper() type settings struct { PromptKit promptkit.Settings `yaml:"promptkit"` @@ -80,11 +86,25 @@ func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contra if err != nil { t.Fatal(err) } - extractor, err := New(engine, Options{}, references...) + extractor, err := New(Options{}, references...) if err != nil { t.Fatal(err) } - return extractor + return &extractionFixture{Extractor: extractor, engine: engine} +} + +func runExtraction(ctx context.Context, fixture *extractionFixture, req contracts.TypedExtractionRequest[dnd.ItemOccurrenceList]) (pipeline.OperationResult[dnd.ItemOccurrenceList], error) { + var extractor *Extractor + var engine *promptkit.Engine + if fixture != nil { + extractor, engine = fixture.Extractor, fixture.engine + } + op := req.Operation + execution := pipeline.ExecutionContext[dnd.ItemOccurrenceList]{Engine: engine, Controls: op.Controls, Assess: op.Assess, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Cache: op.Cache} + input := contracts.ExtractionInput{Source: req.Source, Chunk: req.Chunk, SourceInput: req.SourceInput, SessionID: req.SessionID, References: req.References, LLMProfile: req.LLMProfile, Metadata: req.Metadata, AmbientContext: req.AmbientContext} + return pipeline.ExecuteOperation(ctx, execution, func(ctx context.Context) (contracts.PreparedOperation[dnd.ItemOccurrenceList], error) { + return extractor.PrepareExtraction(ctx, input) + }) } func renderedInput(t *testing.T, request promptkit.GenerateRequest, name string) []byte { diff --git a/internal/modules/dnd/extract/locationoccurrences/extractor.go b/internal/modules/dnd/extract/locationoccurrences/extractor.go index 456c77a0..feec4cbc 100644 --- a/internal/modules/dnd/extract/locationoccurrences/extractor.go +++ b/internal/modules/dnd/extract/locationoccurrences/extractor.go @@ -55,14 +55,10 @@ var _ contracts.Extractor[dnd.LocationOccurrenceList] = (*Extractor)(nil) type Options struct{} type Extractor struct { - engine *promptkit.Engine locationResolver *locationregistry.Resolver } -func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceSet) (*Extractor, error) { - if engine == nil { - return nil, extractorErrorf("native engine must not be nil") - } +func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) { if len(references) > 1 { return nil, extractorErrorf("at most one reference set may be supplied") } @@ -74,34 +70,31 @@ func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceS if err != nil { return nil, extractorErrorf("prepare location registry prompt input: %w", err) } - return &Extractor{engine: engine, locationResolver: locationResolver}, nil + return &Extractor{locationResolver: locationResolver}, nil } func (e *Extractor) Key() string { return Key } func (e *Extractor) ReferenceSlots() []contracts.ReferenceSlot { return referenceSlots() } -func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRequest[dnd.LocationOccurrenceList]) (contracts.TypedExtractionResult[dnd.LocationOccurrenceList], error) { +func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.ExtractionInput) (contracts.PreparedOperation[dnd.LocationOccurrenceList], error) { if e == nil { - return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("extractor must not be nil") + return nil, extractorErrorf("extractor must not be nil") } - if e.engine == nil { - return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("native engine must not be nil") - } - sourceInput, err := shared.PrepareChunkExtraction(ctx, req) + sourceInput, err := shared.PrepareChunkInput(ctx, req) if err != nil { - return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("%w", err) + return nil, extractorErrorf("%w", err) } registry, err := e.locationResolver.Resolve(req.References) if err != nil { - return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("resolve location registry: %w", err) + return nil, extractorErrorf("resolve location registry: %w", err) } if !registry.Bound() { - return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("location registry reference is required") + return nil, extractorErrorf("location registry reference is required") } grounding, err := locationregistry.NewGrounding(registry, req.Source) if err != nil { - return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("prepare location grounding: %w", err) + return nil, extractorErrorf("prepare location grounding: %w", err) } order := shared.NewSourceRefOrder(req.Source) @@ -114,29 +107,22 @@ func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRe inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content)) } initial := promptkit.RunRequest{PromptID: PromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, Inputs: inputs} - value, outcome, err := pipeline.RunProducer(ctx, e.engine, req.Operation, initial, - func(_ context.Context, result *promptkit.RunResult) (*dnd.LocationOccurrenceList, []string, error) { + return contracts.NativeOperation[dnd.LocationOccurrenceList]{Initial: initial, + Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[dnd.LocationOccurrenceList], error) { var response extractionResponse if err := json.Unmarshal([]byte(result.RawOutput), &response); err != nil { - return nil, nil, extractorErrorf("decode native output: %w", err) + return nil, extractorErrorf("decode native output: %w", err) } value, err := canonicalOccurrenceList(response, order, sourceID, grounding) if err != nil { - return nil, []string{"Resolve every occurrence to exactly one supplied location selector. Copy its canonical name and complete ordered registry_refs array; use an empty registry_refs array for a unique name. Omit unsupported or ambiguous selections. Keep occurrence evidence in source_refs separate from registry context, and return the complete replacement occurrence list."}, nil + return contracts.CandidateEvaluation[dnd.LocationOccurrenceList]{Result: contracts.EvaluationView[dnd.LocationOccurrenceList]{Guidance: []string{"Resolve every occurrence to exactly one supplied location selector. Copy its canonical name and complete ordered registry_refs array; use an empty registry_refs array for a unique name. Omit unsupported or ambiguous selections. Keep occurrence evidence in source_refs separate from registry context, and return the complete replacement occurrence list."}}}, nil } - return &value, nil, nil + return contracts.CandidateEvaluation[dnd.LocationOccurrenceList]{Result: contracts.EvaluationView[dnd.LocationOccurrenceList]{Candidate: &value}}, nil }, - func(_ context.Context, guidance []string) (promptkit.RunRequest, error) { - return promptkit.RunRequest{PromptID: CorrectionPromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, - Inputs: map[string]promptkit.ArtifactRef{"guidance": promptkit.Inline(strings.Join(guidance, "\n\n"))}}, nil - }, - func(context.Context, *dnd.LocationOccurrenceList) (dnd.LocationOccurrenceList, error) { + Correction: contracts.PromptCorrection(CorrectionPromptID, "guidance", func(guidance []string) promptkit.ArtifactRef { return promptkit.Inline(strings.Join(guidance, "\n\n")) }), + Fallback: func(context.Context, contracts.Evaluation[dnd.LocationOccurrenceList]) (dnd.LocationOccurrenceList, error) { return dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{}}, nil - }) - if err != nil { - return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("produce occurrences: %w", err) - } - return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{Value: value, Outcome: outcome}, nil + }}, nil } func ModuleSpec() pipeline.ModuleSpec { @@ -154,7 +140,7 @@ func Register(registry *pipeline.ExtractorRegistry) error { if err != nil { return nil, err } - return New(request.Dependencies.Engine, options, request.References) + return New(options, request.References) }) } diff --git a/internal/modules/dnd/extract/locationoccurrences/extractor_test.go b/internal/modules/dnd/extract/locationoccurrences/extractor_test.go index 7fefab3e..a51351d2 100644 --- a/internal/modules/dnd/extract/locationoccurrences/extractor_test.go +++ b/internal/modules/dnd/extract/locationoccurrences/extractor_test.go @@ -31,7 +31,7 @@ func TestExtractMapsKindsOrdersOccurrencesAndPreservesIndependentFacts(t *testin references := registryReferences(t, locations) req := extractionRequest() req.References = references - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if err != nil { t.Fatal(err) } @@ -62,7 +62,7 @@ func TestExtractResolvesContextualSelectorsAndUsesCurrentTranscriptEvidenceOnly( references := registryReferences(t, locations) req := extractionRequest() req.References = references - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if err != nil { t.Fatal(err) } @@ -97,7 +97,7 @@ func TestExtractRejectsUnknownMalformedOrMismatchedSelectorsAtomically(t *testin {{Name: known.Name, RegistryRefs: []locationregistry.RegistryRef{}, Kind: "mentioned", SourceRefs: occurrenceRefs(10, 10)}, {Name: "Unknown", RegistryRefs: []locationregistry.RegistryRef{}, Kind: "mentioned", SourceRefs: occurrenceRefs(20, 20)}}, } { client := &fakeOccurrencesLLMClient{response: extractionResponse{Occurrences: occurrences}} - if result, err := newExtractor(t, client, references).Extract(context.Background(), req); err == nil || result.Value.Occurrences != nil { + if result, err := runExtraction(context.Background(), newExtractor(t, client, references), req); err == nil || result.Value.Occurrences != nil { t.Fatalf("Extract() = %#v, %v", result, err) } } @@ -121,7 +121,7 @@ func TestExtractRejectsUnknownMalformedOrMismatchedSelectorsAtomically(t *testin client := &fakeOccurrencesLLMClient{response: extractionResponse{Occurrences: []occurrenceResponse{{Name: selector.name, RegistryRefs: selector.refs, Kind: "mentioned", SourceRefs: occurrenceRefs(10, 10)}}}} duplicateRequest := extractionRequest() duplicateRequest.References = duplicateReferences - if result, err := newExtractor(t, client, duplicateReferences).Extract(context.Background(), duplicateRequest); err == nil || result.Outcome.Disposition != "" || len(result.Value.Occurrences) != 0 { + if result, err := runExtraction(context.Background(), newExtractor(t, client, duplicateReferences), duplicateRequest); err == nil || result.Outcome.Disposition != "" || len(result.Value.Occurrences) != 0 { t.Fatalf("Extract(%#v) error = %v", selector, err) } } @@ -129,7 +129,7 @@ func TestExtractRejectsUnknownMalformedOrMismatchedSelectorsAtomically(t *testin func TestExtractRequiresRegistryAndAcceptsEmptyRegistryWithNoOccurrences(t *testing.T) { client := &fakeOccurrencesLLMClient{response: extractionResponse{Occurrences: []occurrenceResponse{}}} - if _, err := newExtractor(t, client).Extract(context.Background(), extractionRequest()); err == nil || !strings.Contains(err.Error(), "location registry reference is required") { + if _, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest()); err == nil || !strings.Contains(err.Error(), "location registry reference is required") { t.Fatalf("Extract() error = %v", err) } if len(client.requests) != 0 { @@ -139,7 +139,7 @@ func TestExtractRequiresRegistryAndAcceptsEmptyRegistryWithNoOccurrences(t *test references := registryReferences(t, empty) req := extractionRequest() req.References = references - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if err != nil || result.Value.Occurrences == nil || len(result.Value.Occurrences) != 0 { t.Fatalf("empty registry result = %#v, %v", result, err) } @@ -155,7 +155,7 @@ func TestExtractResolvesGeneratedRegistryAtOperationTimeAndDoesNotMutateResponse req := extractionRequest() req.References = references extractor := newExtractor(t, client) - result, err := extractor.Extract(context.Background(), req) + result, err := runExtraction(context.Background(), extractor, req) if err != nil || result.Value.Occurrences[0].Name != "The Mill" { t.Fatalf("Extract() = %#v, %v", result, err) } @@ -168,16 +168,13 @@ func TestExtractResolvesGeneratedRegistryAtOperationTimeAndDoesNotMutateResponse } func TestExtractorContractsDependenciesAndFailures(t *testing.T) { - if _, err := New(nil, Options{}); err == nil || !strings.Contains(err.Error(), "native engine") { - t.Fatalf("New(nil) error = %v", err) - } - if _, err := New(newExtractor(t, &fakeOccurrencesLLMClient{}).engine, Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one reference set") { + if _, err := New(Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one reference set") { t.Fatalf("New() error = %v", err) } malformed := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{LocationRegistryReferenceSlot: { Items: []contracts.ReferenceItem{{SlotName: LocationRegistryReferenceSlot, MediaType: "application/json", Content: []byte(`{"secret":"registry evidence"}`)}}, }}} - if _, err := New(newExtractor(t, &fakeOccurrencesLLMClient{}).engine, Options{}, malformed); err == nil || !strings.Contains(err.Error(), "prepare location registry") || strings.Contains(err.Error(), "registry evidence") { + if _, err := New(Options{}, malformed); err == nil || !strings.Contains(err.Error(), "prepare location registry") || strings.Contains(err.Error(), "registry evidence") { t.Fatalf("New() error = %v", err) } @@ -186,24 +183,23 @@ func TestExtractorContractsDependenciesAndFailures(t *testing.T) { req := extractionRequest() req.References = references extractor := newExtractor(t, &fakeOccurrencesLLMClient{}, references) - var nilExtractor *Extractor + var nilExtractor *extractionFixture for _, test := range []struct { name string - extractor *Extractor + extractor *extractionFixture req contracts.TypedExtractionRequest[dnd.LocationOccurrenceList] want string }{ {"nil extractor", nilExtractor, req, "extractor"}, - {"nil client", &Extractor{}, req, "native engine"}, {"invalid request", extractor, mismatchedSourceInputRequest(req), "must match chunk"}, } { t.Run(test.name, func(t *testing.T) { - if _, err := test.extractor.Extract(context.Background(), test.req); err == nil || !strings.Contains(err.Error(), test.want) { + if _, err := runExtraction(context.Background(), test.extractor, test.req); err == nil || !strings.Contains(err.Error(), test.want) { t.Fatalf("Extract() error = %v", err) } }) } - if _, err := newExtractor(t, &fakeOccurrencesLLMClient{err: errors.New("provider unavailable")}, references).Extract(context.Background(), req); err == nil || !strings.Contains(err.Error(), "provider unavailable") { + if _, err := runExtraction(context.Background(), newExtractor(t, &fakeOccurrencesLLMClient{err: errors.New("provider unavailable")}, references), req); err == nil || !strings.Contains(err.Error(), "provider unavailable") { t.Fatalf("provider error = %v", err) } diff --git a/internal/modules/dnd/extract/locationoccurrences/native_execution_test.go b/internal/modules/dnd/extract/locationoccurrences/native_execution_test.go index 3ae182e5..f8a771ec 100644 --- a/internal/modules/dnd/extract/locationoccurrences/native_execution_test.go +++ b/internal/modules/dnd/extract/locationoccurrences/native_execution_test.go @@ -59,7 +59,7 @@ func TestNativeCorrectionKeepsRegistryResolutionAndInputsFixed(t *testing.T) { request.References.Slots[LocationRegistryReferenceSlot].Items[0].Content[0] = '!' } } - result, err := newExtractor(t, client, request.References).Extract(context.Background(), request) + result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request) expectedAssessments := 1 if first == invalidCitation { expectedAssessments = 2 @@ -128,7 +128,7 @@ func TestNativeOccurrenceFallbackIsAnExplicitEmptyList(t *testing.T) { return sourceAssessment(ctx, request, value) } client := &fakeOccurrencesLLMClient{raw: test.response, errors: test.errors} - result, err := newExtractor(t, client, request.References).Extract(context.Background(), request) + result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request) if (err != nil) != test.wantError || assessments != test.wantAssessments || prepared != test.wantRuns { t.Fatalf("outcome=%#v %v, assessments/runs=%d/%d", result, err, assessments, prepared) } @@ -155,7 +155,7 @@ func TestCanceledOccurrenceDeliveryCannotConstructFallback(t *testing.T) { request.References, _ = operationReferences(t) request.Operation.Controls.Mode = contracts.ModePermissive client := &fakeOccurrencesLLMClient{raw: knownOccurrence, onGenerate: func(context.Context, promptkit.GenerateRequest) { cancel() }} - result, err := newExtractor(t, client, request.References).Extract(ctx, request) + result, err := runExtraction(ctx, newExtractor(t, client, request.References), request) if !errors.Is(err, context.Canceled) || result.Outcome.Disposition != "" || len(client.requests) != 1 { t.Fatalf("cancellation=%#v %v", result, err) } diff --git a/internal/modules/dnd/extract/locationoccurrences/test_helpers_test.go b/internal/modules/dnd/extract/locationoccurrences/test_helpers_test.go index 36c281b6..d963a32e 100644 --- a/internal/modules/dnd/extract/locationoccurrences/test_helpers_test.go +++ b/internal/modules/dnd/extract/locationoccurrences/test_helpers_test.go @@ -12,6 +12,7 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/core/source" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" + "gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline" "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" ) @@ -45,7 +46,12 @@ func occurrenceRefs(start, end int) []occurrenceSourceRefResponse { return []occurrenceSourceRefResponse{{StartUnitID: start, EndUnitID: end}} } -func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *Extractor { +type extractionFixture struct { + *Extractor + engine *promptkit.Engine +} + +func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *extractionFixture { t.Helper() type settings struct { PromptKit promptkit.Settings `yaml:"promptkit"` @@ -69,11 +75,25 @@ func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contra if err != nil { t.Fatal(err) } - extractor, err := New(engine, Options{}, references...) + extractor, err := New(Options{}, references...) if err != nil { t.Fatal(err) } - return extractor + return &extractionFixture{Extractor: extractor, engine: engine} +} + +func runExtraction(ctx context.Context, fixture *extractionFixture, req contracts.TypedExtractionRequest[dnd.LocationOccurrenceList]) (pipeline.OperationResult[dnd.LocationOccurrenceList], error) { + var extractor *Extractor + var engine *promptkit.Engine + if fixture != nil { + extractor, engine = fixture.Extractor, fixture.engine + } + op := req.Operation + execution := pipeline.ExecutionContext[dnd.LocationOccurrenceList]{Engine: engine, Controls: op.Controls, Assess: op.Assess, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Cache: op.Cache} + input := contracts.ExtractionInput{Source: req.Source, Chunk: req.Chunk, SourceInput: req.SourceInput, SessionID: req.SessionID, References: req.References, LLMProfile: req.LLMProfile, Metadata: req.Metadata, AmbientContext: req.AmbientContext} + return pipeline.ExecuteOperation(ctx, execution, func(ctx context.Context) (contracts.PreparedOperation[dnd.LocationOccurrenceList], error) { + return extractor.PrepareExtraction(ctx, input) + }) } func renderedInput(t *testing.T, request promptkit.GenerateRequest, name string) []byte { diff --git a/internal/modules/dnd/extract/npcoccurrences/extractor.go b/internal/modules/dnd/extract/npcoccurrences/extractor.go index 3feb076e..b901dd42 100644 --- a/internal/modules/dnd/extract/npcoccurrences/extractor.go +++ b/internal/modules/dnd/extract/npcoccurrences/extractor.go @@ -60,14 +60,10 @@ var _ contracts.Extractor[dnd.NPCOccurrenceList] = (*Extractor)(nil) type Options struct{} type Extractor struct { - engine *promptkit.Engine npcResolver *npcregistry.Resolver } -func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceSet) (*Extractor, error) { - if engine == nil { - return nil, extractorErrorf("native engine must not be nil") - } +func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) { if len(references) > 1 { return nil, extractorErrorf("at most one reference set may be supplied") } @@ -79,31 +75,28 @@ func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceS if err != nil { return nil, extractorErrorf("prepare NPC registry prompt input: %w", err) } - return &Extractor{engine: engine, npcResolver: npcResolver}, nil + return &Extractor{npcResolver: npcResolver}, nil } func (e *Extractor) Key() string { return Key } func (e *Extractor) ReferenceSlots() []contracts.ReferenceSlot { return referenceSlots() } -func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRequest[dnd.NPCOccurrenceList]) (contracts.TypedExtractionResult[dnd.NPCOccurrenceList], error) { +func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.ExtractionInput) (contracts.PreparedOperation[dnd.NPCOccurrenceList], error) { if e == nil { - return contracts.TypedExtractionResult[dnd.NPCOccurrenceList]{}, extractorErrorf("extractor must not be nil") + return nil, extractorErrorf("extractor must not be nil") } - if e.engine == nil { - return contracts.TypedExtractionResult[dnd.NPCOccurrenceList]{}, extractorErrorf("native engine must not be nil") - } - sourceInput, err := shared.PrepareChunkExtraction(ctx, req) + sourceInput, err := shared.PrepareChunkInput(ctx, req) if err != nil { - return contracts.TypedExtractionResult[dnd.NPCOccurrenceList]{}, extractorErrorf("%w", err) + return nil, extractorErrorf("%w", err) } order := shared.NewSourceRefOrder(req.Source) npcRegistry, err := e.npcResolver.Resolve(req.References) if err != nil { - return contracts.TypedExtractionResult[dnd.NPCOccurrenceList]{}, extractorErrorf("resolve NPC registry: %w", err) + return nil, extractorErrorf("resolve NPC registry: %w", err) } if !npcRegistry.Bound() { - return contracts.TypedExtractionResult[dnd.NPCOccurrenceList]{}, extractorErrorf("NPC registry reference is required") + return nil, extractorErrorf("NPC registry reference is required") } sourceID := req.Source.ID @@ -114,30 +107,23 @@ func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRe inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content)) } initial := promptkit.RunRequest{PromptID: PromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, Inputs: inputs} - value, outcome, err := pipeline.RunProducer(ctx, e.engine, req.Operation, initial, - func(_ context.Context, result *promptkit.RunResult) (*dnd.NPCOccurrenceList, []string, error) { + return contracts.NativeOperation[dnd.NPCOccurrenceList]{Initial: initial, + Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[dnd.NPCOccurrenceList], error) { var response extractionResponse if err := json.Unmarshal([]byte(result.RawOutput), &response); err != nil { - return nil, nil, extractorErrorf("decode native output: %w", err) + return nil, extractorErrorf("decode native output: %w", err) } canonicalizeResponse(&response, order, sourceID) value, err := canonicalOccurrenceList(response, sourceID, npcRegistry) if err != nil { - return nil, []string{"Resolve every occurrence to an exact canonical name from the supplied NPC registry. Omit occurrences for identities absent from that registry; do not invent an identity. Return the complete replacement occurrence list."}, nil + return contracts.CandidateEvaluation[dnd.NPCOccurrenceList]{Result: contracts.EvaluationView[dnd.NPCOccurrenceList]{Guidance: []string{"Resolve every occurrence to an exact canonical name from the supplied NPC registry. Omit occurrences for identities absent from that registry; do not invent an identity. Return the complete replacement occurrence list."}}}, nil } - return &value, nil, nil + return contracts.CandidateEvaluation[dnd.NPCOccurrenceList]{Result: contracts.EvaluationView[dnd.NPCOccurrenceList]{Candidate: &value}}, nil }, - func(_ context.Context, guidance []string) (promptkit.RunRequest, error) { - return promptkit.RunRequest{PromptID: CorrectionPromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, - Inputs: map[string]promptkit.ArtifactRef{"guidance": promptkit.Inline(strings.Join(guidance, "\n\n"))}}, nil - }, - func(context.Context, *dnd.NPCOccurrenceList) (dnd.NPCOccurrenceList, error) { + Correction: contracts.PromptCorrection(CorrectionPromptID, "guidance", func(guidance []string) promptkit.ArtifactRef { return promptkit.Inline(strings.Join(guidance, "\n\n")) }), + Fallback: func(context.Context, contracts.Evaluation[dnd.NPCOccurrenceList]) (dnd.NPCOccurrenceList, error) { return dnd.NPCOccurrenceList{Occurrences: []dnd.NPCOccurrence{}}, nil - }) - if err != nil { - return contracts.TypedExtractionResult[dnd.NPCOccurrenceList]{}, extractorErrorf("produce occurrences: %w", err) - } - return contracts.TypedExtractionResult[dnd.NPCOccurrenceList]{Value: value, Outcome: outcome}, nil + }}, nil } func ModuleSpec() pipeline.ModuleSpec { @@ -159,7 +145,7 @@ func Register(registry *pipeline.ExtractorRegistry) error { if err != nil { return nil, err } - return New(request.Dependencies.Engine, options, request.References) + return New(options, request.References) }) } diff --git a/internal/modules/dnd/extract/npcoccurrences/extractor_test.go b/internal/modules/dnd/extract/npcoccurrences/extractor_test.go index 4730f6e5..e340265d 100644 --- a/internal/modules/dnd/extract/npcoccurrences/extractor_test.go +++ b/internal/modules/dnd/extract/npcoccurrences/extractor_test.go @@ -29,7 +29,7 @@ func TestExtractMapsEveryKindAndOrdersBySourcePosition(t *testing.T) { req := extractionRequest() req.References = references - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if err != nil { t.Fatalf("Extract() error = %v", err) } @@ -82,7 +82,7 @@ func TestExtractUsesDocumentOrderForReferencesAndOccurrences(t *testing.T) { req.Chunk.Units = append([]source.SourceUnit(nil), req.Source.Units...) req.Chunk.Ref = source.SourceRef{SourceID: req.Source.ID, StartUnitID: 30, EndUnitID: 10} - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if err != nil { t.Fatalf("Extract() error = %v", err) } @@ -103,11 +103,8 @@ func TestExtractUsesDocumentOrderForReferencesAndOccurrences(t *testing.T) { } } -func TestNewRequiresLLMAndRejectsAmbiguousReferenceSets(t *testing.T) { - if _, err := New(nil, Options{}); err == nil || !strings.Contains(err.Error(), "native engine") { - t.Fatalf("New(nil) error = %v", err) - } - if _, err := New(newExtractor(t, &fakeOccurrencesLLMClient{}).engine, Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one reference set") { +func TestNewRejectsAmbiguousReferenceSets(t *testing.T) { + if _, err := New(Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one reference set") { t.Fatalf("New() error = %v", err) } } @@ -119,7 +116,7 @@ func TestExtractUsesNamesOnlyRegistryAndCurrentTranscriptEvidence(t *testing.T) references := requiredRegistryReferences(t, "Mira Thorn", "Hooded Guard") req := extractionRequest() req.References = references - if _, err := newExtractor(t, client, references).Extract(context.Background(), req); err != nil { + if _, err := runExtraction(context.Background(), newExtractor(t, client, references), req); err != nil { t.Fatalf("Extract() error = %v", err) } request := client.requests[0] @@ -140,7 +137,7 @@ func TestExtractUsesNamesOnlyRegistryAndCurrentTranscriptEvidence(t *testing.T) func TestExtractRequiresBoundRegistryBeforeLLMCall(t *testing.T) { client := &fakeOccurrencesLLMClient{} - if _, err := newExtractor(t, client).Extract(context.Background(), extractionRequest()); err == nil || !strings.Contains(err.Error(), "NPC registry reference is required") { + if _, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest()); err == nil || !strings.Contains(err.Error(), "NPC registry reference is required") { t.Fatalf("Extract() error = %v, want required registry failure", err) } if len(client.requests) != 0 { @@ -153,7 +150,7 @@ func TestExtractRequiresBoundRegistryBeforeLLMCall(t *testing.T) { Items: []contracts.ReferenceItem{{SlotName: NPCRegistryReferenceSlot, MediaType: "application/json", Content: []byte(`{"secret":"private source"}`)}}, }, }} - if _, err := New(newExtractor(t, client).engine, Options{}, malformed); err == nil || !strings.Contains(err.Error(), "prepare NPC registry") || strings.Contains(err.Error(), "private source") { + if _, err := New(Options{}, malformed); err == nil || !strings.Contains(err.Error(), "prepare NPC registry") || strings.Contains(err.Error(), "private source") { t.Fatalf("New() error = %v, want content-safe malformed registry error", err) } if len(client.requests) != 0 { @@ -169,7 +166,7 @@ func TestExtractRejectsUnknownNamesWithoutPartialResult(t *testing.T) { }}} req := extractionRequest() req.References = references - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if err == nil || result.Outcome.Disposition != "" { t.Fatalf("Extract() error = %v, want unknown name failure", err) } @@ -185,7 +182,7 @@ func TestExtractCanonicalizesComparisonEquivalentRegistryNames(t *testing.T) { }}}} req := extractionRequest() req.References = references - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if err != nil { t.Fatalf("Extract() error = %v", err) } @@ -201,7 +198,7 @@ func TestExtractResolvesGeneratedRegistryAtOperationTime(t *testing.T) { req := extractionRequest() req.References = references extractor := newExtractor(t, client) - if _, err := extractor.Extract(context.Background(), req); err != nil { + if _, err := runExtraction(context.Background(), extractor, req); err != nil { t.Fatalf("Extract() error = %v", err) } if input := renderedInput(t, client.requests[0], NPCRegistryReferenceSlot); string(input) != `{"npcs":[{"name":"Mira Thorn"}]}` { @@ -224,7 +221,7 @@ func TestExtractAcceptsEmptyBoundRegistryAndEmptyResponse(t *testing.T) { client := &fakeOccurrencesLLMClient{response: extractionResponse{Occurrences: []occurrenceResponse{}}} req := extractionRequest() req.References = references - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if err != nil || result.Value.Occurrences == nil || len(result.Value.Occurrences) != 0 { t.Fatalf("Extract() = %#v, %v; want present empty occurrences", result, err) } @@ -242,7 +239,7 @@ func TestExtractRejectsNonemptyResponseForEmptyBoundRegistry(t *testing.T) { client := &fakeOccurrencesLLMClient{response: extractionResponse{Occurrences: []occurrenceResponse{{Name: "Mira Thorn", Kind: "dialogue", SourceRefs: occurrenceRefs(10, 10)}}}} req := extractionRequest() req.References = references - result, err := newExtractor(t, client, references).Extract(context.Background(), req) + result, err := runExtraction(context.Background(), newExtractor(t, client, references), req) if err == nil || result.Outcome.Disposition != "" || len(result.Value.Occurrences) != 0 { t.Fatalf("Extract() = %#v, %v; want no accepted occurrences", result, err) } @@ -253,25 +250,24 @@ func TestExtractRejectsInvalidRequestsAndProviderFailures(t *testing.T) { valid := extractionRequest() valid.References = references extractor := newExtractor(t, &fakeOccurrencesLLMClient{}, references) - var nilExtractor *Extractor + var nilExtractor *extractionFixture for _, test := range []struct { name string - extractor *Extractor + extractor *extractionFixture ctx context.Context req contracts.TypedExtractionRequest[dnd.NPCOccurrenceList] want string }{ {"nil extractor", nilExtractor, context.Background(), valid, "extractor"}, - {"nil native engine", &Extractor{}, context.Background(), valid, "native engine"}, {"wrapped preflight failure", extractor, context.Background(), mismatchedSourceInputRequest(valid), "must match chunk"}, } { t.Run(test.name, func(t *testing.T) { - if _, err := test.extractor.Extract(test.ctx, test.req); err == nil || !strings.Contains(err.Error(), test.want) { + if _, err := runExtraction(test.ctx, test.extractor, test.req); err == nil || !strings.Contains(err.Error(), test.want) { t.Fatalf("Extract() error = %v, want %q", err, test.want) } }) } - if _, err := newExtractor(t, &fakeOccurrencesLLMClient{err: errors.New("provider unavailable")}, references).Extract(context.Background(), valid); err == nil || !strings.Contains(err.Error(), "provider unavailable") { + if _, err := runExtraction(context.Background(), newExtractor(t, &fakeOccurrencesLLMClient{err: errors.New("provider unavailable")}, references), valid); err == nil || !strings.Contains(err.Error(), "provider unavailable") { t.Fatalf("provider error = %v", err) } } diff --git a/internal/modules/dnd/extract/npcoccurrences/native_execution_test.go b/internal/modules/dnd/extract/npcoccurrences/native_execution_test.go index 50b15ef8..f6dbfe01 100644 --- a/internal/modules/dnd/extract/npcoccurrences/native_execution_test.go +++ b/internal/modules/dnd/extract/npcoccurrences/native_execution_test.go @@ -58,7 +58,7 @@ func TestNativeCorrectionKeepsRegistryResolutionAndInputsFixed(t *testing.T) { request.References.Slots[NPCRegistryReferenceSlot].Items[0].Content[0] = '!' } } - result, err := newExtractor(t, client, request.References).Extract(context.Background(), request) + result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request) expectedAssessments := 1 if first == invalidCitation { expectedAssessments = 2 @@ -127,7 +127,7 @@ func TestNativeOccurrenceFallbackIsAnExplicitEmptyList(t *testing.T) { return sourceAssessment(ctx, request, value) } client := &fakeOccurrencesLLMClient{raw: test.response, errors: test.errors} - result, err := newExtractor(t, client, request.References).Extract(context.Background(), request) + result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request) if (err != nil) != test.wantError || assessments != test.wantAssessments || prepared != test.wantRuns { t.Fatalf("outcome=%#v %v, assessments/runs=%d/%d", result, err, assessments, prepared) } @@ -154,7 +154,7 @@ func TestCanceledOccurrenceDeliveryCannotConstructFallback(t *testing.T) { request.References, _ = operationReferences(t) request.Operation.Controls.Mode = contracts.ModePermissive client := &fakeOccurrencesLLMClient{raw: knownOccurrence, onGenerate: func(context.Context, promptkit.GenerateRequest) { cancel() }} - result, err := newExtractor(t, client, request.References).Extract(ctx, request) + result, err := runExtraction(ctx, newExtractor(t, client, request.References), request) if !errors.Is(err, context.Canceled) || result.Outcome.Disposition != "" || len(client.requests) != 1 { t.Fatalf("cancellation=%#v %v", result, err) } diff --git a/internal/modules/dnd/extract/npcoccurrences/registered_execution_test.go b/internal/modules/dnd/extract/npcoccurrences/registered_execution_test.go new file mode 100644 index 00000000..fb0f64d5 --- /dev/null +++ b/internal/modules/dnd/extract/npcoccurrences/registered_execution_test.go @@ -0,0 +1,110 @@ +package npcoccurrences + +import ( + "context" + "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" + "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" + occurrencecodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/npcoccurrences" + npccodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/npcregistry" + "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity" + "gitea.maximumdirect.net/eric/notarius/internal/modules/generic/merge/appendorder" + "gitea.maximumdirect.net/eric/notarius/internal/modules/generic/normalize/noop" +) + +type generatedInput struct{ document *source.SourceDocument } + +func (generatedInput) Key() string { return "generated/input" } +func (input generatedInput) Parse(context.Context, contracts.ParseRequest) (*source.SourceDocument, error) { + return input.document, nil +} + +type generatedChunker struct{} + +func (generatedChunker) Key() string { return "generated/chunk" } +func (generatedChunker) ReferenceSlots() []contracts.ReferenceSlot { return nil } +func (generatedChunker) PrepareChunk(_ context.Context, request contracts.ChunkInput) (contracts.PreparedOperation[source.ChunkPlan], error) { + plan := source.ChunkPlan{SourceDigest: request.Source.Digest, Ranges: []source.ChunkRange{{StartUnitID: request.Source.Units[0].ID, EndUnitID: request.Source.Units[len(request.Source.Units)-1].ID}}} + return contracts.DeterministicOperation[source.ChunkPlan]{Evaluation: contracts.CandidateEvaluation[source.ChunkPlan]{Result: contracts.EvaluationView[source.ChunkPlan]{Candidate: &plan}}}, nil +} + +type generatedRegistry struct{} + +func (generatedRegistry) Key() string { return "generated/registry" } +func (generatedRegistry) ReferenceSlots() []contracts.ReferenceSlot { return nil } +func (generatedRegistry) PrepareExtraction(_ context.Context, input contracts.ExtractionInput) (contracts.PreparedOperation[dnd.NPCRegistry], error) { + value := dnd.NPCRegistry{NPCs: []dnd.NPC{{ID: identity.DeriveID("Mira Thorn"), Name: "Mira Thorn", SourceRefs: []source.SourceRef{{SourceID: input.Source.ID, StartUnitID: input.Source.Units[0].ID, EndUnitID: input.Source.Units[0].ID}}}}} + return contracts.DeterministicOperation[dnd.NPCRegistry]{Evaluation: contracts.CandidateEvaluation[dnd.NPCRegistry]{Result: contracts.EvaluationView[dnd.NPCRegistry]{Candidate: &value}}}, nil +} + +type generatedOutput struct{ outputs *[]contracts.SerializedOutput } + +func (generatedOutput) Key() string { return "generated/output" } +func (output generatedOutput) Encode(_ context.Context, request contracts.OutputRequest) (contracts.OutputResult, error) { + *output.outputs = request.NormalizeOutputs + return contracts.OutputResult{}, nil +} + +func TestRegisteredOccurrenceExtractionUsesGeneratedRegistry(t *testing.T) { + doc := sourceDocument() + for i := range doc.Units { + doc.Units[i].Ref = source.SourceRef{SourceID: doc.ID, StartUnitID: doc.Units[i].ID, EndUnitID: doc.Units[i].ID} + } + var err error + doc.Digest, err = source.DigestDocument(doc) + if err != nil { + t.Fatal(err) + } + client := &fakeOccurrencesLLMClient{response: extractionResponse{Occurrences: []occurrenceResponse{{Name: "Mira Thorn", Kind: "dialogue", SourceRefs: occurrenceRefs(10, 10)}}}} + engine := newExtractor(t, client).engine + 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: "generated/input", Stage: pipeline.StageInput, ExecutionClass: contracts.ExecutionClassDeterministic, Provides: []string{"source.transcript"}}, func() (contracts.InputAdapter, error) { return generatedInput{doc}, nil })) + check(catalog.Chunkers.RegisterWithSpec(pipeline.ModuleSpec{Key: "generated/chunk", Stage: pipeline.StageChunk, ExecutionClass: contracts.ExecutionClassDeterministic, Provides: []string{"chunks"}}, func() (contracts.Chunker, error) { return generatedChunker{}, nil })) + check(pipeline.RegisterArtifactCodec(catalog.ArtifactCodecs, npccodec.New())) + check(pipeline.RegisterArtifactCodec(catalog.ArtifactCodecs, occurrencecodec.New())) + check(pipeline.RegisterExtractor(catalog.Extractors, pipeline.ModuleSpec{Key: "generated/registry", Stage: pipeline.StageExtract, ArtifactKind: dnd.NPCRegistryKind, ExecutionClass: contracts.ExecutionClassDeterministic, Requires: []string{"chunks"}, Provides: []string{"extracted"}}, func() (contracts.Extractor[dnd.NPCRegistry], error) { return generatedRegistry{}, nil })) + check(Register(catalog.Extractors)) + check(appendorder.RegisterTyped(catalog.Mergers, dnd.NPCRegistryKind, func(values []dnd.NPCRegistry) (dnd.NPCRegistry, error) { return values[0], nil })) + check(appendorder.RegisterTyped(catalog.Mergers, dnd.NPCOccurrenceListKind, func(values []dnd.NPCOccurrenceList) (dnd.NPCOccurrenceList, error) { return values[0], nil })) + check(noop.RegisterTyped[dnd.NPCRegistry](catalog.Normalizers, dnd.NPCRegistryKind)) + check(noop.RegisterTyped[dnd.NPCOccurrenceList](catalog.Normalizers, dnd.NPCOccurrenceListKind)) + var outputs []contracts.SerializedOutput + check(catalog.Outputs.RegisterWithSpec(pipeline.ModuleSpec{Key: "generated/output", Stage: pipeline.StageOutput, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.OutputEncoder, error) { return generatedOutput{&outputs}, nil })) + profile := pipeline.PipelineProfile{ID: "generated", Input: pipeline.Binding("generated/input"), Chunk: pipeline.Binding("generated/chunk"), Output: pipeline.Binding("generated/output"), LLMProfile: "profile-npc-occurrences", Steps: []pipeline.PipelineStepProfile{ + {ID: "build", Artifacts: map[string]pipeline.ArtifactLaneProfile{"registry": {Extract: pipeline.Binding("generated/registry"), Merge: pipeline.Binding(appendorder.Key), Normalize: pipeline.Binding(noop.Key)}}}, + {ID: "consume", Artifacts: map[string]pipeline.ArtifactLaneProfile{"occurrences": {Extract: pipeline.ModuleBinding{Module: Key, References: map[string]pipeline.ReferenceSource{NPCRegistryReferenceSlot: pipeline.GeneratedReference("build", "registry")}}, Merge: pipeline.Binding(appendorder.Key), Normalize: pipeline.Binding(noop.Key)}}}, + }} + 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("input"), Workers: 1}) + check(err) + for _, output := range outputs { + if output.LaneID != "occurrences" { + continue + } + value, err := occurrencecodec.New().Decode(output.Artifact.Content) + check(err) + if len(value.Occurrences) != 1 || value.Occurrences[0].NPCID != identity.DeriveID("Mira Thorn") { + t.Fatalf("occurrences = %#v", value.Occurrences) + } + if len(client.requests) != 1 || strings.Contains(string(renderedInput(t, client.requests[0], "npc_registry")), value.Occurrences[0].NPCID) { + t.Fatal("registry prompt exposed an application ID or did not execute once") + } + return + } + t.Fatalf("occurrence output missing: %#v", outputs) +} diff --git a/internal/modules/dnd/extract/npcoccurrences/test_helpers_test.go b/internal/modules/dnd/extract/npcoccurrences/test_helpers_test.go index 2c5b2aab..4c0673bc 100644 --- a/internal/modules/dnd/extract/npcoccurrences/test_helpers_test.go +++ b/internal/modules/dnd/extract/npcoccurrences/test_helpers_test.go @@ -13,6 +13,7 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/core/source" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" + "gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline" "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" npccodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/npcregistry" "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity" @@ -96,7 +97,12 @@ func mismatchedSourceInputRequest(req contracts.TypedExtractionRequest[dnd.NPCOc return req } -func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *Extractor { +type extractionFixture struct { + *Extractor + engine *promptkit.Engine +} + +func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *extractionFixture { t.Helper() type settings struct { PromptKit promptkit.Settings `yaml:"promptkit"` @@ -120,11 +126,25 @@ func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contra if err != nil { t.Fatal(err) } - extractor, err := New(engine, Options{}, references...) + extractor, err := New(Options{}, references...) if err != nil { t.Fatal(err) } - return extractor + return &extractionFixture{Extractor: extractor, engine: engine} +} + +func runExtraction(ctx context.Context, fixture *extractionFixture, req contracts.TypedExtractionRequest[dnd.NPCOccurrenceList]) (pipeline.OperationResult[dnd.NPCOccurrenceList], error) { + var extractor *Extractor + var engine *promptkit.Engine + if fixture != nil { + extractor, engine = fixture.Extractor, fixture.engine + } + op := req.Operation + execution := pipeline.ExecutionContext[dnd.NPCOccurrenceList]{Engine: engine, Controls: op.Controls, Assess: op.Assess, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Cache: op.Cache} + input := contracts.ExtractionInput{Source: req.Source, Chunk: req.Chunk, SourceInput: req.SourceInput, SessionID: req.SessionID, References: req.References, LLMProfile: req.LLMProfile, Metadata: req.Metadata, AmbientContext: req.AmbientContext} + return pipeline.ExecuteOperation(ctx, execution, func(ctx context.Context) (contracts.PreparedOperation[dnd.NPCOccurrenceList], error) { + return extractor.PrepareExtraction(ctx, input) + }) } func renderedInput(t *testing.T, request promptkit.GenerateRequest, name string) []byte {