From 28e54fb657e7915dd79f8b09bfde0636847ede1a Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 30 Nov 2026 21:24:52 +0000 Subject: [PATCH] Record behavioral equivalence audit findings --- docs/roadmap/audit/10-equivalence.md | 366 +++++++++++++++++++++++++++ 1 file changed, 366 insertions(+) create mode 100644 docs/roadmap/audit/10-equivalence.md diff --git a/docs/roadmap/audit/10-equivalence.md b/docs/roadmap/audit/10-equivalence.md new file mode 100644 index 0000000..16df16a --- /dev/null +++ b/docs/roadmap/audit/10-equivalence.md @@ -0,0 +1,366 @@ +# Behavioral Equivalence And Shared Abstraction Audit + +Reviewed: 2026-11-30 + +Baseline: `bca7cd7c3a263be75549fed7461bcb781e8c4d0f` + +## Scope And Evidence + +This audit followed direct comparison tests and separate tests expressing the +same behavior into their production implementations. It examined configuration +equivalence, preparation and resume, planning and execution, transcript +validation, downloads and replacement, artifact dependencies, checkpoints, and +downstream invocation contexts. Findings identify shared responsibilities worth +considering for consolidation; similar names, repeated assertions, or matching +results alone were insufficient. + +Codebase-memory-mcp supplied symbol discovery, source snippets, and call +relationships. Direct source inspection supplemented incomplete indexing of +same-named Go receiver methods. Recommendations were checked against the +[architecture](../../policy/architecture.md), +[testing](../../policy/testing.md), and focused integration/internal documents. +Tests establish the particular equivalences described below, rather than +equivalence of entire packages or every failure path. + +These existing checks passed using Go 1.27.4 on Linux: + +- `go test -count=1 ./...` +- `go vet ./...` +- `go test -count=1 ./internal/doccheck` after writing this report. + +No production code or tests were changed. No new tests, benchmarks, live +downstream applications, paid APIs, or remote storage services were used. + +## Current Architecture + +Narratio is a fixed-stage Go orchestrator: +`prepare → transcribe → merge → polish → normalize → trim → render → extract → analyze → publish → notify → cleanup`. +The notification stage currently uses the no-op mode. CommandKit owns CLI +execution and ConfigKit owns configuration resolution; Narratio validates and +derives its application-specific configuration after that handoff. + +Application orchestration owns invocation/session locking, planning, execution, +and restore. Stages own domain decisions and use adapter contracts for WhisperX, +Seriatim, Audita, Notarius, Scriptorium, and object storage. Manifest persistence +and the shared stage checkpoint helper retain durable progress. Artifact +services own identities and resolution; narrow file helpers own replacement and +bounded reads. Publication selects immutable remote snapshots, and restore +verifies their contents before installing manifest authority last. + +The opportunities below fit these existing boundaries. None requires a generic +workflow engine, a public reusable library, or a new compatibility layer. + +## EQ-01 — P3: Four boundaries repeat the same minimal transcript-shape validator + +Status: Open + +### Evidence + +- [Seriatim adapter tests](../../../internal/adapters/seriatim/subprocess_test.go): + `TestSubprocessRunnerNormalizeOutputMissingSegmentsFails` (line 472) and + `TestSubprocessRunnerTrimOutputMissingSegmentsFails` (line 331) reject a + successful command's JSON output when its top-level `segments` is missing. +- [Audita adapter tests](../../../internal/adapters/audita/subprocess_test.go): + `TestSubprocessRunnerRejectsMissingOrMalformedTranscript` (line 116) rejects + absent output and `{"segments":"wrong"}` after a successful subprocess. +- [Artifact resolution tests](../../../internal/artifacts/artifact_resolver_test.go): + `TestResolveSessionArtifactValidatesTranscriptShape` (line 255) rejects + manifest-backed polished JSON containing `not_segments` instead of `segments`. +- [Normalize stage tests](../../../internal/stage/normalize_test.go): + `TestNormalizeStageFailsWhenProcessedTranscriptMissingSegments` (line 82), + together with the corresponding trim and analyze stage tests, verifies that + downstream consumers also reject that shape. These consumers reach the shared + artifact resolver; they are not additional independent implementations. + +Together these tests support a common, deliberately minimal envelope rule: +the transcript is JSON with a top-level `segments` array. They do not establish +a universal schema for every JSON product or the contents of each segment. + +### Implementation + +Four functions independently unmarshal into `map[string]any`, require the +`segments` member, and assert `[]any`: + +- [Seriatim](../../../internal/adapters/seriatim/subprocess.go): + `validateJSONFileWithSegments`, lines 656–675. +- [Audita](../../../internal/adapters/audita/subprocess.go): + `validateProcessedOutput`, lines 201–218. +- [Stages](../../../internal/stage/polish.go): + `validateProcessedTranscriptOutput`, lines 171–192. +- [Artifact resolution](../../../internal/artifacts/artifact_resolver.go): + `validateTranscriptSegmentsJSON`, lines 394–411. + +Their surrounding file checks, bounded readers, and diagnostic labels differ. +The duplicated responsibility is the in-memory envelope predicate. + +### Opportunity And Remediation Options + +Prefer a small byte-oriented validator in the existing +`internal/contracts` package. Each boundary can retain its file acquisition and +contextual errors and delegate the common shape check. This gives one owner to +an acceptance rule shared by producers and consumers without coupling adapters +to stages or artifact persistence. + +A viable smaller alternative is to consolidate the adapter validators first +and leave consumer validation local. That reduces some duplication with a +smaller change, but leaves multiple owners of the same envelope rule. + +### Tradeoffs + +A defect in the shared predicate would affect every consumer. Keep independent +literal valid/invalid fixtures and representative tests at each integration +boundary; deriving expected acceptance through the new validator would weaken +those tests. Boundary validation remains useful even when its predicate is +shared. + +Keep size limits, filesystem eligibility, and adapter-specific reporting at +their current owners. Preserve the minimal acceptance rule, including empty +arrays and unrelated JSON members. Seriatim's generic JSON validation and the +stricter segment-ID checks used for session bounds serve different contracts +and remain distinct. Consolidation does not justify imposing IDs, nonempty +segments, or one downstream schema on all transcripts. + +## EQ-02 — P3: Verified downloads duplicate sibling temporary-file ownership + +Status: Open + +### Evidence + +- [Audio materialization tests](../../../internal/audio/s3_audio_test.go): + `TestMaterializeS3AudioFailedDownloadPreservesDestination` (line 71) checks + that an invalid download leaves the old destination intact, removes temporary + debris, and permits a successful retry. `TestMaterializeS3AudioUsesVerifiedPreparedCopy` + checks the installed bytes and the absence of extra files after success. +- [Restore tests](../../../internal/app/restore_commit_test.go): + `TestCommittedRestoreRejectsChangedDeclaredObjectBeforeManifestInstall` + (line 297) rejects a changed ordinary product before manifest installation. + [Restore execution tests](../../../internal/app/restore_execution_test.go), + `TestExecuteRestorePlanInvalidManifestDoesNotCorruptExistingManifest` + (line 497), preserve existing manifest bytes after downloaded content fails + manifest validation. Earlier ordinary products remain installed, confirming + that this is per-file replacement rather than whole-restore rollback. +- [Previous-session preparation tests](../../../internal/stage/prepare_previous_test.go): + `TestHydratePreviousSessionArtifactsDownloadsManifestAndRequiredArtifact` + (line 21) verifies installation and manifest input registration through the + third implementation. It does not independently cover every failed-write + cleanup branch. +- [File operation tests](../../../internal/fileops/fileops_test.go): + `TestReplaceFileAtomicCancellationPreservesDestinationAndCleansTemp` + (line 49) independently establishes the existing lower-level replacement + behavior when a caller's final check rejects installation. + +The common responsibility is staging a complete file separately from its +canonical destination so caller-specific validation can precede replacement. +The tests cover different rejection points; they do not prove identical +validation rules or complete failure-path coverage across all three domains. + +### Implementation + +- [Audio](../../../internal/audio/s3_audio.go): `writeAudioTemp`, lines 121–147. +- [Previous-session preparation](../../../internal/stage/prepare_previous.go): + `writePreviousTemp`, lines 111–137. +- [Ordinary restore](../../../internal/app/restore_execute.go): + `downloadRestoreTemp`, lines 254–280. + +Each checks its arguments, ensures the destination directory, creates a sibling +temporary file, invokes an `io.Writer` callback, closes the file, removes it on +handled write/close failure, and transfers the closed path to its caller on +success. Callers then validate and install it or remove it. The implementations +are nearly identical apart from error context. + +Audio restore already calls `audio.MaterializeS3Audio`; it is not a fourth +independent downloader. Its outer staging step permits committed-object +verification before canonical audio replacement. + +### Opportunity And Remediation Options + +Prefer one small closed-sibling-temp writer in `internal/fileops`, with explicit +ownership transfer on success. Keep download selection, validation, cancellation, +and installation in the existing callers. This replaces three copies of an +error-sensitive resource lifecycle while retaining their sequencing. + +An alternative is a narrow scoped helper that supplies a closed temporary path +to a caller operation and owns its cleanup throughout. That can reduce deferred +cleanup repetition, but makes the callback boundary larger. The closed-path +helper is the less intrusive starting point. + +### Tradeoffs + +`WriteReaderAtomicWithChecksum` is not a direct replacement: it installs the +file before a caller can validate its complete downloaded contents. The +existing `InstallSiblingTempFile` already provides the shared installation +half. Restore also has root-scoped destination checks and manifest rebasing; +previous-session objects have committed identities; audio has its own reuse +and nonempty/size rules. Those responsibilities remain separate. + +Preserve domain-level tests for rejection, retained destinations, and retry; +shared helper tests alone would not prove correct integration. Keep the helper +limited to ordinary file mechanics. A download framework, transaction manager, +platform emulation layer, or stronger crash-durability guarantee would exceed +the demonstrated need. The existing transfer-size issue remains separately +recorded as RS-02 in the [resource audit](05-resources.md). + +## EQ-03 — P3: Configured-artifact dependency mechanics have multiple owners + +Status: Open + +### Evidence + +- [Configuration dependency tests](../../../internal/config/artifact_dependencies_test.go): + `TestArtifactDependencyResolutionUnionsNormalizesAndIsIdempotent` verifies + sorted, deduplicated explicit and inferred dependencies. + `TestExplicitAndInferredDependencyGraphsHaveEqualDigests` directly compares + semantically equivalent authored graphs. `TestInferredArtifactDependencyDiagnosticsPointToInputs` + checks unknown/self/cyclic dependencies and source-oriented diagnostics. +- [Fingerprint tests](../../../internal/stage/analyze_fingerprint_test.go): + `TestComputeAnalyzeFingerprintsOrdersDependenciesAndRejectsInvalidGraphs` + checks dependency-first ordering and rejection of unknown edges and cycles. +- [Work planner tests](../../../internal/stage/analyze_plan_test.go): + `TestPlanAnalyzeWorkRejectsUnknownSelectionAndInvalidGraphs` repeats the + graph-validity requirement. `TestPlanAnalyzeWorkOrderIsDeterministicAcrossMapInsertion` + independently expects `alpha, middle, zeta`, and + `TestPlanAnalyzeWorkSelectionAndDependencyClosure` distinguishes explicit + targets, disabled prerequisites, reuse, and force. +- [Execution tests](../../../internal/stage/analyze_test.go): + `TestAnalyzeRunsDependenciesBeforeDependents` checks that inferred input edges + result in producer-first Scriptorium calls and the correct dependent input. + +These tests establish one configured-artifact dependency relation across +authored configuration, fingerprints, planning, and execution. The validity +tests alone do not demonstrate independent validators: planning and +fingerprinting already call the configuration validator. Source inspection +shows the additional independent normalization and traversal below. + +### Implementation + +[Configuration](../../../internal/config/artifact_dependencies.go), +`resolveArtifactDependencies`, derives the edge union and origin information. +[Validation](../../../internal/config/validate_scriptorium.go), +`ValidateScriptoriumArtifactDependencies` (line 265), rebuilds normalized +adjacency and traverses it with DFS. [Fingerprinting](../../../internal/stage/analyze_fingerprint.go), +`normalizedAnalyzeDependencyKeys` and `orderConfiguredAnalyzeArtifacts`, again +normalizes dependencies and builds adjacency/indegrees for heap-based ordering. +[Planning](../../../internal/stage/analyze_plan.go), `AnalyzeTargetClosure`, +traverses prerequisites and filters that full order. +[Invalidation](../../../internal/stage/analyze.go), +`staleAnalyzeDependentClosure`, independently constructs reverse adjacency. + +The edge union itself is already shared; the remaining duplication is its +graph mechanics and the interfaces exposing targets versus prerequisite work. + +### Opportunity And Remediation Options + +Prefer a small configured-artifact dependency view alongside the existing +derived `config.ArtifactCatalog`. Share validated adjacency, deterministic +ordering, prerequisite queries, and reverse-edge queries across consumers. +Retain origin information so configuration diagnostics identify authored +inputs or family declarations. Callers continue to decide force, reuse, +invalidation eligibility, and required previous inputs. + +A viable alternative is a lower-level internal artifact-graph package taking +plain keys/edges, with configuration translating errors back to their origins. +That gives a cleaner dependency boundary if needed, at the cost of another +representation and package. Reusing the existing catalog owner is the smaller +initial design. + +### Tradeoffs + +Target selection and prerequisite closure are intentionally different results: +force applies to explicit targets, while required disabled prerequisites can +be reused or rebuilt. Preserve both concepts. Raw configuration validation also +rejects empty dependencies, whereas runtime normalization currently skips +empty strings after validation; sharing normalization must preserve that +validation responsibility. Keep literal expected orders and independent +invalid-graph fixtures rather than computing test expectations through the +shared implementation. + +This is the test-grounded consolidation opportunity already identified as +CX-05 in the [complexity audit](03-complexity.md), not another defect count. +FC-01's omitted previous-input closure and EF-02's repeated reverse-index +construction illustrate the consequences of fragmented ownership. A shared +view can support their remediation, but does not itself decide those callers' +policies. The fixed pipeline-stage relation remains a separate domain. + +## EQ-04 — P3: Preparation and resume separately describe the same stable products + +Status: Open + +### Evidence + +- [Preparation tests](../../../internal/stage/prepare_test.go): + `TestPrepareStageMaterializesCanonicalPartyAndDerivedPlayers` (line 162) + checks canonical party/players bytes, distinct checksums and provenance, and + repeatability. `TestPrepareWritesVerifiedGlossaryDocuments` (line 797) + checks resolvable prepared glossary products and manifest records. +- [Resume tests](../../../internal/stage/prepare_resume_test.go): + `TestPrepareResumeDetectsCanonicalPartyChange` runs preparation, verifies + reuse, changes canonical party data, and verifies regeneration is needed. + `TestPrepareResumeValidatesCurrentLocalSourcesAndPreparedCopies` checks + reuse before changes and rejection after prepared glossary tampering. + `TestPrepareResumeRequiresAllGlossaryRecords` checks inventory completeness. + `TestCombinedGlossarySharesVerifiedReferenceAcrossRoles` verifies that the + combined glossary's declared dependencies survive persistence and that + omitting those dependencies prevents reuse. +- `TestPrepareResumeAcceptsRelocatedEquivalentSpeakerAndRosterSources`, in the + same file, requires reuse when source placement changes but content does not. + +These assembled tests require the materializer and read-only resume checker to +agree on which stable products exist, their effective content, and their +dependency evidence. They establish more than a coincidental checksum match. + +### Implementation + +[Preparation](../../../internal/stage/prepare.go), `prepareStage.Run`, and +[resume](../../../internal/stage/prepare_resume.go), `currentPrepareSourceInputs`, +separately enumerate campaign/session snapshots, speakers, autocorrection, +and five glossary products. Both repeat the named-glossary/source-ID mapping +and combined-glossary dependency construction. +[Party materialization](../../../internal/stage/prepare_party.go) and +`currentPreparePartySourceInputs` similarly obtain party and players bytes +through separate product descriptions. +[Semantic selection](../../../internal/stage/semantic_contracts_initial.go), +`prepareStableInputSemantics`, repeats the stable-kind inventory for presence +evidence. + +The underlying renderers, glossary composition, and prepared-input descriptors +are already shared. The opportunity is the remaining product inventory and +its projection into writes versus expected evidence, not a replacement for +those existing components. + +### Opportunity And Remediation Options + +Prefer a stage-owned description of stable prepared products derived from the +final Narratio configuration. Materialization can attach destinations and +write the described content; resume can calculate expected identities from +the same descriptions. Reuse the existing `artifactpolicy` descriptors for +source IDs, kinds, and filenames. Presence-only semantic selection can reuse +the relevant inventory without acquiring file contents. + +A smaller viable alternative is to start with just the five glossary mappings +and combined dependencies, then party/players content. This captures the most +obvious repeated definitions without introducing a generalized input registry. + +### Tradeoffs + +Keep construction read-only and keep effects in materialization. Snapshot +comparison deliberately ignores relocated source references; party, glossary, +and autocorrection products have their own content identities. Audio membership +and remote identities have different acquisition costs and remain separate. +Semantic fingerprinting retains its existing bounded selection role rather +than reading every input merely to share a helper. + +Preserve independent tests for expected products, corruption, and missing +records. Generating all test expectations from the shared inventory would let +an accidental omission pass both writer and reader tests. This finding refines +CX-02 in the [complexity audit](03-complexity.md). It fits within Narratio's +post-ConfigKit domain derivation boundary and requires no inspection of upstream +configuration-resolution internals. + +## Recommendation + +Consider EQ-01 and EQ-02 as focused helper extractions. Address EQ-03 and EQ-04 +with the corresponding existing audit workstreams so their overlapping changes +are designed and reviewed once. Keep representative consumer tests independent +of the shared implementation. Similar behavioral assertions at distinct +boundaries remain useful when they detect incorrect integration; sharing +production mechanics does not automatically make those tests redundant.