From af0baa03b536e2acc6b44ccfe93adae3fca04a5d Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Wed, 2 Dec 2026 20:01:13 +0000 Subject: [PATCH] Plan the remaining audit remediations --- docs/roadmap/implementation.md | 723 +++++++++++++++++++++++++++++++++ 1 file changed, 723 insertions(+) create mode 100644 docs/roadmap/implementation.md diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md new file mode 100644 index 0000000..3353bef --- /dev/null +++ b/docs/roadmap/implementation.md @@ -0,0 +1,723 @@ +# Remaining Audit Remediation: Implementation Plan + +Status: Pending + +Planning baseline: `21d4eeb`. Scope: the 25 open entries in the +[audit catalog](audit/catalog.md), CAT-16–28, CAT-31–33, and CAT-35–43. +The catalog owns findings, their original evidence links, and closure status. +Original audit reports remain historical evidence and are unchanged. + +## Execution Instructions + +This is one end-to-end sprint, divided into sequential Luna-sized prompts. +Implement Stage 1 onward in order. Intermediate stages may leave unresolved +imports, compilation failures, or incomplete cross-package wiring. Complete +each owning change's acceptance checks when its consumers are available; final +verification covers the whole repository. Stage boundaries do not require +compatibility wrappers, duplicate implementations, or intermediate migrations. + +Start with [Development](../development.md), then the agent, architecture, +testing, and documentation policies selected by its reading guide. Read each +stage's linked audit sections and named current files, not every audit report. +Use the original evidence for rationale, not as a literal patch against old +line numbers. Inspect current callers before deleting or changing an API. + +Update the catalog as findings actually close, with concise implementation and +test evidence and corrected counts. Mark each plan stage complete after its +acceptance criteria are verified. A finding spanning stages closes only after +all its assigned work passes. Commit completed, reviewable units with plain +English messages under agent policy. Pushing and releasing are separate tasks. + +### Scope And Preservation Decisions + +- Keep the fixed stage sequence and separate stage invalidation relation. + Dependency consolidation concerns configured artifacts only. +- Keep ConfigKit's authoritative handoff and native startup. Derived catalogs + and graphs are Narratio domain values, separate from immutable configuration. +- Keep actual product validation, local speaker/artifact checkpoints, supplied + product acceptance, import merging, reference-only preparation, publication + locks, pointer-last publication, and existing cleanup authorization. +- Preserve source selection, public command/report shapes, persisted metadata + keys and value meanings, fingerprint payloads, and existing file placement. + These findings call for internal consolidation and accurate documentation. +- Keep diagnostics and missing optional inputs distinct from control evidence + and required inputs. Shared mechanics do not unify different failure policies. +- Use existing owners where specified below. The small dependency-mechanics + package in Stage 6 resolves an actual import-cycle boundary. No generic + workflow, check registry, metadata framework, filesystem transaction layer, + new limits, or configuration restrictions are part of this sprint. +- Update affected canonical documentation with its implemented change. Correct + the remaining independent documentation findings in Stage 25. Link upstream + for library behavior instead of reproducing upstream manuals. + +### Current-Code Review And Adjusted Scope + +All 25 catalog entries still have actionable work at this baseline. Several +original descriptions need the following qualifications: + +| Findings | Verified current state and planning consequence | +| --- | --- | +| CAT-17–18 | `artifacts/dependencies.go` already owns closure, ordering, and normalization. Configuration still builds validation adjacency/DFS; analysis still rebuilds reverse edges. Consolidate the surviving implementations rather than redoing CAT-10. | +| CAT-17, CAT-19, CAT-27 | Analysis now stops historical traversal at supplied products; bounded preparation retains history for reused local checkpoints. Preserve these decisions and the distinct structural/default history collector. | +| CAT-19 | `PrepareReferences`, `Env.ReferenceOnly`, and `PreparePreviousRequirements` exist. Stable product rendering and resume inventories remain duplicated. Share those inventories without replacing the new reference-only workflow. | +| CAT-20–21 | Remote execution snapshots and their temporary upload file are gone. Publication metadata, extraction metadata, and surviving audio/history/restore staging still need consolidation. Do not recreate snapshot machinery. | +| CAT-27 | Preparation's source-matching code already has a kind/destination index. Leave it intact; previous-cache selection, prepared/previous input resolution, and optional-absence reporting still contain the audited scans. | +| CAT-36–37, CAT-40 | The twelve named orphan helpers, six constants, retired path fields, and test-only publish-default writer still exist. Graph results plus direct reference searches confirm their limited call relationships. Recheck at deletion time because earlier sprint stages may remove some. | +| CAT-38 | The four excluded fingerprint fields and nil-only generated extraction-evidence contract remain. Supplied-product and analysis/catalog contracts are live and stay. | +| CAT-39 | Manual cleaning still passes a directory boolean with a test-only file branch. Workspace-wide locking is already implemented and stays. | +| CAT-16, CAT-22–26, CAT-28, CAT-31–33, CAT-35, CAT-41–43 | Current aggregation, validators, adapter/stage boundaries, report scans, stale documentation, order-sensitive assertions, duplicate test, and unused assignment match the linked findings. No whole finding is closed merely by the recent import work. | + +## Coverage + +| Finding | Assigned stages | Disposition | +| --- | --- | --- | +| [CAT-16](audit/catalog.md#cat-16--p3-flatten-inspection-error-aggregation) | 1 | Implement | +| [CAT-17](audit/catalog.md#cat-17--p3-centralize-configured-artifact-dependency-queries) | 6–7 | Finish partially shared graph ownership | +| [CAT-18](audit/catalog.md#cat-18--p3-reuse-the-analysis-reverse-dependency-index-within-an-invocation) | 8 | Implement on shared graph | +| [CAT-19](audit/catalog.md#cat-19--p3-describe-stable-prepared-products-once-for-materialization-and-reuse) | 9–10 | Share surviving stable-product definitions | +| [CAT-20](audit/catalog.md#cat-20--p3-share-typed-publication-control-evidence-across-producer-and-consumers) | 11–12 | Type publication and extraction control fields | +| [CAT-21](audit/catalog.md#cat-21--p3-share-closed-sibling-temporary-file-creation-mechanics) | 13 | Consolidate surviving staged downloads | +| [CAT-22](audit/catalog.md#cat-22--p3-share-the-minimal-transcript-envelope-predicate) | 14 | Implement | +| [CAT-23](audit/catalog.md#cat-23--p3-move-notarius-native-output-mapping-and-executable-lookup-to-their-boundary) | 16 | Move protocol/launch ownership | +| [CAT-24](audit/catalog.md#cat-24--p3-separate-trimextract-invocation-phases-from-product-acceptance) | 17–18 | Split extraction and trim separately | +| [CAT-25](audit/catalog.md#cat-25--p3-separate-inspectionreadiness-collection-assessment-and-presentation) | 19–21 | Split pure interpretation, inspection, readiness | +| [CAT-26](audit/catalog.md#cat-26--p3-place-diagnostic-view-layout-grammar-with-canonical-workspace-paths) | 15 | Move views to existing path owner | +| [CAT-27](audit/catalog.md#cat-27--p3-index-repeated-previous-input-and-prepared-record-lookups) | 22–23 | Index remaining remote and local scans | +| [CAT-28](audit/catalog.md#cat-28--p3-index-restore-report-action-updates) | 24 | Implement | +| [CAT-31](audit/catalog.md#cat-31--p3-correct-annotated-example-dependency-credential-and-cleanup-claims) | 25 | Correct comments only | +| [CAT-32](audit/catalog.md#cat-32--p3-document-seriatim-reports-as-diagnostics) | 25 | Correct documentation only | +| [CAT-33](audit/catalog.md#cat-33--p3-align-credential-ownership-descriptions-with-native-configkit-startup) | 25 | Correct documentation only | +| [CAT-35](audit/catalog.md#cat-35--p3-remove-assertions-on-incidental-serialization-and-validation-order) | 2 | Relax incidental test assertions | +| [CAT-36](audit/catalog.md#cat-36--p3-remove-confirmed-orphaned-production-and-test-helpers) | 3 | Verify and remove listed remnants | +| [CAT-37](audit/catalog.md#cat-37--p3-remove-unused-constants-and-retired-workspace-path-fields) | 3 | Remove inert model elements | +| [CAT-38](audit/catalog.md#cat-38--p3-remove-inert-extraction-descriptor-fields-and-nil-only-plumbing) | 5 | Remove only nil/excluded generated-evidence fields | +| [CAT-39](audit/catalog.md#cat-39--p3-simplify-manual-clean-to-its-live-directory-only-contract) | 4 | Remove unreachable file mode | +| [CAT-40](audit/catalog.md#cat-40--p3-remove-the-superseded-publish-default-mutation-helper) | 3 | Remove obsolete writer, retain native defaults | +| [CAT-41](audit/catalog.md#cat-41--p3-remove-the-duplicate-normalized-transcript-test) | 2 | Retain one authority test | +| [CAT-42](audit/catalog.md#cat-42--p3-discard-the-unused-normalized-path-result-while-retaining-validation) | 3 | Discard value, retain confinement check | +| [CAT-43](audit/catalog.md#cat-43--p3-correct-the-logging-package-summary) | 25 | Correct GoDoc only | + +Stage 26 verifies integration and final catalog closure for all rows. + +## Stage 1: Flatten Publication Inspection Errors + +CAT IDs: CAT-16. Status: Pending. + +Read [EF-05](audit/02-efficiency.md#ef-05--p3-publication-inspection-errors-form-a-quadratic-formatting-tree) +and `internal/app/session_state_command.go` with its inspection tests. + +Replace repeated joining inside `inspectPublishedOutputs` with an ordered +`[]error` and one final `errors.Join`. Apply the same simple collection pattern +to the enclosing inspection's accumulation when it nests these results. Keep +partial reports and per-output error fields unchanged; do not short-circuit +independent inspections or change classification. + +Acceptance: multiple failed lookups retain all output rows, deterministic error +order and `errors.Is`/`errors.As` visibility, without a progressively nested +aggregate. Test observable partial results/causes; source review establishes the +single-join algorithm without timing thresholds or private tree-shape snapshots. + +Validation: `go test ./internal/app -run 'Test.*(Inspection|SessionState|PublishedOutput)'`. + +## Stage 2: Remove Incidental And Duplicate Test Constraints + +CAT IDs: CAT-35, CAT-41. Status: Pending. + +Read [TE-07](audit/08-testing.md#te-07--p3-some-assertions-freeze-incidental-serialization-or-validation-order) +and [TE-08](audit/08-testing.md#te-08--p3-two-normalized-transcript-tests-are-exact-duplicates). + +In `artifactmodel/metadata_test.go`, decode emitted JSON and assert member +names, values, and omissions structurally. Keep genuinely canonical fingerprint +and commit-byte tests unchanged. In `config/native_results_test.go`, make the +campaign fixture isolate its intended invalid field or locate the relevant +diagnostic without requiring its position. Retain native error/source context. +Remove one of the two identical normalized-source tests in +`stage/analyze_test.go`, retaining the manifest-authoritative file assertion. + +Acceptance: equivalent object-member/check ordering does not break these tests; +incorrect data, omitted required metadata, and actual invalid input still do. + +Validation: `go test ./internal/artifactmodel ./internal/config ./internal/stage`. + +## Stage 3: Remove Verified Orphans And Inert Model Elements + +CAT IDs: CAT-36, CAT-37, CAT-40, CAT-42. Status: Pending. + +Read [DD-01](audit/12-deadcode.md#dd-01--p3-completely-orphaned-helper-functions-remain-in-production-and-tests), +[DD-02](audit/12-deadcode.md#dd-02--p3-unused-constants-and-retired-workspace-paths-advertise-obsolete-concepts), +[DD-05](audit/12-deadcode.md#dd-05--p3-a-superseded-publish-default-mutation-helper-survives-only-in-a-no-op-test-call), +and [DD-06](audit/12-deadcode.md#dd-06--p3-input-hashing-stores-a-normalized-path-that-is-never-consumed). + +Recheck the source-listed declarations across production, tests, callbacks and +supported platform files, then remove: + +- production `resolveRegularFile`, `requireRegularFileTree`, `validateCleanRoot`, + `validatePathWithinRoot`, `NormalizedConfigurationPath`, `normalizedProvenancePath`; +- the six test helpers named in DD-01, with newly empty files/imports; +- the six unused constants in DD-02, `SessionPaths.ReportsDir`/`ConfigDir`, + their assignments, and their two otherwise unused directory constants; +- `applyMissingPublishDestinations` and its no-op test call, retaining the + native normalization/derivation path and explicit-destination assertions. + +In `hashAnalyzeInputFile`, discard the normalized return value using `_`, while +retaining the normalization call, its error handling, and actual file checks. +Do not add fallback behavior, delete workspace data, or introduce alias shims. + +Acceptance: only the named inert code is removed; active preparation-ordering, +bundle validation, path confinement, and explicit destination behavior remain. +Confirm source references rather than treating graph in-degree alone as proof. + +Validation: `go test ./internal/config ./internal/artifacts ./internal/app ./internal/stage ./internal/adapters/notarius`; `go vet ./...`. + +## Stage 4: Make Manual Clean Explicitly Directory-Oriented + +CAT IDs: CAT-39. Status: Pending. + +Read [DD-04](audit/12-deadcode.md#dd-04--p3-manual-cleaning-retains-a-file-target-mode-unavailable-through-its-cli). +Inspect `app/clean_command.go`, `clean.go`, `cleanup_targets.go`, and their tests. + +Use `validateScopedDir` as the one directory-validation entry point. Fold the +live logic from `validateScopedTarget` into it, remove `requireDir` forwarding, +the file-only branch, and `validateScopedFile`. Rewire manual command callers +and tests; remove tests only of the unsupported file mode. + +Acceptance: one-session and `--all` deletion retain existing root confinement, +symlink checks, missing-target behavior, dry runs, workspace lock waiting, and +deletion scope. General fileops and final-stage cleanup keep their contracts. + +Validation: `go test ./internal/app -run 'Test.*(Clean|Cleanup|Scoped|Lock)'`. + +## Stage 5: Remove Inert Extraction Descriptor Plumbing + +CAT IDs: CAT-38. Status: Pending. + +Read [DD-03](audit/12-deadcode.md#dd-03--p3-extraction-still-carries-descriptor-fields-that-the-current-model-discarded). +Inspect `stage/extract.go`, `artifacts/extraction_evidence.go`, +`extraction_catalog.go`, `catalog.go`, and supplied-product hydration. + +Remove `MediaType`, `SchemaID`, `SchemaVersion`, and `ModuleKey` from the +JSON-excluded part of `fingerprintOutput`. Remove the generated-only +`ExtractionEvidenceOutput.Contract` field and the nil-only argument/copy in +`markAvailableFromExtractManifest`. Keep shared catalog, supplied-product, +manifest and analysis contracts: imported contracts have actual producers. + +Acceptance: generated extraction fingerprint JSON/digests are unchanged; +supplied extraction metadata and configured-artifact contracts remain usable. +There is no schema version bump or newly required lane descriptor. + +Validation: `go test ./internal/artifacts ./internal/stage ./internal/config`. + +## Stage 6: Establish One Dependency-Mechanics Owner + +CAT IDs: CAT-17, foundation. Status: Pending. + +Read [CX-05](audit/03-complexity.md#cx-05--p3-artifact-dependency-semantics-span-several-representations-and-owners), +[EQ-03](audit/10-equivalence.md#eq-03--p3-configured-artifact-dependency-mechanics-have-multiple-owners), +and [BN-05](audit/11-boundaries.md#bn-05--p3-configured-artifact-graph-operations-are-fragmented-across-domain-owners). + +Create small `internal/artifactdeps`, depending on standard-library key/edge +values, with no imports of config, artifacts, stage, or manifest. This avoids +the current config→artifacts→config cycle that moving validation would create. +Use an immutable graph built from `map[string][]string`: canonical dependencies, +prerequisite-first deterministic order, target closure with explicit stop keys, +and a prebuilt reverse adjacency. Expose ordered dependent traversal with a +caller eligibility predicate; an ineligible node stops traversal through that +node, matching current analysis invalidation semantics. + +Use a small concrete API: `New(map[string][]string) (*Graph, error)`, +`Dependencies(key string) []string`, `Order() []string`, +`Prerequisites(targets []string, stop map[string]bool) ([]string, error)`, and +`Dependents(changed string, eligible func(string) bool) []string`. Returned +slices do not expose mutable graph storage. The closure includes stop keys but +does not follow their prerequisites. Return typed graph errors with failure +kind, node, and dependency so configuration can attach its existing origin. + +Keep key syntax, input-edge inference, family/member origin messages and +configuration errors in `internal/config`. Represent graph failures with +enough node/edge context for those existing domain diagnostics. Reject unknown +edges, self-edges and cycles as today; do not reinterpret invalid configuration +as acceptable because an output is supplied. Preserve sorted deterministic +ordering without freezing incidental diagnostic wording. + +Acceptance: one graph implementation can serve validation, prerequisites and +dependents, including supplied stop boundaries. Test a chain, diamond, +duplicates, invalid edges/cycles, stable ordering and eligibility barriers. + +Validation: `go test ./internal/artifactdeps ./internal/config` once wired. + +## Stage 7: Migrate Configured-Artifact Graph Consumers + +CAT IDs: CAT-17, completion. Status: Pending. + +Read Stage 6's linked sections and current `config/artifact_dependencies.go`, +`artifact_families.go`, `validate_scriptorium.go`, `artifacts/dependencies.go`, +`previous_requirements.go`, and `stage/analyze_{plan,fingerprint,resume}.go`. + +Attach the graph to the separately derived `config.ArtifactCatalog`, with +construction through its normal derivation path. Adapt validation to use the +same mechanics while retaining field-origin context. Domain entry points used +by programmatic tests may construct a graph from concrete definitions when no +derived graph is available; do so once per operation, not per artifact. +Update fixtures that replace or mutate derived artifact maps to rebuild their +graph through the same construction path. Do not add runtime graph-digest, +revision-counter, or stale-cache detection machinery for test-only mutation. + +Migrate closure, ordering and normalization wrappers to this owner; remove +duplicate DFS/topological algorithms. Preserve the explicit target set apart +from structural closure and actual work. Replace `planAnalyzeWork`'s copied +work graph with closure stop keys for validated supplied products, except +explicit forced targets. Keep ordinary local freshness and the separate +`PreviousArtifactRequirementsForKeys` path for planned/local prerequisite history. + +Acceptance: default/explicit/disabled prerequisite selection, inferred edges, +family origins, force, supplied reuse, and history hydration retain behavior. +Only mechanics are shared; no configurable stage DAG or new effective config. + +Validation: `go test ./internal/config ./internal/artifactdeps ./internal/artifacts ./internal/stage ./internal/app`. + +## Stage 8: Reuse Reverse Dependencies Throughout Analysis + +CAT IDs: CAT-18. Status: Pending. + +Read [EF-02](audit/02-efficiency.md#ef-02--p3-analysis-rebuilds-the-same-dependency-index-after-each-completion) +and `stage/analyze.go`, `analyze_execution_state.go`, and checkpoint tests. + +Carry the Stage 6 graph through `analyzeExecutionContext`/execution state and +use its reverse adjacency for success, failure, and unscheduled-dependent +invalidation. Remove per-completion reverse-map construction and sorting. +Reconciliation and resume may each have their own operation-owned graph; +there is no process-global cache of changing configuration. + +Acceptance: eligibility barriers, invalidation timing/order, partial failure +checkpoints, and unrelated current records remain intact. Review construction +placement to establish once-per-operation setup; behavioral tests need not +assert private constructor call counts or wall-clock performance. + +Validation: `go test ./internal/stage -run 'Test.*(Analyze|Checkpoint)'`. + +## Stage 9: Describe Stable Prepared Products Once + +CAT IDs: CAT-19, producer half. Status: Pending. + +Read [CX-02](audit/03-complexity.md#cx-02--p3-prepared-stable-inputs-have-parallel-materialization-and-resume-definitions) +and [EQ-04](audit/10-equivalence.md#eq-04--p3-preparation-and-resume-separately-describe-the-same-stable-products). + +Add a stage-private stable-product description containing existing kind, +canonical destination, rendered bytes or source-copy information, provenance, +and dependencies. Build it once per preparation operation using current +`artifactpolicy` prepared-source descriptors and existing renderers. +Include campaign/session snapshots, pipeline projection, speakers, +autocorrection, party, players, and all five glossary documents. Keep snapshots +distinguishable for their existing semantic normalization. + +Make `prepareInputs` and the party materialization helpers consume these values +instead of independently rebuilding write/register inventories. Audio copying +and previous-session hydration remain explicit subsequent phases. + +Acceptance: preparation emits the same bytes, paths, provenance/dependencies, +metadata and sorted input records, including in reference-only mode. Keep an +independent literal expected inventory in a behavioral test. + +Validation: `go test ./internal/stage -run 'Test.*Prepar'`. + +## Stage 10: Reuse Stable Descriptions For Resume And Semantics + +CAT IDs: CAT-19, completion. Status: Pending. + +Read Stage 9's audit links and `prepare_resume.go`, `semantic_contracts_initial.go`. + +Project expected source identities and managed-kind membership from the same +stable descriptions. Remove parallel party/glossary inventories and redundant +rendering definitions. Preserve the existing raw-copy versus normalized +campaign/session snapshot comparison and presence-only semantic selection. +Give descriptors explicit current-source comparison modes: ordinary source +bytes, normalized campaign/session snapshots, or durable-copy-only checks. +The pipeline projection retains its durable-copy check without comparing the +entire current effective configuration as a new preparation reuse key. +Semantic fingerprinting must not start reading large audio, loading otherwise +unused external vocabulary, or hashing all configuration. Share the appropriate +descriptor projection rather than calling full materialization from fingerprinting. + +Acceptance: unchanged and source-relocated equivalent inputs reuse; changed or +missing copies/sources rerun or fail as currently defined. Combined glossary +dependencies, absent/empty values, immutable ConfigKit results, imported +products and current local prerequisite history retain their distinctions. +The existing preparation matching index remains rather than being replaced by scans. + +Validation: `go test ./internal/stage ./internal/config ./internal/app`. + +## Stage 11: Type Publication Completion And Outcome Evidence + +CAT IDs: CAT-20, publication half. Status: Pending. + +Read [BN-03](audit/11-boundaries.md#bn-03--p3-machine-consumed-publication-metadata-lacks-a-shared-contract-owner) +and [CX-06](audit/03-complexity.md#cx-06--p3-unstructured-metadata-carries-cross-package-control-evidence). + +Place typed publication completion identity and output outcomes plus map codecs +in `internal/artifacts`, alongside publication identities. Cover the fields +consumed by cleanup and inspection: uploaded/skipped, producing run ID, commit +and pointer keys, and per-source outcome values. Keep free-form statistics and +diagnostic fields flexible. Preserve the current five outcome strings and JSON +layout, including both in-memory and decoded collection representations. + +Rewire `publishMetadata`, `publishOutputOutcomeMetadata`, +`validateCleanupPublishEvidence`, and `committedPublishOutputOutcomes` to use +the shared field/type vocabulary. Decode individual control fields with their +presence/type information; keep cleanup's strict authorization and app display's +tolerant omission policy at the callers. One invalid display row must not +silently become a stricter whole-report failure. + +Acceptance: direct and JSON-persisted evidence produce the same cleanup and +inspection decisions. Malformed/absent control evidence cannot authorize +cleanup, and no remote lookup or execution snapshot is introduced. + +Validation: `go test ./internal/artifacts ./internal/stage ./internal/app`. + +## Stage 12: Type Shared Extraction Control Evidence + +CAT IDs: CAT-20, extraction half/completion. Status: Pending. + +Read [CX-06](audit/03-complexity.md#cx-06--p3-unstructured-metadata-carries-cross-package-control-evidence) +and `stage/extract.go`, `extract_resume.go`, `artifacts/extraction_{input,evidence}.go`. + +Add narrow extraction metadata values/codecs under `internal/artifacts` for +machine-read fields: producing Narratio run, configuration fingerprint, direct +input identity, reference identities, and native completion identity/fallback +count. Keep existing keys, omissions and persisted shapes. Use these from the +producer, resume, evidence reader, and fallback reporting; leave incidental +diagnostic fields as ordinary metadata. Normalize already-supported in-memory +and decoded number/container representations in this shared boundary. + +Acceptance: valid direct and persisted metadata agree; absence/obsolete data, +unsafe product evidence, fallback reporting, and supplied extraction bypasses +retain their current policies. Do not reintroduce Stage 5's inert contracts, +require historical metadata for supplied products, or change fingerprint bytes. + +Validation: `go test ./internal/artifacts ./internal/stage ./internal/app`. + +## Stage 13: Share Closed Sibling-Temporary-File Creation + +CAT IDs: CAT-21. Status: Pending. + +Read [EQ-02](audit/10-equivalence.md#eq-02--p3-verified-downloads-duplicate-sibling-temporary-file-ownership). +Inspect `audio/s3_audio.go`, `stage/prepare_previous.go`, and +`app/restore_execute.go`, including the surviving extra-config download path. + +Add `fileops.WriteSiblingTemp(destination string, write func(io.Writer) error) +(string, error)`. It creates a sibling temporary file, runs the writer, closes +it, and removes it on write/close failure, preserving joined causes. Successful +return transfers ownership of the closed temporary path to the caller. +Callers immediately arrange removal, then perform their existing domain +validation and installation with existing modes. Use existing directory/mode +helpers; retain caller root confinement before creation and before installation. + +Migrate the three download families and any same-mechanic config-download +variant. Do not use this helper to replace validation-before-installation with +an unconditional atomic copy. Keep transfer bounds, observed generations, +cancellation and publication-source lifetimes where they currently belong. + +Acceptance: successful files are closed and caller-owned; callback failures +remove only the temporary file, leave canonical targets intact, and retain +causes. Representative consumer failure/retry tests still pass. No fsync, +whole-workspace rollback, new size limit, or remote checkpoint feature is added. + +Validation: `go test ./internal/fileops ./internal/audio ./internal/stage ./internal/app`. + +## Stage 14: Share The Minimal Transcript Envelope Validator + +CAT IDs: CAT-22. Status: Pending. + +Read [EQ-01](audit/10-equivalence.md#eq-01--p3-four-boundaries-repeat-the-same-minimal-transcript-shape-validator). + +Add `contracts.ValidateTranscriptEnvelope([]byte) error` for JSON whose root is +an object with an array-valued `segments`. Rewire the Seriatim +`validateJSONFileWithSegments`, Audita `validateProcessedOutput`, stage +`validateProcessedTranscriptOutput`, and artifact `validateTranscriptSegmentsJSON` +predicates to it. Keep file acquisition, bounds, eligibility and contextual +failure messages at each boundary. Generic JSON and bounds-specific segment-ID +validation remain separate. + +Acceptance: malformed JSON, absent/null/non-array segments and invalid root +shapes fail; empty arrays and unrelated members remain accepted. Retain literal +fixtures and representative adapter/consumer tests, not expectations calculated +by calling the new validator. No universal segment schema is introduced. + +Validation: `go test ./internal/contracts ./internal/adapters/seriatim ./internal/adapters/audita ./internal/artifacts ./internal/stage`. + +## Stage 15: Move Attempt Views To The Workspace Path Owner + +CAT IDs: CAT-26. Status: Pending. + +Read [BN-01](audit/11-boundaries.md#bn-01--p3-diagnostic-view-layout-policy-is-embedded-in-file-operation-mechanics). + +Move `AttemptViews`, begin/revert, managed-view inspection/removal, and the +run/stage/probe target grammar from `fileops/attempt_views.go` into artifacts. +Use `SessionPaths` and its canonical path helpers to construct those targets. +Keep ordinary confined directory creation and generic replacement/removal +mechanics in fileops; artifacts may call those mechanics. Rewire app, stage, +restore, cleanup, and probe callers and move the relevant unit tests. + +Acceptance: fileops no longer knows Narratio's runs/stages/probe grammar; +latest logs/debug advancement, failed-attempt visibility, self-skip reversion, +read-only reuse, recognized-link cleanup and confinement remain unchanged. +The runner still owns when to advance/revert and cleanup owns deletion policy. +Do not create a new workspace package or general symlink framework. + +Validation: `go test ./internal/fileops ./internal/artifacts ./internal/stage ./internal/app`. + +## Stage 16: Put Notarius Native Mapping And Launch Resolution In Its Adapter + +CAT IDs: CAT-23. Status: Pending. + +Read [BN-02](audit/11-boundaries.md#bn-02--p3-notarius-output-protocol-translation-partly-lives-in-stage-orchestration). + +Move lane-ID/native-filename mapping from `stage/notarius_lanes.go` into the +existing Notarius adapter as `LaneRelativePath(string) (string, error)`. This +narrow protocol helper avoids unnecessary changes to `Runner`/`RunResult`. +Move executable discovery from the stage to adapter-owned resolution shared by +execution and readiness, preserving explicit binary/PATH behavior and errors. +Update production/fake callers without inspecting downstream configuration. + +Keep required output keys, canonical filenames, mapped-collision detection, +confinement, JSON validation, checksum checks and promotion in the stage. +Move native naming fixtures with their owner; retain the stage-level mapped +collision and correct-lane-promotion tests. + +Acceptance: stage code contains neither Notarius native naming grammar nor +`exec.LookPath`; execution and readiness keep the same configured behavior. + +Validation: `go test ./internal/adapters/notarius ./internal/stage ./internal/app ./internal/preflight`. + +## Stage 17: Separate Extraction Invocation And Product Acceptance + +CAT IDs: CAT-24, extraction half. Status: Pending. + +Read [CX-03](audit/03-complexity.md#cx-03--p3-trim-and-extraction-mix-invocation-mechanics-with-product-acceptance). + +In `stage/extract.go` and `extract_preflight.go`, extract a stage-private typed +resolved Notarius options value shared by execution and readiness: adapter +binary selection, config/working paths, timeout, credentials, overlay, cache +and debug controls. Keep probe/execution destinations and real/synthetic input +selection explicit. Force still maps extraction to cache refresh. + +Separate request/snapshot setup, invocation, completion/bundle acceptance, +staged-lane validation, and canonical promotion into cohesive operations. +Return typed products/diagnostics, using Stage 12 codecs only when assembling +metadata. Keep `Run` as visible sequencing, including the disabled self-skip. + +Acceptance: verify references after invocation, validate all required staged +lanes before replacing canonical products, preserve partial promotion/failure +retention behavior and warnings, and keep failed-attempt diagnostics. Do not +invent transactional all-lane replacement or a generic subprocess-stage wrapper. + +Validation: `go test ./internal/stage -run 'Test.*(Extract|Notarius)'`; `go test ./internal/app ./internal/preflight`. + +## Stage 18: Separate Trim Bounds, Execution And Final Acceptance + +CAT IDs: CAT-24, completion. Status: Pending. + +Read Stage 17's CX-03 section and `stage/trim.go`, its bounds/selector helpers, +and trim tests. + +Extract typed operations for optional bounds/debug generation, validated bounds +selection, Seriatim trimming, and final transcript acceptance/promotion. Retain +a short disabled-copy branch; enabled and disabled paths converge on the same +final transcript validation/materialization. Preserve distinct bounds artifact +and diagnostic paths. Collect diagnostics from phase results rather than using +a mutable metadata map as inter-phase state. + +Acceptance: enabled/disabled results, selector semantics, debug-only behavior, +validation before promotion, old-file retention and failure diagnostics remain +unchanged. Helpers represent actual phases rather than merely relocating lines. + +Validation: `go test ./internal/stage -run 'Test.*Trim'`; `go test ./internal/app`. + +## Stage 19: Isolate Pure Prompt-Requirements Interpretation + +CAT IDs: CAT-25, prompt-assessment part. Status: Pending. + +Read [CX-04](audit/03-complexity.md#cx-04--p3-inspection-and-readiness-combine-collection-policy-and-presentation) +and `internal/preflight/check.go`/tests. + +Extract pure assessment of one Scriptorium target/report into findings and +required-variable failure state. The existing loop retains transport calls, +context checks, per-target operational errors and ordered aggregation. +Preserve conditional-input/variable warnings, incomplete discovery, and duplicate +missing-variable suppression. No provider registry or new readiness rule. + +Acceptance: pure fixtures cover required/conditional/incomplete reports and +deduplication; loop tests retain cancellation and independent later checks +after ordinary failures. Keep reports and severity meanings unchanged. + +Validation: `go test ./internal/preflight ./internal/app`. + +## Stage 20: Separate Session Inspection Collection From Reporting + +CAT IDs: CAT-25, inspection part. Status: Pending. + +Read Stage 19's CX-04 section and `app/session_state_command.go`, +`artifact_inspection.go`, `operator_inspection.go`, and command tests. + +Collect cohesive local-manifest/catalog, remote-publication/lock, and input +inspection results in small private structs before projecting the existing +`sessionStateReport`. Keep explicit top-level order and stage-owned/artifact-owned +interpretation helpers; do not move I/O into renderers. Reuse Stage 11 codecs +and Stage 1 error accumulation rather than creating new parallel parsers. + +Acceptance: local-only artifacts inspection stays local; remote partial failure +retains local findings and declared locked/carried origins; supplied built-ins +remain recorded without inventing earlier files. Inspection remains read-only +and does not upgrade lightweight evidence display to payload verification. + +Validation: `go test ./internal/app -run 'Test.*(Inspection|SessionState|SessionArtifact|PublishedOutput)'`. + +## Stage 21: Separate Readiness Operations And Presentation + +CAT IDs: CAT-25, completion. Status: Pending. + +Read Stage 19's CX-04 section and `app/session_readiness.go`, +`downstream_readiness.go`, `preflight_targets.go`, and preflight tests. + +Extract tool-specific Scriptorium, Audita and Notarius readiness operations +returning existing typed check/finding results. Retain initialized adapters on +the invocation environment. Separately assess preparation outcome/transcript +projection and project results into `sessionReadinessReport`; keep ordering and +failure aggregation explicit rather than adding a generic registry. + +Acceptance: standalone preflight still prepares/reuses inputs and checks enabled +capabilities, while run checks only projected work. Preparation-blocked checks, +independent checks after ordinary failures, provider effects, cancellation, +reference verification, S3 preparation checks and diagnostic placement remain. +Do not tighten admission rules or require exact diagnostic wording. + +Validation: `go test ./internal/app ./internal/preflight ./internal/stage`. + +## Stage 22: Index Previous Publication Selection And Optional Absence + +CAT IDs: CAT-27, remote/reporting parts. Status: Pending. + +Read [EF-03](audit/02-efficiency.md#ef-03--p3-previous-session-metadata-is-repeatedly-searched-as-a-list). + +In `previouscache.Resolve`, build one source-keyed index of published-output +declarations from its selected inventory instead of rescanning per requirement. +Retain duplicate candidates and the existing ambiguity policy, declaration +validation and sorted return order; no last-write-wins collapse. Keep this +selection bound to the one loaded inventory. In session input inspection, build +one skipped-name membership set instead of scanning the optional-absence list +for each requirement. + +Acceptance: required/optional absence, duplicate/invalid declarations, carried +object identities, transfer verification and deterministic reports are unchanged. +No cross-invocation payload cache is introduced. + +Validation: `go test ./internal/previouscache ./internal/app ./internal/stage`. + +## Stage 23: Index Manifest Input Selection Within A Phase + +CAT IDs: CAT-27, completion. Status: Pending. + +Read Stage 22's EF-03 section and `artifacts/prepared_input.go`, +`artifact_resolver.go`, and `stage/analyze_input_identity.go`. + +Introduce an operation-owned input-record lookup in artifacts with slices by +kind and canonical source plus the canonical-path candidates needed by prepared +input diagnostics. Store all matching records, retaining ambiguity checks. +Add lookup-backed resolver entry points; existing single-call wrappers can +construct one lookup and delegate. Analysis builds one lookup for the current +manifest-input snapshot and passes it through repeated prepared/history source +resolution. Other batch consumers use the same seam where they currently repeat +the scans. Rebuild after preparation replaces `Manifest.Inputs`; never keep a +global index of mutable manifests. +Index construction retains candidates without eagerly rejecting unrelated +malformed records. Apply existing path/type/content validation to the requested +source's candidates, preserving candidate order and failure policy. + +Acceptance: wrong-kind canonical-path diagnostics, duplicate records, missing +optional/required inputs, confinement and content verification remain. The +index accelerates record selection only; it does not cache checksum validation +across operations or substitute incidental filesystem files for evidence. + +Validation: `go test ./internal/artifacts ./internal/stage ./internal/app`. + +## Stage 24: Index Restore Report Updates + +CAT IDs: CAT-28. Status: Pending. + +Read [EF-04](audit/02-efficiency.md#ef-04--p3-restore-reporting-performs-a-full-search-after-each-install) +and `app/restore_report.go`/execution tests. + +Add a private map keyed by `{LocalRelativePath, RemoteKey}` to report indices, +built in `newRestoreReport`; replace `findAction` scans in downloaded/failed +updates. Preserve first-match behavior if duplicate report keys are supplied +programmatically, rather than changing validation policy. The map is not +serialized. Keep counters and update behavior for unmatched actions as today. + +Acceptance: report order/shape, all statuses and counters, dry-run behavior, +partial failure/retry, and manifest-last installation remain. No report schema +change or reordering to match installation is needed. + +Validation: `go test ./internal/app -run 'Test.*Restore'`. + +## Stage 25: Correct Remaining Documentation And Example Comments + +CAT IDs: CAT-31, CAT-32, CAT-33, CAT-43. Status: Pending. + +Read [DOC-05](audit/13-documentation.md#doc-05--p3-annotated-example-comments-retain-obsolete-contracts-and-defaults), +[DOC-04](audit/13-documentation.md#doc-04--p3-seriatim-reports-are-documented-as-canonical-artifact-outputs), +[DOC-06](audit/13-documentation.md#doc-06--p3-internal-credential-ownership-descriptions-predate-native-bootstrap), +and [DOC-08](audit/13-documentation.md#doc-08--p3-logging-package-documentation-advertises-a-removed-responsibility). + +- Correct the annotated pipeline comments: configured artifact inputs infer + dependency edges; secret-reference names are operator examples; cleanup covers + the session's run history. Keep authored values and explicit ordering examples. +- In merge/normalize internals, list canonical transcripts as products and + optional Seriatim reports as run-local diagnostics, linking operations for layout. +- Remove credential precedence/mode policy from generic fileops prose. Describe + invocation acquisition calling ConfigKit's native startup and storage consuming + resolved values; link the adopted upstream guide and operator permissions. +- Correct `internal/logging/doc.go` to describe Reporter and forwarding helpers, + with CommandKit owning presentation. Do not implement a logger constructor. + +Acceptance: documentation agrees with implemented owners; no runtime movement +of reports, duplicate credential bootstrap, or new dependency rules are added. +Do not rely on YAML loading to validate natural-language comments; inspect them. + +Validation: `go test ./internal/doccheck`; `go test ./internal/config -run '^TestExamplesLoadAndValidate$'`. + +## Stage 26: Verify The Sprint And Close Remaining Catalog Entries + +CAT IDs: all 25 coverage rows. Status: Pending. + +Review each coverage row against current source and its assigned acceptance +tests, not merely a green aggregate suite. Verify old implementations actually +disappear where shared owners replaced them. Confirm source-listed dead code +and inert fields are gone while live supplied/analysis contracts remain. +Check updated callers, documentation, and imports for abandoned transitional code. + +Run with the maintained toolchain: + +```sh +GOTOOLCHAIN=go1.27.4 go test -count=1 ./... +GOTOOLCHAIN=go1.27.4 go test -race ./... +GOTOOLCHAIN=go1.27.4 go vet ./... +GOTOOLCHAIN=go1.27.4 go build ./... +git diff --check +``` + +Use existing behavioral workflow tests for original-audio execution, supplied +product import, bounded artifact-only continuation, forced replacement, partial +local retry, publication locks, cleanup authorization and cancellation. Add a +regression only for a meaningful gap exposed by these refactors; do not create +a new broad audit, runtime-safety policy, test harness or timing gate. + +For each finding, update the catalog's closure evidence only after its target +is verified. Preserve original audit documents and source IDs. If all rows pass, +the catalog has 43 closed entries and zero open entries; update counts from +actual statuses. Mark this plan complete after integration and documentation +checks succeed. No tagging or pushing is included in this sprint plan. + +## Open Questions + +None. The plan selects the narrow ownership/API options needed for the audited +work. Newly discovered product-policy choices should be raised explicitly rather +than resolved by adding stronger contracts during implementation.