Add D&D enemy event artifact contract

This commit is contained in:
2026-08-03 20:32:20 +00:00
parent db2adb52da
commit 8834df617f
6 changed files with 535 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "notarius.dnd.enemy_events",
"type": "object",
"additionalProperties": false,
"required": ["events"],
"properties": {
"events": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["name", "kind", "source_refs"],
"properties": {
"name": {"type": "string", "minLength": 1},
"kind": {"type": "string", "enum": ["engaged", "killed", "fled", "captured", "incapacitated"]},
"source_refs": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": false,
"required": ["source_id", "start_unit_id", "end_unit_id"],
"properties": {
"source_id": {"type": "string", "minLength": 1},
"start_unit_id": {"type": "integer", "minimum": 1},
"end_unit_id": {"type": "integer", "minimum": 1}
}
}
}
}
}
}
}
}

View File

@@ -0,0 +1,182 @@
// Package enemyevents encodes durable D&D enemy-event artifacts.
package enemyevents
import (
"embed"
"encoding/json"
"fmt"
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/candidatejson"
)
const (
SchemaID = "notarius.dnd.enemy_events"
SchemaName = "notarius_dnd_enemy_events_v1"
SchemaVersion = "v1"
MediaType = "application/json"
)
//go:embed assets/schemas/dnd_enemy_events.v1.json
var schemaAssets embed.FS
var _ contracts.ArtifactCodec[dnd.EnemyEventList] = (*Codec)(nil)
type Codec struct{}
func New() *Codec { return &Codec{} }
func (c *Codec) Kind() contracts.ArtifactKind { return dnd.EnemyEventListKind }
func (c *Codec) Schema() contracts.ArtifactSchema {
raw, err := schemaAssets.ReadFile("assets/schemas/dnd_enemy_events.v1.json")
if err != nil {
return contracts.ArtifactSchema{}
}
return contracts.ArtifactSchema{
ID: SchemaID,
Name: SchemaName,
Version: SchemaVersion,
JSONSchema: append([]byte(nil), raw...),
}
}
func (c *Codec) MediaType() string { return MediaType }
func (c *Codec) Metadata(value dnd.EnemyEventList) map[string]any {
return map[string]any{"event_count": len(value.Events)}
}
func (c *Codec) Encode(value dnd.EnemyEventList) ([]byte, error) {
if err := validateRequiredValueFields(value); err != nil {
return nil, fmt.Errorf("encode dnd enemy event list: %w", err)
}
return c.EncodeCandidate(value)
}
// EncodeCandidate provides the durable representation before semantic
// validators have approved a value.
func (c *Codec) EncodeCandidate(value dnd.EnemyEventList) ([]byte, error) {
return candidatejson.EncodeCandidate("dnd enemy event list", cloneList(value))
}
func (c *Codec) Decode(content []byte) (dnd.EnemyEventList, error) {
value, err := c.DecodeCandidate(content)
if err != nil {
return dnd.EnemyEventList{}, err
}
if err := validateRequiredJSONFields(content); err != nil {
return dnd.EnemyEventList{}, fmt.Errorf("decode dnd enemy event list: %w", err)
}
return value, nil
}
// DecodeCandidate reads one strict durable JSON value before semantic
// validators have approved it.
func (c *Codec) DecodeCandidate(content []byte) (dnd.EnemyEventList, error) {
value, err := candidatejson.DecodeCandidate[dnd.EnemyEventList]("dnd enemy event list", content)
if err != nil {
return dnd.EnemyEventList{}, err
}
return cloneList(value), nil
}
func validateRequiredValueFields(value dnd.EnemyEventList) error {
if value.Events == nil {
return fmt.Errorf("events must be present")
}
for index, event := range value.Events {
if event.SourceRefs == nil {
return fmt.Errorf("events[%d].source_refs must be present", index)
}
}
return nil
}
func validateRequiredJSONFields(content []byte) error {
var root map[string]json.RawMessage
if err := json.Unmarshal(content, &root); err != nil || root == nil {
return fmt.Errorf("must be a JSON object")
}
events, err := requiredArray(root, "events", "")
if err != nil {
return err
}
for eventIndex, rawEvent := range events {
path := fmt.Sprintf("events[%d]", eventIndex)
var event map[string]json.RawMessage
if err := json.Unmarshal(rawEvent, &event); err != nil || event == nil {
return fmt.Errorf("%s must be an object", path)
}
for _, field := range []string{"name", "kind"} {
if err := requireField(event, field, path); err != nil {
return err
}
}
refs, err := requiredArray(event, "source_refs", path)
if err != nil {
return err
}
for refIndex, rawRef := range refs {
refPath := fmt.Sprintf("%s.source_refs[%d]", path, refIndex)
var ref map[string]json.RawMessage
if err := json.Unmarshal(rawRef, &ref); err != nil || ref == nil {
return fmt.Errorf("%s must be an object", refPath)
}
for _, field := range []string{"source_id", "start_unit_id", "end_unit_id"} {
if err := requireField(ref, field, refPath); err != nil {
return err
}
}
}
}
return nil
}
func requiredArray(object map[string]json.RawMessage, field, path string) ([]json.RawMessage, error) {
raw, err := requiredField(object, field, path)
if err != nil {
return nil, err
}
var values []json.RawMessage
if err := json.Unmarshal(raw, &values); err != nil {
return nil, fmt.Errorf("%s must be an array", fieldPath(path, field))
}
return values, nil
}
func requireField(object map[string]json.RawMessage, field, path string) error {
_, err := requiredField(object, field, path)
return err
}
func requiredField(object map[string]json.RawMessage, field, path string) (json.RawMessage, error) {
raw, ok := object[field]
if !ok || string(raw) == "null" {
return nil, fmt.Errorf("%s must be present", fieldPath(path, field))
}
return raw, nil
}
func fieldPath(path, field string) string {
if path == "" {
return field
}
return path + "." + field
}
func cloneList(value dnd.EnemyEventList) dnd.EnemyEventList {
if value.Events == nil {
return dnd.EnemyEventList{}
}
cloned := dnd.EnemyEventList{Events: make([]dnd.EnemyEvent, len(value.Events))}
for index, event := range value.Events {
cloned.Events[index] = event
if event.SourceRefs != nil {
cloned.Events[index].SourceRefs = append([]source.SourceRef(nil), event.SourceRefs...)
}
}
return cloned
}

