From e0554209f0a774ef579eda783472d952e951500b Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Sun, 29 Nov 2026 18:09:09 +0000 Subject: [PATCH] Prepare structured D&D reference context --- docs/roadmap/implementation.md | 2 + internal/modules/dnd/chunk/scenes/chunker.go | 21 +- .../modules/dnd/chunk/scenes/chunker_test.go | 42 ++-- .../dnd/extract/itemregistry/extractor.go | 14 +- .../extract/itemregistry/extractor_test.go | 6 +- .../itemregistry/native_execution_test.go | 6 +- .../dnd/extract/itemregistry/registry_test.go | 9 + .../dnd/extract/locationregistry/extractor.go | 14 +- .../locationregistry/extractor_test.go | 6 +- .../locationregistry/native_execution_test.go | 6 +- .../extract/locationregistry/registry_test.go | 9 + .../dnd/extract/npcregistry/extractor.go | 14 +- .../dnd/extract/npcregistry/extractor_test.go | 8 +- .../npcregistry/native_execution_test.go | 6 +- .../dnd/extract/npcregistry/registry_test.go | 15 +- .../extract/scenedescriptions/extractor.go | 14 +- .../scenedescriptions/extractor_test.go | 8 +- .../scenedescriptions/registry_test.go | 13 +- internal/modules/dnd/shared/context.go | 205 ++++++++++++++++++ internal/modules/dnd/shared/context_test.go | 90 ++++++++ internal/modules/dnd/shared/references.go | 16 +- .../modules/dnd/shared/references_test.go | 6 +- 22 files changed, 465 insertions(+), 65 deletions(-) create mode 100644 internal/modules/dnd/shared/context.go create mode 100644 internal/modules/dnd/shared/context_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 87cd7d83..112f58ce 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -317,6 +317,8 @@ and focused CLI spell-catalog tests after their fixture migration. ## Stage 7 — Prepare Shared Context For Scenes And Registry Lanes +**Status:** Complete. Remaining context consumers are migrated in the next unit. + **Goal:** Establish one reusable context preparation path and migrate its first coherent consumer group. diff --git a/internal/modules/dnd/chunk/scenes/chunker.go b/internal/modules/dnd/chunk/scenes/chunker.go index 26d0a1c5..cb2eddc3 100644 --- a/internal/modules/dnd/chunk/scenes/chunker.go +++ b/internal/modules/dnd/chunk/scenes/chunker.go @@ -37,10 +37,21 @@ var _ contracts.Chunker = (*Chunker)(nil) type Options struct{} -type Chunker struct{} +type Chunker struct{ context shared.PreparedContext } -func New(_ Options) (*Chunker, error) { - return &Chunker{}, nil +func New(_ Options, references ...contracts.ReferenceSet) (*Chunker, error) { + if len(references) > 1 { + return nil, chunkerErrorf("at most one reference set may be supplied") + } + var set contracts.ReferenceSet + if len(references) == 1 { + set = references[0] + } + context, err := shared.PrepareContext(set) + if err != nil { + return nil, chunkerErrorf("prepare references: %w", err) + } + return &Chunker{context: context}, nil } func (c *Chunker) Key() string { @@ -70,7 +81,7 @@ func (c *Chunker) PrepareChunk(ctx context.Context, req contracts.ChunkInput) (c if err := source.ValidateDocument(req.Source); err != nil { return nil, chunkerErrorf("validate source document: %w", err) } - materials := shared.PromptInputs(req.SourceInput, req.References) + materials := c.context.Inputs(req.SourceInput) inputs := make(map[string]promptkit.ArtifactRef, len(materials)) for name, material := range materials { inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content)) @@ -121,7 +132,7 @@ func Register(registry *pipeline.ChunkerRegistry) error { if err := shared.ValidateReferenceSelections(request.References); err != nil { return nil, err } - return New(options) + return New(options, request.References) }) } diff --git a/internal/modules/dnd/chunk/scenes/chunker_test.go b/internal/modules/dnd/chunk/scenes/chunker_test.go index 5df3b5ef..cd65698b 100644 --- a/internal/modules/dnd/chunk/scenes/chunker_test.go +++ b/internal/modules/dnd/chunk/scenes/chunker_test.go @@ -89,16 +89,17 @@ func TestRegisterNilRegistryReturnsError(t *testing.T) { func wantReferenceSlots() []contracts.ReferenceSlot { accepted := []string{"application/json", "application/x-yaml", "application/yaml", "text/markdown", "text/plain"} + structured := []string{"application/json", "application/x-yaml", "application/yaml"} return []contracts.ReferenceSlot{ { Name: "glossary", Description: "Optional campaign glossary reference material used only for scene disambiguation.", - AcceptedMediaTypes: append([]string(nil), accepted...), + AcceptedMediaTypes: append([]string(nil), structured...), }, { Name: "party", Description: "Optional party roster reference material used only for scene disambiguation.", - AcceptedMediaTypes: append([]string(nil), accepted...), + AcceptedMediaTypes: append([]string(nil), structured...), }, { Name: "players", @@ -108,7 +109,7 @@ func wantReferenceSlots() []contracts.ReferenceSlot { { Name: "roster", Description: "Deprecated alias for party roster reference material used only for scene disambiguation.", - AcceptedMediaTypes: append([]string(nil), accepted...), + AcceptedMediaTypes: append([]string(nil), structured...), }, } } @@ -232,26 +233,26 @@ func TestPlanPassesReferencesAsPromptInputs(t *testing.T) { "party": { Slot: contracts.ReferenceSlot{Name: "party"}, Items: []contracts.ReferenceItem{ - {SlotName: "party", Content: []byte("Aria: cleric")}, + {SlotName: "party", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Aria","classes":[{"name":"cleric"}]}}}}`)}, }, }, "glossary": { Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{ - {SlotName: "glossary", Content: []byte("Brightmantle: local temple")}, + {SlotName: "glossary", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"b","name":"Brightmantle","category":"place","description":"local temple"}]}}}`)}, }, }, }, } - if _, err := runChunk(context.Background(), newChunker(t, client), req); err != nil { + if _, err := runChunk(context.Background(), newChunker(t, client, req.References), req); err != nil { t.Fatalf("Plan() error = %v, want nil", err) } var messages string for _, message := range client.requests[0].Prompt.Messages { messages += message.Content } - for _, reference := range []string{"Alice: Aria", "Aria: cleric", "Brightmantle: local temple"} { + for _, reference := range []string{"Alice: Aria", "cleric", "Brightmantle", "local temple"} { if strings.Count(messages, reference) != 1 { t.Fatalf("reference not rendered once: %q", reference) } @@ -259,20 +260,33 @@ func TestPlanPassesReferencesAsPromptInputs(t *testing.T) { } -func TestPromptInputsMapLegacyRosterReferenceToParty(t *testing.T) { - inputs := shared.PromptInputs(sceneSourceInput(), contracts.ReferenceSet{ +func TestConstructionRejectsInvalidGlossaryReference(t *testing.T) { + refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ + "glossary": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}}, + }} + if _, err := New(Options{}, refs); err == nil { + t.Fatal("invalid glossary accepted during construction") + } +} + +func TestPreparedContextMapsRosterReferenceToParty(t *testing.T) { + prepared, err := shared.PrepareContext(contracts.ReferenceSet{ Slots: map[string]contracts.ResolvedReferenceSlot{ "roster": { Slot: contracts.ReferenceSlot{Name: "roster"}, Items: []contracts.ReferenceItem{ - {SlotName: "roster", Content: []byte("Legacy roster text")}, + {SlotName: "roster", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Aria"}}}}`)}, }, }, }, }) + if err != nil { + t.Fatal(err) + } + inputs := prepared.Inputs(sceneSourceInput()) - if got := string(inputs["party"].Content); got != "Legacy roster text" { - t.Fatalf("party input = %q, want legacy roster content", got) + if got := string(inputs["party"].Content); !strings.Contains(got, "Aria") { + t.Fatalf("party input = %q, want roster content", got) } if _, ok := inputs["roster"]; ok { t.Fatalf("roster prompt input was present; want only party input") @@ -426,7 +440,7 @@ type chunkFixture struct { engine *promptkit.Engine } -func newChunker(t *testing.T, client promptkit.LLMClient) *chunkFixture { +func newChunker(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *chunkFixture { t.Helper() type settings struct { PromptKit promptkit.Settings `yaml:"promptkit"` @@ -450,7 +464,7 @@ func newChunker(t *testing.T, client promptkit.LLMClient) *chunkFixture { if err != nil { t.Fatal(err) } - chunker, err := New(Options{}) + chunker, err := New(Options{}, references...) if err != nil { t.Fatal(err) } diff --git a/internal/modules/dnd/extract/itemregistry/extractor.go b/internal/modules/dnd/extract/itemregistry/extractor.go index 4357f101..62ce3598 100644 --- a/internal/modules/dnd/extract/itemregistry/extractor.go +++ b/internal/modules/dnd/extract/itemregistry/extractor.go @@ -37,13 +37,21 @@ var _ contracts.Extractor[dnd.ItemRegistry] = (*Extractor)(nil) type Options struct{} -type Extractor struct{} +type Extractor struct{ context shared.PreparedContext } func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) { if len(references) > 1 { return nil, extractorErrorf("at most one reference set may be supplied") } - return &Extractor{}, nil + var set contracts.ReferenceSet + if len(references) == 1 { + set = references[0] + } + context, err := shared.PrepareContext(set) + if err != nil { + return nil, extractorErrorf("prepare references: %w", err) + } + return &Extractor{context: context}, nil } func (e *Extractor) Key() string { return Key } @@ -61,7 +69,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract order := shared.NewSourceRefOrderForSource(req.Source, req.SourceIndex) sourceID := req.Source.ID - materials := shared.PromptInputs(sourceInput, req.References) + materials := e.context.Inputs(sourceInput) inputs := make(map[string]promptkit.ArtifactRef, len(materials)) for name, material := range materials { inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content)) diff --git a/internal/modules/dnd/extract/itemregistry/extractor_test.go b/internal/modules/dnd/extract/itemregistry/extractor_test.go index 0f5eded5..da61027e 100644 --- a/internal/modules/dnd/extract/itemregistry/extractor_test.go +++ b/internal/modules/dnd/extract/itemregistry/extractor_test.go @@ -70,12 +70,12 @@ func TestExtractPassesReferencesWithoutTreatingThemAsEvidence(t *testing.T) { client := &fakeItemsLLMClient{response: extractionResponse{Items: []itemResponse{}}} req := extractionRequest() req.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ - "glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Star Compass: heirloom")}}}, + "glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"s","name":"Star Compass","category":"item","description":"heirloom"}]}}}`)}}}, }} - if _, err := runExtraction(context.Background(), newExtractor(t, client), req); err != nil { + if _, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req); err != nil { t.Fatalf("Extract() error = %v", err) } - messageContaining(t, client.requests[0], "Star Compass: heirloom") + messageContaining(t, client.requests[0], "Star Compass") if strings.Contains(messageContaining(t, client.requests[0], string(req.Chunk.Content)).Content, "heirloom") { t.Fatal("references became source evidence") } diff --git a/internal/modules/dnd/extract/itemregistry/native_execution_test.go b/internal/modules/dnd/extract/itemregistry/native_execution_test.go index e3583814..12e50d58 100644 --- a/internal/modules/dnd/extract/itemregistry/native_execution_test.go +++ b/internal/modules/dnd/extract/itemregistry/native_execution_test.go @@ -41,7 +41,7 @@ func assessRegistry(ctx context.Context, request extractionTestInput, value dnd. func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) { client := &fakeItemsLLMClient{responses: []string{ungroundedRegistry, groundedRegistry}} request := extractionRequest() - request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"glossary": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}} + request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"players": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}} request.Execution.Controls.MaxAdditionalTurns = 1 request.Execution.Execution.Execution = &promptkit.ExecutionTargetOverride{Model: "registry-override"} var prepared []promptkit.PreparedRun @@ -56,11 +56,11 @@ func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) { } // Changes after capture must not cause source/reference preparation again. request.SourceInput.Content[0] = '!' - request.References.Slots["glossary"].Items[0].Content[0] = '!' + request.References.Slots["players"].Items[0].Content[0] = '!' } return assessment, err } - result, err := runExtraction(context.Background(), newExtractor(t, client), request) + result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request) if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || !result.Outcome.ReuseEligible || assessments != 2 || len(client.requests) != 2 || len(prepared) != 2 || len(result.Value.Items) != 1 { t.Fatalf("corrected registry=%#v %v, assessments/provider/prepared=%d/%d/%d", result, err, assessments, len(client.requests), len(prepared)) diff --git a/internal/modules/dnd/extract/itemregistry/registry_test.go b/internal/modules/dnd/extract/itemregistry/registry_test.go index 2ebd85e9..f21b28ee 100644 --- a/internal/modules/dnd/extract/itemregistry/registry_test.go +++ b/internal/modules/dnd/extract/itemregistry/registry_test.go @@ -10,6 +10,15 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" ) +func TestConstructionRejectsInvalidPartyReference(t *testing.T) { + refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ + "party": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}}, + }} + if _, err := New(Options{}, refs); err == nil { + t.Fatal("invalid party accepted during construction") + } +} + func TestModuleRegistrationAndNativeDependencies(t *testing.T) { if _, err := New(Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one") { t.Fatalf("New() error = %v, want reference-set rejection", err) diff --git a/internal/modules/dnd/extract/locationregistry/extractor.go b/internal/modules/dnd/extract/locationregistry/extractor.go index 32968bc6..3935472b 100644 --- a/internal/modules/dnd/extract/locationregistry/extractor.go +++ b/internal/modules/dnd/extract/locationregistry/extractor.go @@ -37,13 +37,21 @@ var _ contracts.Extractor[dnd.LocationRegistry] = (*Extractor)(nil) type Options struct{} -type Extractor struct{} +type Extractor struct{ context shared.PreparedContext } func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) { if len(references) > 1 { return nil, extractorErrorf("at most one reference set may be supplied") } - return &Extractor{}, nil + var set contracts.ReferenceSet + if len(references) == 1 { + set = references[0] + } + context, err := shared.PrepareContext(set) + if err != nil { + return nil, extractorErrorf("prepare references: %w", err) + } + return &Extractor{context: context}, nil } func (e *Extractor) Key() string { return Key } @@ -61,7 +69,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract order := shared.NewSourceRefOrderForSource(req.Source, req.SourceIndex) sourceID := req.Source.ID - materials := shared.PromptInputs(sourceInput, req.References) + materials := e.context.Inputs(sourceInput) inputs := make(map[string]promptkit.ArtifactRef, len(materials)) for name, material := range materials { inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content)) diff --git a/internal/modules/dnd/extract/locationregistry/extractor_test.go b/internal/modules/dnd/extract/locationregistry/extractor_test.go index dc0d466c..ba13b216 100644 --- a/internal/modules/dnd/extract/locationregistry/extractor_test.go +++ b/internal/modules/dnd/extract/locationregistry/extractor_test.go @@ -73,12 +73,12 @@ func TestExtractPassesReferencesWithoutTreatingThemAsEvidence(t *testing.T) { client := &fakeLocationsLLMClient{response: extractionResponse{Locations: []locationResponse{}}} req := extractionRequest() req.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ - "glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Old Mill: abandoned granary")}}}, + "glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"m","name":"Old Mill","category":"place","description":"abandoned granary"}]}}}`)}}}, }} - if _, err := runExtraction(context.Background(), newExtractor(t, client), req); err != nil { + if _, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req); err != nil { t.Fatalf("Extract() error = %v", err) } - messageContaining(t, client.requests[0], "Old Mill: abandoned granary") + messageContaining(t, client.requests[0], "abandoned granary") if strings.Contains(messageContaining(t, client.requests[0], string(req.Chunk.Content)).Content, "abandoned granary") { t.Fatal("references became source evidence") } diff --git a/internal/modules/dnd/extract/locationregistry/native_execution_test.go b/internal/modules/dnd/extract/locationregistry/native_execution_test.go index 4f19b3cf..09d7e55c 100644 --- a/internal/modules/dnd/extract/locationregistry/native_execution_test.go +++ b/internal/modules/dnd/extract/locationregistry/native_execution_test.go @@ -41,7 +41,7 @@ func assessRegistry(ctx context.Context, request extractionTestInput, value dnd. func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) { client := &fakeLocationsLLMClient{responses: []string{ungroundedRegistry, groundedRegistry}} request := extractionRequest() - request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"glossary": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}} + request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"players": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}} request.Execution.Controls.MaxAdditionalTurns = 1 request.Execution.Execution.Execution = &promptkit.ExecutionTargetOverride{Model: "registry-override"} var prepared []promptkit.PreparedRun @@ -56,11 +56,11 @@ func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) { } // Changes after capture must not cause source/reference preparation again. request.SourceInput.Content[0] = '!' - request.References.Slots["glossary"].Items[0].Content[0] = '!' + request.References.Slots["players"].Items[0].Content[0] = '!' } return assessment, err } - result, err := runExtraction(context.Background(), newExtractor(t, client), request) + result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request) if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || !result.Outcome.ReuseEligible || assessments != 2 || len(client.requests) != 2 || len(prepared) != 2 || len(result.Value.Locations) != 1 { t.Fatalf("corrected registry=%#v %v, assessments/provider/prepared=%d/%d/%d", result, err, assessments, len(client.requests), len(prepared)) diff --git a/internal/modules/dnd/extract/locationregistry/registry_test.go b/internal/modules/dnd/extract/locationregistry/registry_test.go index df0b820d..33006683 100644 --- a/internal/modules/dnd/extract/locationregistry/registry_test.go +++ b/internal/modules/dnd/extract/locationregistry/registry_test.go @@ -10,6 +10,15 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" ) +func TestConstructionRejectsInvalidPartyReference(t *testing.T) { + refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ + "party": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}}, + }} + if _, err := New(Options{}, refs); err == nil { + t.Fatal("invalid party accepted during construction") + } +} + func TestModuleRegistrationAndNativeDependencies(t *testing.T) { if _, err := New(Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one") { t.Fatalf("New() error = %v, want reference-set rejection", err) diff --git a/internal/modules/dnd/extract/npcregistry/extractor.go b/internal/modules/dnd/extract/npcregistry/extractor.go index 4fa77853..21f911c4 100644 --- a/internal/modules/dnd/extract/npcregistry/extractor.go +++ b/internal/modules/dnd/extract/npcregistry/extractor.go @@ -43,13 +43,21 @@ var _ contracts.Extractor[dnd.NPCRegistry] = (*Extractor)(nil) type Options struct{} -type Extractor struct{} +type Extractor struct{ context shared.PreparedContext } func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) { if len(references) > 1 { return nil, extractorErrorf("at most one reference set may be supplied") } - return &Extractor{}, nil + var set contracts.ReferenceSet + if len(references) == 1 { + set = references[0] + } + context, err := shared.PrepareContext(set) + if err != nil { + return nil, extractorErrorf("prepare references: %w", err) + } + return &Extractor{context: context}, nil } func (e *Extractor) Key() string { return Key } @@ -67,7 +75,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract order := shared.NewSourceRefOrderForSource(req.Source, req.SourceIndex) sourceID := req.Source.ID - materials := shared.PromptInputs(sourceInput, req.References) + materials := e.context.Inputs(sourceInput) inputs := make(map[string]promptkit.ArtifactRef, len(materials)) for name, material := range materials { inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content)) diff --git a/internal/modules/dnd/extract/npcregistry/extractor_test.go b/internal/modules/dnd/extract/npcregistry/extractor_test.go index f6ed01eb..5e74b854 100644 --- a/internal/modules/dnd/extract/npcregistry/extractor_test.go +++ b/internal/modules/dnd/extract/npcregistry/extractor_test.go @@ -131,15 +131,15 @@ func TestExtractPassesCampaignReferencesAsPromptInputs(t *testing.T) { req := extractionRequest() req.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ "players": {Slot: contracts.ReferenceSlot{Name: "players"}, Items: []contracts.ReferenceItem{{SlotName: "players", Content: []byte("Dana: Mira")}}}, - "party": {Slot: contracts.ReferenceSlot{Name: "party"}, Items: []contracts.ReferenceItem{{SlotName: "party", Content: []byte("Mira: ranger")}}}, - "glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Greencloak: local title")}}}, + "party": {Slot: contracts.ReferenceSlot{Name: "party"}, Items: []contracts.ReferenceItem{{SlotName: "party", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.rpg.party.v1","characters":{"m":{"character":{"name":"Mira","classes":[{"name":"ranger"}]}}}}`)}}}, + "glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"g","name":"Greencloak","category":"title","description":"local title"}]}}}`)}}}, }} - if _, err := runExtraction(context.Background(), newExtractor(t, client), req); err != nil { + if _, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req); err != nil { t.Fatalf("Extract() error = %v, want nil", err) } request := client.requests[0] references := messageContaining(t, request, "Dana: Mira").Content - if !strings.Contains(references, "Mira: ranger") || !strings.Contains(references, "Greencloak: local title") { + if !strings.Contains(references, "Mira") || !strings.Contains(references, "ranger") || !strings.Contains(references, "Greencloak") || !strings.Contains(references, "local title") { t.Fatal("campaign references missing") } if strings.Contains(messageContaining(t, request, string(req.Chunk.Content)).Content, "local title") { diff --git a/internal/modules/dnd/extract/npcregistry/native_execution_test.go b/internal/modules/dnd/extract/npcregistry/native_execution_test.go index 5a2cddb1..8b3284bf 100644 --- a/internal/modules/dnd/extract/npcregistry/native_execution_test.go +++ b/internal/modules/dnd/extract/npcregistry/native_execution_test.go @@ -41,7 +41,7 @@ func assessRegistry(ctx context.Context, request extractionTestInput, value dnd. func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) { client := &fakeNPCsLLMClient{responses: []string{ungroundedRegistry, groundedRegistry}} request := extractionRequest() - request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"glossary": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}} + request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"players": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}} request.Execution.Controls.MaxAdditionalTurns = 1 request.Execution.Execution.Execution = &promptkit.ExecutionTargetOverride{Model: "registry-override"} var prepared []promptkit.PreparedRun @@ -56,11 +56,11 @@ func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) { } // Changes after capture must not cause source/reference preparation again. request.SourceInput.Content[0] = '!' - request.References.Slots["glossary"].Items[0].Content[0] = '!' + request.References.Slots["players"].Items[0].Content[0] = '!' } return assessment, err } - result, err := runExtraction(context.Background(), newExtractor(t, client), request) + result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request) if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || !result.Outcome.ReuseEligible || assessments != 2 || len(client.requests) != 2 || len(prepared) != 2 || len(result.Value.NPCs) != 1 { t.Fatalf("corrected registry=%#v %v, assessments/provider/prepared=%d/%d/%d", result, err, assessments, len(client.requests), len(prepared)) diff --git a/internal/modules/dnd/extract/npcregistry/registry_test.go b/internal/modules/dnd/extract/npcregistry/registry_test.go index d129ae54..2255c687 100644 --- a/internal/modules/dnd/extract/npcregistry/registry_test.go +++ b/internal/modules/dnd/extract/npcregistry/registry_test.go @@ -10,6 +10,15 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" ) +func TestConstructionRejectsInvalidPartyReference(t *testing.T) { + refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ + "party": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}}, + }} + if _, err := New(Options{}, refs); err == nil { + t.Fatal("invalid party accepted during construction") + } +} + func TestNewRejectsAmbiguousReferences(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, want reference-set error", err) @@ -30,10 +39,10 @@ func TestModuleSpecAndReferenceSlots(t *testing.T) { Provides: []string{"dnd.npc_registry"}, ArtifactKind: dnd.NPCRegistryKind, ReferenceSlots: []contracts.ReferenceSlot{ - {Name: "glossary", Description: "Optional campaign glossary reference material used only for NPC disambiguation.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml", "text/markdown", "text/plain"}}, - {Name: "party", Description: "Optional party roster reference material used only for NPC disambiguation.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml", "text/markdown", "text/plain"}}, + {Name: "glossary", Description: "Optional campaign glossary reference material used only for NPC disambiguation.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml"}}, + {Name: "party", Description: "Optional party roster reference material used only for NPC disambiguation.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml"}}, {Name: "players", Description: "Optional player list reference material used only for NPC disambiguation.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml", "text/markdown", "text/plain"}}, - {Name: "roster", Description: "Deprecated alias for party roster reference material used only for NPC disambiguation.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml", "text/markdown", "text/plain"}}, + {Name: "roster", Description: "Deprecated alias for party roster reference material used only for NPC disambiguation.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml"}}, }, } if !reflect.DeepEqual(got, want) { diff --git a/internal/modules/dnd/extract/scenedescriptions/extractor.go b/internal/modules/dnd/extract/scenedescriptions/extractor.go index c12d5062..379505aa 100644 --- a/internal/modules/dnd/extract/scenedescriptions/extractor.go +++ b/internal/modules/dnd/extract/scenedescriptions/extractor.go @@ -49,13 +49,21 @@ var _ contracts.Extractor[dnd.SceneDescriptionList] = (*Extractor)(nil) type Options struct{} -type Extractor struct{} +type Extractor struct{ context shared.PreparedContext } func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) { if len(references) > 1 { return nil, extractorErrorf("at most one reference set may be supplied") } - return &Extractor{}, nil + var set contracts.ReferenceSet + if len(references) == 1 { + set = references[0] + } + context, err := shared.PrepareContext(set) + if err != nil { + return nil, extractorErrorf("prepare references: %w", err) + } + return &Extractor{context: context}, nil } func (e *Extractor) Key() string { return Key } @@ -86,7 +94,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract value.Scenes[0].ID = chunk.ID return sceneFallback(&value, chunk, *index) } - materials := shared.PromptInputs(sourceInput, req.References) + materials := e.context.Inputs(sourceInput) inputs := make(map[string]promptkit.ArtifactRef, len(materials)) for name, material := range materials { inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content)) diff --git a/internal/modules/dnd/extract/scenedescriptions/extractor_test.go b/internal/modules/dnd/extract/scenedescriptions/extractor_test.go index 7ab0ebeb..66d0f056 100644 --- a/internal/modules/dnd/extract/scenedescriptions/extractor_test.go +++ b/internal/modules/dnd/extract/scenedescriptions/extractor_test.go @@ -50,17 +50,17 @@ func TestExtractPassesOptionalReferencesAndUsesEmptyPlaceholders(t *testing.T) { } req.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ "players": {Slot: contracts.ReferenceSlot{Name: "players"}, Items: []contracts.ReferenceItem{{SlotName: "players", Content: []byte("Dana: Mira")}}}, - "party": {Slot: contracts.ReferenceSlot{Name: "party"}, Items: []contracts.ReferenceItem{{SlotName: "party", Content: []byte("Mira: ranger")}}}, - "glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Greencloak: local title")}}}, + "party": {Slot: contracts.ReferenceSlot{Name: "party"}, Items: []contracts.ReferenceItem{{SlotName: "party", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.rpg.party.v1","characters":{"m":{"character":{"name":"Mira","classes":[{"name":"ranger"}]}}}}`)}}}, + "glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"g","name":"Greencloak","category":"title","description":"local title"}]}}}`)}}}, }} - if _, err := runExtraction(newExtractor(t, client), context.Background(), req); err != nil { + if _, err := runExtraction(newExtractor(t, client, req.References), context.Background(), req); err != nil { t.Fatalf("Extract() error = %v, want nil", err) } var text string for _, message := range client.requests[1].Prompt.Messages { text += message.Content } - for _, reference := range []string{"Dana: Mira", "Mira: ranger", "Greencloak: local title"} { + for _, reference := range []string{"Dana: Mira", "ranger", "Greencloak", "local title"} { if strings.Count(text, reference) != 1 { t.Fatalf("optional input not rendered once: %q", reference) } diff --git a/internal/modules/dnd/extract/scenedescriptions/registry_test.go b/internal/modules/dnd/extract/scenedescriptions/registry_test.go index c2badb28..ae02fac9 100644 --- a/internal/modules/dnd/extract/scenedescriptions/registry_test.go +++ b/internal/modules/dnd/extract/scenedescriptions/registry_test.go @@ -10,6 +10,15 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" ) +func TestConstructionRejectsInvalidPartyReference(t *testing.T) { + refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ + "party": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}}, + }} + if _, err := New(Options{}, refs); err == nil { + t.Fatal("invalid party accepted during construction") + } +} + func TestNewRejectsAmbiguousReferences(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, want reference-set error", err) @@ -23,8 +32,8 @@ func TestModuleSpecAndReferenceSlots(t *testing.T) { want := pipeline.ModuleSpec{ Key: Key, Stage: pipeline.StageExtract, ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID}, Requires: []string{"chunks", "source.transcript"}, Provides: []string{"dnd.scene_descriptions"}, ArtifactKind: dnd.SceneDescriptionListKind, ReferenceSlots: []contracts.ReferenceSlot{ - {Name: "glossary", Description: "Optional campaign glossary reference material used only to disambiguate scene descriptions.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml", "text/markdown", "text/plain"}}, - {Name: "party", Description: "Optional party roster reference material used only to disambiguate scene descriptions.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml", "text/markdown", "text/plain"}}, + {Name: "glossary", Description: "Optional campaign glossary reference material used only to disambiguate scene descriptions.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml"}}, + {Name: "party", Description: "Optional party roster reference material used only to disambiguate scene descriptions.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml"}}, {Name: "players", Description: "Optional player list reference material used only to disambiguate scene descriptions.", AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml", "text/markdown", "text/plain"}}, }, } diff --git a/internal/modules/dnd/shared/context.go b/internal/modules/dnd/shared/context.go new file mode 100644 index 00000000..1ab73e8f --- /dev/null +++ b/internal/modules/dnd/shared/context.go @@ -0,0 +1,205 @@ +package shared + +import ( + "encoding/json" + "fmt" + "mime" + "sort" + "strings" + + "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" + "gitea.maximumdirect.net/eric/notarius/internal/integrations/domainrefs" +) + +// PreparedContext holds immutable, task-specific reference material. +type PreparedContext struct { + party, glossary, players contracts.LLMInputMaterial +} + +type partyMember struct { + Name string `json:"name"` + Aliases []string `json:"aliases,omitempty"` + Player string `json:"player,omitempty"` + Classes []partyClass `json:"classes,omitempty"` +} + +type partyClass struct { + Name string `json:"name"` + Level any `json:"level,omitempty"` +} + +type glossaryEntry struct { + Name string `json:"name"` + Aliases []string `json:"aliases,omitempty"` + Category string `json:"category"` + Description *string `json:"description,omitempty"` + Plural *string `json:"plural,omitempty"` +} + +// PrepareContext validates supplied typed references and prepares model-facing views. +func PrepareContext(references contracts.ReferenceSet) (PreparedContext, error) { + if err := ValidateReferenceSelections(references); err != nil { + return PreparedContext{}, err + } + party, partyBound, err := prepareParty(references.Slots["party"], "party") + if err != nil { + return PreparedContext{}, err + } + roster, _, err := prepareParty(references.Slots["roster"], "roster") + if err != nil { + return PreparedContext{}, err + } + if !partyBound { + party = roster + } + glossary, err := prepareGlossary(references.Slots["glossary"]) + if err != nil { + return PreparedContext{}, err + } + return PreparedContext{ + party: party, + glossary: glossary, + players: ReferencePromptMaterial("players", references.Slots["players"]), + }, nil +} + +// Inputs combines fixed reference context with the current transcript. +func (context PreparedContext) Inputs(source contracts.LLMInputMaterial) contracts.LLMInputSet { + return contracts.LLMInputSet{ + "transcript": TranscriptPromptMaterial(source), + "party": context.party.Clone(), + "glossary": context.glossary.Clone(), + "players": context.players.Clone(), + } +} + +func referenceDocument(slot contracts.ResolvedReferenceSlot, name string) (map[string]any, *contracts.ReferenceItem, error) { + if len(slot.Items) == 0 { + return nil, nil, nil + } + if len(slot.Items) != 1 { + return nil, nil, fmt.Errorf("reference slot %q must contain zero or one item", name) + } + item := &slot.Items[0] + mediaType, _, err := mime.ParseMediaType(item.MediaType) + if err != nil { + return nil, nil, fmt.Errorf("reference slot %q: invalid media type: %w", name, err) + } + doc, err := domainrefs.Load(name, strings.ToLower(mediaType), item.Content) + if err != nil { + return nil, nil, err + } + return doc, item, nil +} + +func prepareParty(slot contracts.ResolvedReferenceSlot, name string) (contracts.LLMInputMaterial, bool, error) { + doc, item, err := referenceDocument(slot, name) + if err != nil { + return contracts.LLMInputMaterial{}, false, err + } + if item == nil { + return contextMaterial("party", nil), false, nil + } + if err := domainrefs.ValidateParty(doc); err != nil { + return contracts.LLMInputMaterial{}, false, fmt.Errorf("reference slot %q: %w", name, err) + } + characters := doc["characters"].(map[string]any) + ids := make([]string, 0, len(characters)) + for id := range characters { + ids = append(ids, id) + } + sort.Strings(ids) + members := make([]partyMember, 0, len(ids)) + for _, id := range ids { + entry := characters[id].(map[string]any) + character := entry["character"].(map[string]any) + member := partyMember{Name: character["name"].(string), Aliases: stringList(character["aliases"])} + if player, ok := entry["player"].(map[string]any); ok { + member.Player = player["name"].(string) + } + if classes, ok := character["classes"].([]any); ok { + for _, raw := range classes { + class := raw.(map[string]any) + member.Classes = append(member.Classes, partyClass{Name: class["name"].(string), Level: class["level"]}) + } + } + members = append(members, member) + } + content, err := json.Marshal(members) + if err != nil { + return contracts.LLMInputMaterial{}, false, fmt.Errorf("reference slot %q projection: %w", name, err) + } + if len(members) == 0 { + content = nil + } + return contextMaterial("party", content), true, nil +} + +func prepareGlossary(slot contracts.ResolvedReferenceSlot) (contracts.LLMInputMaterial, error) { + doc, item, err := referenceDocument(slot, "glossary") + if err != nil { + return contracts.LLMInputMaterial{}, err + } + if item == nil { + return contextMaterial("glossary", nil), nil + } + if err := domainrefs.ValidateGlossary(doc); err != nil { + return contracts.LLMInputMaterial{}, fmt.Errorf("reference slot %q: %w", "glossary", err) + } + collections := doc["collections"].(map[string]any) + var defaults []string + for _, name := range []string{"campaign", "setting"} { + if _, ok := collections[name]; ok { + defaults = append(defaults, name) + } + } + names, err := domainrefs.SelectCollections(doc, item.Collections, defaults) + if err != nil { + return contracts.LLMInputMaterial{}, fmt.Errorf("reference slot %q: %w", "glossary", err) + } + var projected []glossaryEntry + for _, name := range names { + entries := append([]any(nil), collections[name].(map[string]any)["entries"].([]any)...) + sort.Slice(entries, func(i, j int) bool { + return entries[i].(map[string]any)["id"].(string) < entries[j].(map[string]any)["id"].(string) + }) + for _, raw := range entries { + entry := raw.(map[string]any) + value := glossaryEntry{Name: entry["name"].(string), Category: entry["category"].(string), Aliases: stringList(entry["aliases"])} + if description, ok := entry["description"].(string); ok { + value.Description = &description + } + if plural, ok := entry["plural"].(string); ok { + value.Plural = &plural + } + projected = append(projected, value) + } + } + var content []byte + if len(projected) != 0 { + content, err = json.Marshal(projected) + if err != nil { + return contracts.LLMInputMaterial{}, fmt.Errorf("reference slot %q projection: %w", "glossary", err) + } + } + return contextMaterial("glossary", content), nil +} + +func stringList(value any) []string { + items, ok := value.([]any) + if !ok { + return nil + } + result := make([]string, len(items)) + for i, item := range items { + result[i] = item.(string) + } + return result +} + +func contextMaterial(name string, content []byte) contracts.LLMInputMaterial { + if len(content) == 0 { + content = []byte(" ") + } + return contracts.NewLLMInputMaterial(name, "text/plain", content, "", "") +} diff --git a/internal/modules/dnd/shared/context_test.go b/internal/modules/dnd/shared/context_test.go new file mode 100644 index 00000000..0720b234 --- /dev/null +++ b/internal/modules/dnd/shared/context_test.go @@ -0,0 +1,90 @@ +package shared + +import ( + "strings" + "testing" + + "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" +) + +func contextReference(content string, collections []string) contracts.ResolvedReferenceSlot { + return contracts.ResolvedReferenceSlot{Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte(content), Collections: collections}}} +} + +func TestPreparedContextProjectsSelectedReferences(t *testing.T) { + party := `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"z":{"character":{"name":"Mira","aliases":["Shadow"],"classes":[{"name":"Ranger","level":3}]},"player":{"name":"Dana"}},"a":{"character":{"name":"Mira"},"player":{"name":"Lee"}}},"instruction":"not a prompt"}` + glossary := `{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"z","name":"Greencloak","category":"title","aliases":["Green"],"description":"local title","plural":"Greencloaks","instruction":"not a prompt"}]},"setting":{"entries":[]},"spells":{"entries":[{"id":"x","name":"Hidden Spell","category":"spell"}]}}}` + references := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ + "party": contextReference(party, nil), + "glossary": contextReference(glossary, nil), + "players": {Items: []contracts.ReferenceItem{{Content: []byte("Supplemental players")}}}, + }} + prepared, err := PrepareContext(references) + if err != nil { + t.Fatal(err) + } + inputs := prepared.Inputs(contracts.NewLLMInputMaterial("source", "text/plain", []byte("current transcript"), "", "")) + partyBody := string(inputs["party"].Content) + if strings.Count(partyBody, `"name":"Mira"`) != 2 || !strings.Contains(partyBody, "Shadow") || !strings.Contains(partyBody, "Dana") || !strings.Contains(partyBody, "Ranger") || strings.Index(partyBody, "Lee") > strings.Index(partyBody, "Dana") { + t.Fatalf("party projection = %s", partyBody) + } + glossaryBody := string(inputs["glossary"].Content) + for _, value := range []string{"Greencloak", "Green", "title", "local title", "Greencloaks"} { + if !strings.Contains(glossaryBody, value) { + t.Fatalf("glossary projection missing %q: %s", value, glossaryBody) + } + } + if strings.Contains(glossaryBody, "Hidden Spell") || strings.Contains(partyBody+glossaryBody, "not a prompt") || strings.Contains(glossaryBody, `"id"`) { + t.Fatal("irrelevant document content reached model context") + } + if string(inputs["players"].Content) != "Supplemental players" || string(inputs["transcript"].Content) != "current transcript" { + t.Fatalf("supplemental context or transcript changed: %#v", inputs) + } + inputs["party"].Content[0] = '!' + if strings.HasPrefix(string(prepared.Inputs(contracts.LLMInputMaterial{})["party"].Content), "!") { + t.Fatal("caller mutated prepared context") + } +} + +func TestPreparedContextValidatesAllTypedSlotsAndSelection(t *testing.T) { + validParty := `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Aria"}}}}` + glossary := `{"schema_version":"maximumdirect.glossary.v1","collections":{"other":{"entries":[{"id":"a","name":"Chosen","category":"term"}]}}}` + refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ + "party": contextReference(validParty, nil), + "roster": contextReference("{}", nil), + }} + if _, err := PrepareContext(refs); err == nil || !strings.Contains(err.Error(), "roster") { + t.Fatalf("invalid overridden roster accepted: %v", err) + } + delete(refs.Slots, "roster") + refs.Slots["glossary"] = contextReference(glossary, []string{"other"}) + got, err := PrepareContext(refs) + if err != nil || !strings.Contains(string(got.Inputs(contracts.LLMInputMaterial{})["glossary"].Content), "Chosen") { + t.Fatalf("selected glossary missing: %v", err) + } + refs.Slots["glossary"] = contextReference(glossary, []string{}) + got, err = PrepareContext(refs) + if err != nil || string(got.Inputs(contracts.LLMInputMaterial{})["glossary"].Content) != " " { + t.Fatalf("empty selection = %#v, %v", got, err) + } + refs.Slots["glossary"] = contextReference(glossary, []string{"missing"}) + if _, err := PrepareContext(refs); err == nil || !strings.Contains(err.Error(), "missing") { + t.Fatalf("missing selection accepted: %v", err) + } +} + +func TestPreparedContextRosterFallbackAndPartyPrecedence(t *testing.T) { + party := `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Party member"}}}}` + roster := `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"b":{"character":{"name":"Roster member"}}}}` + refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"roster": contextReference(roster, nil)}} + prepared, err := PrepareContext(refs) + if err != nil || !strings.Contains(string(prepared.Inputs(contracts.LLMInputMaterial{})["party"].Content), "Roster member") { + t.Fatalf("roster fallback: %v", err) + } + refs.Slots["party"] = contextReference(party, nil) + prepared, err = PrepareContext(refs) + body := string(prepared.Inputs(contracts.LLMInputMaterial{})["party"].Content) + if err != nil || !strings.Contains(body, "Party member") || strings.Contains(body, "Roster member") { + t.Fatalf("party precedence = %q, %v", body, err) + } +} diff --git a/internal/modules/dnd/shared/references.go b/internal/modules/dnd/shared/references.go index ea6e04b3..82b0cd3e 100644 --- a/internal/modules/dnd/shared/references.go +++ b/internal/modules/dnd/shared/references.go @@ -42,6 +42,16 @@ var referenceMediaTypes = []string{ "text/plain", } +var structuredReferenceMediaTypes = []string{ + "application/json", + "application/x-yaml", + "application/yaml", +} + +func StructuredReferenceMediaTypes() []string { + return append([]string(nil), structuredReferenceMediaTypes...) +} + func ReferenceMediaTypes() []string { return append([]string(nil), referenceMediaTypes...) } @@ -51,12 +61,12 @@ func ReferenceSlots(descriptions ReferenceSlotDescriptions) []contracts.Referenc { Name: "glossary", Description: descriptions.Glossary, - AcceptedMediaTypes: ReferenceMediaTypes(), + AcceptedMediaTypes: StructuredReferenceMediaTypes(), }, { Name: "party", Description: descriptions.Party, - AcceptedMediaTypes: ReferenceMediaTypes(), + AcceptedMediaTypes: StructuredReferenceMediaTypes(), }, { Name: "players", @@ -66,7 +76,7 @@ func ReferenceSlots(descriptions ReferenceSlotDescriptions) []contracts.Referenc { Name: "roster", Description: descriptions.Roster, - AcceptedMediaTypes: ReferenceMediaTypes(), + AcceptedMediaTypes: StructuredReferenceMediaTypes(), }, }) } diff --git a/internal/modules/dnd/shared/references_test.go b/internal/modules/dnd/shared/references_test.go index 1b1cd9ac..15f15c61 100644 --- a/internal/modules/dnd/shared/references_test.go +++ b/internal/modules/dnd/shared/references_test.go @@ -50,10 +50,10 @@ func TestReferenceSlotsUseDescriptionsAndExpectedOrder(t *testing.T) { } got := ReferenceSlots(descriptions) want := []contracts.ReferenceSlot{ - {Name: "glossary", Description: descriptions.Glossary, AcceptedMediaTypes: ReferenceMediaTypes()}, - {Name: "party", Description: descriptions.Party, AcceptedMediaTypes: ReferenceMediaTypes()}, + {Name: "glossary", Description: descriptions.Glossary, AcceptedMediaTypes: StructuredReferenceMediaTypes()}, + {Name: "party", Description: descriptions.Party, AcceptedMediaTypes: StructuredReferenceMediaTypes()}, {Name: "players", Description: descriptions.Players, AcceptedMediaTypes: ReferenceMediaTypes()}, - {Name: "roster", Description: descriptions.Roster, AcceptedMediaTypes: ReferenceMediaTypes()}, + {Name: "roster", Description: descriptions.Roster, AcceptedMediaTypes: StructuredReferenceMediaTypes()}, } if !reflect.DeepEqual(got, want) { t.Fatalf("ReferenceSlots() = %#v, want %#v", got, want)