Files
notarius/internal/modules/dnd/spells/catalog/effective.go

304 lines
9.8 KiB
Go
Raw Normal View History

2026-07-20 19:10:44 +00:00
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"
2026-07-20 19:10:44 +00:00
)
const SpellCatalogReferenceSlot = "spell_catalog"
2026-07-20 19:10:44 +00:00
// EffectiveCatalog is the immutable spell-name recognition catalog assembled
// from the embedded SRD catalog and an optional shared glossary.
2026-07-20 19:10:44 +00:00
type EffectiveCatalog struct {
baseID string
ruleset string
collectionNames []string
canonicalNames []string
promptSpells []PromptSpell
lookup map[string]string
digest string
2026-07-20 19:10:44 +00:00
}
// 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...)
}
2026-07-20 19:10:44 +00:00
// 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
}
2026-07-20 19:10:44 +00:00
// 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.
2026-07-20 19:10:44 +00:00
func ResolveEffectiveCatalog(references contracts.ReferenceSet) (EffectiveCatalog, error) {
base, err := LoadSRD5E2014()
if err != nil {
return EffectiveCatalog{}, err
}
2026-08-09 01:27:28 +00:00
slot, ok := references.Slots[SpellCatalogReferenceSlot]
2026-07-20 19:10:44 +00:00
if !ok || len(slot.Items) == 0 {
return composeEffectiveCatalog(base, nil, nil)
2026-07-20 19:10:44 +00:00
}
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)
2026-07-20 19:10:44 +00:00
if err != nil {
return EffectiveCatalog{}, err
}
if err := domainrefs.ValidateGlossary(doc); err != nil {
return EffectiveCatalog{}, fmt.Errorf("reference slot %q: %w", SpellCatalogReferenceSlot, err)
2026-07-20 19:10:44 +00:00
}
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)
2026-07-20 19:10:44 +00:00
}
entries = append(entries, spell)
2026-07-20 19:10:44 +00:00
}
}
return composeEffectiveCatalog(base, names, entries)
2026-07-20 19:10:44 +00:00
}
type recognitionEntry struct {
collection, id, name string
aliases []string
2026-07-20 19:10:44 +00:00
}
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) {
2026-07-20 19:10:44 +00:00
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)
2026-07-20 19:10:44 +00:00
}
}
}
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}
}
2026-07-20 19:10:44 +00:00
digest, err := effectiveDigest(base, builder, canonicalNames)
2026-07-20 19:10:44 +00:00
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,
2026-07-20 19:10:44 +00:00
}, 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 {
2026-07-20 19:10:44 +00:00
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"`
2026-07-20 19:10:44 +00:00
}
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) {
2026-07-20 19:10:44 +00:00
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
}