Files
notarius/docs/roadmap/audit/10-equivalence.md

26 KiB
Raw Blame History

Behavioral Equivalence And Shared Abstraction Audit

Baseline And Method

Reviewed revision ee94d7902571117e9dea654b6c207544a19c979b on 2026-11-24. Production code and tests are unchanged from the preceding audits. This pass adds only this report; it changes no production code or tests.

The review started with tests: direct comparisons, round trips, mutation/isolation checks, and separate assertions of the same transformations or failure rules. Code-graph discovery, source inspection, and caller tracing then established whether the corresponding implementations independently own a common mechanism. Matching names, similar interfaces, and repeated test setup were not sufficient evidence for a finding. Existing shared implementations were checked before recommending another abstraction.

The review applied the testing, architecture, and agent policies. In particular, tests are evidence of behavior, not independent authority to invent a requirement. The accepted reconciliation boundary, native producer/assessment boundary, and configuration ownership decisions support the shared responsibilities described below.

Scope included configuration/runtime conversion, pipeline and CLI reference selection, prepared-input ownership, native result handling, registry resolution, registry reconciliation, deterministic normalization, codecs, source-reference helpers, and representative assembled workflows. This is a risk-directed audit, not an exhaustive proof of equivalence across every package or configuration.

Current Architecture

Notarius retains its fixed typed pipeline:

input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output

The CLI owns application composition and physical publication. The framework owns typed preparation, complete assessment, native producer coordination, ready-job scheduling, generated handoffs, and accepted-result reuse. Artifact families own identity, interpretation, domain validation, normalization policy, and durable codecs. ConfigKit, PromptKit, CommandKit, and ReleaseKit retain their selected native responsibilities; assets remain content-only.

Several important abstractions already exist: RunProducer, AssessProducer, FinishProducerFailure, source indexes/reference ordering, typed reconciliation preparation/application, candidate JSON encoding, diagnostic collection, and the immutable registry resolver. The remaining opportunities concern common work around those boundaries, not replacement of the architecture.

Findings Summary

Priority expresses relative refactoring value, not a new runtime severity score. Five opportunities have supporting tests and corresponding duplicated logic.

ID Priority Common responsibility Recommended boundary
EQ-001 High Registry reconciliation operation lifecycle Small typed lifecycle support beside the existing reconciliation core.
EQ-002 Medium Stable exact-duplicate group bookkeeping Pure D&D helper; family-owned eligibility, identity, ordering, and output.
EQ-003 Medium Detached copies of pipeline-owned values Pure copying in the package owning those values, separate from normalization.
EQ-004 High Structural pipeline interpretation and selected target inventory Pipeline-owned layout/selection helpers used by configuration and CLI callers.
EQ-005 Low Native-result usability before interpretation One small framework check, retaining separate caller outcomes.

EQ-001, EQ-003, and EQ-004 substantiate CPLX-004, CPLX-007, and CPLX-003 in the complexity audit with test-level evidence. They are the same work opportunities, not additional independent defects. EQ-005 is best considered alongside ERR-001 from the error-handling audit.

EQ-001 — Registry Normalizers Repeat One Reconciliation Lifecycle

Evidence

The NPC and location TestNativeCorrectionPreservesFixedHistoryAndAssessesEachRevision tests, and item TestNativeNormalizationReassessesRevisionsAndUsesOnlyTheFinalProposal independently establish the same lifecycle:

  • Retain original records and fixed evidence across revisions.
  • Apply each complete proposal afresh; do not accumulate earlier safe groups.
  • Reassess each usable revision, including unchanged candidates.
  • Preserve explicit native model/profile/session selections and conversation.
  • Disclose permissive fallback and exclude it from reuse.

The location native-failure matrix and corresponding NPC/item native execution suites additionally prohibit recovering an earlier proposal after a failed response. Preparation-limit tests for NPCs, locations, and items all require zero model/ordinary-assessment calls for preparation-limit failure and the same strict/permissive terminal decision. Cancellation tests in those suites require cancellation rather than fallback.

These requirements are also explicit in ADRs 0013 and 0022. This is not an inference that similarly named entities have the same identity rules.

Implementation

The Normalize methods for NPCs, locations, and items are near-identical 127–133-line operation bodies. Each independently retains merged versus deterministic originals, tracks current findings/omissions, builds fallback and finish closures, handles no-model/preparation dispositions, records the same evidence envelopes, decodes/assesses proposals, builds correction requests, and delegates execution to pipeline.RunProducer.

The existing semanticreconcile core already shares proposal safety and typed application, while RunProducer already shares native iteration. The duplication is the reconciliation-specific operation glue between those abstractions.

