Files
notarius/internal/modules/dnd/npcs/registry/registry.go

330 lines
9.6 KiB
Go

// Package registry resolves normalized NPC artifacts into immutable grounding
// data for D&D extraction modules.
package registry
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"mime"
"strings"
"sync"
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
npccodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/npcs"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
)
const (
ReferenceSlot = "npcs"
MaxBytes = 1048576
emptyPrompt = `{"npcs":[]}`
)
// Registry is an immutable, validated NPC registry prepared for prompt
// grounding. All accessors return defensive copies.
type Registry struct {
bound bool
list dnd.NPCList
canonical []byte
digest string
projectionDigest string
promptInput contracts.LLMInputMaterial
lookupByKey map[string]int
}
// Resolver retains only the validated construction-time registry and immutable
// canonical registries keyed by their semantic digest. Operation references
// are resolved on demand; caller-owned reference bytes are never retained.
type Resolver struct {
seeded *Registry
mu sync.Mutex
cache map[string]*Registry
rawCache map[string]*Registry
}
// NewResolver validates the optional construction-time NPC reference and
// prepares the operation-time registry cache. A malformed static reference
// therefore fails before any operation starts.
func NewResolver(references contracts.ReferenceSet) (*Resolver, error) {
seeded, err := Resolve(constructionReferences(references))
if err != nil {
return nil, err
}
return &Resolver{seeded: seeded, cache: make(map[string]*Registry), rawCache: make(map[string]*Registry)}, nil
}
func constructionReferences(references contracts.ReferenceSet) contracts.ReferenceSet {
slot, ok := references.Slots[ReferenceSlot]
if !ok || len(slot.Items) > 0 {
return references
}
cloned := contracts.ReferenceSet{Slots: make(map[string]contracts.ResolvedReferenceSlot, len(references.Slots))}
for name, value := range references.Slots {
cloned.Slots[name] = value
}
delete(cloned.Slots, ReferenceSlot)
return cloned
}
// Seeded returns the immutable construction-time registry. Its accessors are
// defensive, so callers may safely use the returned view for static metadata.
func (r *Resolver) Seeded() *Registry {
if r == nil {
return nil
}
return r.seeded
}
// Resolve returns the effective registry for one operation. An operation
// without an NPC item uses the construction-time registry. A canonical item
// matching that registry reuses it; other canonical registries are cached by
// digest for concurrent chunk operations.
func (r *Resolver) Resolve(references contracts.ReferenceSet) (*Registry, error) {
if r == nil {
return Resolve(references)
}
if _, ok := references.Slots[ReferenceSlot]; !ok {
return r.seeded, nil
}
slot := references.Slots[ReferenceSlot]
rawKey := ""
if len(slot.Items) == 1 {
rawKey = strings.ToLower(strings.TrimSpace(slot.Items[0].MediaType)) + "\x00" + semanticDigest(slot.Items[0].Content)
}
r.mu.Lock()
defer r.mu.Unlock()
if rawKey != "" {
if cached, ok := r.rawCache[rawKey]; ok {
return cached, nil
}
}
resolved, err := Resolve(references)
if err != nil {
return nil, err
}
if sameRegistryIdentity(r.seeded, resolved) {
if rawKey != "" {
r.rawCache[rawKey] = r.seeded
}
return r.seeded, nil
}
if cached, ok := r.cache[resolved.Digest()]; ok {
if rawKey != "" {
r.rawCache[rawKey] = cached
}
return cached, nil
}
r.cache[resolved.Digest()] = resolved
if rawKey != "" {
r.rawCache[rawKey] = resolved
}
return resolved, nil
}
func sameRegistryIdentity(first, second *Registry) bool {
if first == nil || second == nil {
return first == second
}
return first.bound == second.bound && first.digest == second.digest
}
// Resolve prepares the optional NPC registry reference. An absent slot
// produces the exact empty prompt input and no semantic registry identity.
func Resolve(references contracts.ReferenceSet) (*Registry, error) {
slot, ok := references.Slots[ReferenceSlot]
if !ok {
content := []byte(emptyPrompt)
projectionDigest := semanticDigest(content)
return &Registry{
list: dnd.NPCList{NPCs: []dnd.NPC{}},
canonical: append([]byte(nil), content...),
projectionDigest: projectionDigest,
promptInput: contracts.NewLLMInputMaterial(ReferenceSlot, npccodec.MediaType, content, projectionDigest, ""),
lookupByKey: map[string]int{},
}, nil
}
if len(slot.Items) != 1 {
return nil, fmt.Errorf("reference slot %q must contain exactly one item", ReferenceSlot)
}
item := slot.Items[0]
mediaType, _, err := mime.ParseMediaType(item.MediaType)
if err != nil {
return nil, fmt.Errorf("reference slot %q item media type is invalid", ReferenceSlot)
}
if !strings.EqualFold(mediaType, npccodec.MediaType) {
return nil, fmt.Errorf("reference slot %q item media type must be %s", ReferenceSlot, npccodec.MediaType)
}
if len(item.Content) > MaxBytes {
return nil, fmt.Errorf("reference slot %q item is %d bytes, limit %d", ReferenceSlot, len(item.Content), MaxBytes)
}
codec := npccodec.New()
value, err := codec.Decode(item.Content)
if err != nil {
return nil, fmt.Errorf("decode NPC registry: invalid approved NPC JSON")
}
if issues := identity.ValidateList(value); len(issues) > 0 {
return nil, fmt.Errorf("%s", formatIdentityIssues(issues))
}
content, err := codec.Encode(value)
if err != nil {
return nil, fmt.Errorf("encode canonical NPC registry: approved NPC value could not be encoded")
}
list := cloneNPCList(value)
lookupByKey := make(map[string]int, len(list.NPCs))
for index, npc := range list.NPCs {
lookupByKey[identity.ComparisonKey(npc.Name)] = index
}
digest := semanticDigest(content)
projection, err := nameProjection(list)
if err != nil {
return nil, fmt.Errorf("encode NPC name projection: %w", err)
}
projectionDigest := semanticDigest(projection)
return &Registry{
bound: true,
list: list,
canonical: append([]byte(nil), content...),
digest: digest,
projectionDigest: projectionDigest,
promptInput: contracts.NewLLMInputMaterial(ReferenceSlot, npccodec.MediaType, projection, projectionDigest, ""),
lookupByKey: lookupByKey,
}, nil
}
// Bound reports whether an NPC reference was supplied and validated.
func (r *Registry) Bound() bool { return r != nil && r.bound }
// NPCs returns a defensive copy of the validated NPC records.
func (r *Registry) NPCs() []dnd.NPC {
if r == nil {
return nil
}
return cloneNPCs(r.list.NPCs)
}
// List returns a defensive copy of the validated NPC list.
func (r *Registry) List() dnd.NPCList {
if r == nil {
return dnd.NPCList{}
}
return cloneNPCList(r.list)
}
// CanonicalBytes returns a defensive copy of the canonical durable JSON.
func (r *Registry) CanonicalBytes() []byte {
if r == nil {
return nil
}
return append([]byte(nil), r.canonical...)
}
// Digest returns the semantic SHA-256 digest of the canonical JSON, or an
// empty string when the registry is unbound.
func (r *Registry) Digest() string {
if r == nil {
return ""
}
return r.digest
}
// ProjectionDigest returns the SHA-256 digest of the exact names-only prompt
// projection, including for an unbound or empty registry.
func (r *Registry) ProjectionDigest() string {
if r == nil {
return ""
}
return r.projectionDigest
}
// Count returns the number of validated NPC records.
func (r *Registry) Count() int {
if r == nil {
return 0
}
return len(r.list.NPCs)
}
// PromptInput returns the names-only registry projection as a content-safe
// prompt input. Durable IDs, evidence, and reference provenance are omitted.
func (r *Registry) PromptInput() contracts.LLMInputMaterial {
if r == nil {
return contracts.LLMInputMaterial{}
}
return r.promptInput.Clone()
}
// Lookup returns the canonical NPC for an exact canonical-name match under the
// NPC identity comparison policy.
func (r *Registry) Lookup(value string) (dnd.NPC, bool) {
if r == nil {
return dnd.NPC{}, false
}
index, ok := r.lookupByKey[identity.ComparisonKey(value)]
if !ok {
return dnd.NPC{}, false
}
return cloneNPC(r.list.NPCs[index]), true
}
func semanticDigest(content []byte) string {
sum := sha256.Sum256(content)
return "sha256:" + hex.EncodeToString(sum[:])
}
type projectedNPC struct {
Name string `json:"name"`
}
type projectedNPCList struct {
NPCs []projectedNPC `json:"npcs"`
}
func nameProjection(list dnd.NPCList) ([]byte, error) {
projection := projectedNPCList{NPCs: make([]projectedNPC, len(list.NPCs))}
for index, npc := range list.NPCs {
projection.NPCs[index] = projectedNPC{Name: npc.Name}
}
return json.Marshal(projection)
}
func formatIdentityIssues(issues []identity.Issue) string {
parts := make([]string, len(issues))
for index, issue := range issues {
location := fmt.Sprintf("record %d", issue.RecordIndex)
parts[index] = fmt.Sprintf("%s at %s", issue.Code, location)
}
return diagnostics.Aggregate("validate NPC registry identity", parts)
}
func cloneNPCList(value dnd.NPCList) dnd.NPCList {
return dnd.NPCList{NPCs: cloneNPCs(value.NPCs)}
}
func cloneNPCs(values []dnd.NPC) []dnd.NPC {
if values == nil {
return nil
}
cloned := make([]dnd.NPC, len(values))
for index, value := range values {
cloned[index] = cloneNPC(value)
}
return cloned
}
func cloneNPC(value dnd.NPC) dnd.NPC {
value.SourceRefs = append([]source.SourceRef(nil), value.SourceRefs...)
return value
}