View File

@@ -0,0 +1,99 @@
package enemyevents
import (
"encoding/json"
"reflect"
"strings"
"testing"
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
)
func validList() dnd.EnemyEventList {
return dnd.EnemyEventList{Events: []dnd.EnemyEvent{
{Name: "Ashfang", Kind: dnd.EnemyEventKindEngaged, SourceRefs: refs(1, 2)},
{Name: "Ashfang", Kind: dnd.EnemyEventKindFled, SourceRefs: refs(5, 6)},
}}
}
func refs(start, end int) []source.SourceRef {
return []source.SourceRef{{SourceID: "session", StartUnitID: start, EndUnitID: end}}
}
func TestCodecRoundTripAndIdentity(t *testing.T) {
codec := New()
value := validList()
content, err := codec.Encode(value)
if err != nil {
t.Fatalf("Encode() error = %v", err)
}
decoded, err := codec.Decode(content)
if err != nil || !reflect.DeepEqual(decoded, value) {
t.Fatalf("Decode() = %#v, %v; want %#v", decoded, err, value)
}
schema := codec.Schema()
if codec.Kind() != dnd.EnemyEventListKind || codec.MediaType() != MediaType || schema.ID != SchemaID || schema.Name != SchemaName || schema.Version != SchemaVersion || !json.Valid(schema.JSONSchema) {
t.Fatalf("codec identity/schema = %q/%q %#v", codec.Kind(), codec.MediaType(), schema)
}
registry := pipeline.NewArtifactCodecRegistry()
if err := pipeline.RegisterArtifactCodec(registry, codec); err != nil {
t.Fatal(err)
}
spec, ok := registry.Spec(dnd.EnemyEventListKind)
if !ok || spec.SchemaDigest != contracts.DigestArtifactSchema(schema) {
t.Fatalf("registered spec = %#v, %t", spec, ok)
}
}
func TestCodecRejectsStrictJSONAndMissingRequiredFields(t *testing.T) {
validJSON := `{"events":[{"name":"Ashfang","kind":"engaged","source_refs":[{"source_id":"session","start_unit_id":1,"end_unit_id":1}]}]}`
tests := []struct {
name, raw, want string
}{
{"invalid JSON", `{`, "decode dnd enemy event list"},
{"unknown root field", `{"events":[],"unexpected":true}`, "unknown field"},
{"unknown event field", strings.Replace(validJSON, `"kind":"engaged"`, `"kind":"engaged","unexpected":true`, 1), "unknown field"},
{"missing events", `{}`, "events must be present"},
{"missing name", strings.Replace(validJSON, `"name":"Ashfang",`, "", 1), "events[0].name must be present"},
{"missing kind", strings.Replace(validJSON, `"kind":"engaged",`, "", 1), "events[0].kind must be present"},
{"missing refs", strings.Replace(validJSON, `,"source_refs":[{"source_id":"session","start_unit_id":1,"end_unit_id":1}]`, "", 1), "events[0].source_refs must be present"},
{"missing source ID", strings.Replace(validJSON, `"source_id":"session",`, "", 1), "source_refs[0].source_id must be present"},
{"trailing JSON", `{"events":[]} {}`, "multiple JSON values"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if _, err := New().Decode([]byte(test.raw)); err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("Decode() error = %v, want %q", err, test.want)
}
})
}
}
func TestCodecDefensivelyOwnsValuesAndDefersSemanticValidation(t *testing.T) {
codec := New()
candidate := dnd.EnemyEventList{Events: []dnd.EnemyEvent{{
Name: " ", Kind: "unsupported", SourceRefs: []source.SourceRef{{SourceID: "", StartUnitID: 0, EndUnitID: -1}},
}}}
content, err := codec.EncodeCandidate(candidate)
if err != nil {
t.Fatal(err)
}
decoded, err := codec.Decode(content)
if err != nil || !reflect.DeepEqual(decoded, candidate) {
t.Fatalf("Decode() = %#v, %v; want semantic candidate preservation", decoded, err)
}
decoded.Events[0].SourceRefs[0].SourceID = "changed"
if candidate.Events[0].SourceRefs[0].SourceID != "" {
t.Fatal("Decode() retained caller-owned source references")
}
first := codec.Schema()
first.JSONSchema[0] = '['
if second := codec.Schema(); !json.Valid(second.JSONSchema) || second.JSONSchema[0] == '[' {
t.Fatal("Schema() returned shared bytes")
}
}

