Add D&D item event artifact contract

This commit is contained in:
2026-07-25 21:41:17 +00:00
parent 4ba1e50a89
commit f320c2fcee
6 changed files with 740 additions and 0 deletions

View File

@@ -0,0 +1,209 @@
// Package itemevents owns canonical ordering and durable domain rules for D&D
// item-event artifacts.
package itemevents
import (
"strconv"
"strings"
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
)
const partyHolder = "party"
// SupportedKind reports whether kind is one of the durable item-event kinds.
func SupportedKind(kind dnd.ItemEventKind) bool {
switch kind {
case dnd.ItemEventKindDiscovered,
dnd.ItemEventKindAcquired,
dnd.ItemEventKindLost,
dnd.ItemEventKindConsumed,
dnd.ItemEventKindTransferred:
return true
default:
return false
}
}
// DisplayValue returns the durable display form used for item and holder
// comparisons without changing the observed internal spelling.
func DisplayValue(value string) string { return strings.TrimSpace(value) }
// ComparisonKey returns the shared D&D Unicode- and case-insensitive key for
// a trimmed item or holder display value.
func ComparisonKey(value string) string { return identity.ComparisonKey(DisplayValue(value)) }
// HolderPresent reports whether value is a nonblank optional holder.
func HolderPresent(value string) bool { return DisplayValue(value) != "" }
// IsPartyHolder reports whether value denotes collective party possession.
func IsPartyHolder(value string) bool { return ComparisonKey(value) == partyHolder }
// ValidHolderCombination reports whether the optional holder fields satisfy
// the durable rules for kind. Blank holders are treated as absent so callers
// can preserve invalid extraction candidates for their owning validators.
func ValidHolderCombination(kind dnd.ItemEventKind, from, to string) bool {
hasFrom := HolderPresent(from)
hasTo := HolderPresent(to)
switch kind {
case dnd.ItemEventKindDiscovered:
return !hasFrom && !hasTo
case dnd.ItemEventKindAcquired:
return !hasFrom && hasTo
case dnd.ItemEventKindLost, dnd.ItemEventKindConsumed:
return hasFrom && !hasTo
case dnd.ItemEventKindTransferred:
return hasFrom && hasTo && !IsPartyHolder(from) && !IsPartyHolder(to) && ComparisonKey(from) != ComparisonKey(to)
default:
return false
}
}
// SourceRefsEqual reports whether two source-reference sequences have the
// same representation and values, including nil-versus-empty distinction.
func SourceRefsEqual(left, right []source.SourceRef) bool {
if (left == nil) != (right == nil) || len(left) != len(right) {
return false
}
for index := range left {
if left[index] != right[index] {
return false
}
}
return true
}
// ValidSourceRefs reports whether refs are non-empty and valid for index.
func ValidSourceRefs(index source.DocumentIndex, refs []source.SourceRef) bool {
if len(refs) == 0 {
return false
}
for _, ref := range refs {
if index.ValidateRef(ref) != nil {
return false
}
}
return true
}
// Less defines the canonical event order. Invalid source references remain
// comparable through SourceRefOrder's literal fallback so malformed candidates
// are still safe to sort and diagnose.
func Less(order shared.SourceRefOrder, left, right dnd.ItemEvent) bool {
leftPosition, leftHasEvidence := order.EarliestValid(left.SourceRefs)
rightPosition, rightHasEvidence := order.EarliestValid(right.SourceRefs)
if leftHasEvidence != rightHasEvidence {
return leftHasEvidence
}
if leftHasEvidence && leftPosition != rightPosition {
return leftPosition < rightPosition
}
if leftKey, rightKey := ComparisonKey(left.Name), ComparisonKey(right.Name); leftKey != rightKey {
return leftKey < rightKey
}
if leftName, rightName := DisplayValue(left.Name), DisplayValue(right.Name); leftName != rightName {
return leftName < rightName
}
if left.Kind != right.Kind {
return left.Kind < right.Kind
}
if less, decided := optionalStringLess(left.From, right.From); decided {
return less
}
if less, decided := optionalStringLess(left.To, right.To); decided {
return less
}
if less, decided := optionalQuantityLess(left.Quantity, right.Quantity); decided {
return less
}
return sourceRefsLess(order, order.Canonicalize(left.SourceRefs), order.Canonicalize(right.SourceRefs))
}
// ExactEqual reports whether events are exact duplicates after their display
// fields and evidence have been canonicalized for the supplied source order.
func ExactEqual(order shared.SourceRefOrder, left, right dnd.ItemEvent) bool {
if DisplayValue(left.Name) != DisplayValue(right.Name) || left.Kind != right.Kind ||
DisplayValue(left.From) != DisplayValue(right.From) || DisplayValue(left.To) != DisplayValue(right.To) ||
(left.Quantity == nil) != (right.Quantity == nil) {
return false
}
if left.Quantity != nil && *left.Quantity != *right.Quantity {
return false
}
return SourceRefsEqual(order.Canonicalize(left.SourceRefs), order.Canonicalize(right.SourceRefs))
}
// ExactIdentity returns a collision-safe duplicate key after display and
// evidence canonicalization. It is intended for callers that have already
// decided the event is eligible for duplicate handling.
func ExactIdentity(order shared.SourceRefOrder, event dnd.ItemEvent) string {
var key strings.Builder
writeKeyString(&key, DisplayValue(event.Name))
writeKeyString(&key, string(event.Kind))
writeKeyString(&key, DisplayValue(event.From))
writeKeyString(&key, DisplayValue(event.To))
if event.Quantity == nil {
key.WriteByte('0')
} else {
key.WriteByte('1')
writeKeyInt(&key, *event.Quantity)
}
for _, ref := range order.Canonicalize(event.SourceRefs) {
writeKeyString(&key, ref.SourceID)
writeKeyInt(&key, ref.StartUnitID)
writeKeyInt(&key, ref.EndUnitID)
}
return key.String()
}
func optionalStringLess(left, right string) (bool, bool) {
leftPresent, rightPresent := HolderPresent(left), HolderPresent(right)
if leftPresent != rightPresent {
return !leftPresent, true
}
if !leftPresent {
return false, false
}
if leftKey, rightKey := ComparisonKey(left), ComparisonKey(right); leftKey != rightKey {
return leftKey < rightKey, true
}
if leftValue, rightValue := DisplayValue(left), DisplayValue(right); leftValue != rightValue {
return leftValue < rightValue, true
}
return false, false
}
func optionalQuantityLess(left, right *int) (bool, bool) {
if (left == nil) != (right == nil) {
return left == nil, true
}
if left != nil && *left != *right {
return *left < *right, true
}
return false, false
}
func sourceRefsLess(order shared.SourceRefOrder, left, right []source.SourceRef) bool {
for index := 0; index < len(left) && index < len(right); index++ {
if left[index] == right[index] {
continue
}
return order.Less(left[index], right[index])
}
return len(left) < len(right)
}
func writeKeyString(builder *strings.Builder, value string) {
builder.WriteString(strconv.Itoa(len(value)))
builder.WriteByte(':')
builder.WriteString(value)
}
func writeKeyInt(builder *strings.Builder, value int) {
builder.WriteString(strconv.Itoa(value))
builder.WriteByte(';')
}

