Add item registry domain foundation

This commit is contained in:
2026-08-05 19:19:58 +00:00
parent e8965ebbbb
commit ce04387dbc
9 changed files with 938 additions and 0 deletions

View File

@@ -0,0 +1,149 @@
// Package identity owns the stable identity policy for D&D item types.
package identity
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/unicode/norm"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
)
const (
// Policy identifies the complete item comparison and ID derivation policy.
// A future semantic change must use a new value.
Policy = "dnd.item_registry.identity.v1"
// IdentityPolicy is an explicit alias for callers recording policy
// fingerprints.
IdentityPolicy = Policy
)
const idPrefix = "item:sha256:"
// IssueCode identifies one deterministic registry identity problem.
type IssueCode string
const (
IssueEmptyCanonicalName IssueCode = "empty_canonical_name"
IssueInvalidID IssueCode = "invalid_id"
IssueIDMismatch IssueCode = "id_mismatch"
IssueDuplicateCanonical IssueCode = "duplicate_canonical_identity"
IssueDuplicateID IssueCode = "duplicate_id"
)
// Issue is an inspectable identity validation problem.
type Issue struct {
Code IssueCode
RecordIndex int
Value string
}
// NormalizeDisplay trims and collapses Unicode whitespace while retaining all
// other observed spelling and punctuation.
func NormalizeDisplay(value string) string {
return strings.Join(strings.Fields(value), " ")
}
// ComparisonKey returns the stable key used for item-type identity comparisons.
func ComparisonKey(value string) string {
value = norm.NFKC.String(value)
value = strings.Map(func(r rune) rune {
switch r {
case '\u2018', '\u2019', '\u02bc':
return '\''
default:
return r
}
}, value)
value = strings.Join(strings.Fields(value), " ")
return cases.Fold().String(value)
}
// DeriveID returns the deterministic ID for an item type. Empty identity keys
// intentionally produce an empty ID so shape validation can report the missing
// identity instead of manufacturing one.
func DeriveID(name string) string {
key := ComparisonKey(name)
if key == "" {
return ""
}
identity, err := json.Marshal([]string{Policy, key})
if err != nil {
return ""
}
digest := sha256.Sum256(identity)
return idPrefix + hex.EncodeToString(digest[:])
}
// IDFor is a concise alias for DeriveID for callers that work with IDs as
// values rather than derivation operations.
func IDFor(name string) string { return DeriveID(name) }
// IsValidID reports whether value has the exact durable item ID syntax.
func IsValidID(value string) bool {
if len(value) != len(idPrefix)+sha256.Size*2 || !strings.HasPrefix(value, idPrefix) {
return false
}
for _, r := range value[len(idPrefix):] {
if !(r >= '0' && r <= '9') && !(r >= 'a' && r <= 'f') {
return false
}
}
return true
}
// ValidID is an alias for IsValidID.
func ValidID(value string) bool { return IsValidID(value) }
// ValidateRegistry checks item-type identity invariants without changing the
// input. Items with the same comparison name describe the same item type and
// are rejected as duplicate registry records.
func ValidateRegistry(items []dnd.Item) []Issue {
issues := make([]Issue, 0)
canonicalOwners := make(map[string][]int)
idOwners := make(map[string][]int)
for recordIndex, item := range items {
canonical := ComparisonKey(item.Name)
if canonical == "" {
issues = append(issues, Issue{Code: IssueEmptyCanonicalName, RecordIndex: recordIndex, Value: item.Name})
} else {
canonicalOwners[canonical] = append(canonicalOwners[canonical], recordIndex)
}
if !IsValidID(item.ID) {
issues = append(issues, Issue{Code: IssueInvalidID, RecordIndex: recordIndex, Value: item.ID})
} else if expected := DeriveID(item.Name); item.ID != expected {
issues = append(issues, Issue{Code: IssueIDMismatch, RecordIndex: recordIndex, Value: item.ID})
}
if item.ID != "" {
idOwners[item.ID] = append(idOwners[item.ID], recordIndex)
}
}
for recordIndex, item := range items {
canonical := ComparisonKey(item.Name)
if canonical != "" && len(canonicalOwners[canonical]) > 1 && canonicalOwners[canonical][0] != recordIndex {
issues = append(issues, Issue{Code: IssueDuplicateCanonical, RecordIndex: recordIndex, Value: item.Name})
}
if item.ID != "" && len(idOwners[item.ID]) > 1 && idOwners[item.ID][0] != recordIndex {
issues = append(issues, Issue{Code: IssueDuplicateID, RecordIndex: recordIndex, Value: item.ID})
}
}
return issues
}
// ValidateList validates the identity members of list.
func ValidateList(list dnd.ItemRegistry) []Issue { return ValidateRegistry(list.Items) }
// Error makes an issue useful in simple callers while preserving its
// structured fields for aggregate diagnostics.
func (i Issue) Error() string {
return fmt.Sprintf("%s at record %d", i.Code, i.RecordIndex)
}