Opportunity And Remediation Approach

Factor that operation glue into a small typed helper beside the existing reconciliation mechanism. Give one owner to fixed preparation, native request and proposal bookkeeping, evidence recording, current-proposal replacement, and disposition handoff. Continue using RunProducer, AssessProducer, and FinishProducerFailure; introduce no additional execution or retry engine.

Family adapters should supply preprocessing, cloning, typed proposal application, fallback validity, prompt selection, and domain diagnostic construction. Return current-proposal omission/application information explicitly rather than making three modules maintain parallel mutable closure state. Keep domain diagnostic types out of the domain-neutral framework; a D&D-local adapter may translate the neutral result into existing findings.

This is a useful extraction of a demonstrated repeated lifecycle, not a reason to design a general normalization plugin framework. A few typed callbacks or a small operation value are sufficient if they make the call sites clearer.

Tradeoffs And Test Independence

Item reconciliation has additional currency-denomination compatibility, rejected group accounting, guidance, and advisory findings. Locations retain same-name places at distinct evidence anchors; NPCs have their own canonical-name policy. Those differences remain in family code. Shared mechanics must not make all domains collapse equal labels or use one fallback-validity rule.

The main risk is replacing three readable procedures with an overly configurable callback framework. Extract the proven common lifecycle, not all record logic. Keep representative tests in each family using literal expected domain values, including item currency and same-name location cases. Common lifecycle tests can own the transition matrix, but family tests must still prove correct adaptation; do not compute expected artifacts with the helper being tested.

EQ-002 — Exact-Duplicate Collapse Repeats Stable Group Bookkeeping

Evidence

TestNormalizeOrdersAndCollapsesExactDuplicatesOnly, TestNormalizeKeepsSameNamedIDsAndDistinctEvidence, and the combat normalizer tests establish the same mechanical requirement: collapse eligible exact duplicates, retain distinct identity/evidence/kind values, preserve ineligible references, and report removed original input indices. The spell duplicate-group test also requires retaining the first representative after canonicalization and accounting for removed groups without rewriting the retained caster text.

These tests do not establish one common definition of entity/event identity or one global sort order. For example, TestNormalizePreservesStableOrderForEqualEvidencePositions protects combat's stable ties, while occurrence tests exercise category-specific ordering. They support sharing grouping mechanics after family preparation.

Implementation

collapseDuplicates in NPC occurrences, location occurrences, and combat turns repeats the same keep mask, key-to-group index, first representative, removed-index list, output traversal, and diagnostic-group traversal. The spell collapseDuplicateSpellCasts adds a no-removal fast path around essentially the same grouping.

Item occurrences have related bookkeeping but deliberately use key buckets plus CanonicalExactEqual, rather than trusting a key alone. The item model equality tests distinguish canonicalization-aware versus already-canonical comparison and preserve optional quantity/evidence differences.

Opportunity And Remediation Approach

Introduce one pure helper under the existing D&D shared area that computes kept record positions and duplicate groups from caller-supplied eligibility/keys. Keep it unaware of domain structs, diagnostic prose, source parsing, and model execution. Callers retain their preprocessing, ordering, record cloning, and mapping from record positions to original input indices.

Start with NPC occurrences, location occurrences, and combat turns, where the grouping loops match directly. Include spells if its allocation/nil behavior can remain outside the helper. Item occurrences should participate only if the helper preserves the explicit equality check within each key bucket; leaving that one variant local is preferable to weakening equality or overcomplicating all callers.

Tradeoffs And Test Independence

A generic grouping helper reduces repeated index-accounting code but must not grow into one universal event normalizer. Preserve the domain-owned eligibility and exact keys, nil versus present-empty representations, original-index diagnostics, and each family's output cloning. Do not merge overlapping or adjacent evidence merely because it is convenient for deduplication.

There are intentional pre-grouping differences: NPC occurrences reject unknown or mismatched registry identities, while location occurrences retain unknown values with advisories and canonicalize known names. Combat and spells have different matching and ordering policies. Preserve these differences.

Keep the existing package-level output tests and independent expected records; test the shared grouping helper with small controlled keys/eligibility, not domain normalizers as its oracle. A wholesale replacement of all family tests by one parameterized conformance harness would lose useful independent protection.

EQ-003 — Configuration And Pipeline Boundaries Independently Copy The Same Values

Evidence

TestEffectiveConfigAndResolutionInputsDoNotAliasSource mutates both effective configuration and resolved pipeline options/references and requires the source configuration to remain unchanged. TestLoadedConfigOwnsRuntimeValuesAndKeepsFrozenInspection requires independent runtime copies and unchanged frozen inspection.

