package catalog import ( "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "mime" "sort" "strings" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" "gitea.maximumdirect.net/eric/notarius/internal/integrations/domainrefs" ) const SpellCatalogReferenceSlot = "spell_catalog" // EffectiveCatalog is the immutable spell-name recognition catalog assembled // from the embedded SRD catalog and an optional shared glossary. type EffectiveCatalog struct { 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 // prompts. It intentionally contains no catalog provenance or source data. type PromptSpell struct { CanonicalName string `json:"canonical_name"` 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) CollectionNames() []string { return append([]string(nil), c.collectionNames...) } // CanonicalNames returns the globally sorted canonical spell names without // exposing the catalog's internal storage. func (c EffectiveCatalog) CanonicalNames() []string { return append([]string(nil), c.canonicalNames...) } // PromptSpells returns canonical names and their recognized aliases in // deterministic canonical-name order. The result is safe for callers to // modify. func (c EffectiveCatalog) PromptSpells() []PromptSpell { out := make([]PromptSpell, len(c.promptSpells)) for index, spell := range c.promptSpells { aliases := make([]string, len(spell.Aliases)) copy(aliases, spell.Aliases) out[index] = PromptSpell{ CanonicalName: spell.CanonicalName, Aliases: aliases, } } return out } // Lookup matches canonical names and aliases after applying the same // normalization used by the embedded catalog. The returned string is the // established canonical display name. func (c EffectiveCatalog) Lookup(name string) (string, bool) { canonical, ok := c.lookup[lookupKey(name)] return canonical, ok } // 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, 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) } doc, err := domainrefs.Load(SpellCatalogReferenceSlot, strings.ToLower(mediaType), item.Content) if err != nil { return EffectiveCatalog{}, err } if err := domainrefs.ValidateGlossary(doc); err != nil { return EffectiveCatalog{}, fmt.Errorf("reference slot %q: %w", SpellCatalogReferenceSlot, err) } names, err := domainrefs.SelectCollections(doc, item.Collections, []string{"spells"}) if err != nil { return EffectiveCatalog{}, fmt.Errorf("reference slot %q: %w", SpellCatalogReferenceSlot, 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 composeEffectiveCatalog(base, names, entries) } type recognitionEntry struct { collection, id, name string aliases []string } type effectiveSpell struct { name string canonicalKey string aliases map[string]string } type effectiveBuilder struct { spells map[string]*effectiveSpell canonicalByKey map[string]string lookup map[string]string } 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)), lookup: make(map[string]string, len(base.lookup)), } for _, spell := range base.Spells() { if err := builder.addCanonical(spell.Name); err != nil { return EffectiveCatalog{}, fmt.Errorf("base catalog: %w", err) } for _, alias := range spell.Aliases { if err := builder.addAlias(spell.Name, alias); err != nil { return EffectiveCatalog{}, fmt.Errorf("base catalog: %w", 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) } } } canonicalNames := make([]string, 0, len(builder.spells)) for _, spell := range builder.spells { canonicalNames = append(canonicalNames, spell.name) } sort.Strings(canonicalNames) promptSpells := make([]PromptSpell, len(canonicalNames)) for index, name := range canonicalNames { spell := builder.spells[name] aliases := make([]string, 0, len(spell.aliases)) for _, alias := range spell.aliases { aliases = append(aliases, alias) } sort.Strings(aliases) promptSpells[index] = PromptSpell{CanonicalName: spell.name, Aliases: aliases} } digest, err := effectiveDigest(base, builder, canonicalNames) if err != nil { return EffectiveCatalog{}, err } return EffectiveCatalog{ baseID: base.ID(), ruleset: base.Ruleset(), collectionNames: append([]string(nil), collections...), canonicalNames: canonicalNames, promptSpells: promptSpells, lookup: cloneStringMap(builder.lookup), digest: digest, }, nil } func (b *effectiveBuilder) ensureCanonical(name string) (string, error) { key := lookupKey(name) if key == "" { return "", fmt.Errorf("spell %q has an empty lookup key", name) } if canonical, exists := b.canonicalByKey[key]; exists { return canonical, nil } if canonical, exists := b.lookup[key]; exists { return "", fmt.Errorf("canonical lookup key %q collides with alias of spell %q", key, canonical) } spell := &effectiveSpell{name: name, canonicalKey: key, aliases: make(map[string]string)} b.spells[name] = spell b.canonicalByKey[key] = name b.lookup[key] = name return name, nil } func (b *effectiveBuilder) addCanonical(name string) error { _, err := b.ensureCanonical(name) return err } func (b *effectiveBuilder) addAlias(canonical string, alias string) error { key := lookupKey(alias) if key == "" { return fmt.Errorf("spell %q has an empty alias lookup key", canonical) } if existing, exists := b.lookup[key]; exists && existing != canonical { return fmt.Errorf("lookup key %q maps to spells %q and %q", key, existing, canonical) } spell, exists := b.spells[canonical] if !exists { return fmt.Errorf("spell %q is not present", canonical) } if key == spell.canonicalKey { return nil } b.lookup[key] = canonical 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"` Spells []effectiveDigestSpell `json:"spells"` } type effectiveDigestSpell struct { Key string `json:"key"` Name string `json:"name"` Aliases []effectiveDigestAlias `json:"aliases,omitempty"` } type effectiveDigestAlias struct { Key string `json:"key"` Display string `json:"display"` } func effectiveDigest(base Catalog, builder effectiveBuilder, canonicalNames []string) (string, error) { document := effectiveDigestDocument{ BaseID: base.ID(), BaseRuleset: base.Ruleset(), BaseSource: base.Source(), Spells: make([]effectiveDigestSpell, 0, len(canonicalNames)), } for _, name := range canonicalNames { spell := builder.spells[name] digestSpell := effectiveDigestSpell{Key: spell.canonicalKey, Name: spell.name} keys := make([]string, 0, len(spell.aliases)) for key := range spell.aliases { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { digestSpell.Aliases = append(digestSpell.Aliases, effectiveDigestAlias{Key: key, Display: spell.aliases[key]}) } document.Spells = append(document.Spells, digestSpell) } raw, err := json.Marshal(document) if err != nil { return "", fmt.Errorf("encode effective spell catalog digest: %w", err) } sum := sha256.Sum256(raw) return "sha256:" + hex.EncodeToString(sum[:]), nil } func cloneStringMap(values map[string]string) map[string]string { if len(values) == 0 { return nil } out := make(map[string]string, len(values)) for key, value := range values { out[key] = value } return out }