View File

@@ -0,0 +1,89 @@
package identity
import (
"encoding/json"
"reflect"
"strings"
"testing"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
)
func TestComparisonKeyNormalizesSupportedEquivalences(t *testing.T) {
tests := []struct {
name string
left string
right string
}{
{name: "case", left: "Silver Key", right: "sILVER kEY"},
{name: "compatibility", left: " ", right: "Silver Key"},
{name: "whitespace", left: " Silver\u2003Key ", right: "Silver Key"},
{name: "apostrophe", left: "Healers Kit", right: "healer's kit"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if ComparisonKey(test.left) != ComparisonKey(test.right) {
t.Fatalf("ComparisonKey(%q) = %q, ComparisonKey(%q) = %q", test.left, ComparisonKey(test.left), test.right, ComparisonKey(test.right))
}
})
}
if ComparisonKey("Silver Key") == ComparisonKey("Gold Key") {
t.Fatal("different item types received the same comparison key")
}
}
func TestDeriveIDUsesExactCompactIdentityBytes(t *testing.T) {
const wantID = "item:sha256:2f211c60b9bdcf3a6dd64086cc4c05df5b3357ae02cb462f7ef8988d9bd2fa4f"
const wantIdentity = `["dnd.item_registry.identity.v1","silver key"]`
encoded, err := json.Marshal([]string{Policy, ComparisonKey("Silver Key")})
if err != nil || string(encoded) != wantIdentity {
t.Fatalf("identity bytes = %q, %v; want %s", encoded, err, wantIdentity)
}
if Policy != "dnd.item_registry.identity.v1" || IdentityPolicy != Policy {
t.Fatalf("identity policy = %q/%q", Policy, IdentityPolicy)
}
if got := DeriveID(" SILVER\u2003KEY "); got != wantID || !IsValidID(got) || got != IDFor("Silver Key") {
t.Fatalf("DeriveID() = %q, want %q", got, wantID)
}
if DeriveID(" \u2003 ") != "" {
t.Fatal("empty identity produced an ID")
}
for _, invalid := range []string{"", "item:sha256:", "item:sha256:ABC", "item:sha256:" + strings.Repeat("0", 63), "item:sha256:" + strings.Repeat("0", 65)} {
if IsValidID(invalid) {
t.Fatalf("IsValidID(%q) = true, want false", invalid)
}
}
}
func TestValidateRegistryReportsDeterministicIdentityProblemsWithoutMutation(t *testing.T) {
items := []dnd.Item{
{ID: DeriveID("Silver Key"), Name: "Silver Key"},
{ID: DeriveID("Silver Key"), Name: " silver key "},
{ID: "bad", Name: "Gold Key"},
{ID: DeriveID("Silver Key"), Name: "Healer's Kit"},
{ID: "", Name: " "},
}
before := append([]dnd.Item(nil), items...)
issues := ValidateRegistry(items)
if !reflect.DeepEqual(items, before) {
t.Fatal("ValidateRegistry() mutated its input")
}
want := []IssueCode{
IssueDuplicateCanonical,
IssueDuplicateID,
IssueInvalidID,
IssueIDMismatch,
IssueEmptyCanonicalName,
}
seen := make(map[IssueCode]bool)
for _, issue := range issues {
seen[issue.Code] = true
}
for _, code := range want {
if !seen[code] {
t.Errorf("ValidateRegistry() issues = %#v, missing %s", issues, code)
}
}
}