At framework boundaries, TestValidatorChainRegistryReturnsDefensiveCopies and TestOutputProfileValidationReceivesOwnedOptionsAndLaneIDs require the same ownership property for module bindings and nested options. These tests establish a common detached-value requirement for the pipeline-owned data, rather than merely similar function signatures.

Implementation

Configuration copying implements its own recursive pipeline/step/lane/binding/reference/validator-option tree. Framework copying in validator_chain_registry.go, profile.go, and prepared value construction independently traverses the same types and mutable fields.

The implementations are not interchangeable today: framework cloneModuleBinding also trims module/profile names, while configuration copying preserves them. Option switches differ too: framework copying explicitly handles []string, []byte, and json.RawMessage; configuration copying handles maps and []any. The inspected ownership tests establish the overlapping nested-value contract, not that every extra container is already guaranteed at every boundary.

Opportunity And Remediation Approach

Give pipeline-owned values one pure copying implementation in pipeline, usable by configuration conversion and framework callers. Small clone methods/functions for the existing types are sufficient. Separate identifier normalization from copying and make existing trimming explicit where resolution requires it. Keep configuration-only scalar/root copying in config.

Inventory the currently supported mutable option representations before unifying the two switches. Preserve established representations and omission/explicit-zero controls; do not turn the extraction into an arbitrary reflection deep copier or silently expand/restrict the option contract. This factors runtime value ownership, not ConfigKit's frozen-result/provenance machinery.

Tradeoffs And Test Independence

Exporting a small internal-package copy API adds a dependency surface, but config already imports the package that owns these types. This is preferable to moving pipeline types into configuration or creating another generic data model. Calling the current normalizing clone directly would be an incorrect shortcut because inspection/source values can change under apparent copying. Source profiles and resolved pipelines remain different types; share their common binding/reference/options subtrees rather than converting one model into another.

Retain mutation-based tests at both runtime conversion and framework boundaries, with independently constructed source values. Sharing implementation does not make those boundary tests redundant. Keep source-metadata validation, native evidence copying, and domain record cloning separate: their accepted values and failure semantics differ.

EQ-004 — Configuration, Runtime Resolution, And CLI Reference Selection Reinterpret Composition

Evidence

TestValidateIdentifiersAfterTrimming requires canonical nonblank/unique lane and reference identities. Runtime resolver tests independently require normalized identity handling, deterministic lane selection, ordered-step interpretation, and selected-lane reference completeness.

TestReferenceSelectorsRejectInvalidOrUnselectedScopesBeforeMaterialization requires CLI selectors to operate on that same selected composition before file access. TestReferenceTargetLookupUsesArtifactVariantsAndReportsMissingContext requires lane-kind-specific merger/normalizer slots; framework TestResolveTypedHeterogeneousLanes and TestResolveTypedLaneRejectsIncompatibleComposition require the corresponding artifact-kind-specific module selection and failures.

Together these tests imply that reference expansion and execution must select the same application composition. They do not imply identical diagnostic strings or equal validation depth at loading, selection, and full runtime resolution.

Implementation

config.validatePipelineProfiles constructs implicit steps and checks step/lane identities. pipeline.ResolvePipeline does those operations again, selects lanes, applies module defaults, and resolves kind-specific variants. cli.selectedReferenceTargets again flattens/selects lanes, applies defaults, and looks up extractor/merger/ normalizer variants solely to discover reference slots.

There are already smaller helpers such as selectedArtifactLanes, but the CLI does not consume one authoritative selected-target inventory. Changing a module default or layout rule still requires coordinated edits to separate traversals.

Opportunity And Remediation Approach

Extract a pure pipeline-layout operation for the common runtime-value structural rules, and a separate catalog-aware selected-target inventory for module choices, artifact kinds, and reference slots. Let runtime resolution and CLI expansion consume these results rather than independently reconstruct them. Configuration validation can reuse the catalog-independent portion and add its own path context.

Keep CLI selector parsing, specificity, bind/unbind actions, and invocation-relative paths in the CLI. Keep capability flow, complete typed compatibility, required reference satisfaction, validator resolution, and generated dependency validation at their existing later boundaries. Share choices, not every validation phase.

Tradeoffs And Test Independence

The CLI needs the inventory before its reference overrides have satisfied required slots. Calling the complete resolver there would be circular or reject a legitimate invocation too early. Likewise, configuration loading need not acquire a full production catalog merely to validate structural fields.

Raw-document presence and source-path diagnostics remain distinct. For example, document shape tests can distinguish an explicitly present empty artifacts field from absence; a decoded value alone cannot recover all those facts. Do not replace ConfigKit composition/presence handling with a new application loader, erase useful source diagnostics, add identifier restrictions, or change supported selection behavior.