View File

@@ -0,0 +1,107 @@
// Package enemyevents owns canonical ordering and identity policy for D&D
// enemy-event artifacts.
package enemyevents
import (
"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"
)
// NormalizeDisplay returns the durable display form for an enemy subject.
func NormalizeDisplay(value string) string { return identity.NormalizeDisplay(value) }
// ComparisonKey returns the shared D&D identity key for an enemy subject.
func ComparisonKey(value string) string { return identity.ComparisonKey(NormalizeDisplay(value)) }
// SupportedKind reports whether kind belongs to the durable enemy-event vocabulary.
func SupportedKind(kind dnd.EnemyEventKind) bool {
_, ok := KindRank(kind)
return ok
}
// KindRank returns the explicit chronological tie-break order for event kinds.
func KindRank(kind dnd.EnemyEventKind) (int, bool) {
switch kind {
case dnd.EnemyEventKindEngaged:
return 0, true
case dnd.EnemyEventKindIncapacitated:
return 1, true
case dnd.EnemyEventKindCaptured:
return 2, true
case dnd.EnemyEventKindFled:
return 3, true
case dnd.EnemyEventKindKilled:
return 4, true
default:
return 0, false
}
}
// SourceRefsEqual reports whether two reference sequences are equal after
// canonical ordering and exact duplicate removal.
func SourceRefsEqual(order shared.SourceRefOrder, left, right []source.SourceRef) bool {
left = order.Canonicalize(left)
right = order.Canonicalize(right)
if (left == nil) != (right == nil) || len(left) != len(right) {
return false
}
for index := range left {
if left[index] != right[index] {
return false
}
}
return true
}
// ExactEqual reports whether events have the same subject identity, kind, and
// complete canonical evidence sequence.
func ExactEqual(order shared.SourceRefOrder, left, right dnd.EnemyEvent) bool {
return ComparisonKey(left.Name) == ComparisonKey(right.Name) &&
left.Kind == right.Kind &&
SourceRefsEqual(order, left.SourceRefs, right.SourceRefs)
}
// Less defines the canonical stable event order. Invalid source references
// remain comparable through SourceRefOrder's literal fallback so malformed
// candidates can still be sorted for later validation.
func Less(order shared.SourceRefOrder, left, right dnd.EnemyEvent) 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 := NormalizeDisplay(left.Name), NormalizeDisplay(right.Name); leftName != rightName {
return leftName < rightName
}
if leftRank, leftKnown := KindRank(left.Kind); leftKnown {
if rightRank, rightKnown := KindRank(right.Kind); rightKnown && leftRank != rightRank {
return leftRank < rightRank
} else if !rightKnown {
return true
}
} else if _, rightKnown := KindRank(right.Kind); rightKnown {
return false
}
if left.Kind != right.Kind {
return left.Kind < right.Kind
}
return sourceRefsLess(order, order.Canonicalize(left.SourceRefs), order.Canonicalize(right.SourceRefs))
}
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)
}

View File

