diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 10fc581b..87cd7d83 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -282,6 +282,8 @@ or configuration composition mechanism is introduced. ## Stage 6 — Cut Spell Recognition Over To Shared Glossaries +**Status:** Complete. Maintained example files are migrated in the documentation unit below. + **Goal:** Replace the private overlay format across the whole spell family. **Inspect:** `internal/modules/dnd/spells/catalog/effective.go`, extraction and diff --git a/internal/cli/production_contract_test.go b/internal/cli/production_contract_test.go index e24ce0e5..46377998 100644 --- a/internal/cli/production_contract_test.go +++ b/internal/cli/production_contract_test.go @@ -359,7 +359,7 @@ func TestProductionSpellNormalizerRejectsInvalidCatalogReferencesBeforeExecution t.Fatalf("MaterializeReferences() error = %v, want malformed JSON to reach preparation", err) } _, err = pipeline.Prepare(materialized, components.registries, pipeline.ModuleDependencies{Engine: productionNativeEngine(t, &productionFakeLLMClient{})}) - for _, fragment := range []string{`pipeline "dnd-session"`, `lane "spells"`, "normalize", `module "dnd/spells"`, "decode spell catalog overlay"} { + for _, fragment := range []string{`pipeline "dnd-session"`, `lane "spells"`, "normalize", `module "dnd/spells"`, "invalid JSON syntax"} { if err == nil || !strings.Contains(err.Error(), fragment) { t.Fatalf("Prepare() error = %v, want context fragment %q", err, fragment) } @@ -388,7 +388,7 @@ func TestProductionSpellNormalizerRejectsInvalidCatalogReferencesBeforeExecution t.Fatal(err) } content := productionSpellCatalogContractConfig(t) - catalogSource := repositoryPath("examples", "dnd-complete", "spell-catalog.json") + catalogSource := loadMaintainedExample(t, writeProductionContractConfig(t, content)).Pipelines["dnd-session"].Artifacts["spells"].Extract.References["spell_catalog"].Path content = strings.Replace(content, catalogSource, "__extract_catalog__", 1) content = replaceRequiredOnce(t, content, catalogSource, catalogPath) content = replaceRequiredOnce(t, content, "__extract_catalog__", catalogSource) @@ -622,6 +622,10 @@ func maintainedExampleFiles(t *testing.T) []maintainedExample { func productionSpellCatalogContractConfig(t *testing.T) string { t.Helper() + catalogPath := filepath.Join(t.TempDir(), "spell-catalog.json") + if err := os.WriteFile(catalogPath, []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"aegis","name":"Aegis of Emberfall","category":"spell","aliases":["Emberfall Aegis"]}]}}}`), 0o600); err != nil { + t.Fatal(err) + } return fmt.Sprintf(`version: 6 pipelines: dnd-session: @@ -644,7 +648,7 @@ pipelines: references: spell_catalog: path: %q -`, repositoryPath("examples", "dnd-complete", "party.txt"), repositoryPath("examples", "dnd-complete", "glossary.txt"), repositoryPath("examples", "dnd-complete", "spell-catalog.json"), repositoryPath("examples", "dnd-complete", "spell-catalog.json")) +`, repositoryPath("examples", "dnd-complete", "party.txt"), repositoryPath("examples", "dnd-complete", "glossary.txt"), catalogPath, catalogPath) } func writeProductionSpellCatalogContractConfig(t *testing.T) string { diff --git a/internal/cli/spell_catalog_identity_contract_test.go b/internal/cli/spell_catalog_identity_contract_test.go index 94a8aaca..c997f57d 100644 --- a/internal/cli/spell_catalog_identity_contract_test.go +++ b/internal/cli/spell_catalog_identity_contract_test.go @@ -68,7 +68,7 @@ func TestMaterializedSpellCatalogOrderingPreservesSemanticContents(t *testing.T) if err != nil { t.Fatal(err) } - if catalogA.Digest() != catalogB.Digest() || !reflect.DeepEqual(catalogA.OverlayIDs(), []string{"campaign.a", "campaign.b"}) || !reflect.DeepEqual(catalogB.OverlayIDs(), catalogA.OverlayIDs()) || !reflect.DeepEqual(catalogA.PromptSpells(), catalogB.PromptSpells()) { + if catalogA.Digest() != catalogB.Digest() || !reflect.DeepEqual(catalogA.CollectionNames(), []string{"spells"}) || !reflect.DeepEqual(catalogB.CollectionNames(), catalogA.CollectionNames()) || !reflect.DeepEqual(catalogA.PromptSpells(), catalogB.PromptSpells()) { t.Fatal("catalog ordering changed semantic recognition") } } @@ -76,7 +76,8 @@ func TestMaterializedSpellCatalogOrderingPreservesSemanticContents(t *testing.T) func TestConfiguredSpellCatalogBindingChangesResolvedPipelineIdentity(t *testing.T) { base := productionSpellCatalogContractConfig(t) - changed := strings.Replace(base, repositoryPath("examples", "dnd-complete", "spell-catalog.json"), filepath.Join(t.TempDir(), "alternate-spell-catalog.json"), 1) + source := loadMaintainedExample(t, writeProductionContractConfig(t, base)).Pipelines["dnd-session"].Artifacts["spells"].Extract.References["spell_catalog"].Path + changed := strings.Replace(base, source, filepath.Join(t.TempDir(), "alternate-spell-catalog.json"), 1) if changed == base { t.Fatal("production configuration did not contain the maintained catalog binding") } @@ -139,11 +140,11 @@ func TestProductionOverlayRunAlignsGroundingAndValidation(t *testing.T) { } const reorderedOverlayA = `{ - "schema_version": "notarius.dnd.spell-catalog-overlay.v1", - "catalogs": [ - {"id":"campaign.a","ruleset":"dnd-5e-2014","source":{"title":"Campaign A"},"spells":[{"name":"Aegis of Emberfall","aliases":["Emberfall Aegis"]}]}, - {"id":"campaign.b","ruleset":"dnd-5e-2014","source":{"title":"Campaign B"},"spells":[{"name":"Cinder Veil","aliases":["Veil of Cinder","Cinder Shroud"]}]} - ] + "schema_version": "maximumdirect.glossary.v1", + "collections": {"spells": {"entries": [ + {"id":"a","name":"Aegis of Emberfall","category":"spell","aliases":["Emberfall Aegis"]}, + {"id":"b","name":"Cinder Veil","category":"spell","aliases":["Veil of Cinder","Cinder Shroud"]} + ]}} }` -const reorderedOverlayB = `{"catalogs":[{"spells":[{"aliases":["Cinder Shroud","Veil of Cinder"],"name":"Cinder Veil"}],"source":{"title":"Campaign B"},"ruleset":"dnd-5e-2014","id":"campaign.b"},{"spells":[{"aliases":["Emberfall Aegis"],"name":"Aegis of Emberfall"}],"source":{"title":"Campaign A"},"ruleset":"dnd-5e-2014","id":"campaign.a"}],"schema_version":"notarius.dnd.spell-catalog-overlay.v1"}` +const reorderedOverlayB = `{"collections":{"spells":{"entries":[{"aliases":["Cinder Shroud","Veil of Cinder"],"name":"Cinder Veil","id":"b","category":"spell"},{"aliases":["Emberfall Aegis"],"name":"Aegis of Emberfall","id":"a","category":"spell"}]}},"schema_version":"maximumdirect.glossary.v1"}` diff --git a/internal/modules/dnd/extract/spells/extractor.go b/internal/modules/dnd/extract/spells/extractor.go index 5a99ca3f..b24e6bd2 100644 --- a/internal/modules/dnd/extract/spells/extractor.go +++ b/internal/modules/dnd/extract/spells/extractor.go @@ -47,7 +47,7 @@ func referenceSlots() []contracts.ReferenceSlot { slots = append(slots, contracts.ReferenceSlot{ Name: spellcatalog.SpellCatalogReferenceSlot, Description: "Optional canonical spell-name catalog used for extraction grounding.", - AcceptedMediaTypes: []string{"application/json"}, + AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml"}, MaxBytes: 1048576, }, contracts.ReferenceSlot{ Name: NPCRegistryReferenceSlot, diff --git a/internal/modules/dnd/extract/spells/extractor_test.go b/internal/modules/dnd/extract/spells/extractor_test.go index 8092f75f..14f6276e 100644 --- a/internal/modules/dnd/extract/spells/extractor_test.go +++ b/internal/modules/dnd/extract/spells/extractor_test.go @@ -142,7 +142,7 @@ func TestExtractUsesAliasRecognitionToRequestCanonicalSpellNames(t *testing.T) { } func TestExtractAliasOnlyCatalogChangesPromptMaterial(t *testing.T) { - aliasReference := spellCatalogReference(`{"schema_version":"notarius.dnd.spell-catalog-overlay.v1","catalogs":[{"id":"campaign.example","ruleset":"dnd-5e-2014","source":{"title":"Private campaign source","version":"1","url":"file:///private-source.json","license":"private"},"spells":[{"name":"Cure Wounds","aliases":["Campaign Woundweave"]}]}]}`) + aliasReference := spellCatalogReference(`{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"cure","name":"Cure Wounds","category":"spell","aliases":["Campaign Woundweave"]}]}}}`) baseClient := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}} aliasClient := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}} baseExtractor := newExtractor(t, baseClient) diff --git a/internal/modules/dnd/extract/spells/registry_test.go b/internal/modules/dnd/extract/spells/registry_test.go index 7b3d3b47..b148cb00 100644 --- a/internal/modules/dnd/extract/spells/registry_test.go +++ b/internal/modules/dnd/extract/spells/registry_test.go @@ -63,7 +63,7 @@ func TestModuleSpec(t *testing.T) { { Name: "spell_catalog", Description: "Optional canonical spell-name catalog used for extraction grounding.", - AcceptedMediaTypes: []string{"application/json"}, + AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml"}, MaxBytes: 1048576, }, }, diff --git a/internal/modules/dnd/extract/spells/test_helpers_test.go b/internal/modules/dnd/extract/spells/test_helpers_test.go index 5f359012..0f6df716 100644 --- a/internal/modules/dnd/extract/spells/test_helpers_test.go +++ b/internal/modules/dnd/extract/spells/test_helpers_test.go @@ -162,7 +162,7 @@ func spellCatalogReference(content string) contracts.ReferenceSet { } func overlaySpellCatalogReference() contracts.ReferenceSet { - return spellCatalogReference(`{"schema_version":"notarius.dnd.spell-catalog-overlay.v1","catalogs":[{"id":"campaign.example","ruleset":"dnd-5e-2014","source":{"title":"Private campaign source","version":"1","url":"file:///private-source.json","license":"private"},"spells":[{"name":"Aegis of Emberfall","aliases":["Emberfall Aegis"]}]}]}`) + return spellCatalogReference(`{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"aegis","name":"Aegis of Emberfall","category":"spell","aliases":["Emberfall Aegis"]}]}}}`) } type fakeSpellsLLMClient struct { diff --git a/internal/modules/dnd/normalize/spells/normalizer.go b/internal/modules/dnd/normalize/spells/normalizer.go index f09311a2..548b777d 100644 --- a/internal/modules/dnd/normalize/spells/normalizer.go +++ b/internal/modules/dnd/normalize/spells/normalizer.go @@ -279,7 +279,7 @@ func referenceSlots() []contracts.ReferenceSlot { return []contracts.ReferenceSlot{{ Name: spellcatalog.SpellCatalogReferenceSlot, Description: "Optional canonical spell-name catalog used for normalization and duplicate identity.", - AcceptedMediaTypes: []string{"application/json"}, + AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml"}, MaxBytes: 1048576, }} } diff --git a/internal/modules/dnd/normalize/spells/normalizer_test.go b/internal/modules/dnd/normalize/spells/normalizer_test.go index e4384495..1b4937ab 100644 --- a/internal/modules/dnd/normalize/spells/normalizer_test.go +++ b/internal/modules/dnd/normalize/spells/normalizer_test.go @@ -33,7 +33,7 @@ func TestModuleContractAndStrictOptions(t *testing.T) { ReferenceSlots: []contracts.ReferenceSlot{{ Name: spellcatalog.SpellCatalogReferenceSlot, Description: "Optional canonical spell-name catalog used for normalization and duplicate identity.", - AcceptedMediaTypes: []string{"application/json"}, + AcceptedMediaTypes: []string{"application/json", "application/x-yaml", "application/yaml"}, MaxBytes: 1048576, }}, } @@ -59,7 +59,7 @@ func TestNewBuildsEmbeddedAndOverlayCatalogs(t *testing.T) { if err != nil { t.Fatalf("New() error = %v, want nil", err) } - if base.effectiveCatalog.BaseID() != spellcatalog.SRD5E2014ID || base.effectiveCatalog.Digest() == "" || len(base.effectiveCatalog.OverlayIDs()) != 0 { + if base.effectiveCatalog.BaseID() != spellcatalog.SRD5E2014ID || base.effectiveCatalog.Digest() == "" || len(base.effectiveCatalog.CollectionNames()) != 0 { t.Fatalf("base catalog identity = %#v, want embedded catalog identity", base.effectiveCatalog) } if canonical, ok := base.effectiveCatalog.Lookup(" cure wounds "); !ok || canonical != "Cure Wounds" { @@ -73,8 +73,8 @@ func TestNewBuildsEmbeddedAndOverlayCatalogs(t *testing.T) { if err != nil { t.Fatalf("New(overlay) error = %v, want nil", err) } - if got := overlay.effectiveCatalog.OverlayIDs(); !reflect.DeepEqual(got, []string{"campaign.example"}) { - t.Fatalf("overlay IDs = %#v, want campaign.example", got) + if got := overlay.effectiveCatalog.CollectionNames(); !reflect.DeepEqual(got, []string{"spells"}) { + t.Fatalf("collection names = %#v, want spells", got) } if canonical, ok := overlay.effectiveCatalog.Lookup(" emberfall aegis "); !ok || canonical != "Aegis of Emberfall" { t.Fatalf("overlay alias lookup = %q, %t, want Aegis of Emberfall", canonical, ok) @@ -87,7 +87,7 @@ func TestNewRejectsInvalidCatalogReferencesDuringConstruction(t *testing.T) { Items: []contracts.ReferenceItem{{MediaType: "text/plain", Content: []byte("not a catalog")}}, }, }} - if _, err := New(Options{}, invalid); err == nil || !strings.Contains(err.Error(), "application/json") { + if _, err := New(Options{}, invalid); err == nil || !strings.Contains(err.Error(), "media type") { t.Fatalf("New(invalid reference) error = %v, want media type failure", err) } @@ -145,7 +145,7 @@ func TestNormalizeLimitsFindingsWithoutChangingSpellValues(t *testing.T) { func TestNormalizeBoundsUnicodeNamesAndQuotesCanonicalReplacement(t *testing.T) { longName := strings.Repeat("火", 140) - reference := spellCatalogReference(fmt.Sprintf(`{"schema_version":"notarius.dnd.spell-catalog-overlay.v1","catalogs":[{"id":"campaign.long","ruleset":"dnd-5e-2014","source":{"title":"Private campaign source"},"spells":[{"name":%q,"aliases":["long alias"]}]}]}`, longName)) + reference := spellCatalogReference(fmt.Sprintf(`{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"long","name":%q,"category":"spell","aliases":["long alias"]}]}}}`, longName)) normalizer, err := New(Options{}, reference) if err != nil { t.Fatalf("New() error = %v, want nil", err) @@ -503,7 +503,7 @@ func diagnosticByReason(diagnostics []contracts.ProducerDiagnostic, reason strin } func overlayReference() contracts.ReferenceSet { - return spellCatalogReference(`{"schema_version":"notarius.dnd.spell-catalog-overlay.v1","catalogs":[{"id":"campaign.example","ruleset":"dnd-5e-2014","source":{"title":"Private campaign source","version":"1","url":"file:///private-source.json","license":"private"},"spells":[{"name":"Aegis of Emberfall","aliases":["Emberfall Aegis"]}]}]}`) + return spellCatalogReference(`{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"aegis","name":"Aegis of Emberfall","category":"spell","aliases":["Emberfall Aegis"]}]}}}`) } func spellCatalogReference(content string) contracts.ReferenceSet { diff --git a/internal/modules/dnd/spells/catalog/effective.go b/internal/modules/dnd/spells/catalog/effective.go index 56e6d1df..cdcf7b4b 100644 --- a/internal/modules/dnd/spells/catalog/effective.go +++ b/internal/modules/dnd/spells/catalog/effective.go @@ -1,34 +1,30 @@ package catalog import ( - "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" - "io" "mime" "sort" "strings" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" + "gitea.maximumdirect.net/eric/notarius/internal/integrations/domainrefs" ) -const ( - SpellCatalogReferenceSlot = "spell_catalog" - overlaySchemaVersion = "notarius.dnd.spell-catalog-overlay.v1" -) +const SpellCatalogReferenceSlot = "spell_catalog" // EffectiveCatalog is the immutable spell-name recognition catalog assembled -// from the embedded SRD catalog and an optional set of campaign overlays. +// from the embedded SRD catalog and an optional shared glossary. type EffectiveCatalog struct { - baseID string - ruleset string - overlayIDs []string - canonicalNames []string - promptSpells []PromptSpell - lookup map[string]string - digest string + baseID string + ruleset string + collectionNames []string + canonicalNames []string + promptSpells []PromptSpell + lookup map[string]string + digest string } // PromptSpell is the recognition-only catalog entry supplied to extraction @@ -38,10 +34,12 @@ type PromptSpell struct { Aliases []string `json:"aliases"` } -func (c EffectiveCatalog) BaseID() string { return c.baseID } -func (c EffectiveCatalog) Ruleset() string { return c.ruleset } -func (c EffectiveCatalog) Digest() string { return c.digest } -func (c EffectiveCatalog) OverlayIDs() []string { return append([]string(nil), c.overlayIDs...) } +func (c EffectiveCatalog) BaseID() string { return c.baseID } +func (c EffectiveCatalog) Ruleset() string { return c.ruleset } +func (c EffectiveCatalog) Digest() string { return c.digest } +func (c EffectiveCatalog) CollectionNames() []string { + return append([]string(nil), c.collectionNames...) +} // CanonicalNames returns the globally sorted canonical spell names without // exposing the catalog's internal storage. @@ -73,154 +71,61 @@ func (c EffectiveCatalog) Lookup(name string) (string, bool) { return canonical, ok } -// ResolveEffectiveCatalog loads the embedded SRD catalog and applies the -// optional spell-catalog overlay found in its spell_catalog reference slot. It -// does not resolve paths or perform filesystem access. +// ResolveEffectiveCatalog assembles recognition vocabulary from the shared glossary. func ResolveEffectiveCatalog(references contracts.ReferenceSet) (EffectiveCatalog, error) { base, err := LoadSRD5E2014() if err != nil { return EffectiveCatalog{}, err } - slot, ok := references.Slots[SpellCatalogReferenceSlot] if !ok || len(slot.Items) == 0 { - return composeEffectiveCatalog(base, nil) + return composeEffectiveCatalog(base, nil, nil) } if len(slot.Items) != 1 { return EffectiveCatalog{}, fmt.Errorf("reference slot %q must contain zero or one item", SpellCatalogReferenceSlot) } - item := slot.Items[0] mediaType, _, err := mime.ParseMediaType(item.MediaType) if err != nil { return EffectiveCatalog{}, fmt.Errorf("reference slot %q item media type %q is invalid: %w", SpellCatalogReferenceSlot, item.MediaType, err) } - if !strings.EqualFold(mediaType, "application/json") { - return EffectiveCatalog{}, fmt.Errorf("reference slot %q item media type %q must be application/json", SpellCatalogReferenceSlot, item.MediaType) - } - overlays, err := decodeOverlayBundle(item.Content) + doc, err := domainrefs.Load(SpellCatalogReferenceSlot, strings.ToLower(mediaType), item.Content) if err != nil { return EffectiveCatalog{}, err } - return composeEffectiveCatalog(base, overlays) -} - -type overlayBundle struct { - SchemaVersion string `json:"schema_version"` - Catalogs []overlayCatalog `json:"catalogs"` -} - -type overlayCatalog struct { - ID string `json:"id"` - Ruleset string `json:"ruleset"` - Source overlaySource `json:"source"` - Spells []overlaySpell `json:"spells"` -} - -type overlaySource struct { - Title string `json:"title"` - Version json.RawMessage `json:"version"` - URL json.RawMessage `json:"url"` - License json.RawMessage `json:"license"` -} - -type overlaySpell struct { - Name string `json:"name"` - Aliases json.RawMessage `json:"aliases,omitempty"` -} - -func decodeOverlayBundle(content []byte) ([]overlayCatalog, error) { - decoder := json.NewDecoder(bytes.NewReader(content)) - decoder.DisallowUnknownFields() - var bundle overlayBundle - if err := decoder.Decode(&bundle); err != nil { - return nil, fmt.Errorf("decode spell catalog overlay: %w", err) + if err := domainrefs.ValidateGlossary(doc); err != nil { + return EffectiveCatalog{}, fmt.Errorf("reference slot %q: %w", SpellCatalogReferenceSlot, err) } - var trailing any - if err := decoder.Decode(&trailing); err != io.EOF { - return nil, fmt.Errorf("decode spell catalog overlay: multiple JSON values") + names, err := domainrefs.SelectCollections(doc, item.Collections, []string{"spells"}) + if err != nil { + return EffectiveCatalog{}, fmt.Errorf("reference slot %q: %w", SpellCatalogReferenceSlot, err) } - if bundle.SchemaVersion != overlaySchemaVersion { - return nil, fmt.Errorf("spell catalog overlay schema_version %q does not match %q", bundle.SchemaVersion, overlaySchemaVersion) - } - if len(bundle.Catalogs) == 0 { - return nil, fmt.Errorf("spell catalog overlay catalogs must not be empty") - } - - seenIDs := make(map[string]struct{}, len(bundle.Catalogs)) - for catalogIndex := range bundle.Catalogs { - catalog := &bundle.Catalogs[catalogIndex] - if catalog.ID != strings.TrimSpace(catalog.ID) || catalog.ID == "" { - return nil, fmt.Errorf("catalog[%d] id must be non-empty and trimmed", catalogIndex) - } - if _, exists := seenIDs[catalog.ID]; exists { - return nil, fmt.Errorf("catalog id %q is duplicated", catalog.ID) - } - seenIDs[catalog.ID] = struct{}{} - if catalog.Ruleset != SRD5E2014Ruleset { - return nil, fmt.Errorf("catalog %q ruleset %q does not match %q", catalog.ID, catalog.Ruleset, SRD5E2014Ruleset) - } - if catalog.Source.Title != strings.TrimSpace(catalog.Source.Title) || catalog.Source.Title == "" { - return nil, fmt.Errorf("catalog %q source title must be non-empty and trimmed", catalog.ID) - } - for field, raw := range map[string]json.RawMessage{ - "version": catalog.Source.Version, - "url": catalog.Source.URL, - "license": catalog.Source.License, - } { - if _, err := decodeOptionalString(raw); err != nil { - return nil, fmt.Errorf("catalog %q source %s: %w", catalog.ID, field, err) - } - } - if len(catalog.Spells) == 0 { - return nil, fmt.Errorf("catalog %q spells must not be empty", catalog.ID) - } - for spellIndex := range catalog.Spells { - spell := &catalog.Spells[spellIndex] - if spell.Name != strings.TrimSpace(spell.Name) || spell.Name == "" { - return nil, fmt.Errorf("catalog %q spell[%d] name must be non-empty and trimmed", catalog.ID, spellIndex) - } - _, err := decodeAliases(spell.Aliases) - if err != nil { - return nil, fmt.Errorf("catalog %q spell %q aliases: %w", catalog.ID, spell.Name, err) + collections := doc["collections"].(map[string]any) + var entries []recognitionEntry + for _, name := range names { + raw := collections[name].(map[string]any)["entries"].([]any) + ordered := append([]any(nil), raw...) + sort.Slice(ordered, func(i, j int) bool { + return ordered[i].(map[string]any)["id"].(string) < ordered[j].(map[string]any)["id"].(string) + }) + for _, value := range ordered { + entry := value.(map[string]any) + spell := recognitionEntry{collection: name, id: entry["id"].(string), name: strings.TrimSpace(entry["name"].(string))} + if aliases, ok := entry["aliases"].([]any); ok { + for _, alias := range aliases { + spell.aliases = append(spell.aliases, strings.TrimSpace(alias.(string))) + } + sort.Strings(spell.aliases) } + entries = append(entries, spell) } } - - return bundle.Catalogs, nil + return composeEffectiveCatalog(base, names, entries) } -func decodeOptionalString(raw json.RawMessage) (string, error) { - if len(raw) == 0 { - return "", nil - } - if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { - return "", fmt.Errorf("must be a string when present") - } - var value string - if err := json.Unmarshal(raw, &value); err != nil { - return "", fmt.Errorf("must be a string when present: %w", err) - } - return value, nil -} - -func decodeAliases(raw json.RawMessage) ([]string, error) { - if len(raw) == 0 { - return nil, nil - } - if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { - return nil, fmt.Errorf("must be an array when present") - } - var aliases []string - if err := json.Unmarshal(raw, &aliases); err != nil { - return nil, fmt.Errorf("must be an array of strings: %w", err) - } - for index, alias := range aliases { - if alias != strings.TrimSpace(alias) || alias == "" { - return nil, fmt.Errorf("value at index %d must be non-empty and trimmed", index) - } - } - return aliases, nil +type recognitionEntry struct { + collection, id, name string + aliases []string } type effectiveSpell struct { @@ -235,7 +140,7 @@ type effectiveBuilder struct { lookup map[string]string } -func composeEffectiveCatalog(base Catalog, overlays []overlayCatalog) (EffectiveCatalog, error) { +func composeEffectiveCatalog(base Catalog, collections []string, entries []recognitionEntry) (EffectiveCatalog, error) { builder := effectiveBuilder{ spells: make(map[string]*effectiveSpell, len(base.spells)), canonicalByKey: make(map[string]string, len(base.lookup)), @@ -252,23 +157,14 @@ func composeEffectiveCatalog(base Catalog, overlays []overlayCatalog) (Effective } } - sort.Slice(overlays, func(i, j int) bool { return overlays[i].ID < overlays[j].ID }) - overlayIDs := make([]string, len(overlays)) - for i, overlay := range overlays { - overlayIDs[i] = overlay.ID - for _, spell := range overlay.Spells { - canonical, err := builder.ensureCanonical(spell.Name) - if err != nil { - return EffectiveCatalog{}, fmt.Errorf("catalog %q: %w", overlay.ID, err) - } - aliases, err := decodeAliases(spell.Aliases) - if err != nil { - return EffectiveCatalog{}, fmt.Errorf("catalog %q spell %q aliases: %w", overlay.ID, spell.Name, err) - } - for _, alias := range aliases { - if err := builder.addAlias(canonical, alias); err != nil { - return EffectiveCatalog{}, fmt.Errorf("catalog %q spell %q: %w", overlay.ID, spell.Name, err) - } + for _, entry := range entries { + canonical, err := builder.ensureCanonical(entry.name) + if err != nil { + return EffectiveCatalog{}, fmt.Errorf("collection %q entry %q name: %w", entry.collection, entry.id, err) + } + for _, alias := range entry.aliases { + if err := builder.addAlias(canonical, alias); err != nil { + return EffectiveCatalog{}, fmt.Errorf("collection %q entry %q alias %q: %w", entry.collection, entry.id, alias, err) } } } @@ -289,18 +185,18 @@ func composeEffectiveCatalog(base Catalog, overlays []overlayCatalog) (Effective promptSpells[index] = PromptSpell{CanonicalName: spell.name, Aliases: aliases} } - digest, err := effectiveDigest(base, overlays, builder, canonicalNames) + digest, err := effectiveDigest(base, builder, canonicalNames) if err != nil { return EffectiveCatalog{}, err } return EffectiveCatalog{ - baseID: base.ID(), - ruleset: base.Ruleset(), - overlayIDs: overlayIDs, - canonicalNames: canonicalNames, - promptSpells: promptSpells, - lookup: cloneStringMap(builder.lookup), - digest: digest, + baseID: base.ID(), + ruleset: base.Ruleset(), + collectionNames: append([]string(nil), collections...), + canonicalNames: canonicalNames, + promptSpells: promptSpells, + lookup: cloneStringMap(builder.lookup), + digest: digest, }, nil } @@ -310,9 +206,6 @@ func (b *effectiveBuilder) ensureCanonical(name string) (string, error) { return "", fmt.Errorf("spell %q has an empty lookup key", name) } if canonical, exists := b.canonicalByKey[key]; exists { - if canonical != name { - return "", fmt.Errorf("canonical lookup key %q has conflicting display names %q and %q", key, canonical, name) - } return canonical, nil } if canonical, exists := b.lookup[key]; exists { @@ -346,29 +239,17 @@ func (b *effectiveBuilder) addAlias(canonical string, alias string) error { return nil } b.lookup[key] = canonical - if previous, exists := spell.aliases[key]; !exists || alias < previous { + if _, exists := spell.aliases[key]; !exists { spell.aliases[key] = alias } return nil } type effectiveDigestDocument struct { - BaseID string `json:"base_id"` - BaseRuleset string `json:"base_ruleset"` - BaseSource Source `json:"base_source"` - Overlays []effectiveDigestOverlay `json:"overlays"` - Spells []effectiveDigestSpell `json:"spells"` -} - -type effectiveDigestOverlay struct { - ID string `json:"id"` - Ruleset string `json:"ruleset"` - Source struct { - Title string `json:"title"` - Version string `json:"version"` - URL string `json:"url"` - License string `json:"license"` - } `json:"source"` + BaseID string `json:"base_id"` + BaseRuleset string `json:"base_ruleset"` + BaseSource Source `json:"base_source"` + Spells []effectiveDigestSpell `json:"spells"` } type effectiveDigestSpell struct { @@ -382,34 +263,13 @@ type effectiveDigestAlias struct { Display string `json:"display"` } -func effectiveDigest(base Catalog, overlays []overlayCatalog, builder effectiveBuilder, canonicalNames []string) (string, error) { +func effectiveDigest(base Catalog, builder effectiveBuilder, canonicalNames []string) (string, error) { document := effectiveDigestDocument{ BaseID: base.ID(), BaseRuleset: base.Ruleset(), BaseSource: base.Source(), - Overlays: make([]effectiveDigestOverlay, len(overlays)), Spells: make([]effectiveDigestSpell, 0, len(canonicalNames)), } - for index, overlay := range overlays { - document.Overlays[index].ID = overlay.ID - document.Overlays[index].Ruleset = overlay.Ruleset - version, err := decodeOptionalString(overlay.Source.Version) - if err != nil { - return "", fmt.Errorf("catalog %q source version: %w", overlay.ID, err) - } - url, err := decodeOptionalString(overlay.Source.URL) - if err != nil { - return "", fmt.Errorf("catalog %q source url: %w", overlay.ID, err) - } - license, err := decodeOptionalString(overlay.Source.License) - if err != nil { - return "", fmt.Errorf("catalog %q source license: %w", overlay.ID, err) - } - document.Overlays[index].Source.Title = overlay.Source.Title - document.Overlays[index].Source.Version = version - document.Overlays[index].Source.URL = url - document.Overlays[index].Source.License = license - } for _, name := range canonicalNames { spell := builder.spells[name] digestSpell := effectiveDigestSpell{Key: spell.canonicalKey, Name: spell.name} diff --git a/internal/modules/dnd/spells/catalog/effective_test.go b/internal/modules/dnd/spells/catalog/effective_test.go index e59c0ebf..3dd4cb3b 100644 --- a/internal/modules/dnd/spells/catalog/effective_test.go +++ b/internal/modules/dnd/spells/catalog/effective_test.go @@ -1,340 +1,133 @@ package catalog import ( - "encoding/json" "reflect" - "sort" "strings" "testing" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" ) -func TestResolveEffectiveCatalogBaseAndImmutability(t *testing.T) { - effective, err := ResolveEffectiveCatalog(contracts.ReferenceSet{}) - if err != nil { - t.Fatal(err) - } - if effective.BaseID() != SRD5E2014ID || effective.Ruleset() != SRD5E2014Ruleset { - t.Fatalf("identity = %q/%q", effective.BaseID(), effective.Ruleset()) - } - if got := effective.OverlayIDs(); len(got) != 0 { - t.Fatalf("overlay IDs = %#v", got) - } - names := effective.CanonicalNames() - if len(names) != 319 || !sort.StringsAreSorted(names) { - t.Fatalf("canonical names count/order = %d/%t", len(names), sort.StringsAreSorted(names)) - } - if got, ok := effective.Lookup(" HUNTER'S MARK "); !ok || got != "Hunter’s Mark" { - t.Fatalf("Hunter's Mark lookup = %q, present=%t", got, ok) - } - if got, ok := effective.Lookup("Definitely Not A Spell"); ok || got != "" { - t.Fatalf("unknown lookup = %q, present=%t", got, ok) - } - if !strings.HasPrefix(effective.Digest(), "sha256:") { - t.Fatalf("digest = %q", effective.Digest()) - } - - names[0] = "changed" - ids := effective.OverlayIDs() - ids = append(ids, "changed") - again, err := ResolveEffectiveCatalog(contracts.ReferenceSet{}) - if err != nil { - t.Fatal(err) - } - if reflect.DeepEqual(names, again.CanonicalNames()) || len(again.OverlayIDs()) != 0 { - t.Fatal("effective catalog exposed mutable result storage") - } -} - -func TestResolveEffectiveCatalogAddsAndAugmentsSpells(t *testing.T) { - overlay := testOverlayJSON(t, testOverlayCatalog( - "campaign.example", - testOverlaySpell("Aegis of Emberfall", "Emberfall Aegis"), - testOverlaySpell("Cure Wounds", "Healing Touch"), - )) - effective, err := ResolveEffectiveCatalog(overlayReference([]byte(overlay), "application/json")) - if err != nil { - t.Fatal(err) - } - if got := effective.OverlayIDs(); !reflect.DeepEqual(got, []string{"campaign.example"}) { - t.Fatalf("overlay IDs = %#v", got) - } - if len(effective.CanonicalNames()) != 320 { - t.Fatalf("canonical name count = %d, want 320", len(effective.CanonicalNames())) - } - if got, ok := effective.Lookup("aegis of emberfall"); !ok || got != "Aegis of Emberfall" { - t.Fatalf("new spell lookup = %q, present=%t", got, ok) - } - if got, ok := effective.Lookup("Emberfall Aegis"); !ok || got != "Aegis of Emberfall" { - t.Fatalf("new alias lookup = %q, present=%t", got, ok) - } - if got, ok := effective.Lookup("Healing Touch"); !ok || got != "Cure Wounds" { - t.Fatalf("augmentation alias lookup = %q, present=%t", got, ok) - } - for _, name := range effective.CanonicalNames() { - if name == "Emberfall Aegis" || name == "Healing Touch" { - t.Fatalf("alias %q was exposed as a canonical name", name) - } - } -} - -func TestEffectiveCatalogPromptSpellsIncludeSortedAliasesWithoutProvenance(t *testing.T) { - overlay := testOverlayJSON(t, testOverlayCatalog( - "campaign.example", - testOverlaySpell("Aegis of Emberfall", "Z Emberfall", "Emberfall Aegis", "emberfall aegis"), - testOverlaySpell("Cure Wounds", "Healing Touch"), - )) - effective, err := ResolveEffectiveCatalog(overlayReference([]byte(overlay), "application/json")) - if err != nil { - t.Fatal(err) - } - - spells := effective.PromptSpells() - if len(spells) != len(effective.CanonicalNames()) { - t.Fatalf("prompt spell count = %d, want %d", len(spells), len(effective.CanonicalNames())) - } - for index := 1; index < len(spells); index++ { - if spells[index-1].CanonicalName > spells[index].CanonicalName { - t.Fatalf("prompt spells are not sorted: %q before %q", spells[index-1].CanonicalName, spells[index].CanonicalName) - } - } - - aliases := make(map[string][]string, len(spells)) - for _, spell := range spells { - aliases[spell.CanonicalName] = spell.Aliases - if !sort.StringsAreSorted(spell.Aliases) { - t.Fatalf("aliases for %q are not sorted: %#v", spell.CanonicalName, spell.Aliases) - } - } - if got := aliases["Aegis of Emberfall"]; !reflect.DeepEqual(got, []string{"Emberfall Aegis", "Z Emberfall"}) { - t.Fatalf("Aegis aliases = %#v, want normalized aliases once", got) - } - if got := aliases["Cure Wounds"]; !reflect.DeepEqual(got, []string{"Healing Touch"}) { - t.Fatalf("Cure Wounds aliases = %#v", got) - } - - encoded, err := json.Marshal(spells) - if err != nil { - t.Fatal(err) - } - if strings.Contains(string(encoded), `"aliases":null`) { - t.Fatalf("prompt projection encoded missing aliases as null: %s", encoded) - } - for _, forbidden := range []string{"campaign.example", "spells", "source", "license", "ruleset", "provenance"} { - if strings.Contains(string(encoded), forbidden) { - t.Fatalf("prompt projection leaked %q: %s", forbidden, encoded) - } - } - - for index := range spells { - if spells[index].CanonicalName == "Aegis of Emberfall" { - spells[index].Aliases[0] = "changed" - break - } - } - for _, spell := range effective.PromptSpells() { - if spell.CanonicalName == "Aegis of Emberfall" && spell.Aliases[0] == "changed" { - t.Fatal("effective catalog exposed mutable prompt projection storage") - } - } -} - -func TestResolveEffectiveCatalogTreatsRepeatedAliasesAsIdempotent(t *testing.T) { - single := testOverlayJSON(t, testOverlayCatalog( - "campaign.example", - testOverlaySpell("Aegis of Emberfall", "Emberfall Aegis"), - )) - repeated := testOverlayJSON(t, testOverlayCatalog( - "campaign.example", - testOverlaySpell("Aegis of Emberfall", "Emberfall Aegis"), - testOverlaySpell("Aegis of Emberfall", "emberfall aegis"), - )) - first, err := ResolveEffectiveCatalog(overlayReference([]byte(single), "application/json")) - if err != nil { - t.Fatal(err) - } - second, err := ResolveEffectiveCatalog(overlayReference([]byte(repeated), "application/json")) - if err != nil { - t.Fatal(err) - } - if first.Digest() != second.Digest() || !reflect.DeepEqual(first.CanonicalNames(), second.CanonicalNames()) { - t.Fatalf("repeated alias changed effective result: digest=%q/%q", first.Digest(), second.Digest()) - } -} - -func TestResolveEffectiveCatalogDigestIgnoresOrderingAndFormatting(t *testing.T) { - first := `{"schema_version":"notarius.dnd.spell-catalog-overlay.v1","catalogs":[{"id":"campaign.z","ruleset":"dnd-5e-2014","source":{"title":"Z spells","version":"1","url":"","license":""},"spells":[{"name":"Aegis of Emberfall","aliases":["Z Alias","Another Alias"]}]},{"id":"campaign.a","ruleset":"dnd-5e-2014","source":{"title":"A spells","version":"1","url":"","license":""},"spells":[{"name":"Cure Wounds","aliases":["Healing Touch","Cure Mend"]}]}]}` - second := `{ - "catalogs": [ - {"source":{"license":"","url":"","version":"1","title":"A spells"},"spells":[{"aliases":["Cure Mend","Healing Touch"],"name":"Cure Wounds"}],"ruleset":"dnd-5e-2014","id":"campaign.a"}, - {"spells":[{"aliases":["Another Alias","Z Alias"],"name":"Aegis of Emberfall"}],"source":{"title":"Z spells","version":"1","url":"","license":""},"ruleset":"dnd-5e-2014","id":"campaign.z"} - ], - "schema_version":"notarius.dnd.spell-catalog-overlay.v1" -}` - firstCatalog, err := ResolveEffectiveCatalog(overlayReference([]byte(first), "application/json")) - if err != nil { - t.Fatal(err) - } - secondCatalog, err := ResolveEffectiveCatalog(overlayReference([]byte(second), "application/json")) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(firstCatalog.CanonicalNames(), secondCatalog.CanonicalNames()) || firstCatalog.Digest() != secondCatalog.Digest() { - t.Fatalf("reordered overlays changed effective result: names=%t digest=%q/%q", reflect.DeepEqual(firstCatalog.CanonicalNames(), secondCatalog.CanonicalNames()), firstCatalog.Digest(), secondCatalog.Digest()) - } -} - -func TestResolveEffectiveCatalogRejectsInvalidOverlays(t *testing.T) { - valid := validOverlayJSON() - tests := []struct { - name string - content string - }{ - {name: "wrong schema version", content: strings.Replace(valid, "notarius.dnd.spell-catalog-overlay.v1", "notarius.dnd.spell-catalog-overlay.v2", 1)}, - {name: "empty catalogs", content: `{"schema_version":"notarius.dnd.spell-catalog-overlay.v1","catalogs":[]}`}, - {name: "duplicate IDs", content: testOverlayJSON(t, testOverlayCatalog("campaign.example", testOverlaySpell("Aegis of Emberfall")), testOverlayCatalog("campaign.example", testOverlaySpell("Another Spell")))}, - {name: "wrong ruleset", content: strings.Replace(valid, `"ruleset":"dnd-5e-2014"`, `"ruleset":"dnd-5e-other"`, 1)}, - {name: "empty ID", content: strings.Replace(valid, `"id":"campaign.example"`, `"id":""`, 1)}, - {name: "empty source title", content: strings.Replace(valid, `"title":"Example campaign spells"`, `"title":""`, 1)}, - {name: "empty spells", content: testOverlayJSON(t, testOverlayCatalog("campaign.example"))}, - {name: "empty spell name", content: strings.Replace(valid, `"name":"Aegis of Emberfall"`, `"name":""`, 1)}, - {name: "null aliases", content: strings.Replace(valid, `"aliases":["Emberfall Aegis"]`, `"aliases":null`, 1)}, - {name: "unknown bundle field", content: strings.Replace(valid, `"schema_version":"notarius.dnd.spell-catalog-overlay.v1","catalogs"`, `"schema_version":"notarius.dnd.spell-catalog-overlay.v1","unexpected":true,"catalogs"`, 1)}, - {name: "unknown catalog field", content: strings.Replace(valid, `"id":"campaign.example","ruleset"`, `"id":"campaign.example","unexpected":true,"ruleset"`, 1)}, - {name: "unknown source field", content: strings.Replace(valid, `"title":"Example campaign spells","version"`, `"title":"Example campaign spells","unexpected":true,"version"`, 1)}, - {name: "unknown spell field", content: strings.Replace(valid, `"name":"Aegis of Emberfall","aliases"`, `"name":"Aegis of Emberfall","unexpected":true,"aliases"`, 1)}, - {name: "trailing JSON", content: valid + `{}`}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if _, err := ResolveEffectiveCatalog(overlayReference([]byte(test.content), "application/json")); err == nil { - t.Fatal("invalid overlay was accepted") - } - }) - } -} - -func TestResolveEffectiveCatalogRejectsReferenceMultiplicityAndMediaType(t *testing.T) { - valid := []byte(validOverlayJSON()) - tests := []struct { - name string - refs contracts.ReferenceSet - }{ - { - name: "multiple items", - refs: contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ - SpellCatalogReferenceSlot: {Items: []contracts.ReferenceItem{ - {MediaType: "application/json", Content: valid}, - {MediaType: "application/json", Content: valid}, - }}, - }}, - }, - { - name: "non JSON item", - refs: overlayReference(valid, "text/plain"), - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if _, err := ResolveEffectiveCatalog(test.refs); err == nil { - t.Fatal("invalid reference set was accepted") - } - }) - } - - for _, refs := range []contracts.ReferenceSet{ - {}, {Slots: map[string]contracts.ResolvedReferenceSlot{SpellCatalogReferenceSlot: {}}}, - } { - if effective, err := ResolveEffectiveCatalog(refs); err != nil || len(effective.CanonicalNames()) != 319 { - t.Fatalf("missing overlay should use base catalog: effective=%#v err=%v", effective, err) - } - } -} - -func TestResolveEffectiveCatalogRejectsCrossSpellCollisions(t *testing.T) { - tests := []struct { - name string - spells []overlaySpell - content string - }{ - { - name: "same key display conflict with embedded canonical", - spells: []overlaySpell{testOverlaySpell("cure wounds")}, - }, - { - name: "same key display conflict between canonical names", - spells: []overlaySpell{testOverlaySpell("Moon Beam"), testOverlaySpell("moon beam")}, - }, - { - name: "canonical versus alias", - spells: []overlaySpell{testOverlaySpell("Alpha Spell", "Beta Spell"), testOverlaySpell("Beta Spell")}, - }, - { - name: "alias versus canonical", - spells: []overlaySpell{testOverlaySpell("Alpha Spell"), testOverlaySpell("Beta Spell", "Alpha Spell")}, - }, - { - name: "alias versus alias", - spells: []overlaySpell{testOverlaySpell("Alpha Spell", "Shared Name"), testOverlaySpell("Beta Spell", "Shared Name")}, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - content := test.content - if content == "" { - content = testOverlayJSON(t, testOverlayCatalog("campaign.example", test.spells...)) - } - if _, err := ResolveEffectiveCatalog(overlayReference([]byte(content), "application/json")); err == nil { - t.Fatal("cross-spell collision was accepted") - } - }) - } -} - -func overlayReference(content []byte, mediaType string) contracts.ReferenceSet { +func spellReference(content, mediaType string, selection []string) contracts.ReferenceSet { return contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ - SpellCatalogReferenceSlot: { - Items: []contracts.ReferenceItem{{ - SlotName: SpellCatalogReferenceSlot, - MediaType: mediaType, - Content: append([]byte(nil), content...), - }}, - }, + SpellCatalogReferenceSlot: {Items: []contracts.ReferenceItem{{SlotName: SpellCatalogReferenceSlot, MediaType: mediaType, Content: []byte(content), Collections: selection}}}, }} } -func testOverlaySpell(name string, aliases ...string) overlaySpell { - content, err := json.Marshal(aliases) - if err != nil { - panic(err) - } - return overlaySpell{Name: name, Aliases: content} -} - -func testOverlayCatalog(id string, spells ...overlaySpell) overlayCatalog { - return overlayCatalog{ - ID: id, - Ruleset: SRD5E2014Ruleset, - Source: overlaySource{ - Title: id + " spells", - Version: json.RawMessage(`"1"`), - URL: json.RawMessage(`""`), - License: json.RawMessage(`""`), - }, - Spells: spells, - } -} - -func testOverlayJSON(t *testing.T, catalogs ...overlayCatalog) string { - t.Helper() - content, err := json.Marshal(overlayBundle{SchemaVersion: overlaySchemaVersion, Catalogs: catalogs}) +func TestSharedGlossaryRecognition(t *testing.T) { + content := `{ + "schema_version":"maximumdirect.glossary.v1", + "collections":{ + "spells":{"entries":[ + {"id":"z","name":"Aegis of Emberfall","category":"custom","aliases":["Emberfall Aegis"]}, + {"id":"a","name":" cure wounds ","category":"anything","aliases":["Campaign Woundweave"]}, + {"id":"b","name":"Null Alias","category":"custom","aliases":null}, + {"id":"c","name":"No Alias","category":"custom"} + ]}, + "other":{"entries":[{"id":"other","name":"Hidden Spell","category":"custom"}]} + }}` + got, err := ResolveEffectiveCatalog(spellReference(content, "application/json", nil)) if err != nil { t.Fatal(err) } - return string(content) + for alias, want := range map[string]string{ + "emberfall aegis": "Aegis of Emberfall", + "campaign woundweave": "Cure Wounds", + "cure wounds": "Cure Wounds", + "null alias": "Null Alias", + "no alias": "No Alias", + } { + if actual, ok := got.Lookup(alias); !ok || actual != want { + t.Errorf("Lookup(%q) = %q, %t; want %q", alias, actual, ok, want) + } + } + if _, ok := got.Lookup("Hidden Spell"); ok { + t.Fatal("unselected collection affected recognition") + } + if got.BaseID() != SRD5E2014ID || got.Digest() == "" || !reflect.DeepEqual(got.CollectionNames(), []string{"spells"}) { + t.Fatalf("unexpected catalog metadata: %#v", got) + } } -func validOverlayJSON() string { - return `{"schema_version":"notarius.dnd.spell-catalog-overlay.v1","catalogs":[{"id":"campaign.example","ruleset":"dnd-5e-2014","source":{"title":"Example campaign spells","version":"1","url":"","license":""},"spells":[{"name":"Aegis of Emberfall","aliases":["Emberfall Aegis"]}]}]}` +func TestSharedGlossarySelectionAndMedia(t *testing.T) { + yaml := "schema_version: maximumdirect.glossary.v1\ncollections:\n spells: {entries: []}\n custom: {entries: [{id: x, name: Star Lance, category: spell}]}\n" + for _, media := range []string{"application/yaml", "application/x-yaml"} { + got, err := ResolveEffectiveCatalog(spellReference(yaml, media, []string{"custom", "custom"})) + if err != nil { + t.Fatal(err) + } + if _, ok := got.Lookup("Star Lance"); !ok { + t.Fatal("selected spell not recognized") + } + } + base, err := ResolveEffectiveCatalog(contracts.ReferenceSet{}) + if err != nil { + t.Fatal(err) + } + empty, err := ResolveEffectiveCatalog(spellReference(yaml, "application/yaml", []string{})) + if err != nil || !reflect.DeepEqual(base.PromptSpells(), empty.PromptSpells()) { + t.Fatalf("empty selection did not retain embedded vocabulary: %v", err) + } + for _, selection := range [][]string{nil, {"missing"}} { + _, err := ResolveEffectiveCatalog(spellReference("schema_version: maximumdirect.glossary.v1\ncollections: {}\n", "application/yaml", selection)) + if err == nil || !strings.Contains(err.Error(), "collection") { + t.Fatalf("expected missing collection error, got %v", err) + } + } +} + +func TestSharedGlossaryDeterministicDisplayAndCollisions(t *testing.T) { + first := `{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"z","name":"MOON LIGHT","category":"x","aliases":["Lunar Ray"]},{"id":"a","name":"Moon Light","category":"x","aliases":["Lunar Ray"]}]}}}` + second := `{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"a","name":"Moon Light","category":"x","aliases":["Lunar Ray"]},{"id":"z","name":"MOON LIGHT","category":"x","aliases":["Lunar Ray"]}]}}}` + a, err := ResolveEffectiveCatalog(spellReference(first, "application/json", nil)) + if err != nil { + t.Fatal(err) + } + b, err := ResolveEffectiveCatalog(spellReference(second, "application/json", nil)) + if err != nil || a.Digest() != b.Digest() || !reflect.DeepEqual(a.PromptSpells(), b.PromptSpells()) { + t.Fatalf("entry order changed catalog: %v", err) + } + if name, ok := a.Lookup("lunar ray"); !ok || name != "Moon Light" { + t.Fatalf("deterministic display = %q, %t", name, ok) + } + for _, entries := range []string{ + `[{"id":"a","name":"Alpha","category":"x","aliases":["Shared"]},{"id":"b","name":"Beta","category":"x","aliases":["Shared"]}]`, + `[{"id":"a","name":"Alpha","category":"x","aliases":["Beta"]},{"id":"b","name":"Beta","category":"x"}]`, + `[{"id":"a","name":" ","category":"x"}]`, + `[{"id":"a","name":"Alpha","category":"x","aliases":[" "]}]`, + } { + doc := `{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":` + entries + `}}}` + _, err := ResolveEffectiveCatalog(spellReference(doc, "application/json", nil)) + if err == nil || !strings.Contains(err.Error(), "collection \"spells\" entry") { + t.Fatalf("expected contextual suitability error: %v", err) + } + } +} + +func TestSharedGlossaryCollectionOrderDeterminesExternalDisplay(t *testing.T) { + doc := `{"schema_version":"maximumdirect.glossary.v1","collections":{"z":{"entries":[{"id":"a","name":"STAR LANCE","category":"spell"}]},"a":{"entries":[{"id":"z","name":"Star Lance","category":"spell"}]}}}` + got, err := ResolveEffectiveCatalog(spellReference(doc, "application/json", []string{"z", "a"})) + if err != nil { + t.Fatal(err) + } + if name, ok := got.Lookup("star lance"); !ok || name != "Star Lance" { + t.Fatalf("collection ordering display = %q, %t", name, ok) + } + if !reflect.DeepEqual(got.CollectionNames(), []string{"a", "z"}) { + t.Fatalf("selected collections = %#v", got.CollectionNames()) + } +} + +func TestSharedGlossaryRejectsInvalidReferences(t *testing.T) { + for _, content := range []string{ + `{"schema_version":"notarius.dnd.spell-catalog-overlay.v1","catalogs":[]}`, + `{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[]}, "other":{"entries":[{"id":"x","name":"X","category":"x","aliases":3}]}}}`, + } { + if _, err := ResolveEffectiveCatalog(spellReference(content, "application/json", nil)); err == nil { + t.Fatal("invalid complete glossary accepted") + } + } + if _, err := ResolveEffectiveCatalog(spellReference("x", "text/plain", nil)); err == nil { + t.Fatal("unsupported media accepted") + } } diff --git a/internal/modules/dnd/validate/spells/catalog/validator_test.go b/internal/modules/dnd/validate/spells/catalog/validator_test.go index 49771abb..293b34d4 100644 --- a/internal/modules/dnd/validate/spells/catalog/validator_test.go +++ b/internal/modules/dnd/validate/spells/catalog/validator_test.go @@ -153,13 +153,10 @@ func validCast(name string) dnd.SpellCast { func overlayReferences() contracts.ReferenceSet { content := []byte(`{ - "schema_version": "notarius.dnd.spell-catalog-overlay.v1", - "catalogs": [{ - "id": "campaign-spells", - "ruleset": "dnd-5e-2014", - "source": {"title": "Campaign spell names"}, - "spells": [{"name": "Aegis of Emberfall", "aliases": ["Emberfall Aegis"]}] - }] + "schema_version": "maximumdirect.glossary.v1", + "collections": {"spells": {"entries": [ + {"id": "aegis", "name": "Aegis of Emberfall", "category": "spell", "aliases": ["Emberfall Aegis"]} + ]}} }`) return contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ spellreference.SpellCatalogReferenceSlot: {