Add combat turn normalization and invariants
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
// Package invariants validates normalized D&D combat-turn artifacts.
|
||||
package invariants
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"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"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
|
||||
combatshape "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/validate/combatturns/shape"
|
||||
)
|
||||
|
||||
const (
|
||||
Key = "normalize/dnd/combat-turns/invariants"
|
||||
ReasonCode = "invalid_combat_turn_normalization"
|
||||
policy = "dnd.combat_turns.validator.normalized.v1"
|
||||
)
|
||||
|
||||
type Options struct{}
|
||||
type Validator struct{}
|
||||
|
||||
var _ contracts.TypedValidator[dnd.CombatTurnList] = (*Validator)(nil)
|
||||
var _ pipeline.CheckpointFingerprintProvider = (*Validator)(nil)
|
||||
|
||||
func New(Options) *Validator { return &Validator{} }
|
||||
func (v *Validator) Name() string { return Key }
|
||||
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (v *Validator) CheckpointFingerprints() []pipeline.CheckpointFingerprint {
|
||||
return []pipeline.CheckpointFingerprint{{Name: "policy", Value: policy}}
|
||||
}
|
||||
|
||||
func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationRequest[dnd.CombatTurnList]) (contracts.ValidationResult, error) {
|
||||
if err := Validate(req.Source, req.Value); err != nil {
|
||||
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: err.Error()}, nil
|
||||
}
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
|
||||
// Validate checks only invariants owned by normalized combat-turn output. A
|
||||
// shape or source-reference failure is deliberately deferred to its owner.
|
||||
func Validate(doc *source.SourceDocument, value dnd.CombatTurnList) error {
|
||||
if combatshape.Validate(value) != nil || !sourceRefsValid(doc, value) {
|
||||
return nil
|
||||
}
|
||||
issues := issuesFor(doc, value)
|
||||
if len(issues) == 0 {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s", diagnostics.Aggregate("invalid combat turn normalization", issues))
|
||||
}
|
||||
|
||||
func issuesFor(doc *source.SourceDocument, value dnd.CombatTurnList) []string {
|
||||
issues := make([]string, 0)
|
||||
seenIdentity := make(map[string]int)
|
||||
previousPosition := -1
|
||||
for turnIndex, turn := range value.CombatTurns {
|
||||
prefix := fmt.Sprintf("combat_turns[%d]", turnIndex)
|
||||
if turn.Actor != identity.NormalizeDisplay(turn.Actor) {
|
||||
issues = append(issues, prefix+".actor is not display-normalized: "+diagnostics.Quote(turn.Actor))
|
||||
}
|
||||
if turn.Summary != identity.NormalizeDisplay(turn.Summary) {
|
||||
issues = append(issues, prefix+".summary is not display-normalized: "+diagnostics.Quote(turn.Summary))
|
||||
}
|
||||
for actionIndex, action := range turn.Actions {
|
||||
actionPrefix := fmt.Sprintf("%s.actions[%d]", prefix, actionIndex)
|
||||
if action.Declaration != identity.NormalizeDisplay(action.Declaration) {
|
||||
issues = append(issues, actionPrefix+".declaration is not display-normalized: "+diagnostics.Quote(action.Declaration))
|
||||
}
|
||||
seenTargets := make(map[string]int, len(action.Targets))
|
||||
for targetIndex, target := range action.Targets {
|
||||
if target != identity.NormalizeDisplay(target) {
|
||||
issues = append(issues, fmt.Sprintf("%s.targets[%d] is not display-normalized: %s", actionPrefix, targetIndex, diagnostics.Quote(target)))
|
||||
}
|
||||
key := identity.ComparisonKey(target)
|
||||
if previous, exists := seenTargets[key]; exists {
|
||||
issues = append(issues, fmt.Sprintf("%s.targets[%d] duplicates target %d under comparison identity", actionPrefix, targetIndex, previous))
|
||||
} else {
|
||||
seenTargets[key] = targetIndex
|
||||
}
|
||||
}
|
||||
if action.Resolution != nil && *action.Resolution != identity.NormalizeDisplay(*action.Resolution) {
|
||||
issues = append(issues, actionPrefix+".resolution is not display-normalized: "+diagnostics.Quote(*action.Resolution))
|
||||
}
|
||||
}
|
||||
|
||||
for refIndex := 1; refIndex < len(turn.SourceRefs); refIndex++ {
|
||||
previous := turn.SourceRefs[refIndex-1]
|
||||
current := turn.SourceRefs[refIndex]
|
||||
if sourceRefLess(current, previous) {
|
||||
issues = append(issues, fmt.Sprintf("%s.source_refs are not in canonical order at index %d", prefix, refIndex))
|
||||
} else if current == previous {
|
||||
issues = append(issues, fmt.Sprintf("%s.source_refs[%d] duplicates the previous reference", prefix, refIndex))
|
||||
}
|
||||
}
|
||||
|
||||
position, ok := earliestSourcePosition(doc, turn)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if previousPosition > position {
|
||||
issues = append(issues, fmt.Sprintf("%s is out of chronological order: evidence position %d follows %d", prefix, position, previousPosition))
|
||||
}
|
||||
previousPosition = position
|
||||
|
||||
if key, ok := duplicateKey(turn); ok {
|
||||
if previous, exists := seenIdentity[key]; exists {
|
||||
issues = append(issues, fmt.Sprintf("%s duplicates combat turn %d under normalized identity", prefix, previous))
|
||||
} else {
|
||||
seenIdentity[key] = turnIndex
|
||||
}
|
||||
}
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
func sourceRefsValid(doc *source.SourceDocument, value dnd.CombatTurnList) bool {
|
||||
for _, turn := range value.CombatTurns {
|
||||
for _, ref := range turn.SourceRefs {
|
||||
if source.ValidateRef(doc, ref) != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sourceRefLess(left, right source.SourceRef) bool {
|
||||
if left.SourceID != right.SourceID {
|
||||
return left.SourceID < right.SourceID
|
||||
}
|
||||
if left.StartUnitID != right.StartUnitID {
|
||||
return left.StartUnitID < right.StartUnitID
|
||||
}
|
||||
return left.EndUnitID < right.EndUnitID
|
||||
}
|
||||
|
||||
func earliestSourcePosition(doc *source.SourceDocument, turn dnd.CombatTurn) (int, bool) {
|
||||
if doc == nil {
|
||||
return 0, false
|
||||
}
|
||||
earliest := 0
|
||||
found := false
|
||||
for _, ref := range turn.SourceRefs {
|
||||
if source.ValidateRef(doc, ref) != nil {
|
||||
continue
|
||||
}
|
||||
index, ok := source.UnitIndex(doc, ref.StartUnitID)
|
||||
if !ok || (found && index >= earliest) {
|
||||
continue
|
||||
}
|
||||
earliest = index
|
||||
found = true
|
||||
}
|
||||
return earliest, found
|
||||
}
|
||||
|
||||
func duplicateKey(turn dnd.CombatTurn) (string, bool) {
|
||||
if len(turn.SourceRefs) == 0 {
|
||||
return "", false
|
||||
}
|
||||
var key strings.Builder
|
||||
writeKeyString(&key, identity.ComparisonKey(turn.Actor))
|
||||
writeKeyString(&key, string(turn.TurnKind))
|
||||
if turn.Round == nil {
|
||||
key.WriteByte('0')
|
||||
} else {
|
||||
key.WriteByte('1')
|
||||
writeKeyInt(&key, *turn.Round)
|
||||
}
|
||||
for _, ref := range turn.SourceRefs {
|
||||
writeKeyString(&key, ref.SourceID)
|
||||
writeKeyInt(&key, ref.StartUnitID)
|
||||
writeKeyInt(&key, ref.EndUnitID)
|
||||
}
|
||||
return key.String(), true
|
||||
}
|
||||
|
||||
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(';')
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
|
||||
}
|
||||
|
||||
func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
return pipeline.RegisterTypedValidatorBuilder(registry, dnd.CombatTurnListKind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[dnd.CombatTurnList], error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(options), nil
|
||||
})
|
||||
}
|
||||
|
||||
func DecodeOptions(options map[string]any) (Options, error) {
|
||||
if err := pipeline.RejectUnknownOptions(options); err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
return Options{}, nil
|
||||
}
|
||||
|
||||
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
|
||||
@@ -0,0 +1,141 @@
|
||||
package invariants
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"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 TestValidatorApprovesNormalizedCombatTurns(t *testing.T) {
|
||||
result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.CombatTurnList]{Source: invariantDocument(), Value: normalizedList()})
|
||||
if err != nil || !result.Approved || len(result.Warnings) != 0 {
|
||||
t.Fatalf("Validate() = %#v, %v; want approval without warnings", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsOwnedNormalizedInvariants(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*dnd.CombatTurnList, *source.SourceDocument)
|
||||
want string
|
||||
}{
|
||||
{name: "actor display whitespace", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) { value.CombatTurns[0].Actor = " Aria " }, want: "actor is not display-normalized"},
|
||||
{name: "summary display whitespace", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) {
|
||||
value.CombatTurns[0].Summary = "Aria attacks"
|
||||
}, want: "summary is not display-normalized"},
|
||||
{name: "declaration display whitespace", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) {
|
||||
value.CombatTurns[0].Actions[0].Declaration = "Aria attacks"
|
||||
}, want: "declaration is not display-normalized"},
|
||||
{name: "target display whitespace", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) {
|
||||
value.CombatTurns[0].Actions[0].Targets = []string{" Goblin"}
|
||||
}, want: "targets[0] is not display-normalized"},
|
||||
{name: "duplicate target identity", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) {
|
||||
value.CombatTurns[0].Actions[0].Targets = []string{"Goblin", " goblin"}
|
||||
}, want: "duplicates target"},
|
||||
{name: "resolution display whitespace", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) {
|
||||
resolution := " hit "
|
||||
value.CombatTurns[0].Actions[0].Resolution = &resolution
|
||||
}, want: "resolution is not display-normalized"},
|
||||
{name: "reference order", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) {
|
||||
value.CombatTurns[0].SourceRefs = []source.SourceRef{{SourceID: "session", StartUnitID: 20, EndUnitID: 20}, {SourceID: "session", StartUnitID: 10, EndUnitID: 10}}
|
||||
}, want: "not in canonical order"},
|
||||
{name: "duplicate reference", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) {
|
||||
value.CombatTurns[0].SourceRefs = append(value.CombatTurns[0].SourceRefs, value.CombatTurns[0].SourceRefs[0])
|
||||
}, want: "duplicates the previous reference"},
|
||||
{name: "chronology", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) {
|
||||
value.CombatTurns = []dnd.CombatTurn{withRef(value.CombatTurns[0], source.SourceRef{SourceID: "session", StartUnitID: 20, EndUnitID: 20}), value.CombatTurns[0]}
|
||||
}, want: "out of chronological order"},
|
||||
{name: "duplicate identity", mutate: func(value *dnd.CombatTurnList, _ *source.SourceDocument) {
|
||||
duplicate := value.CombatTurns[0]
|
||||
duplicate.Summary = "different prose"
|
||||
value.CombatTurns = append(value.CombatTurns, duplicate)
|
||||
}, want: "duplicates combat turn"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
value := normalizedList()
|
||||
doc := invariantDocument()
|
||||
test.mutate(&value, doc)
|
||||
err := Validate(doc, value)
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) {
|
||||
t.Fatalf("Validate() error = %v, want %q", err, test.want)
|
||||
}
|
||||
result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.CombatTurnList]{Source: doc, Value: value})
|
||||
if err != nil || result.Approved || result.ReasonCode != ReasonCode {
|
||||
t.Fatalf("Validator result = %#v, %v; want normalized-invariant rejection", result, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatorDefersShapeAndSourceReferenceFailures(t *testing.T) {
|
||||
doc := invariantDocument()
|
||||
shapeInvalid := normalizedList()
|
||||
shapeInvalid.CombatTurns[0].Actor = " "
|
||||
result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.CombatTurnList]{Source: doc, Value: shapeInvalid})
|
||||
if err != nil || !result.Approved {
|
||||
t.Fatalf("shape-invalid result = %#v, %v; want deferral", result, err)
|
||||
}
|
||||
sourceInvalid := normalizedList()
|
||||
sourceInvalid.CombatTurns[0].SourceRefs[0].StartUnitID = 999
|
||||
result, err = New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.CombatTurnList]{Source: doc, Value: sourceInvalid})
|
||||
if err != nil || !result.Approved {
|
||||
t.Fatalf("source-invalid result = %#v, %v; want deferral", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatorBoundsDiagnosticsAndRegistration(t *testing.T) {
|
||||
value := normalizedList()
|
||||
value.CombatTurns = make([]dnd.CombatTurn, 30)
|
||||
for index := range value.CombatTurns {
|
||||
value.CombatTurns[index] = normalizedList().CombatTurns[0]
|
||||
value.CombatTurns[index].Actor = strings.Repeat("火", 300)
|
||||
}
|
||||
result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.CombatTurnList]{Source: invariantDocument(), Value: value})
|
||||
if err != nil || result.Approved || !utf8.ValidString(result.Message) || len([]byte(result.Message)) > 4096 || !strings.Contains(result.Message, "additional issue(s) omitted") {
|
||||
t.Fatalf("bounded result = %#v, %v; want bounded rejection", result, err)
|
||||
}
|
||||
if got := New(Options{}).CheckpointFingerprints(); len(got) != 1 || got[0].Name != "policy" || got[0].Value != policy {
|
||||
t.Fatalf("CheckpointFingerprints() = %#v, want policy fingerprint", got)
|
||||
}
|
||||
if spec := Spec(); spec.Key != Key || spec.ExecutionClass != contracts.ExecutionClassDeterministic {
|
||||
t.Fatalf("Spec() = %#v", spec)
|
||||
}
|
||||
registry := pipeline.NewValidatorRegistry()
|
||||
if err := Register(registry); err != nil {
|
||||
t.Fatalf("Register() error = %v", err)
|
||||
}
|
||||
if _, err := DecodeOptions(map[string]any{"unexpected": true}); err == nil {
|
||||
t.Fatal("DecodeOptions() accepted unknown option")
|
||||
}
|
||||
if !reflect.DeepEqual(New(Options{}).CheckpointFingerprints(), []pipeline.CheckpointFingerprint{{Name: "policy", Value: policy}}) {
|
||||
t.Fatal("policy fingerprint changed unexpectedly")
|
||||
}
|
||||
}
|
||||
|
||||
func normalizedList() dnd.CombatTurnList {
|
||||
resolution := "hit"
|
||||
return dnd.CombatTurnList{CombatTurns: []dnd.CombatTurn{{
|
||||
Actor: "Aria", TurnKind: dnd.CombatTurnKindTurn, Round: intPointer(1),
|
||||
Actions: []dnd.CombatAction{{Category: dnd.CombatActionCategoryAttack, Declaration: "Aria attacks", Targets: []string{"Goblin"}, Resolution: &resolution}},
|
||||
Summary: "Aria attacks", SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 10, EndUnitID: 10}},
|
||||
}}}
|
||||
}
|
||||
|
||||
func invariantDocument() *source.SourceDocument {
|
||||
return &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 10}, {ID: 20}}}
|
||||
}
|
||||
|
||||
func intPointer(value int) *int { return &value }
|
||||
|
||||
func withRef(turn dnd.CombatTurn, ref source.SourceRef) dnd.CombatTurn {
|
||||
turn.SourceRefs = []source.SourceRef{ref}
|
||||
return turn
|
||||
}
|
||||
Reference in New Issue
Block a user