219 lines
7.5 KiB
Go
219 lines
7.5 KiB
Go
// 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 }
|