@@ -0,0 +1,90 @@
package enemyevents
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 TestSupportedKindAndRank(t *testing.T) {
tests := []struct {
kind dnd.EnemyEventKind
rank int
}{
{dnd.EnemyEventKindEngaged, 0},
{dnd.EnemyEventKindIncapacitated, 1},
{dnd.EnemyEventKindCaptured, 2},
{dnd.EnemyEventKindFled, 3},
{dnd.EnemyEventKindKilled, 4},
}
for _, test := range tests {
if rank, ok := KindRank(test.kind); !ok || rank != test.rank || !SupportedKind(test.kind) {
t.Fatalf("kind %q = (%d, %t), supported %t", test.kind, rank, ok, SupportedKind(test.kind))
}
}
if _, ok := KindRank("unknown"); ok || SupportedKind("unknown") {
t.Fatal("unsupported kind was accepted")
}
}
func TestLessOrdersChronologyThenKind(t *testing.T) {
order := testOrder()
events := []dnd.EnemyEvent{
{Name: "Ashfang", Kind: dnd.EnemyEventKindKilled, SourceRefs: refs(20)},
{Name: "Ashfang", Kind: dnd.EnemyEventKindFled, SourceRefs: refs(20)},
{Name: "Ashfang", Kind: dnd.EnemyEventKindCaptured, SourceRefs: refs(20)},
{Name: "Ashfang", Kind: dnd.EnemyEventKindIncapacitated, SourceRefs: refs(20)},
{Name: "Ashfang", Kind: dnd.EnemyEventKindEngaged, SourceRefs: refs(20)},
{Name: "Later", Kind: dnd.EnemyEventKindEngaged, SourceRefs: refs(30)},
{Name: "Earlier", Kind: dnd.EnemyEventKindKilled, SourceRefs: refs(10)},
}
sort.SliceStable(events, func(left, right int) bool { return Less(order, events[left], events[right]) })
want := []dnd.EnemyEventKind{
dnd.EnemyEventKindKilled,
dnd.EnemyEventKindEngaged,
dnd.EnemyEventKindIncapacitated,
dnd.EnemyEventKindCaptured,
dnd.EnemyEventKindFled,
dnd.EnemyEventKindKilled,
dnd.EnemyEventKindEngaged,
}
for index, kind := range want {
if events[index].Kind != kind {
t.Fatalf("event %d kind = %q, want %q", index, events[index].Kind, kind)
}
}
}
func TestExactEqualUsesSubjectIdentityAndCanonicalEvidence(t *testing.T) {
order := testOrder()
first := dnd.EnemyEvent{Name: " ASHFANG ", Kind: dnd.EnemyEventKindFled, SourceRefs: []source.SourceRef{
{SourceID: "session", StartUnitID: 30, EndUnitID: 30},
{SourceID: "session", StartUnitID: 10, EndUnitID: 10},
{SourceID: "session", StartUnitID: 10, EndUnitID: 10},
}}
second := dnd.EnemyEvent{Name: "Ashfang", Kind: dnd.EnemyEventKindFled, SourceRefs: []source.SourceRef{
{SourceID: "session", StartUnitID: 10, EndUnitID: 10},
{SourceID: "session", StartUnitID: 30, EndUnitID: 30},
}}
if !ExactEqual(order, first, second) || !SourceRefsEqual(order, first.SourceRefs, second.SourceRefs) {
t.Fatal("canonical duplicate identity was not recognized")
}
differentKind := second
differentKind.Kind = dnd.EnemyEventKindKilled
differentEvidence := second
differentEvidence.SourceRefs = []source.SourceRef{{SourceID: "session", StartUnitID: 20, EndUnitID: 20}}
if ExactEqual(order, first, differentKind) || ExactEqual(order, first, differentEvidence) {
t.Fatal("distinct event was treated as an exact duplicate")
}
}
func refs(unitID int) []source.SourceRef {
return []source.SourceRef{{SourceID: "session", StartUnitID: unitID, EndUnitID: unitID}}
}
func testOrder() shared.SourceRefOrder {
return shared.NewSourceRefOrder(&source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 10}, {ID: 20}, {ID: 30}}})
}

View File

@@ -18,6 +18,8 @@ const SceneDescriptionListKind contracts.ArtifactKind = "dnd/scene-description-l
const ItemEventListKind contracts.ArtifactKind = "dnd/item-event-list"
const EnemyEventListKind contracts.ArtifactKind = "dnd/enemy-event-list"
type SpellList struct {
SpellCasts []SpellCast `json:"spell_casts"`
}
@@ -122,3 +124,23 @@ type ItemEvent struct {
To string `json:"to,omitempty"`
SourceRefs []source.SourceRef `json:"source_refs"`
}
type EnemyEventKind string
const (
EnemyEventKindEngaged EnemyEventKind = "engaged"
EnemyEventKindKilled EnemyEventKind = "killed"
EnemyEventKindFled EnemyEventKind = "fled"
EnemyEventKindCaptured EnemyEventKind = "captured"
EnemyEventKindIncapacitated EnemyEventKind = "incapacitated"
)
type EnemyEventList struct {
Events []EnemyEvent `json:"events"`
}
type EnemyEvent struct {
Name string `json:"name"`
Kind EnemyEventKind `json:"kind"`
SourceRefs []source.SourceRef `json:"source_refs"`
}