Retain independent CLI mapping and framework resolution tests. A small differential test using a test catalog may check that CLI expansion and execution select the same targets, but each owner still needs literal expected examples; comparing two callers of one helper is not an independent correctness oracle. This refactor has high value but needs more care than the local grouping extraction.

EQ-005 — Producers And An LLM Validator Duplicate The Native Usability Gate

Evidence

TestNativeProducerDoesNotInterpretFailedNativeValidation requires both initial and correction responses with failed native validation to remain uninterpreted and unassessed. The combat validator's TestNilErrorFailedNativeValidationCannotBecomeApproval explicitly constructs a failed native validation result with nil Go error and requires no semantic approval or corrective guidance.

These tests support the common rule that native call completion alone does not make its output usable. They do not equate producer fallback with validator unavailability. The validator test's current ErrValidation sentinel assertion is the category problem already identified in ERR-001/TEST-003, not a requirement to preserve during consolidation.

Implementation

RunProducer's evaluator and combat_semantics.Validator.Validate independently check nil result, ValidationFailed, and IsValid before interpreting native content. Both substitute generic text and promptkit.ErrValidation for a completed failed check, losing available content-check details and conflating that outcome with the native operational category.

Opportunity And Remediation Approach

When addressing ERR-001, give the usability check and descriptive nonacceptance construction one small framework owner beside the existing native helpers. Keep the native RunResult and validation details as the input; distinguish an absent result from a present failed check and preserve actual native Go causes. Callers retain their contextual wrapping and terminal behavior. A new execution interface or package is unnecessary for this small shared check.

Tradeoffs And Test Independence

This is a low-cost adjunct to the known diagnostic fix, not justification for another native adapter layer. Do not put semantic acceptance, capture terminalization, cancellation precedence, or continuation policy into the helper. In particular, do not route the validator through producer semantic retries: validators still execute once per assessment and report unavailability separately.

Keep producer and validator tests asserting their distinct outcomes. Shared helper tests can cover native result states and retained details, while each caller test proves that failed output never reaches its domain interpreter. Do not make both tests derive expected categories/messages by calling the helper.

Scope Limits And Existing Abstractions

No further abstraction is recommended merely because multiple codecs round-trip, multiple validators reject malformed input, or command aliases accept the same arguments. Inspected candidate JSON and registry caching mechanics already use shared helpers. Shared source ordering/matching and diagnostics also have real owners; their use by several families is not missing consolidation.

The review specifically avoids unifying all normalizers, registry identity rules, schema and semantic validation, source metadata and option copying, or producer and validator outcomes. Native kit ownership and typed stage boundaries remain unchanged. Shared test fixtures are useful only where they reduce setup without making expected results depend on the same implementation as actual results.

No new runtime defect is claimed by this report. Existing findings remain open; the opportunities above should be coordinated with their remediation rather than implemented as competing abstractions. The strongest next candidates are the registry lifecycle and composition inventory, with pure copying/grouping offering smaller independent refactors.

Validation

The following fresh offline checks passed with Go 1.27.0 and cached declared dependencies:

GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \
  ./internal/core/config ./internal/framework/pipeline \
  ./internal/framework/semanticreconcile ./internal/modules/dnd/normalize/... \
  ./internal/modules/dnd/shared/... \
  ./internal/modules/dnd/validate/scenedescriptions/combat_semantics \
  ./internal/modules/integration

GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \
  ./internal/cli \
  -run '^(TestReference|TestPipelineScopedCLIReference|TestCLIReference|TestNativeConfiguration)'

GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \
  ./internal/modules/dnd/itemoccurrences ./internal/modules/dnd/npcoccurrences \
  ./internal/modules/dnd/codec/candidatejson \
  ./internal/modules/dnd/npcs/registry ./internal/modules/dnd/items/registry \
  ./internal/modules/dnd/locations/registry \
  ./internal/modules/dnd/scenedescriptions/registry

GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \
  ./internal/cli \
  -run '^(TestCompleteDNDSharedCLIReferencesExpandAcrossCompatibleTargets|TestExecutableRunRoutesDeclareTheSameRequiredInputs)$'

The npcoccurrences model package has no separate test files; its consumers' tests provide the relevant exercised behavior. No credentials, live providers, paid calls, new tests, or production modifications were used. Test success confirms the inspected baseline expectations, not a proof that proposed refactors are equivalent. Future changes should retain those independent output/state assertions and add focused helper coverage where it provides distinct confidence.

The previous testing audit records the fresh full coverage suite at unchanged code; another coverage measurement was unnecessary for this audit's architectural question. Local report links and the final diff are checked before committing.