View File

@@ -0,0 +1,169 @@
package itemevents
import (
"sort"
"testing"
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
)
func TestValidHolderCombination(t *testing.T) {
valid := []struct {
kind dnd.ItemEventKind
from, to string
}{
{dnd.ItemEventKindDiscovered, "", ""},
{dnd.ItemEventKindAcquired, "", "party"},
{dnd.ItemEventKindLost, "party", ""},
{dnd.ItemEventKindConsumed, "party", ""},
{dnd.ItemEventKindTransferred, "Aria", "Borin"},
}
for _, test := range valid {
if !ValidHolderCombination(test.kind, test.from, test.to) {
t.Fatalf("ValidHolderCombination(%q, %q, %q) = false", test.kind, test.from, test.to)
}
}
invalid := []struct {
kind dnd.ItemEventKind
from, to string
}{
{dnd.ItemEventKindDiscovered, "Aria", ""},
{dnd.ItemEventKindAcquired, "", ""},
{dnd.ItemEventKindLost, "", ""},
{dnd.ItemEventKindConsumed, "", "Borin"},
{dnd.ItemEventKindTransferred, "party", "Borin"},
{dnd.ItemEventKindTransferred, "Aria", "Party"},
{dnd.ItemEventKindTransferred, "Aria", "aria"},
{dnd.ItemEventKindTransferred, "Åria", "Åria"},
{"unsupported", "", ""},
}
for _, test := range invalid {
if ValidHolderCombination(test.kind, test.from, test.to) {
t.Fatalf("ValidHolderCombination(%q, %q, %q) = true", test.kind, test.from, test.to)
}
}
}
func TestLessUsesEveryCanonicalTieBreaker(t *testing.T) {
order := testOrder()
ref := func(start, end int) []source.SourceRef {
return []source.SourceRef{{SourceID: "session", StartUnitID: start, EndUnitID: end}}
}
quantity := func(value int) *int { return &value }
base := dnd.ItemEvent{Name: "Amulet", Kind: dnd.ItemEventKindAcquired, To: "Borin", SourceRefs: ref(20, 20)}
tests := []struct {
name string
left, right dnd.ItemEvent
}{
{"earlier evidence", withRefs(base, ref(10, 10)), base},
{"valid evidence before malformed", base, withRefs(base, ref(999, 999))},
{"normalized name", withName(base, "Amulet"), withName(base, "Blade")},
{"exact trimmed name", withName(base, "Amulet"), withName(base, "amulet")},
{"kind", withKind(base, dnd.ItemEventKindAcquired), withKind(base, dnd.ItemEventKindLost)},
{"from presence", withFrom(base, ""), withFrom(base, "Aria")},
{"from normalized value", withFrom(base, "Aria"), withFrom(base, "Borin")},
{"from exact value", withFrom(base, "Aria"), withFrom(base, "aria")},
{"to presence", withoutTo(base), withTo(base, "Borin")},
{"to normalized value", withTo(base, "Aria"), withTo(base, "Borin")},
{"to exact value", withTo(base, "Aria"), withTo(base, "aria")},
{"quantity presence", withQuantity(base, nil), withQuantity(base, quantity(1))},
{"quantity value", withQuantity(base, quantity(1)), withQuantity(base, quantity(2))},
{"canonical source reference sequence", withRefs(base, ref(20, 20)), withRefs(base, ref(30, 30))},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if !Less(order, test.left, test.right) || Less(order, test.right, test.left) {
t.Fatalf("Less() did not order %#v before %#v", test.left, test.right)
}
})
}
}
func TestLessAndExactEqualityCanonicalizeEvidence(t *testing.T) {
order := testOrder()
first := dnd.ItemEvent{
Name: " Silver Coin ", Kind: dnd.ItemEventKindAcquired, To: " party ",
SourceRefs: []source.SourceRef{
{SourceID: "session", StartUnitID: 30, EndUnitID: 30},
{SourceID: "session", StartUnitID: 10, EndUnitID: 10},
{SourceID: "session", StartUnitID: 10, EndUnitID: 10},
},
}
second := dnd.ItemEvent{
Name: "Silver Coin", Kind: dnd.ItemEventKindAcquired, To: "party",
SourceRefs: []source.SourceRef{
{SourceID: "session", StartUnitID: 10, EndUnitID: 10},
{SourceID: "session", StartUnitID: 30, EndUnitID: 30},
},
}
if !ExactEqual(order, first, second) {
t.Fatal("ExactEqual() = false, want canonical duplicate")
}
if Less(order, first, second) || Less(order, second, first) {
t.Fatal("Less() distinguished canonically equal records")
}
if ExactIdentity(order, first) != ExactIdentity(order, second) {
t.Fatal("ExactIdentity() differs for canonical duplicates")
}
quantity := 1
differentQuantity := second
differentQuantity.Quantity = &quantity
differentEvidence := second
differentEvidence.SourceRefs = append([]source.SourceRef(nil), second.SourceRefs...)
differentEvidence.SourceRefs[1].EndUnitID = 20
if ExactEqual(order, second, differentQuantity) || ExactEqual(order, second, differentEvidence) {
t.Fatal("ExactEqual() collapsed distinct optional field or evidence values")
}
}
func TestSourceReferenceHelpers(t *testing.T) {
refs := []source.SourceRef{{SourceID: "session", StartUnitID: 10, EndUnitID: 20}}
if !SourceRefsEqual(refs, append([]source.SourceRef(nil), refs...)) || SourceRefsEqual(nil, []source.SourceRef{}) {
t.Fatal("SourceRefsEqual() did not preserve source-reference representation")
}
doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 10}, {ID: 20}, {ID: 30}}}
if !ValidSourceRefs(source.NewDocumentIndex(doc), refs) {
t.Fatal("ValidSourceRefs() = false, want valid reference")
}
if ValidSourceRefs(source.NewDocumentIndex(doc), []source.SourceRef{{SourceID: "other", StartUnitID: 10, EndUnitID: 20}}) {
t.Fatal("ValidSourceRefs() = true, want invalid source identifier rejection")
}
}
func TestLessSortsMalformedReferencesDeterministically(t *testing.T) {
order := testOrder()
events := []dnd.ItemEvent{
{Name: "A", Kind: dnd.ItemEventKindDiscovered, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 999, EndUnitID: 999}}},
{Name: "A", Kind: dnd.ItemEventKindDiscovered, SourceRefs: []source.SourceRef{{SourceID: "other", StartUnitID: 1, EndUnitID: 1}}},
{Name: "A", Kind: dnd.ItemEventKindDiscovered, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 10, EndUnitID: 10}}},
}
sort.SliceStable(events, func(left, right int) bool { return Less(order, events[left], events[right]) })
if events[0].SourceRefs[0].StartUnitID != 10 || events[1].SourceRefs[0].SourceID != "other" || events[2].SourceRefs[0].StartUnitID != 999 {
t.Fatalf("canonical sort = %#v", events)
}
}
func testOrder() shared.SourceRefOrder {
return shared.NewSourceRefOrder(&source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 10}, {ID: 20}, {ID: 30}}})
}
func withName(event dnd.ItemEvent, value string) dnd.ItemEvent { event.Name = value; return event }
func withKind(event dnd.ItemEvent, value dnd.ItemEventKind) dnd.ItemEvent {
event.Kind = value
return event
}
func withFrom(event dnd.ItemEvent, value string) dnd.ItemEvent { event.From = value; return event }
func withTo(event dnd.ItemEvent, value string) dnd.ItemEvent { event.To = value; return event }
func withoutTo(event dnd.ItemEvent) dnd.ItemEvent { event.To = ""; return event }
func withQuantity(event dnd.ItemEvent, value *int) dnd.ItemEvent {
event.Quantity = value
return event
}
func withRefs(event dnd.ItemEvent, value []source.SourceRef) dnd.ItemEvent {
event.SourceRefs = value
return event
}