diff --git a/docs/roadmap/audio-inputs.md b/docs/roadmap/audio-inputs.md deleted file mode 100644 index fae0194..0000000 --- a/docs/roadmap/audio-inputs.md +++ /dev/null @@ -1,255 +0,0 @@ -# Multi-Format Audio Inputs and Shared Discovery - -Status: Implemented and verified - -## Goal - -Accept ordinary audio recordings without a FLAC-only restriction. MP3, AAC, OGG, -WAV, FLAC, and other audio formats can be supplied to the transcription backend. -The backend determines whether it can decode a recording; Narratio coordinates -selection, preparation, upload, and local progress. - -Use shared read-only discovery so preparation and operator inspection agree on -the selected sources. Apply the regular-file requirement approved during -[audit topic 7](audit/discussion.md#7-give-preparation-and-inspection-the-same-audio-selection-rules), -incorporating the subsequent operator clarification permitting multiple audio -formats. Earlier FLAC-only descriptions are not the target contract. - -This is a feature roadmap, not a staged implementation plan. It extends the -shared-discovery remediation in -[CAT-12](audit/catalog.md#cat-12--p2-share-audio-discovery-and-accept-valid-same-basename-recordings-in-inspection). -The original audit identified inconsistent discovery under the old behavior; -the multi-format scope follows the operator's later decision. - -## Historical Baseline - -Reviewed against `aa0379294fba8422f7e6469261e4730b1c19bd8e`. - -| Area | Current behavior | -| --- | --- | -| Local preparation | Explicit paths must have a `.flac` extension; directory scanning filters to FLAC. | -| S3 preparation | Object discovery filters to FLAC keys. | -| Operator inspection | Independently repeats local/S3 FLAC filtering and disagrees with preparation on duplicates. | -| Transcription | Both manifest-selected audio validation and fallback directory discovery independently require FLAC. | -| Preparation reuse | Reconstructs source inventory through preparation's discovery functions. | -| Speaker naming | Removes the final filename extension to derive speaker ID and raw transcript path. | -| Local copying/S3 materialization | Preserves selected filenames and copies bytes without transcoding. | -| WhisperX upload | Preserves the prepared basename and uses a generic multipart file part; no FLAC media type is forced. | -| Speaker checkpoints | Store paths, byte identities, and settings without a FLAC-specific schema requirement. | - -Relevant owners are [preparation](../../internal/stage/prepare.go), -[inspection](../../internal/app/operator_inspection.go), -[transcription](../../internal/stage/transcribe.go), -[preparation reuse](../../internal/stage/prepare_resume.go), -[speaker reconciliation](../../internal/stage/transcribe_reconciliation.go), -[speaker state](../../internal/manifest/transcribe_state.go), and -[multipart upload](../../internal/adapters/whisperx/multipart_body.go). - -Two naming cases need to remain distinct: - -- Different local sources with the same full basename are already given distinct - prepared names. Inspection currently rejects those valid selections. -- `speaker.mp3` and `speaker.wav` have different basenames but derive the same - speaker ID, `speaker`. Existing preparation disambiguation does not resolve this - case. Transcription currently detects the ambiguity before dispatch rather - than silently overwriting `transcripts/raw/speaker.json`. - -Existing tests explicitly expect MP3 rejection and FLAC-only directory selection. -Those expectations encode behavior intentionally changed by this feature. - -## Agreed Target - -### One selection responsibility - -Share path resolution, source eligibility, deterministic selection order, and -duplicate handling between preparation and inspection. Keep file copying, -workspace writes, and manifest transitions with preparation. Inspection remains -read-only; it does not execute preparation to discover inputs. - -Use the existing audio-focused owner or another narrow shared operation where -dependency direction requires it. A discovery framework or public reusable -library is unnecessary. - -Preserve these established behaviors: - -- Reject repeated selection of the same resolved local source path. -- Preserve distinct local recordings sharing a full basename through the - existing prepared-name disambiguation. -- Keep the existing local and S3 duplicate-basename rules distinct. -- Preserve ordinary unambiguous speaker IDs and prepared names. - -Detect remaining same-stem collisions across different extensions during shared -discovery, after applying existing prepared-name disambiguation. Identify both -source paths and ask the operator to select one encoding or give the recordings -distinct names. Preserve stem-based speaker IDs rather than adding automatic -renaming for cross-extension collisions. This moves an existing transcription -failure earlier; it does not add content-based audio deduplication. - -### Regular files, without a codec allowlist for explicit sources - -An explicitly selected local recording must resolve to a regular file. It need -not have a `.flac` suffix or belong to a Narratio-maintained codec allowlist. -Existing path rules remain applicable; this decision adds no blanket symlink -prohibition or unrelated filesystem hardening. - -S3 discovery deals with object entries; local regular-file checks apply to local -sources and materialized copies rather than inventing filesystem types for S3. - -### Broad extension filtering for automatic discovery - -Use one shared, case-insensitive extension filter when scanning a local audio -directory or S3 prefix. The initial discovery set is: - -```text -.aac .aif .aifc .aiff .alac .amr .ape .au .caf .flac -.m4a .m4b .mka .mp2 .mp3 .mp4 .oga .ogg .opus .snd -.wav .wave .weba .webm .wma .wv -``` - -These suffixes identify candidates, including common audio-bearing containers; -they do not guarantee backend decoding or the presence of a valid audio stream. -Keep the set in one central, discoverable location in the shared audio-selection -owner. Preserve existing enumeration scope and directory-marker handling. - -Automatic scans ignore nonmatching entries such as `ignore.txt`, unfamiliar -suffixes, and extensionless files. Explicit local file selections remain -extension-agnostic, as do already registered manifest audio inputs. The discovery -set is not a universal codec-validation rule. Document its scope, including that -S3 currently selects by prefix and therefore uses this filter; no new S3 override -or per-object selector is introduced by this feature. - -Automatic scans in preparation, inspection, preparation reuse, and transcription -must use the same filter. This supports mixed-content source directories without -submitting obvious sidecars and avoids divergent format lists among consumers. - -### Carry selected audio through the whole pipeline - -Remove FLAC-only acceptance checks from transcription, including its manifest -input path and fallback directory path. A recording selected during preparation -must not be rejected later solely because of its extension. - -Preserve the actual bytes and meaningful filename suffix during copying, -disambiguation, S3 materialization, and upload. Keep the existing format-neutral -multipart transport and replay mechanics. This feature requires no transcoding, -new MIME registry, or local decoder/probe before submitting audio. - -Backend rejection of unsupported or malformed audio remains a transcription -failure. Accepting a candidate in Narratio is not a guarantee that every backend -deployment supports every codec or container. - -### Retain local retry and reuse - -Preparation, its reuse checks, and inspection must derive the same source -inventory under the chosen discovery policy. Transcription must continue to -checkpoint and reuse individual speakers with mixed-format inputs. - -Keep path, checksum, size, and observable transcription settings as ordinary -local reuse evidence. No codec-specific manifest fields or schema migration are -required merely to admit additional formats. Keep existing unambiguous FLAC -inputs reusable under their ordinary evidence rather than renaming them wholesale. - -After transcription, merge and later stages consume transcript JSON; this feature -does not require codec changes in Audita, Notarius, or Scriptorium. - -## Required Changes - -### Discovery and eligibility - -Replace duplicated `isFlac`/`isInspectionFlacPath` selection rules and error messages -in local and S3 discovery. Implement the approved regular-file check consistently -for local recordings. Resolve same-source duplicates and the existing basename -disagreement through the shared selection owner. - -Apply the shared extension set to automatic source discovery and transcription's -fallback enumeration. Manifest-registered audio is already explicitly selected; -it should not encounter another extension-based gate. - -Primary areas: `internal/stage/prepare.go`, -`internal/app/operator_inspection.go`, `internal/audio`, and -`internal/stage/transcribe.go`. - -### Speaker identity and prepared destinations - -Detect unresolved same-stem ambiguity consistently during shared discovery, -before transcription dispatch. Account for prepared filenames as well as original -source paths: checking original stems alone must not reject the distinct -same-basename inputs that preparation already disambiguates successfully. - -Keep speaker mappings, raw transcript paths, and checkpoint keys consistent with -the existing IDs. Report both ambiguous sources and direct the operator to select -one encoding or rename recordings. Preserve actual format suffixes and the -established disambiguation of identical full basenames. Do not silently choose -an encoding or extend automatic naming to the unresolved cross-extension case. -Use existing reporting paths to make any derived names understandable to operators. - -Primary areas: preparation's destination naming, `buildTranscribeJobs`, source -inspection, and the speaker/input mapping documentation. - -### Reuse and transport verification - -Review source-inventory reconstruction in `prepare_resume.go` and input discovery -used by transcribe reconciliation. Preserve per-speaker success across ordinary -retries with mixed formats. The current generic copy, hash, checkpoint, and upload -mechanisms should be reused rather than replaced with format-specific machinery. - -Confirm that multipart filenames and audio bytes survive initial submission and -transport replay unchanged. The existing generic file-part content type is not -a FLAC-only assumption and need not change for this feature. - -### Documentation and tests - -Update configuration, operations, preparation/transcription internals, examples, -and the WhisperX integration description where needed to explain the approved -discovery and naming behavior. FLAC can remain an example; it should not be -presented as the only permissible input format. Keep backend-specific decoding -capabilities under the backend's ownership. - -Replace tests whose purpose is to reject MP3 or require FLAC-only selection with -tests of the chosen contract. Retain unrelated file, path, and failure coverage; -do not mechanically rename every FLAC fixture. - -## Validation Outcomes - -Use representative offline behavior tests with real temporary files and fakes at -the transcription/storage boundaries: - -- Preparation and inspection agree for explicit mixed-format sources and for - directory/S3 discovery. Automatic scans recognize the shared suffix set - case-insensitively and ignore nonmatching sidecars; explicit files with other - suffixes or no extension are not rejected solely by their names. -- Non-FLAC audio registered in the manifest reaches transcription. Fallback - discovery follows the same candidate-selection policy. -- Duplicate resolved paths are rejected, distinct same-basename local recordings - remain usable, and unresolved cross-extension same-stem cases fail during - discovery with both sources identified, before transcription is dispatched. -- Copying and S3 materialization retain the selected bytes and suffixes; upload - and replay retain the multipart filename and payload. -- A partial mixed-format transcription can retry without repeating previously - checkpointed speakers, while changed inputs still receive normal reconciliation. -- Non-regular local inputs are rejected consistently, and ordinary existing FLAC - inputs retain their established naming and reuse behavior. -- Backend decoding errors remain visible failures; discovery does not claim to - have validated the actual encoding. - -Offline tests verify Narratio's selection and transport, not a live backend's -codec support. No paid/live transcription gate, local codec toolchain, or new -benchmark requirement is introduced. - -## Relationship to Other Work - -This roadmap owns the multi-format extension and shared discovery work associated -with CAT-12. CAT-12 is closed after implementation and verification; the -historical audit reports remain unchanged. - -The agreed source-identity and transfer-size changes in -[topic 4](audit/discussion.md#4-keep-downloaded-audio-and-its-source-identity-together) -are implemented, as is streaming local audio copying (CAT-04, CAT-06, and -CAT-08 are closed in the catalog). Build on those acquisition paths while -changing discovery; preserve their identity, transfer bounds, and streaming -behavior. This feature does not reopen the storage/resource remediation scope. - -The implemented [publication-import workflow](../operations.md#restore-workflow) enables downstream work without -raw audio. This roadmap concerns workflows that actually select and transcribe -audio. These features have independent scopes. Remote execution -checkpoints, new audio-size caps, additional format conversions, and live-stream -input support are outside this scope. diff --git a/docs/roadmap/audit/01-correctness.md b/docs/roadmap/audit/01-correctness.md deleted file mode 100644 index b394c2f..0000000 --- a/docs/roadmap/audit/01-correctness.md +++ /dev/null @@ -1,178 +0,0 @@ -# Functional Correctness Audit - -Reviewed on 2026-11-30 against commit -`723b788161f59fd3b0a45eabd370385cc5640b4d`. - -## Scope And Evidence - -The review examined configuration acquisition and domain projections, canonical -stage execution, semantic resume and invalidation, speaker/artifact checkpoints, -artifact resolution, subprocess and HTTP boundaries, prepared previous-session -inputs, publication, restore, and cleanup. Findings use the current application -contracts in the architecture policy, operations guide, and focused internal -documents. They do not require compatibility shims or stronger transactional -guarantees. - -The unmodified repository passed these checks with `GOTOOLCHAIN=go1.27.4`: - -- `go test ./...` -- `go test -race -count=1 ./...` -- `go vet ./...` -- `go build ./...` - -Four temporary offline diagnostics, supplied through Go's `-overlay` facility, -reproduced the three findings below. They exercised real internal collaborators -and existing filesystem fixtures, with the in-memory storage adapter at the -remote boundary. Their expected-behavior assertions failed as described below; -no production code or repository tests were changed. Live downstream tools, -paid providers, and a real S3 service were not exercised. This review does not -establish the absence of other defects. - -## FC-01 — P2: Previous-session hydration omits analysis prerequisites - -Status: Open - -Relevant code: - -- [Preparation](../../../internal/stage/prepare.go): - `collectPreparePreviousRequirements` (line 533) and its caller in `Run`. -- [Requirement collection](../../../internal/artifacts/previous_requirements.go): - `CollectPreviousArtifactRequirements`, particularly lines 32–36. -- [Analysis planning](../../../internal/stage/analyze_plan.go): - `planAnalyzeWork` and `AnalyzeTargetClosure`. -- [Restore planning](../../../internal/app/restore_plan.go): - `buildPreviousCacheRestoreActions` uses the same target-only collector. - -**Trigger.** An enabled target `summary` depends on a disabled artifact -`history`, and `history` consumes -`narratio.previous_session.artifact.history`. The same issue occurs with an -explicit `--artifacts summary` selection that excludes its prerequisite from -the target set, even if that prerequisite is otherwise enabled. A previous -session and its published history can be available remotely. - -**Expected.** The prerequisite participates in the documented analysis work -closure, so preparation makes its previous-session inputs available before -analysis executes. Required and optional inputs retain their configured -meaning. See [analysis behavior](../../internal/stage-analyze.md) and -[artifact selection](../../operations.md#artifact-development-workflows). - -**Actual.** Preparation scans only `EffectiveArtifactSet` targets. Analysis -separately expands those targets to prerequisites. In the diagnostic, -analysis's closure was `[history summary]`, but preparation collected no -previous-session requirements. A required input consequently fails later with -prepare-rerun guidance; repeating the same preparation cannot supply it. An -optional input can instead be omitted despite an available remote artifact. -Restore's previous-cache planning has the same omission for disabled -prerequisites of enabled targets. - -**Remediation approaches.** Collect previous-session requirements over the -existing shared analysis dependency closure. Use that requirement set -consistently for preparation, its semantic evidence, object-store composition, -and restore. Preserve explicit targets separately so this change does not -broaden force or publication selection. An alternative is to pass a separately -derived prerequisite-inclusive input-requirement set to these consumers; -avoid maintaining a second dependency algorithm. - -**Verification to retain when fixed.** Exercise enabled-target/disabled- -prerequisite and explicit-target/prerequisite cases, including required and -optional previous inputs, followed by analysis and previous-cache restore. - -## FC-02 — P2: Carried publication bytes conflict with restored manifest evidence - -Status: Open - -Relevant code: - -- [Publication planning](../../../internal/stage/publish_output_plan.go): - `buildPublishOutputPlan` preserves an exact prior declaration for a locked - source. -- [Committed session manifest](../../../internal/stage/publish_commit.go): - `writeCommittedSessionManifest` (lines 103–134) copies current local output - evidence unchanged. -- [Restore planning](../../../internal/app/restore_plan.go): - `buildCommittedRestoreActions` (lines 172–193) maps the carried object to the - canonical product path. -- [Manifest installation](../../../internal/app/restore_manifest_paths.go): - `rebaseRestoredManifestPaths` changes paths and diagnostic references while - retaining output checksums and completion evidence. - -**Trigger.** Publish transcript or artifact version A, lock its source, then -generate local version B and publish again. The new remote commit correctly -carries A's exact declaration while its session-manifest object records B's -local completion. Restore that committed snapshot into an empty workspace. - -**Expected.** Restore preserves the locked publication and installs a ledger -whose output authority agrees with the available bytes. It must not claim -that A is the completed B result. The relevant contracts are -[committed publication](../../internal/stage-publish.md) and -[manifest-authoritative resolution](../../internal/manifest.md). - -**Actual.** Restore installs A into the canonical product path and preserves -B's checksum and successful stage record. It can return success, but the -restored product then fails normal artifact resolution. The real publication -diagnostic confirmed the conflicting declaration and session-manifest -checksums. A second diagnostic passed that shape through the real restore -planner, installer, manifest loader, and resolver: restore succeeded, then -`narratio.transcript.final_trimmed` failed with `checksum mismatch`. A bounded -analysis run consuming that transcript cannot use the restored publication; -configured-artifact evidence similarly becomes non-current. - -**Remediation approaches.** Reconcile restored authority with the selected -commit's actual product identities. Where carried bytes replace a different -local generation, preserve truthful provenance and reconcile affected stage, -per-artifact, and dependent completion state. Another approach is to -separate the generation-ledger snapshot from the restore/publication projection -and explicitly construct a coherent restored manifest. Simply replacing a -checksum while preserving B's fingerprint or dependent success would falsely -certify A as B. Preserve exact carried declarations and checksum validation. - -**Verification to retain when fixed.** Publish A, lock, generate B, republish, -restore into a new workspace, and inspect both restored content and reuse -decisions. Include a built-in transcript and a configured analysis artifact. - -## FC-03 — P2: Session planning reports reusable S3 preparation as changed - -Status: Open - -Relevant code: - -- [Work projection](../../../internal/app/plan.go): - `projectSelectedWork` (lines 81–104) constructs a stage environment without - an object store. -- [Preparation resume](../../../internal/stage/prepare_resume.go): - `currentPrepareAudioSourceInputs` (lines 196–200) requires an S3 listing; - `ValidateResume` (lines 50–55) converts that failure to a changed-input result. -- [Runtime composition](../../../internal/app/runner_stage_execution.go): - `executeSelectedStage` composes preparation collaborators before checking - its resume evidence, unlike the planning path. - -**Trigger.** A session uses `inputs.audio_s3`, preparation has succeeded, and -the prepared copies and remote key/size/ETag identities remain unchanged. Run -`session plan` over a range containing preparation. - -**Expected.** The plan reflects verified resume evidence, or identifies evidence -it could not inspect. The documented shared planning semantics should not -describe unchanged inputs as changed solely because a planning collaborator -was omitted. See [planning](../../cli.md#session-plan). - -**Actual.** The projection cannot list S3 audio without an object store. It -reports `prepare` as `run` with reason "prepared inputs or their current sources -changed; rerun prepare" and models dependent invalidation. Ordinary execution -supplies the store and can reuse the same preparation. The diagnostic prepared -S3 audio with the existing fake backend, verified `Resumable=true` with that -backend, then projected the identical configuration and manifest and observed -the erroneous `run` decision. This is misleading planning output, not a -durable invalidation or an observed execution rerun. - -**Remediation approaches.** Obtain read-only audio identity evidence at the -planning boundary and provide it to the shared decision, keeping stage -execution and the projection's mutation-free behavior separate. A storage -reader or an acquired identity snapshot can supply that evidence. If planning -is deliberately kept free of this remote lookup, expose an unverified or -conditional decision and document that limit instead of reporting a definite -input change. Avoid treating unverifiable inputs as proven reusable. - -**Verification to retain when fixed.** Compare plan and execution for unchanged -and changed S3 object identities, and distinguish an unavailable remote source -from an actual content change. Confirm that planning leaves the workspace and -manifest untouched. diff --git a/docs/roadmap/audit/02-efficiency.md b/docs/roadmap/audit/02-efficiency.md deleted file mode 100644 index 8ccd7e7..0000000 --- a/docs/roadmap/audit/02-efficiency.md +++ /dev/null @@ -1,211 +0,0 @@ -# Algorithmic Efficiency Audit - -Reviewed on 2026-11-30 against commit -`89ea4ff1556633f217844b4a8c81a4bc2c9ffede`. - -## Scope And Method - -The review traced repository-owned loops, lookups, copying, graph traversal, -error construction, and their callers across configuration, orchestration, -stages, artifact resolution, storage, restore, and subprocess adapters. -Complexities below follow from source-level operation counts. Hash-map bounds -are expected bounds; path, key, and error-message lengths are treated as -bounded unless stated otherwise. No benchmarks or production performance -measurements were collected. Production code and tests remain unchanged. - -The five findings concern implementation choices without an expressly selected -algorithm requiring the current cost. They preserve the existing data and -execution contracts. - -## EF-01 — P2: Local audio copying buffers the complete recording - -Status: Open - -**Code.** [prepare.go](../../../internal/stage/prepare.go), -`materializeLocalAudioInputs` (line 367) and `copyFileIfChanged` (lines 635–663). - -On the missing or changed destination path, `copyFileIfChanged` first hashes -the source, then calls `os.ReadFile(src)` and passes the complete byte slice to -`store.WriteFileAtomic`. This path handles prepared local `.flac` files as well -as small configuration inputs. - -**Complexity.** For a recording of B bytes, copying takes Θ(B) time and Θ(B) -auxiliary RAM. Sequential processing limits this to the current recording, -but a single large speaker file still requires a file-sized allocation. The -same copy can take Θ(B) time and O(1) auxiliary RAM relative to B using a -fixed-size streaming buffer. This is a space-complexity improvement, not an -asymptotic time improvement. - -**Refactoring opportunity.** Retain the existing unchanged-destination check, -then use the streaming artifact-copy path. `artifacts.Store.CopyInputFor` is -already available; its local implementation delegates to -[fileops.CopyFileAtomic](../../../internal/fileops/fileops.go). -`CopyFileAtomicWithChecksum` and `WriteReaderAtomicWithChecksum` also provide -the underlying streaming replacement mechanism. Preserve destination naming, -workspace modes, atomic visibility, and the recorded checksum. File-sized -buffering is not required for any of those behaviors. No new input-size cap -is needed. - -## EF-02 — P3: Analysis rebuilds the same dependency index after each completion - -Status: Open - -**Code.** [analyze_execution_state.go](../../../internal/stage/analyze_execution_state.go), -`acceptArtifact` (lines 93–101), and -[analyze.go](../../../internal/stage/analyze.go), -`staleUnscheduledAnalyzeDependents` / `staleAnalyzeDependentClosure` -(lines 278–319). - -Every newly generated artifact, or artifact whose output identity changed, -calls the invalidation helper. That helper rebuilds the entire reverse -dependency map, renormalizes dependency lists, and sorts reverse adjacency -lists before traversing the affected descendants. Configuration is unchanged -throughout the execution. - -**Complexity.** Let V be configured artifacts, E dependency edges, and K -new/changed completions. Graph construction alone costs at least Ω(K(V+E)), -with repeated dependency/adjacency sorting adding up to O(K E log V) work. -On an initial execution of V independent artifacts, E=0 and K=V: this setup -still costs Θ(V²), although each descendant traversal is empty. It also -repeatedly allocates graph maps and edge slices. - -**Refactoring opportunity.** Build the immutable reverse dependency index once -for the analysis execution, retaining any required deterministic ordering. -Pass it to success and failure invalidation. Setup then costs O(V+E), plus -any one-time sorting, followed by O(reached vertices + reached edges) for each -affected traversal. For independent artifacts, the invalidation work becomes -O(V+K). Preserve the current eligibility rule for evaluated artifacts and the -timing of dependent invalidation. - -The selected complete-collection checkpoints still have their own cumulative -cost. This finding removes redundant graph work; it does not claim that the -whole analysis stage becomes linear. - -## EF-03 — P3: Previous-session metadata is repeatedly searched as a list - -Status: Open - -Three related lookup paths have straightforward indexing alternatives: - -1. **Remote declarations.** - [previouscache.go](../../../internal/previouscache/previouscache.go), - `Resolve` (lines 145–147) calls `committedPublishedArtifactBySource` - (lines 196–209) separately for every requirement. With R requirements and - C commit declarations, the lookup work is O(RC), including quadratic - cases when both grow together. Build one source-keyed index of validated - `published_output` declarations in O(C), then resolve requirements in - O(R). Existing sorting of the returned plan remains unchanged. The index - must remain bound to the single pointer-selected commit. - -2. **Local input records.** - [artifact_resolver.go](../../../internal/artifacts/artifact_resolver.go), - `ResolvePreviousSessionArtifactWithCatalog` (lines 271–288), scans every - `manifest.Inputs` entry for each previous-artifact binding. The prepared - stable-input resolver in - [prepared_input.go](../../../internal/artifacts/prepared_input.go), - `ResolvePreparedInput`, also searches that collection on each call. - Analysis invokes these through input-identity resolution across configured - artifacts. For U lookups and I input records, record selection costs O(UI) - before content verification. A phase-local kind/source index reduces - selection to O(I+U), plus candidate validation. Retain candidate - multiplicity and existing ambiguity/path checks; a last-write-wins map - would change behavior. Continue verifying the selected files' content. - -3. **Optional-absence reporting.** - [session_state_command.go](../../../internal/app/session_state_command.go), - `inspectSessionState` (lines 227–232), calls - [previousRequirementSkipped](../../../internal/app/operator_inspection.go) - for each requirement. It linearly searches the skipped-name list. With R - requirements and S skipped names, membership costs O(RS); when all are - optional and absent, it performs a triangular Θ(R²) number of comparisons. - Build a skipped-name set once for O(R+S) total work. Binary search is also - viable while the existing sorted-result property is retained, giving - O(R log S) membership work. - -These indexes can remain private to each phase. They need not become a generic -manifest framework or cache file contents across executions. Required/optional -policy, checksum validation, and selected-commit authority remain intact. - -## EF-04 — P3: Restore reporting performs a full search after each install - -Status: Open - -**Code.** [restore_execute.go](../../../internal/app/restore_execute.go), -`executeRestorePlan` (lines 81–93), and -[restore_report.go](../../../internal/app/restore_report.go), -`markDownloaded`, `markFailed`, and `findAction` (lines 102–153). - -The report is built from the complete restore plan. Each downloaded file then -calls `markDownloaded`, which searches the report from the first action to -find the matching local-path/remote-key pair. Failure marking uses the same -search. - -**Complexity.** For A report actions and D downloads, successful reporting -costs O(DA). When every action downloads, the searches perform -1+2+...+A = Θ(A²) comparisons, even though each report entry changes once. -Moving the manifest install last does not change that sum. - -**Refactoring opportunity.** Build a private composite-key-to-report-index map -when constructing the report: O(A) setup and space, then expected O(1) per -update, for O(A+D) total bookkeeping. Alternatively, carry the original report -index alongside each execution action, including when moving the manifest -action last. Preserve public report order, serialized fields, and install -ordering. Downloading, verification, and report serialization are separate -costs and are not removed by this change. - -## EF-05 — P3: Publication-inspection errors form a quadratic-formatting tree - -Status: Open - -**Code.** [session_state_command.go](../../../internal/app/session_state_command.go), -`inspectPublishedOutputs` (lines 300–303). - -For every failed publication lookup, the loop assigns -`resultErr = errors.Join(resultErr, err)`. Multiple failures, such as object -metadata requests failing during a storage outage, produce a left-nested -error tree. The returned error is subsequently rendered by command reporting. - -**Complexity.** Creating each join is constant work, so aggregation itself is -linear in F failures. Formatting is different: Go 1.27.4's -`errors.joinError.Error` recursively formats the previous join and copies its -growing message into the parent result. For bounded-size leaf messages, one -final formatting pass takes Θ(F²) time and cumulative allocation, with Θ(F) -tree depth, even though the final text is only Θ(F) bytes. - -**Refactoring opportunity.** Append failures to `[]error` and call -`errors.Join(failures...)` once after the loop. Formatting then takes O(F+T), -where T is the total rendered leaf-message size, with a flat aggregate. -Retain per-output error details, error order, partial results, and -`errors.Is`/`errors.As` visibility. The existing preflight collectors already -use this approach. - -## Deliberately Retained Designs And Review Results - -The following were treated as selected behavior rather than optimization -findings: - -- the fixed canonical stage sequence, separate invalidation relation, and - pure planning projection; -- deterministic topological artifact ordering and required dependency closure; -- complete-collection manifest checkpoints after each accepted speaker or - artifact, including the detached-copy boundary; -- manifest-authoritative checksum/content validation, publication commit - ordering, and restore's manifest-last installation; -- native ConfigKit configuration resolution and upstream-owned processing - algorithms. - -Nested loops over independent collections were not classified as quadratic -without tracing the relevant input dimensions. Fixed-stage and fixed-glossary -loops are bounded by the application model. Existing map-based publication -mapping and prepared-record matching, heap-based artifact ordering, streaming -WhisperX upload, and streaming remote downloads already avoid the corresponding -simple scaling pitfalls. - -No additional ordinary functional defect was established in this pass. The -previously recorded findings remain in [01-correctness.md](01-correctness.md); -they were not duplicated here. - -Validation: `GOTOOLCHAIN=go1.27.4 go test ./...` passed. This is behavioral -baseline evidence, not a performance measurement or proof that the identified -costs are operational bottlenecks. The findings identify available asymptotic -improvements; their practical priority remains a maintainer decision. diff --git a/docs/roadmap/audit/03-complexity.md b/docs/roadmap/audit/03-complexity.md deleted file mode 100644 index b4b24d7..0000000 --- a/docs/roadmap/audit/03-complexity.md +++ /dev/null @@ -1,355 +0,0 @@ -# Complexity And Maintainability Audit - -Reviewed on 2026-11-30 against commit -`3c00167912a47e566a1622097dcea2904fe50094`. - -## Scope And Method - -The review covered repository-owned configuration/domain derivation, -application orchestration, stages, manifests, artifact resolution, restore, -publication, file operations, and external adapters. It considered both local -control-flow complexity and duplicated responsibilities across package -boundaries. Production code and repository tests were left unchanged. - -Codebase-memory-mcp supplied symbol discovery, call relationships, and -cyclomatic/cognitive metrics. Its Go index merges some same-named receiver -methods, including stage `Run` methods, so those rankings are incomplete. A -temporary standard-library Go AST scanner supplemented the graph with -receiver-qualified metrics across non-test Go files. `gocyclo`, `gocognit`, and -`staticcheck` were not installed. - -The scanner's **decision score** is one plus the count of `if`, `for`, `range`, -non-default case/communication clauses, and `&&`/`||` expressions inside a -function, including nested closures. **Span** includes comments and blank -lines from the function declaration through its closing brace. These are -screening signals, not formal quality thresholds or active-LOC measurements. -Representative results were: - -| Function | File | Decision score | Span | -| --- | --- | ---: | ---: | -| `extractStage.Run` | `internal/stage/extract.go` | 56 | 200 | -| `trimStage.Run` | `internal/stage/trim.go` | 55 | 326 | -| `prepareStage.Run` | `internal/stage/prepare.go` | 44 | 238 | -| `publishStage.Run` | `internal/stage/publish.go` | 39 | 208 | -| `assessSessionReadiness` | `internal/app/session_readiness.go` | 35 | 116 | -| `inspectSessionState` | `internal/app/session_state_command.go` | 33 | 129 | -| `executeSelectedStage` | `internal/app/runner_stage_execution.go` | 31 | 125 | - -The graph additionally reported cognitive scores of 81 for -`inspectSessionState`, 78 for `assessSessionReadiness`, and 51 for -`preflight.Check`. Source inspection determined which scores corresponded to -useful refactoring seams. Guard clauses and explicit failure ordering account -for substantial scores in otherwise readable functions. - -No benchmarks, production measurements, or live-provider tests were used. Two -temporary offline diagnostics, supplied through Go's `-overlay` facility, -confirmed the reporting defect in CX-01. The metric scanner and diagnostics -ran with the maintained Go 1.27.4 toolchain and were not added to the repository. - -## CX-01 — P2: Audio discovery is duplicated and inspection rejects valid inputs - -Status: Open - -**Code.** [Preparation](../../../internal/stage/prepare.go): -`resolveLocalAudioFiles` (line 311), `localAudioDestinations` (line 381), and -`listS3AudioObjects` (line 487). -[Operator inspection](../../../internal/app/operator_inspection.go): -`resolveLocalInspectionAudioPaths` (line 207) and -`inspectRemoteAudioPresence` (line 101). - -**Complexity.** Preparation and inspection independently implement relative-path -resolution, explicit-file versus directory discovery, FLAC filtering, file -checks, duplicate handling, and deterministic ordering. The local discovery -functions occupy 56 and 54 lines respectively and both have graph cognitive -scores of 25. Remote discovery repeats prefix/list/filter/basename logic with -different return shapes. Maintaining these implementations requires tracing -both call paths to know which rules actually govern accepted audio. - -**Confirmed correctness issue.** Given `first/speaker.flac` and -`second/speaker.flac` in `inputs.audio_files`, preparation accepts both and -assigns distinct managed destination names. Inspection instead rejects the -second file with `duplicate audio basename`. Consequently `session status` -can report valid local audio as unavailable and return an error even though -preparation can succeed. Configuration validation does not prohibit this -selection. The existing -[distinct-recording test](../../../internal/stage/audio_destinations_test.go) -also protects preparation's preservation of these recordings. - -One temporary diagnostic executed the real preparation stage and confirmed two -distinct recorded audio destinations. A second exercised -`inspectLocalAudioPresence` over the same input shape; its expected-available -assertion failed with the duplicate-basename error. This is a local -inspection defect, separate from the S3 planning defect in FC-03. - -**Refactoring opportunity.** Give read-only audio discovery one owner, naturally -the existing `internal/audio` area or a small adjacent domain helper. Return -normalized local sources or remote object identities and let preparation own -copying/checkpoints while inspection owns reporting. Keep session-prefix -construction at the Narratio boundary and pass explicit prefixes to storage. -Share the remote object filter and duplicate rules as well as local discovery. - -Fix inspection to accept distinct same-basename local recordings. Retain -preparation's rejection of duplicate resolved local sources, destination -disambiguation, and the separately selected S3 basename rule. A shared helper -must express these real differences rather than impose a new global basename -restriction. A durable regression should exercise accepted local inputs -through preparation and operator inspection. - -## CX-02 — P3: Prepared stable inputs have parallel materialization and resume definitions - -Status: Open - -**Code.** [prepare.go](../../../internal/stage/prepare.go): `prepareStage.Run`; -[prepare_resume.go](../../../internal/stage/prepare_resume.go): -`currentPrepareSourceInputs`, `currentPreparePartySourceInputs`, and -`prepareSourceInputsMatch`; -[prepare_party.go](../../../internal/stage/prepare_party.go): -`materializeCanonicalPartyInputs`; -[semantic_contracts_initial.go](../../../internal/stage/semantic_contracts_initial.go): -`prepareStableInputSemantics`. - -**Complexity.** Execution builds input records through several local closures, -individual render/write/register blocks, a glossary list, and a separate party -writer. Resume reconstructs much of the same rendering and glossary dependency -information in a different representation, then maintains another explicit -managed-kind set. Semantic selection has its own stable-input enumeration. -Adding a prepared source requires finding all the relevant definitions and -keeping their kind, content, dependencies, and presence semantics aligned. - -The existing -[prepared-source descriptors](../../../internal/artifactpolicy/policy.go) -already centralize source IDs, manifest kinds, and filenames. The opportunity -is to reuse that investment, not introduce a competing registry. - -**Refactoring opportunity.** Build a small stage-owned stable-input description -from the resolved domain data, reused by materialization and current-source -identity calculation. Share the glossary name/descriptor/dependency mapping and -party/player rendering. Derive managed-kind membership from those descriptions -where appropriate. Keep audio and previous-session hydration as explicit phases -with their distinct acquisition rules. This also shortens `prepareStage.Run` -without replacing it with a configurable preparation engine. - -Preserve the distinction between raw materialized checksums and the intentional -semantic normalization of campaign/session snapshots. Semantic fingerprint -projection should continue to select result-affecting evidence, not hash all -configuration or perform materialization. Keep the ConfigKit result immutable -and use only post-handoff Narratio domain data. Focused regression coverage -should compare fresh preparation with reuse after unchanged and changed -inputs, including combined-glossary dependencies and source relocation. - -## CX-03 — P3: Trim and extraction mix invocation mechanics with product acceptance - -Status: Open - -**Code.** [trim.go](../../../internal/stage/trim.go): `trimStage.Run` (line 23); -[extract.go](../../../internal/stage/extract.go): `extractStage.Run` (line 38); -[extract_preflight.go](../../../internal/stage/extract_preflight.go): -`BuildNotariusReadiness`. - -**Complexity.** Trim's 326-line entry point interleaves input/layout discovery, -disabled-copy behavior, optional Scriptorium debug rendering, bounds generation -and validation, selector interpretation, Seriatim execution, output promotion, -and extensive diagnostic-map assembly. The disabled and enabled branches both -perform trimmed-transcript validation and promotion. A change to bounds -execution requires reading through several unrelated phases. - -Extraction's 200-line entry point similarly combines resolved options, -reference snapshots, invocation paths, subprocess execution, completion and -bundle checks, staged lane selection, canonical promotion, and evidence -construction. Execution and `BuildNotariusReadiness` independently resolve the -binary, configuration/working paths, timeout, and force-to-cache-refresh option. -Those copies must remain aligned even though probe and execution destinations -legitimately differ. - -**Refactoring opportunity.** Extract cohesive operations with typed inputs and -results: obtain validated bounds, optionally render diagnostics, produce the -trimmed transcript, and promote accepted products. Keep a small explicit -disabled branch and share the final transcript acceptance path. For extraction, -share the resolved Notarius invocation options with readiness, then isolate -native-completion acceptance and staged-lane promotion from request setup. -Return diagnostic information from those operations instead of using one -long-lived mutable map as their communication channel. - -The benefit should be fewer duplicated rules and smaller reasoning scopes, -not a helper for each statement. Keep orchestration visible in `Run`, CLI -translation in adapters, validation before canonical promotion, reference -verification after invocation, and failed-attempt diagnostics available. -Existing phase separation in -[analysis execution](../../../internal/stage/analyze_artifact_execution.go) -and shared request construction for polish offer local examples. No generic -subprocess-stage or workflow framework is warranted. - -## CX-04 — P3: Inspection and readiness combine collection, policy, and presentation - -Status: Open - -**Code.** [session_state_command.go](../../../internal/app/session_state_command.go): -`inspectSessionState` (line 109); -[session_readiness.go](../../../internal/app/session_readiness.go): -`assessSessionReadiness` (line 93); -[downstream_readiness.go](../../../internal/app/downstream_readiness.go): -`checkDownstreamReadiness` (line 27); -[preflight/check.go](../../../internal/preflight/check.go): `Check`. - -**Complexity.** Inspection loads ledger/catalog evidence, discovers a remote -commit, reads locks and publication state, inspects stable inputs/audio/previous -requirements, mutates a public report, and accumulates failures in one function. -Readiness combines preparation outcome interpretation, transcript projection, -tool checks, severity/category formatting, storage initialization, and lock -reporting. Deep per-tool initialization/build/check branches further obscure -which work is blocked, canceled, or independently eligible. - -`preflight.Check` has a related smaller seam: its target loop handles transport -failures and cancellation while also interpreting required/conditional inputs, -variables, incomplete reports, and duplicate missing-variable findings. -These rules are easier to understand separately from iteration and I/O. - -**Refactoring opportunity.** Keep explicit top-level sequencing, but collect -cohesive local-state, remote-publication, and input-readiness results before -projecting them into reports. Extract tool-specific readiness operations that -retain the initialized adapters on the invocation. Existing result types and -the current `record` helper provide a starting point; a broad check registry is -unnecessary. Isolate Scriptorium report interpretation as a pure operation -over one target/report, leaving inspection calls and cancellation in the loop. - -Preserve partial findings, independent checks after ordinary failures, blocked -checks when preparation is unavailable, cancellation, and the distinction -between preparation and readiness. Keep inspection read-only and standalone -preflight's preparation/provider effects explicit. Reuse current report shapes; -there is no need for new commands, stricter readiness rules, or exact diagnostic -wording guarantees. The nested-error performance issue is already EF-05 and is -not a new finding here. - -## CX-05 — P3: Artifact dependency semantics span several representations and owners - -Status: Open - -**Code.** [validate_scriptorium.go](../../../internal/config/validate_scriptorium.go): -`ValidateScriptoriumArtifactDependencies` (line 265); -[analyze_fingerprint.go](../../../internal/stage/analyze_fingerprint.go): -`normalizedAnalyzeDependencyKeys` and `orderConfiguredAnalyzeArtifacts`; -[analyze_plan.go](../../../internal/stage/analyze_plan.go): -`planAnalyzeWork` and `AnalyzeTargetClosure`; -[analyze.go](../../../internal/stage/analyze.go): `staleAnalyzeDependentClosure`; -[effective_set.go](../../../internal/artifacts/effective_set.go): -`EffectiveArtifactSet`; -[previous_requirements.go](../../../internal/artifacts/previous_requirements.go): -`CollectPreviousArtifactRequirements`. - -**Complexity.** Configuration builds normalized dependency adjacency and a DFS -for validation. Stage code separately normalizes edges, builds topological -ordering, expands prerequisite closure, and constructs reverse adjacency for -invalidation. Other consumers receive `EffectiveArtifactSet`, whose keys are -explicit/enabled targets rather than the prerequisite-inclusive work set. Its -comment describes artifacts an invocation will execute, which obscures that -distinction. Several consumers must reconstruct enough graph semantics to ask -what inputs or capabilities the invocation needs. - -The omission in FC-01 demonstrates the maintenance risk of these interfaces: -preparation collects previous inputs from targets while analysis separately -expands prerequisites. EF-02 records the repeated reverse-index construction -cost; neither defect is duplicated as a new correctness/performance finding. - -**Refactoring opportunity.** Centralize normalized configured-artifact graph -mechanics under a small domain owner, potentially alongside the separately -derived `config.ArtifactCatalog`. Reuse its dependency view for validation, -deterministic ordering, prerequisite queries, and dependent traversal. Expose -target selection and required work closure distinctly to preparation, -preflight/planning, analysis, and restore. Narrow domain helpers are sufficient; -a general graph library or workflow engine is unnecessary. - -Keep execution flat and canonical. Artifact force/publication targets remain -distinct from prerequisites, and invalidation eligibility remains caller policy. -Preserve family-origin diagnostics and semantic dependency fingerprints. Do not -merge this graph with the fixed stage invalidation relation: they represent -different domains. The outcome should be one definition of dependency -mechanics and clearer caller contracts, not another effective configuration. - -## CX-06 — P3: Unstructured metadata carries cross-package control evidence - -Status: Open - -**Code.** [publish.go](../../../internal/stage/publish.go): `publishMetadata` -(line 316); -[publish_output_plan.go](../../../internal/stage/publish_output_plan.go): -`publishOutputOutcomeMetadata`; -[cleanup_plan.go](../../../internal/stage/cleanup_plan.go): -`validateCleanupPublishEvidence` (line 84); -[artifact_inspection.go](../../../internal/app/artifact_inspection.go): -`committedPublishOutputOutcomes` (line 41); -[extraction_evidence.go](../../../internal/artifacts/extraction_evidence.go): -`InspectExtractionEvidence`. - -**Complexity.** `StageRecord.Metadata` serves both free-form diagnostics and -machine-consumed evidence. Publication writes string-keyed completion and -outcome maps; cleanup reconstructs required types/keys and identity evidence; -application inspection manually decodes outcomes. Extraction similarly writes -metadata in stage code and reads it in artifact resolution. A producer/consumer -change can compile while silently changing what another package recognizes. -Publication outcomes also require separate handling of freshly built -`[]map[string]any` and JSON-decoded `[]any`. - -**Refactoring opportunity.** Start with the publication completion/outcome -payload: provide narrowly typed construction and decoding under an existing -shared contract owner. Let consumers use named fields while retaining -stage-specific decisions, such as cleanup eligibility, at the stage boundary. -Apply the same treatment to extraction control evidence if it removes repeated -producer/consumer knowledge. Keep arbitrary diagnostic metadata flexible. - -This can preserve the existing JSON shape; a new manifest schema or generic -metadata framework is not needed just to centralize conversion. Fresh versus -decoded collection shapes are normal JSON behavior, not a legacy migration -surface. Preserve missing/malformed evidence handling and test a persistence -round trip as well as direct in-memory use. Typed decoding does not replace -identity checks or make successful publication imply that every local output -matches a carried remote object; FC-02 remains a separate correctness issue. - -## Deliberately Retained Complexity - -The audit does not recommend a package split merely because `internal/stage` -and `internal/app` are large. They already contain 51 and 54 non-test Go files -respectively. Moving unchanged branches between files would not address the -duplicated models or mixed responsibilities above. - -Several complex areas have useful existing boundaries: - -- Publication exposes immutable uploads, commit creation, lock revalidation, - and pointer selection in an understandable ordered sequence. Restore - separates discovery, planning, conflict classification, and installation. - Keep those protocol boundaries visible rather than hiding them in a generic - transaction abstraction. -- The runner's explicit stage lifecycle and manifest save ordering coordinate - real failure transitions. Shared invocation handling and checkpoint helpers - already consolidate behavior. A lower decision count alone would not justify - rewriting them. -- Artifact-family expansion and manifest/evidence validation contain many - genuine domain rules. Prefer the shared dependency/source models identified - above to mechanically fragmenting every validator. -- File-operation helpers already have narrow owners. The inspected path - walkers have different read/create/install responsibilities; this audit did - not establish that replacing them with one configurable FileOps framework - would simplify their contracts. -- ConfigKit, CommandKit, external tool semantics, streaming transport, and - adapter isolation remain appropriate upstream/boundary responsibilities. - -## Review Outcome - -Six findings warrant consideration: one confirmed P2 reporting defect with a -cross-package consolidation opportunity, and five P3 maintainability -opportunities. Fix CX-01 first. The highest-leverage structural work is sharing -prepared-input definitions and artifact dependency semantics; phase extraction -can then reduce the reasoning scope of stage and operator entry points. -Publication metadata typing is a narrower follow-up. These are opportunities, -not a requirement to implement all refactors together. - -Earlier open findings remain in [01-correctness.md](01-correctness.md) and -[02-efficiency.md](02-efficiency.md). Apart from CX-01, this pass established no -additional ordinary correctness defect. It does not establish the absence of -other defects or guarantee a net LOC reduction. The main expected gain is fewer -independent definitions and clearer ownership; helpers that only relocate -complexity should be avoided. - -Validation: `GOTOOLCHAIN=go1.27.4 go test ./...`, the focused documentation-link -check, and `git diff --check` passed. The temporary expected-available inspection -diagnostic failed as described in CX-01; the corresponding preparation -diagnostic passed. No bug fixes or refactors were implemented in this pass. diff --git a/docs/roadmap/audit/04-concurrency.md b/docs/roadmap/audit/04-concurrency.md deleted file mode 100644 index 1dd1395..0000000 --- a/docs/roadmap/audit/04-concurrency.md +++ /dev/null @@ -1,317 +0,0 @@ -# Concurrency Audit - -Reviewed on 2026-11-30 against commit -`f02e7ec8deabc0ad7527803298c317f0cfcff21b`. - -## Scope And Evidence - -The review followed goroutine ownership, shared mutable state, channel -lifetimes, cancellation, subprocess supervision, local session locking, -destructive commands, remote publication, and input acquisition. It included -interactions among application orchestration, stages, manifests, artifact -storage, HTTP/subprocess adapters, and object storage. - -Codebase-memory-mcp supplied symbol discovery and caller/callee tracing. Direct -source inspection supplemented incomplete same-named Go method indexing, and a -non-test-source search checked the inventory of goroutines, channels, -synchronization primitives, and cancellation operations. The maintained Go -1.27.4 `os/exec` implementation was inspected for wait and stream-copy lifetime -semantics. - -Existing checks passed with `GOTOOLCHAIN=go1.27.4`: - -```sh -go test -race -count=1 ./... -go test -race -shuffle=on -count=5 ./internal/stage ./internal/artifacts ./internal/adapters/whisperx ./internal/adapters/subprocess -go vet ./... -``` - -No race-detector warning was observed. The findings below are source-established -ordering/lifetime hazards; this pass did not dynamically reproduce their -specific interleavings. Existing tests were inspected to establish what they -exercise. No production code or tests were added or modified. No live S3 -service or paid downstream provider was used. Native execution evidence is -from Linux, not macOS. - -Passing race tests cover only exercised memory-access interleavings. They do -not establish cross-process filesystem exclusion, atomic remote creation, or -correct behavior after the exceptional reaping timeout described below. - -## Current Concurrency Architecture - -Narratio executes its fixed pipeline stages sequentially. Application -orchestration owns the invocation and session lock; stage code owns its local -work, and adapters own HTTP and subprocess lifetimes. ConfigKit configuration -resolution completes before stage execution. The manifest is invocation-owned -mutable authority rather than a generally concurrent store. - -| Area | Implemented ownership and synchronization | -| --- | --- | -| Run, standalone preflight, restore, and final cleanup stage | One per-session OS file lock spans local state transitions. Finalization precedes release. Restore plans local changes under that lock. | -| Transcription | A bounded `errgroup` owns speaker workers and joins them before returning. A mutex serializes collection checkpoints and promotion of saved manifest evidence. Jobs have distinct output paths. | -| WhisperX HTTP | One immutable client can serve workers. Each attempt/replay has its own audio handle and multipart reader. Mutexes protect close/error state; context callbacks close sources to release reads. | -| Subprocesses | One goroutine calls `Cmd.Wait`; a buffered channel reports completion. The supervisor handles cancellation, timeout, and capture failure, with process-group termination on supported platforms. Stdout/stderr copying is concurrent. | -| Diagnostics | Per-stream redactors normally have one copying owner. A shared mutex protects diagnostic file writes, tails, and limit reporting; safe final flush depends on stream-copy completion. | -| Configuration and shared schemas | Configuration acquisition belongs to an invocation. Bundled schema compilation uses `sync.Once`, followed by read-only schema access. | -| Remote publication | Immutable objects and a commit precede current-pointer selection. Lock creation/replacement uses provider conditions; publication rechecks initially unlocked sources before selecting the pointer. This is not a distributed transaction. | - -Manual whole-session cleaning is the important exception to local lock -participation, as described in CN-01. - -## CN-01 — P1: Whole-session cleaning bypasses and can dismantle session exclusion - -Status: Open - -**Relevant code.** -[clean_command.go](../../../internal/app/clean_command.go): -`cleanSelectedSession` (line 70) and `cleanScopedTarget` (line 115); -[paths.go](../../../internal/artifacts/paths.go): `buildSessionPathsFromRoot` -(line 228); -[local.go](../../../internal/artifacts/local.go): -`AcquireSessionLockForContext` (line 204) and `acquireSessionLockForPaths` -(line 229); -[runner.go](../../../internal/app/runner.go): `withLockedInvocation`; -[restore_command.go](../../../internal/app/restore_command.go): -`restoreSessionState`. - -**Circumstances.** A run, restore, or standalone preflight holds the session's -`.lock` while `session clean SESSION` or `session clean --all` executes in -another process. Cleaning validates the target and immediately calls recursive -removal without acquiring an execution lock. The lock file itself lies inside -the removed session tree. - -A possible ordering is: - -1. Invocation A holds the lock on the original `.lock` inode and starts work. -2. Cleaning removes its active inputs, outputs, manifest, diagnostics, and lock - pathname. Holding an advisory file lock does not prevent these removals. -3. Invocation B recreates the session layout and a new `.lock` inode, which it - can lock while A still holds the unlinked original inode. -4. A continues running or finalizing against pathnames that B now also owns. - -**Consequences.** Active work can lose its files or recreate part of a supposedly -cleaned session. More seriously, two invocations can pass the local exclusion -boundary and overwrite each other's manifest/products. Cancellation and restore -recovery markers cannot repair a lock-identity split after the fact. - -**Potential remediation.** Make destructive manual cleaning participate in the -same local coordination scheme as the other mutating operations. Keep the -coordination identity outside every tree that cleaning can delete, or retain -an equivalent stable admission gate while deleting/recreating session paths. -For `--all`, coordinate new session admission as well as already enumerated -sessions; checking existing lock files once leaves another creation race. -Choose wait-versus-busy-error behavior deliberately. - -A stable workspace gate plus session locks can preserve unrelated-session -concurrency. A single exclusive workspace gate is simpler if serializing -different sessions is acceptable, but that would be a separate operational -tradeoff. Merely acquiring the current in-tree lock and then deleting it does -not solve the problem. - -**Existing evidence and gap.** Lock contention, cancellation, process-death -recovery, and preflight-versus-final-cleanup exclusion have existing coverage. -The manual clean tests exercise deletion and path confinement without an active -lock holder. The final pipeline `cleanup` stage already runs under the session -lock and preserves its root/lock; this finding concerns the distinct manual -whole-session commands. It does not require defending against a privileged -external filesystem attacker. - -## CN-02 — P2: Session initialization's no-overwrite check is not atomic - -Status: Open - -**Relevant code.** -[operator_helpers.go](../../../internal/app/operator_helpers.go): -`writeLocalFile` (line 27); -[session_init_command.go](../../../internal/app/session_init_command.go): -`initializeSession` (line 96), particularly local installation and the remote -`Exists`/`Upload` sequence; -[object_store.go](../../../internal/adapters/storage/object_store.go): -`UploadConditional` and `WriteCondition`; -[s3_backend.go](../../../internal/adapters/storage/s3_backend.go): -`UploadConditional` and `uploadReader`. - -**Circumstances.** Two `session init` invocations target the same absent output -without `--force`. Locally, both can pass `os.Stat` before either performs -`os.WriteFile`. That write uses create/truncate behavior rather than exclusive -creation. Remotely, both can observe `Exists=false` before unconditional uploads -to the same key. A different ordinary writer creating the destination during -either interval has the same effect. - -**Consequences.** Initialization can overwrite an output without the requested -force authorization, and both callers can report success. Local writes can -also truncate or mix content under an unlucky open/write ordering. Remote -initialization loses whichever independently authored session document was -uploaded first. - -**Potential remediation.** Enforce absence at the write itself. For local -non-forced creation, use an exclusive create such as -`os.OpenFile(..., O_WRONLY|O_CREATE|O_EXCL, ...)`, with normal write/close error -handling. For remote non-forced creation, use the existing -`UploadConditional` boundary with `RequireAbsent=true` and translate a failed -condition into the existing already-exists/conflict outcome. The preliminary -existence lookup can remain an operator hint, but cannot authorize a later -unconditional write. - -Keep deliberate forced replacement separate. This fix needs neither a -distributed lock nor a new crash/power-loss guarantee. Existing initialization -tests cover local/remote creation and configuration semantics, but do not race -two creators against the same target. Existing storage conditional-write tests -already protect the necessary provider-side mechanism. - -## CN-03 — P2: The exceptional subprocess reap timeout releases ownership too early - -Status: Open - -**Relevant code.** -[execution.go](../../../internal/adapters/subprocess/execution.go): -`executeOwnedCommand` (line 32) and `terminateAndReap` (line 73); -[run.go](../../../internal/adapters/subprocess/run.go): `Run` (line 41); -[diagnostics.go](../../../internal/adapters/subprocess/diagnostics.go): -`diagnosticWriter.Write`, `Flush`, and `logWriters.Close`; -[result.go](../../../internal/adapters/subprocess/result.go): -`boundedResultWriter`; -[Scriptorium adapter](../../../internal/adapters/scriptorium/subprocess.go): -`RunArtifact` and `RenderArtifact`. - -**Circumstances.** After cancellation or capture abort, graceful and forceful -wait timers expire before the wait channel yields a result. `terminateAndReap` -returns an error without receiving from `waitCh`. `executeOwnedCommand` then -reads `cmd.ProcessState`, and `Run` proceeds toward diagnostic flush/closure -and caller return, even though the goroutine running `cmd.Wait` may still be -active. - -This is an exceptional path, for example when process reaping or output-copy -completion is delayed beyond the internal wait windows. It is not necessary -to assume that normal cancellation always reaches it. Go's `Cmd.Wait` sets -`ProcessState` and joins stream copying before returning. `WaitDelay` closes -pipes when its timer expires, but its implementation still waits for copying -goroutines; it cannot interrupt an arbitrary blocked destination `Write`. -Process-group disposal does not join the Go wait goroutine. - -**Consequences.** There is no completion-channel synchronization for reading -`ProcessState` on this branch. A delayed wait can subsequently write that field. -Stream copy can also overlap final redactor flushing, whose per-stream pending -state relies on a single owner rather than a flush/write mutex. Callers can -close a stdout result file after `Run` returns while its copying goroutine -still owns a write to it. A blocked write can also stall final flushing or -leave the wait/copy goroutines alive. Returning an error does not by itself -make those shared resources safe to reuse or close. - -**Potential remediation.** Keep one supervisor responsible for the command and -all associated I/O until completion is joined. Signal-escalation deadlines and -completion/ownership are different concerns: do not treat expiry of the former -as proof of the latter. Inspect `Cmd` state and flush/close writers only after -the wait result is received. Where bounded pipe teardown is necessary, own -and close the relevant pipes before joining their copying operations. - -The simplest safe approach can retain bounded graceful/forceful escalation -while joining completion afterward. If returning before completion remains a -requirement, it needs an explicit ownership handoff that also protects -caller-owned output destinations; adding a mutex around `ProcessState` reads -or starting an unowned background reaper would not suffice. Scope shutdown -claims accurately for delayed kernel I/O rather than introducing an absolute -termination-time guarantee. - -**Existing evidence and gap.** Tests exercise ordinary cancellation, timeout, -capture overflow, retained descendant streams, and descendant disposal after -leader exit. `TestTerminateAndReapPreservesWaitAndCleanupErrors` starts with an -already populated wait channel. Those tests passed, including repeated race -runs, but do not establish safe ownership after the final wait timer expires. -No dynamic race or permanent goroutine leak was reproduced in this pass. - -## CN-04 — P2: S3 audio provenance can combine two object generations - -Status: Open - -**Relevant code.** -[prepare.go](../../../internal/stage/prepare.go): -`materializeS3AudioInputs` (line 423) and `listS3AudioObjects`; -[s3_audio.go](../../../internal/audio/s3_audio.go): -`MaterializeS3Audio` (line 35) and `downloadObjectAtomic`; -[download_writer.go](../../../internal/adapters/storage/download_writer.go): -`DownloadTo`; -[s3_backend.go](../../../internal/adapters/storage/s3_backend.go): -`Read` and `DownloadTo`. - -**Circumstances.** Preparation lists object generation A with size N and ETag -A. Before downloading that key, an ordinary uploader replaces it with different -generation B of the same size. The download fetches the current body, B. -Materialization checks the expected size and hashes those bytes, while -preparation records size/ETag from the earlier listing, A. - -The S3 `Read` operation already returns metadata correlated with its response -body. `S3Backend.DownloadTo` discards that metadata, and the audio result -returns a checksum without a downloaded generation. Nothing on this path -detects the mismatch before installing the file and recording its provenance. - -**Consequences.** The manifest associates B's bytes/checksum with A's source -identity. A later listing of B normally causes a redundant download. A more -consequential sequence is a remote rollback to the original A: the recorded -ETag/size then match A again, while the local B bytes still match their recorded -checksum, so the prepared-copy reuse check can accept B for current source A. -This undermines the existing source-identity-plus-checksum reuse evidence. - -**Potential remediation.** Preserve metadata from the same object read used to -stream the body. Compare its key/size/generation with the selected identity and -fail or reacquire on drift, or explicitly adopt that observed generation and -return it for the manifest record. Either approach must keep the recorded -identity and materialized bytes from one read together. The existing `Read` -boundary provides this information; a second independent listing after download -does not reliably bind the body to a generation. - -This is a per-input provenance correction, not a requirement for a bucket-wide -or whole-session atomic snapshot. Preserve streaming, sibling-temp installation, -and the existing reuse checks. Restore's committed-object checksum/generation -verification is a separate additional check; this finding specifically follows -normal preparation's audio record construction. - -**Existing evidence and gap.** Audio tests cover changed advertised generations, -corrupt or missing prepared copies, failed downloads, size mismatches, and -cancellation. They do not replace the remote object between listing and reading -or exercise the rollback/reuse sequence. This finding follows the concrete -metadata/body data flow; no live-storage interleaving was reproduced. - -## Other Reviewed Behavior - -- Speaker work is joined before the stage returns. Loop jobs are captured - separately, concurrency is bounded, and the first worker error cancels - sibling adapter contexts. Accepted completions serialize through one mutex - and save detached collections before updating live manifest authority. -- Analysis executes configured artifact work sequentially. It shares the - checkpoint mechanism with transcription without adding another concurrent - writer to the same invocation's manifest. -- HTTP body factories own independent handles for replay. Body/source locks, - the once-completed close channel, and cancellation callbacks avoid double - closing and release blocked reads in the existing tests. Shared HTTP client - settings are read-only during speaker work. -- Normal subprocess completion receives the wait result before final stream - handling. Buffered wait/abort channels avoid requiring a receiver at every - send, and only the supervisor calls `Cmd.Wait`. CN-03 concerns the exceptional - completion timeout, not that normal protocol. -- Run, restore, preflight, and final pipeline cleanup share a session lock. - Terminal manifest persistence narrowly detaches cancellation while holding - that lock; adapter work and ordinary checkpoints retain operation contexts. -- Remote lock creation/replacement uses provider preconditions. Publication's - final lock-check/pointer-write interval is an expressly documented limited - race window, not a newly discovered distributed-transaction defect. Read-only - inspection similarly does not promise a transactional local/remote snapshot. -- Test-fake request/object operations and shared schema initialization have - synchronization. Their mutable setup fields are configured before use; - this audit does not impose concurrent reconfiguration on those types. - -## Review Outcome - -Four findings warrant consideration. CN-01 is the highest-priority data-safety -gap; CN-02 and CN-04 concern check/use races across persistence boundaries. -CN-03 identifies unsafe ownership on an exceptional shutdown path despite -passing normal-path race tests. The current architecture does not need a -general concurrency framework to address them. - -Prior findings remain in [01-correctness.md](01-correctness.md), -[02-efficiency.md](02-efficiency.md), and [03-complexity.md](03-complexity.md). -This pass does not duplicate them, implement remediations, or establish the -absence of other races, deadlocks, or leaks. - -The documentation-link check and whitespace validation also passed. Only this -audit record was changed. diff --git a/docs/roadmap/audit/05-resources.md b/docs/roadmap/audit/05-resources.md deleted file mode 100644 index b373301..0000000 --- a/docs/roadmap/audit/05-resources.md +++ /dev/null @@ -1,285 +0,0 @@ -# Resource Management Audit - -Reviewed on 2026-11-30 against commit -`f0e45b60350f930e4de05d4d7c76ffc9ca350077`. - -## Scope And Evidence - -The review traced file descriptors, temporary files/directories, memory and -buffer retention, network bodies and transports, timers, cancellation callbacks, -goroutines, process supervision, and cleanup ownership. It followed their -lifecycles across application orchestration, stages, manifests, artifact -resolution, file operations, and HTTP/subprocess/object-storage adapters. - -Codebase-memory-mcp supplied symbol discovery and caller tracing. Direct -source inspection and a non-test-source search supplemented incomplete indexing -of same-named Go methods. Acquisition sites were matched to normal, error, and -cancellation cleanup paths. Previous audit records were checked to avoid -duplicating their findings. - -These existing checks passed with `GOTOOLCHAIN=go1.27.4`: - -```sh -go test ./... -go test -count=1 ./internal/fileops ./internal/audio ./internal/adapters/storage ./internal/adapters/whisperx ./internal/adapters/subprocess ./internal/stage -go vet ./... -``` - -The focused run exercised existing body-close, cancellation, temporary-file, -failed-transfer, bounded-output, checkpoint, and publication tests. Those tests -support the baseline resource mechanisms; they do not reproduce every finding -below. No production code or tests were added or modified. No benchmarks, -heap profiles, descriptor-exhaustion experiments, disk-filling tests, live S3 -requests, or paid-provider calls were performed. Native execution evidence is -from Linux. - -## Current Resource Ownership - -Narratio runs its fixed stages sequentially and bounds concurrent speaker -transcription. The invocation owns its session lock and composed collaborators; -stages own local attempts and product promotion; adapters own HTTP bodies, -subprocesses, and transfer mechanics. The manifest is the durable progress -ledger. Failed attempts and diagnostics are intentionally retained under -`runs/` until authorized cleanup, while subprocess applications own their -separate state and caches. - -| Resource | Implemented lifecycle | -| --- | --- | -| Session locks | A held file descriptor owns the OS lock. Run, preflight, and restore defer release through terminal persistence. | -| Speaker workers | A bounded `errgroup` joins workers before stage return. Checkpoint updates are serialized and retain the selected complete-collection behavior. | -| HTTP uploads/responses | Multipart attempts and replays own independent audio handles. Cancellation closes sources; the attempt closes all tracked bodies and its response body. | -| Subprocesses and logs | The shared supervisor owns process groups and a wait goroutine. Normal completion joins stream copying before final flushing/closure. Diagnostic streams and result stdout have explicit per-invocation limits. | -| Ordinary file replacement | Sibling temporary files are closed and either renamed or removed on handled errors. Canonical promotion follows validation. | -| Remote control objects | Bounded readers enforce byte limits during transfer, close bodies on every exit, and retain only control-document-sized payloads. | -| Remote products/audio | Transfers stream into temporary files, with validation before installation. RS-02 concerns the missing transfer-time enforcement of already-known sizes. | -| Publication sources | Sources are opened and retained through publication. RS-01 concerns how this scales with the complete source inventory. | -| Configuration and schemas | ConfigKit owns resolution. Configuration acquisition owns downloaded session-file cleanup; compiled bundled schemas are retained once for reuse. | - -## RS-01 — P2: Publication retains one open descriptor per source - -Status: Open - -**Relevant code.** -[publish.go](../../../internal/stage/publish.go): `publishStage.Run`; -[publish_sources.go](../../../internal/stage/publish_sources.go): -`openPublishRunFiles` (line 249), `openPublishSourceUnderRoot`, and -`closePublishSources`; -[publish_transfer.go](../../../internal/stage/publish_transfer.go): -`buildPublishTransferPlan` (line 24), `uploadPublishTransfers` (line 151), and -`closePublishTransfers` (line 309). - -**Circumstances.** Publication first opens every declared current-run archive -file and retains those descriptors. It then opens every previous-cache source, -opens each selected local publication output, and adds the committed manifest. -All remain open until the stage's deferred cleanup. Uploading is sequential; -completed transfers do not release their source descriptors as they finish. - -For R run files, P previous-cache files, and O newly published outputs, the -retained source-descriptor count is R+P+O+1, plus locks, network connections, -diagnostic handles, and temporary directory traversal handles. A product can -also be opened separately for its run archive and publication destination. -Artifact families, per-artifact logs/configuration, speaker outputs, and -previous-session products all contribute to this count. - -**Consequences.** A sufficiently large valid inventory can exhaust the -process's descriptor limit before uploading begins, even though the transfer -algorithm needs only one active upload. Publication then fails with an -open-file error and retrying the same inventory has the same pressure. -Successful/error defers generally close the descriptors afterward: this is -over-retention and capacity scaling, not a demonstrated permanent normal-path -descriptor leak. - -The audit host's soft descriptor limit was 1,048,576; this review did not attempt -to exhaust it. That limit is an environment setting, not a Narratio guarantee. -The source-count dependency remains relevant to deployments with lower limits; -no universal failure threshold is asserted. - -**Potential remediation.** Separate the complete immutable destination mapping -from possession of all its source handles. Use a bounded source-opening window -and close a source after its verified transfer/reuse check, preserving confined -opening, checksum validation, and hashing/uploading through the same descriptor. -Keep the current-pointer write after every declared object has been accepted. - -An upfront validation pass can remain bounded as well. Review the documented -upfront source-rejection behavior when designing that pass; merely replacing -verified descriptors with unchecked pathname uploads would discard an existing -safety boundary. If pinning every original inode for the entire attempt is a -deliberate requirement, disk-backed verified snapshots offer a bounded-FD -alternative with an explicit disk/I/O tradeoff. Raising the descriptor limit -is an operational mitigation, not removal of the scaling dependency. Avoid -imposing a new artifact-count restriction as the default fix. - -**Existing evidence and gap.** Publication tests cover declared-source -confinement/replacement rejection, immutable mapping, upload failure, and pointer -ordering. Their small inventories do not establish behavior near a low -descriptor limit. Retain those safety checks when changing handle lifetime. - -## RS-02 — P2: Known-size downloads consume the full response before rejecting oversize - -Status: Open - -**Relevant code.** -[restore_execute.go](../../../internal/app/restore_execute.go): -`executeRestoreDownloadAction` (line 97), `downloadRestoreTemp`, and -`verifyRestoredObject` (line 282); -[prepare_previous.go](../../../internal/stage/prepare_previous.go): -`hydratePreviousSessionArtifacts` (line 35), `writePreviousTemp`, and -`validatePreviousTemp`; -[s3_audio.go](../../../internal/audio/s3_audio.go): -`downloadObjectAtomic` (line 95) and `validateLocalAudio`; -[publish_transfer.go](../../../internal/stage/publish_transfer.go): -`verifyExistingImmutableObject` (line 219); -[temp_download.go](../../../internal/adapters/storage/temp_download.go) and -[s3_backend.go](../../../internal/adapters/storage/s3_backend.go): streaming -download implementations. - -**Circumstances.** These callers know an expected object size from a committed -declaration, selected source identity, or already-hashed local upload source. -They nevertheless stream the entire remote body into a temporary file and check -size only after the download completes. The underlying `DownloadTo`/`Download` -paths copy to EOF without a caller-supplied byte boundary. - -Examples include restoring a small committed artifact whose remote key was -accidentally replaced with a much larger object, or downloading audio after its -listed object was replaced. The content will eventually be rejected when its -declared size/checksum disagrees, but every returned byte has already consumed -staging space. A faulty or unexpectedly long response can consume far more -space than the already-selected object identity permits. - -**Consequences.** An invalid transfer can fill the workspace or system temporary -volume, interfere with other operations, and hold the session lock for a large -unnecessary download. Handled failures generally remove the temporary file and -preserve the canonical destination; that cleanup does not prevent temporary -exhaustion or the effects on other writers before removal. - -**Potential remediation.** Enforce the existing expected size while streaming. -For a known-size object, inspect metadata from the opened response and perform -a bounded size-plus-one read/copy so the caller can distinguish exact content -from oversize and stop promptly. Close the body and remove partial staging on -failure. A larger `Content-Length` can reject early, but the actual byte count -must remain authoritative. Retain checksum/generation validation and canonical -installation ordering. - -This does not require buffering artifact bodies or using the small-control- -object helper for large payloads. Preserve the current meaning of unknown-size -audio; a universal audio cap would be a separate policy choice. For committed -objects, a declared zero-byte size is known, rather than an unknown-size signal. -Errors should identify the responsible transfer boundary and expected byte -count. The observed-size metadata work in CN-04 is a related acquisition seam, -but provenance correctness and transfer-space enforcement are distinct concerns. - -Stopping at a size already required by validation adds no new user-data limit. -Aggregate workload size and intentionally retained outputs still require the -existing [capacity guidance](../../operations.md#local-state-layout) and -[retention policy](../../operations.md#cleanup). This finding does not promise -to prevent every disk-full condition or reserve disk space. - -**Existing evidence and gap.** Tests establish that short/wrong-size downloads -fail and preserve destinations, and that failed temporary downloads are removed. -The bounded control-object tests demonstrate early metadata rejection and -limit-plus-one enforcement. The large-payload callers above do not use an -equivalent transfer boundary, and existing tests do not establish that an -oversized body is stopped before it is fully staged. - -## RS-03 — P3: Publication's temporary manifest has cleanup gaps before ownership transfer - -Status: Open - -**Relevant code.** -[publish_commit.go](../../../internal/stage/publish_commit.go): -`writeCommittedSessionManifest` (line 99); -[publish.go](../../../internal/stage/publish.go): the helper call followed by -`appendCommittedSessionManifest`; -[publish_transfer.go](../../../internal/stage/publish_transfer.go): -`appendCommittedSessionManifest` (line 117) and `closePublishTransfers`. - -**Circumstances.** The writer creates a file in the system temporary directory. -If writing or closing fails, it returns an empty pathname without removing the -file. The descriptor is closed or a close is attempted, but the created path -remains. On successful writing, a later `os.Open` in -`appendCommittedSessionManifest` can fail before adding the path to the -transfer collection. The caller has no separate removal defer for that gap. -Descriptor exhaustion from RS-01 is one possible cause of this second failure. - -**Consequences.** Failed publication can leave partial or complete -`narratio-committed-session-manifest-*.json` files outside the session's `runs/` -tree. Repeated disk-pressure, permission, or open-file failures can accumulate -untracked temporary files. Session cleanup does not own this system-temp -location. These are disposable publication intermediates, not intentionally -retained attempt diagnostics. - -**Potential remediation.** Give the creator cleanup responsibility immediately -after creation, retaining that responsibility on every error. On successful -return, make the caller responsible for removal until the transfer plan -explicitly accepts ownership. Normal transfer cleanup can then remain the -successful-path owner. Straightforward deferred removal with a clear handoff -is sufficient; no general temporary-resource framework is needed. - -**Existing evidence and gap.** Normal publication puts `TemporaryPath` on the -transfer and `closePublishTransfers` closes/removes it. This finding concerns -the earlier error paths, not a successful-publication leak. Existing tests do -not inject temp-manifest write/close or ownership-handoff open failures. - -## Previously Recorded Resource Findings - -- **EF-01**, in [02-efficiency.md](02-efficiency.md), already records local - recording copies buffered through `os.ReadFile`. One large speaker recording - can require recording-sized RAM even though the repository has a streaming - copy primitive. It remains the clearest existing memory-pressure finding. -- **CN-03**, in [04-concurrency.md](04-concurrency.md), already records the - exceptional subprocess reap-timeout ownership gap. Its effects include live - wait/copy goroutines and premature writer cleanup. It remains relevant to - resource release after cancellation and is not duplicated here. -- **EF-05** records nested inspection-error aggregation whose formatting can - allocate quadratically. That finding also remains relevant without becoming - a new memory-retention issue in this pass. - -## Other Reviewed Lifecycles And Deliberately Retained Behavior - -- Ordinary file/root handles have local closes or explicit ownership returns. - Restore planning closes inspected files and traversed roots; installation - processes temporary objects sequentially. Shared file-replacement helpers - remove sibling temporary files on handled pre-rename failures. -- Downloaded remote session configuration normally transfers its removal - callback to invocation-owned configuration acquisition. Error and - cancellation paths invoke cleanup; successful command finalization closes - that acquisition. Audita's synthetic preflight directory has a local removal - defer. -- WhisperX response bodies, original upload bodies, and replay bodies have - cleanup paths. Per-attempt timeout contexts are canceled after use, and - retry/lock-wait/supervisor timers are stopped where appropriate. Multipart - cancellation callbacks are unregistered or complete through source closure. - No additional normal-path goroutine/timer leak was established. -- HTTP transport pooling and shared compiled schemas have useful reuse - lifetimes. The current CLI does not establish a further unbounded connection - or schema-retention defect merely because those resources remain reusable. - SDK/library-owned pools are not reimplemented in Narratio. -- Diagnostic redaction/tails and adapter result buffers are individually - bounded. Scriptorium requirement inspection uses a bounded stdout writer - despite retaining its JSON in memory. Notarius lanes are validated/staged - one at a time rather than retaining every lane's bytes together. -- Manifests keep current stage/collection state rather than an append-only - invocation history. Whole-collection checkpoint copying and serialization - have a cost, but are deliberately selected behavior rather than a new leak. -- Original tool bundles, failed runs, debug files, reference snapshots, and - subprocess-owned state/caches follow their selected retention/ownership - rules. This audit does not introduce automatic pruning or reinterpret retained - diagnostics as leaked temporary files. Ordinary aggregate disk use remains - an operator capacity/quota responsibility. - -## Review Outcome - -Three new findings warrant consideration: descriptor capacity during -publication, late oversize rejection during known-size transfers, and an -error-path temporary-file ownership gap. They arise within helpers and across -stage/adapter boundaries. The earlier audio-copy memory and subprocess -lifetime findings should also be included when prioritizing remediation. - -No additional ordinary correctness defect was established independently of -these resource findings. The review does not establish absence of other leaks -or exhaustion conditions. The expected direction is shorter resource lifetimes, -streaming, and explicit ownership, rather than new global limits or a generic -resource-management framework. - -The documentation-link check and whitespace validation also passed. Only this -audit record was changed. diff --git a/docs/roadmap/audit/06-error-handling.md b/docs/roadmap/audit/06-error-handling.md deleted file mode 100644 index cad4998..0000000 --- a/docs/roadmap/audit/06-error-handling.md +++ /dev/null @@ -1,200 +0,0 @@ -# Error-Handling Audit - -Reviewed: 2026-11-30 - -Baseline: `7a9bbbde9f850debc87e17e6d305c755b6b53fd8` - -## Scope And Evidence - -This review examined failure detection, propagation, reporting, cancellation, -timeouts, and recovery across configuration acquisition, CLI outcomes, -preflight, pipeline execution, speaker/artifact checkpoints, subprocess and -HTTP adapters, local persistence, remote publication, restore, and cleanup. - -The knowledge graph located implementations and call relationships. Direct -source inspection supplemented its incomplete indexing of same-named Go -receiver methods. Findings were checked against the architecture, CLI, -configuration, manifest, artifact, stage, storage, and operator documentation -and relevant existing failure tests. - -Verification used Go 1.27.4: - -- `go test ./...` passed; this run used cached package results. -- Fresh `go test -count=1` runs passed for `internal/app`, `internal/stage`, - `internal/preflight`, `internal/adapters/whisperx`, - `internal/adapters/subprocess`, `internal/adapters/storage`, - `internal/manifest`, `internal/fileops`, and `internal/artifacts`. -- `go vet ./...` passed. -- `go test -count=1 ./internal/doccheck` passed after writing this report. -- A temporary CLI binary reproduced EH-01 using maintained examples and two - small configuration fixtures outside the repository. These commands performed - planning and configuration validation; they invoked no providers or pipeline - stages. - -No production code or tests were changed. This was an offline implementation -review, not live infrastructure, disk-failure, or kernel-stall fault injection. -Existing tests and successful checks establish the paths they exercise; they -do not prove that every exceptional condition is covered. - -## Current Failure-Handling Architecture - -- CommandKit owns CLI execution and reporting; ckconfig adapts native ConfigKit - diagnostics. Narratio adds domain-input classification and preserves mixed - operational failures through wrapped and joined errors. -- The application runner holds a session lock, persists stage transitions, - stops on failure, and attempts terminal manifest persistence with cancellation - detached from that final local save. Persistence and lock-release errors are - returned alongside the originating failure. -- Transcription joins bounded concurrent speaker workers. Transcription and - analysis checkpoint typed progress collections through the shared manifest - persistence helper. Failed checkpoint saves retain prior durable authority. -- Adapters own external transport and process failures. WhisperX uses - replayable streaming request bodies, per-attempt timeouts, selected retries, - and cancellable retry delays. The subprocess runner owns process-tree - termination, bounded output capture, credential redaction, and diagnostics. -- Stages validate run-local products before canonical promotion. Resume uses - manifest evidence and content identities; missing or changed evidence can - request regeneration without certifying incidental files as completed work. -- Publication selects a remote snapshot only after immutable transfers and - commit creation. Restore verifies selected objects, installs the manifest - last, and retains an incomplete-restore marker after installation failure. - Cleanup is a separate, explicitly enabled stage. - -## EH-01 — P3: Domain configuration failures lose the CLI input classification - -Status: Open - -**Relevant code.** - -- [Resolved validation](../../../internal/config/validate.go), `Validate` - (lines 41–45), returns product-destination and cross-document validation - failures without a typed input-error marker. -- [Cross-document validation](../../../internal/config/validate_core.go), - `validateCrossConfig` (lines 109–123), rejects incompatible storage/audio - selections using ordinary errors. -- [Product destination validation](../../../internal/config/product_destinations.go), - `validateProductDestinations` (lines 29–33), returns ordinary errors for - invalid placement or colliding configured destinations. -- [CLI classification](../../../internal/app/command_outcome.go), - `classifyOperationError` (lines 31–56), recognizes Narratio request errors, - artifact-catalog input errors, and native ConfigKit diagnostics. These - unmarked domain errors fall through to ckconfig's operational classification. -- [Execution entry point](../../../internal/app/execution_command.go), - `executeSelectedPipeline`, returns `config.Validate` failures unchanged. - Planning, preflight, status, restore, and lock commands also consume resolved - domain validation. - -**Failure condition.** Individually loadable documents form an invalid resolved -configuration, or a completed configuration selects colliding product paths. -The failure is an identified configuration mistake, rather than a missing file, -network failure, cancellation, or ambiguous loading callback failure. - -**Expected behavior.** The existing [CLI exit-status contract](../../cli.md#cancellation-and-exit-status) -assigns status `2` to identifiable invalid configuration input. These domain -rejections should retain that classification and their explanatory cause. -Unrelated operational, cleanup, and cancellation causes must retain precedence -when joined with them. - -**Actual behavior and reproduction.** A CLI built from the baseline produced: - -1. With the maintained minimal pipeline, sample campaign, and S3-audio session: - - ```sh - narratio session plan 2026-05-03 \ - --config examples/pipeline.minimal.yml \ - --campaign-file examples/campaigns/sample-campaign/campaign.yml \ - --session-file examples/session.s3-audio.yml - ``` - - It reported that `pipeline.storage.backend must be s3 when - session.inputs.audio_s3 is configured`, but exited with status `1`. - The same command using `examples/session.local-audio.yml` succeeded with - status `0`. - -2. A temporary pipeline containing the required valid WhisperX URL and - `normalize.output_path: transcripts/base.json`, combined with the sample - campaign and local-audio session, was rejected because the base and final - transcripts share a destination. It also exited with status `1`. - -3. As a control, a temporary pipeline with an invalid WhisperX URL was rejected - by native ConfigKit validation and exited with status `2`. - -The error messages are useful and the commands stop before execution. The -defect is inconsistent failure classification, not acceptance of invalid -configuration or observed data corruption. Automation cannot consistently -distinguish configuration corrections from operational failures using the -documented statuses. - -**Potential remediation.** Give positively identified domain-validation failures -a small typed configuration-input error that preserves its cause, and recognize -it at the existing CLI classification boundary. Apply it where these semantic -checks reject supplied values, following the existing artifact-catalog input -error pattern. Preserve the current wrapped/joined-error operational precedence. -Path-resolution or other environmental failures remain operational. - -An alternative is to adapt these domain checks into native ConfigKit validation -diagnostics at a suitable completed-configuration boundary. That requires more -coordination because the checks span separately loaded documents; it should -preserve ConfigKit's configuration-resolution ownership. A narrow domain error -is the simpler local approach. Neither approach requires new validation rules or -reclassifying every error returned by configuration code as an input mistake. - -**Verification when addressed.** Retain behavioral CLI checks for a cross-document -storage conflict and a destination collision returning status `2`, a valid -combination succeeding, and input errors joined with cancellation or operational -failures returning status `1` with both causes preserved. Existing native -configuration and artifact-catalog classification tests cover the neighboring -cases, not these two rejections. - -## Related Findings Already Recorded - -These failure-path issues remain relevant and retain their existing owners: - -- [FC-02](01-correctness.md#fc-02--p2-carried-publication-bytes-conflict-with-restored-manifest-evidence): - restore can report success while installed carried products disagree with - restored completion evidence. -- [FC-03](01-correctness.md#fc-03--p2-session-planning-reports-reusable-s3-preparation-as-changed): - planning converts its missing S3 inspection collaborator into a definite - changed-input result rather than representing the inspection limitation. -- [CN-03](04-concurrency.md#cn-03--p2-the-exceptional-subprocess-reap-timeout-releases-ownership-too-early): - an exceptional reap timeout returns while process waiting and stream copying - may still own resources that callers subsequently close. -- [RS-02](05-resources.md#rs-02--p2-known-size-downloads-consume-the-full-response-before-rejecting-oversize): - some downloads detect an oversized object only after consuming the body. -- [RS-03](05-resources.md#rs-03--p3-publications-temporary-manifest-has-cleanup-gaps-before-ownership-transfer): - publication can orphan a temporary manifest on write, close, or - ownership-handoff failure. - -These are cross-references, not additional findings from this pass. - -## Deliberate Behavior And Review Outcome - -The following choices were not treated as defects: - -- Console-reporting methods intentionally leave delivery-error retention to - CommandKit so broken output does not interrupt checkpoint persistence. - Delivery failure can still fail the invocation after durable work completes. -- Secondary Audita report discovery is best-effort after a primary process or - output-validation failure. The primary error and diagnostic locations remain - available. -- Read-handle close errors and best-effort temporary cleanup are not uniformly - required to override an already useful failure. RS-03 concerns a specific - missing ownership cleanup, rather than every ignored cleanup error. -- Preparation explicitly treats changed or unavailable resume evidence as a - normal rerun. This audit does not introduce a general requirement that every - failed evidence check preserve prior success. FC-03 covers the distinct - planning/execution discrepancy. -- Optional source absence and explicitly non-current artifact evidence can be - represented as unavailable under their existing contracts. This does not - establish a general license to suppress unrelated transport or persistence - errors. -- Partial canonical promotion and restore do not promise rollback of every - completed write. Durable manifest authority, output verification, and the - restore recovery marker govern subsequent recovery. -- Abrupt process death, power-loss durability, automatic retry of every failure, - and atomic rollback across multiple products are outside the selected - guarantees. - -One new P3 finding was confirmed. The reviewed ordinary failure, retry, -checkpoint, cancellation, and terminal-reporting paths otherwise preserve the -selected behavior, subject to the separately recorded findings above. diff --git a/docs/roadmap/audit/08-testing.md b/docs/roadmap/audit/08-testing.md deleted file mode 100644 index c891794..0000000 --- a/docs/roadmap/audit/08-testing.md +++ /dev/null @@ -1,334 +0,0 @@ -# Test Coverage And Effectiveness Audit - -Reviewed: 2026-11-30 - -Baseline: `8f7d2ab1811314f0ae0af9feb4bdc67d2b27ff5a` - -## Scope, Policy, And Evidence - -This audit evaluated both missing behavioral protection and candidates for -removal or simplification against the [testing policy](../../policy/testing.md). -The review covered CLI classification, configuration, stage transitions, -speaker/artifact checkpoints, adapters, publication/restore, concurrency, -destructive operations, and shared file/manifest helpers. Existing contract and -implementation documents supplied the requirements; coverage percentages did -not create additional requirements. - -The knowledge graph located tests and collaborators. Source inspection -supplemented its incomplete indexing of same-named receiver methods. The review -examined assertions and fixture behavior as well as executed statements. - -Verification used Go 1.27.4 on Linux: - -- `go test -count=1 -covermode=atomic -coverpkg=./... -coverprofile= ./...` - passed. `go tool cover -func=` reported **83.9%** total - statement coverage. Cross-package instrumentation includes coverage supplied - by consumers, rather than treating each package's own tests as its only - protection. -- `go test -race -shuffle=on -count=3 ./...` passed. -- `go test -count=1 ./internal/doccheck` passed after writing the report. -- Two temporary S3 adapter mutations were evaluated with Go's `-overlay` - option. Replacing the upload body with fixed incorrect bytes survived the - full existing suite. Changing the provider request key failed the existing - upload test, establishing that the overlay was effective. -- A temporary metadata struct-field reorder failed the existing JSON test - while retaining the same JSON object members and values. - -Coverage profiles, overlay files, and mutated source copies were outside the -repository. No application code or tests were changed. The mutation checks were -targeted experiments, not an exhaustive mutation score. No paid services, live -object storage, or optional external-binary compatibility checks were used. - -## Architecture And Existing Strengths - -Narratio is a fixed-stage Go orchestrator. CommandKit owns CLI execution and -reporting; ConfigKit owns configuration resolution. Narratio derives and -validates its domain configuration, then runs stages under a session lock. -Stages use adapter interfaces for WhisperX, Seriatim, Audita, Notarius, -Scriptorium, and object storage. Shared manifest persistence records stage and -sub-stage progress. Publication selects an immutable remote snapshot through a -current pointer; restore verifies that snapshot and installs manifest authority -last. Cleanup is a separate stage and a separate whole-session command. - -The suite generally follows the policy's classical style: real local files and -manifest stores, HTTP test servers, subprocess helper executables, and fakes at -external boundaries. Particularly useful protection includes: - -- durable speaker/artifact progress after adapter and checkpoint failures; -- retry reuse and preservation of unrelated completed work; -- cancellation propagation, request-body replay, process-tree cleanup, and - credential redaction across subprocess integrations; -- bounded-read boundary cases and atomic replacement preserving old content; -- immutable publication ordering, conditional remote locks, and interrupted - restore recovery; -- configuration provenance, secret-safe projections, maintained examples, - native structured CLI reports, and output-delivery failures. - -These tests should be retained. The findings below concern specific missing -conditions or avoidable coupling, not a proposal to replace the suite. - -## TE-01 — P2: S3 upload tests do not verify the transmitted content - -Status: Open - -**Functionality and tests.** -[S3 backend](../../../internal/adapters/storage/s3_backend.go), `uploadReader`; -[S3 tests](../../../internal/adapters/storage/s3_backend_test.go), -`fakeS3API.PutObject` (lines 111–119), `TestS3BackendUploadAndExists`, and -`TestS3BackendConditionalUploadUsesProviderPrecondition`. - -**Deficiency.** The fake records `PutObjectInput` and returns an ETag without -consuming its body. Assertions inspect keys, returned metadata, and -preconditions, but never compare the supplied stream with the expected bytes. -Higher-level publication tests use the separate `storage.FakeBackend`, so they -also bypass this production adapter mapping. - -**Evidence and unprotected failure.** A temporary overlay changed the production -request from `Body: source` to a reader containing a fixed incorrect string. -`go test -count=1 -overlay= ./...` still passed. A separate wrong-key -overlay failed `TestS3BackendUploadAndExists` as expected. Thus the suite can -accept an adapter that uploads unrelated content despite exercising the upload -function. This is a test gap; the unmodified adapter currently passes the -correct source reader. - -**Improvement.** Have the narrow SDK fake consume and retain request bytes during -`PutObject`, then compare them with the caller's payload for file-backed and -reader/conditional uploads. Include propagation of a simulated stream-read -failure where warranted. A small HTTP test server exercising the real SDK is -also viable if it adds useful transport confidence. Live S3 is unnecessary. -Retain the current key and precondition checks; they detected the control -mutation. - -## TE-02 — P2: Publication and restore tests do not prove carried-output authority is coherent - -Status: Open - -**Functionality and tests.** -[Publication tests](../../../internal/stage/publish_test.go), -`TestPublishCarriesLockedRequiredOutputAndCommits` (line 726); -[restore commit tests](../../../internal/app/restore_commit_test.go), -`TestCommittedRestoreDownloadsCarriedOutputFromDeclaredRun` (line 129) and -`seedCommittedRestoreSnapshot` (line 442); -[restore workflow tests](../../../internal/app/restore_workflow_test.go). - -**Deficiency.** Publication assertions prove that a lock carries the old object -declaration and avoids uploading a replacement. Restore assertions prove that -the exact carried object is downloaded. They do not follow a real publication -through restoration and resolve the resulting artifact against its restored -stage/per-artifact evidence. The general restore fixture uses a synthetic -`fixture` stage rather than authentic producer/checkpoint state. One previous- -cache workflow repairs manifest evidence after restoration before testing the -consumer, so that test proves the consumer's behavior after repair. - -**Unprotected behavior.** Publish A, lock it, generate local B, republish while -carrying A, and restore into an empty workspace. The restored bytes and -completion authority must agree. [FC-02](01-correctness.md) establishes that -current code can return successful restoration with A's bytes and B's evidence; -the existing green tests do not detect that interaction. - -**Improvement.** Add one focused cross-package round trip using the real publish, -remote-state discovery, restore, and artifact resolver with an in-memory object -store. Inspect restored bytes, checksums/provenance, and appropriate reuse or -rebuild decisions without repairing the restored manifest in the test. Include -the distinct built-in and configured-artifact authority paths when fixing -FC-02. Keep narrow transfer tests for their separate risks; every restore test -does not need a full pipeline fixture. - -## TE-03 — P2: Previous-session hydration coverage stops short of dependency closure - -Status: Open - -**Functionality and tests.** -[Effective-set tests](../../../internal/artifacts/effective_set_test.go), -`TestCollectPreviousArtifactRequirementsUsesExactEffectiveSet`; -[prepare selection test](../../../internal/stage/prepare_effective_artifacts_test.go), -`TestCollectPreparePreviousRequirementsUsesExplicitDisabledArtifact`; -[hydration tests](../../../internal/stage/prepare_previous_test.go); -[incremental analysis tests](../../../internal/stage/analyze_incremental_execution_test.go), -`TestAnalyzeRebuildsNestedStalePrerequisitesInDependencyOrder`. - -**Deficiency.** Requirement-collection tests select a disabled artifact directly. -Analysis tests independently verify rebuilding disabled prerequisites. Hydration -tests pass an already constructed requirements list. These fixtures omit the -combination in which an enabled or explicitly selected child requires a disabled -prerequisite that itself consumes previous-session input. - -**Unprotected behavior.** Preparation must hydrate history needed by actual -prerequisite work while excluding unrelated disabled artifacts. Required -history must reach the downstream request; optional history must not disappear -solely because its consumer was scheduled as a prerequisite. The missing -combination allowed [FC-01](01-correctness.md). - -**Improvement.** Exercise preparation followed by analysis for a selected child, -a disabled prerequisite with a previous-session binding, and an unrelated -disabled artifact. Use real selection/hydration/planning and fake external -storage/generation. Assert the hydrated source identity and downstream binding, -as well as exclusion of unrelated work. A small required/optional table can -protect the different observable failure modes. Do not broaden the meaning of -explicit publication targets merely to make this test pass. - -## TE-04 — P2: Whole-session cleanup tests never contend with an active invocation - -Status: Open - -**Functionality and tests.** -[Manual cleanup](../../../internal/app/clean_command.go); -[cleanup command tests](../../../internal/app/clean_test.go) and -[selection tests](../../../internal/app/clean_command_test.go); -[local lock tests](../../../internal/artifacts/local_test.go); -[restore locking tests](../../../internal/app/restore_recovery_test.go), -`TestRestoreHoldsTransitionLockBeforePlanning`. - -**Deficiency.** Manual cleanup tests verify scope, preserved storage, missing -targets, dry-run behavior, and unsafe destinations with no lock holder. Separate -tests prove that the lock implementation and restore coordinate with runners. -No test combines `session clean` or `--all` with an active runner, restore, or -preflight. Final-stage cleanup tests exercise a different, already locked path. - -**Unprotected behavior.** Deletion must not dismantle an active session's -single-writer exclusion or let a second invocation acquire a new lock inode -while the first still writes. [CN-01](04-concurrency.md) records the current -production defect. A passing race detector cannot establish this filesystem -coordination property. - -**Improvement.** Use real temporary workspaces and OS locks, with channels -holding an invocation at a known active point. Exercise session-scoped and -whole-workspace deletion and a second contender. Assert no deletion during -active ownership and no overlapping writers. Encode wait-versus-busy behavior -after that remediation decision is selected; the test should not invent it. -Include whole-workspace admission behavior in the `--all` case rather than -assuming a single existing session lock covers new invocations. - -## TE-05 — P2: Subprocess lifecycle tests do not exercise a delayed reap after escalation - -Status: Open - -**Functionality and tests.** -[Owned execution](../../../internal/adapters/subprocess/execution.go), -`terminateAndReap` (lines 73–92); -[execution unit test](../../../internal/adapters/subprocess/execution_test.go), -`TestTerminateAndReapPreservesWaitAndCleanupErrors`; -[process-tree tests](../../../internal/adapters/subprocess/process_tree_supported_test.go). - -**Deficiency.** The unit test preloads the wait channel, so it always takes the -early completion path. Real-process cancellation, timeout, capture-limit, and -descendant-disposal tests cover useful ordinary behavior, but none withholds -wait completion beyond escalation. Coverage reports `terminateAndReap` at -45.5%; its post-grace escalation and final forceful-wait outcomes are unexecuted -in this run. - -**Unprotected behavior.** A delayed waiter or stream copier must retain ownership -until the relevant cleanup boundary is safe. Otherwise caller cleanup can race -with still-running work. [CN-03](04-concurrency.md) identifies that exceptional -path in the production implementation. Ordinary process tests and a successful -race run do not exercise it. - -**Improvement.** When addressing CN-03, use a controlled process-tree/waiter -boundary that completes only after escalation and observes when output -resources are released. Assert the ownership/join relationship and preservation -of wait/cleanup causes. Reuse the existing real-process tests for normal OS -behavior. Avoid requiring an actual unkillable process, freezing private delay -constants, or adding a new absolute kernel-I/O completion guarantee. - -## TE-06 — P3: CLI classification tests omit real resolved-domain rejections - -Status: Open - -**Functionality and tests.** -[Outcome tests](../../../internal/app/commands_boundary_test.go), -`TestOperationOutcomePreservesCausesAndOperationalPrecedence`; -[catalog command tests](../../../internal/app/config_artifacts_test.go), -`TestNativeCatalogValidationErrorsAreUsage`; -[configuration validation tests](../../../internal/config/storage_publish_test.go). - -**Deficiency.** Tests cover native loader errors, explicit request markers, -artifact-catalog markers, and joined operational causes. Configuration tests -check that conflicting storage selections fail, but do not carry that actual -failure through a command and assert its exit classification. Destination -validation likewise lacks that CLI assertion. - -**Unprotected behavior.** Identified domain configuration mistakes should produce -status `2` under the [CLI contract](../../cli.md#cancellation-and-exit-status). -[EH-01](06-error-handling.md) reproduced status `1` for both a storage/audio -conflict and a product-path collision while the current suite passed. - -**Improvement.** Add a small real-command table covering those two rejections, -their valid counterparts, and operational precedence where causes are joined. -Assert status and cause/classification rather than complete error prose. Keep -missing/unreadable sources and environmental failures operational; do not -reclassify every configuration-package error as invalid input. - -## TE-07 — P3: Some assertions freeze incidental serialization or validation order - -Status: Open - -**Relevant tests.** - -- [Metadata serialization](../../../internal/artifactmodel/metadata_test.go), - `TestArtifactMetadataJSON` (lines 32–34), compares the entire JSON byte string, - including object-member order. -- [Native campaign validation](../../../internal/config/native_results_test.go), - `TestNativeCampaignResultValidatesConfigurationWithoutReadingResources` - (lines 106–114), supplies a campaign missing multiple required application - fields and requires the first diagnostic to identify `speakers_file`. - -**Deficiency and evidence.** A temporary overlay swapping only the declaration -order of `ContractMetadata.SchemaID` and `MediaType` failed the metadata test. -The JSON object still had identical members and values. The asserted byte order -is not the data-shape contract. Likewise, reordering otherwise valid campaign -checks would fail the diagnostic assertion even though the same invalid input -is rejected. These assertions make correct internal changes unnecessarily -expensive under the testing policy. - -**Improvement/removal scope.** Replace the complete byte snapshot with structural -JSON assertions for the public member names, values, and omission behavior. -Give the campaign test one intended invalid condition or locate the relevant -diagnostic without prescribing its position. Retain the meaningful -serialization, native-error, and path-context checks; the whole tests need not -be deleted. This recommendation does not apply to deliberately canonical byte -formats used by fingerprints or remote commit contracts. - -## TE-08 — P3: Two normalized-transcript tests are exact duplicates - -Status: Open - -**Relevant tests.** In -[analysis tests](../../../internal/stage/analyze_test.go): - -- `TestAnalyzeSupportsCanonicalNormalizedTranscriptSourceFromManifestOutput` - (lines 1279–1305); -- `TestAnalyzeSupportsNormalizedTranscriptSourceFromManifestOutput` - (lines 1307–1333). - -**Deficiency.** Their bodies are identical. Both create the same incidental -`final.json`, declare the same alternate manifest-backed file, bind the same -`narratio.transcript.final` source, run the same stage, and assert the same -request path. Their different names do not exercise separate formats or -contracts. The second execution adds no distinct protection. - -**Improvement/removal scope.** Remove one copy and retain the manifest-authority -test. Keep neighboring missing-input and other source-kind cases, which protect -different behavior. If future cases differ only in source kind, a small table -can consolidate shared setup while preserving the distinct assertions. - -## Proportionate Follow-Up - -TE-01 provides a direct, low-cost opportunity to strengthen an external adapter -boundary. TE-02 through TE-06 should accompany their associated remediation -work; the earlier audit records remain the owners of the production defects. -TE-07 and TE-08 reduce test maintenance without weakening selected contracts. - -Other earlier findings, including concurrent session initialization, same-size -S3 object replacement, and oversized download handling, also identify useful -regression conditions when their implementations are corrected. Their existing -audit records describe those conditions; this report does not duplicate each -one as another testing finding. - -No blanket coverage threshold, exhaustive fault matrix, generic mock framework, -mandatory live service test, or native macOS CI gate is recommended. Uncovered -dead helpers and trivial executable wrappers do not automatically warrant new -tests. Optional external compatibility checks remain explicitly opt-in. - -The suite has substantial behavioral coverage, but is not fully aligned with -the policy's sufficiency criteria: consequential cross-package gaps coexist -with a small amount of redundant and implementation-sensitive protection. diff --git a/docs/roadmap/audit/10-equivalence.md b/docs/roadmap/audit/10-equivalence.md deleted file mode 100644 index 16df16a..0000000 --- a/docs/roadmap/audit/10-equivalence.md +++ /dev/null @@ -1,366 +0,0 @@ -# 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. diff --git a/docs/roadmap/audit/11-boundaries.md b/docs/roadmap/audit/11-boundaries.md deleted file mode 100644 index 8f20af4..0000000 --- a/docs/roadmap/audit/11-boundaries.md +++ /dev/null @@ -1,327 +0,0 @@ -# Package Cohesion And Architectural Boundaries Audit - -Reviewed: 2026-11-30 - -Baseline: `28e54fb657e7915dd79f8b09bfde0636847ede1a` - -## Scope And Method - -The review covered the repository's 26 internal Go packages and the executable -entry point. It examined declared responsibilities, actual imports, public -contracts, and representative implementations and callers across configuration, -orchestration, stages, adapters, manifests, artifacts, workspace operations, -input preparation, readiness, publication, and restore. Third-party package -implementations and vendor code were outside scope. - -Codebase-memory-mcp supplied package exploration, symbol discovery, source -snippets, and call tracing. Its coarse package grouping and same-named receiver -method resolution were supplemented with source inspection and `go list`'s -actual production imports. Package size or a graph metric alone was not treated -as evidence of poor cohesion. - -The [architecture policy](../../policy/architecture.md) supplied the intended -ownership boundaries. Focused internal documents and existing tests supplied -additional implementation evidence. These checks passed on Linux with Go 1.27.4: - -- `go list -f '{{.ImportPath}}|{{join .Imports ","}}' ./...` -- `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, live provider calls, -external subprocess applications, or remote-storage experiments were needed. -This is an ownership audit, not proof that every runtime path is correct. - -## Current Architecture - -Narratio is a fixed-stage orchestrator: -`prepare → transcribe → merge → polish → normalize → trim → render → extract → analyze → publish → notify → cleanup`. -Notification currently uses the no-op mode. - -| Package area | Implemented responsibility | -| --- | --- | -| `cmd/narratio`, `internal/app` | Entry, native CommandKit composition, configuration acquisition, invocation/session lifecycle, planning, execution, operator commands, and restore. | -| `internal/config` | Typed ConfigKit handoff, Narratio validation, party/family/catalog derivation, and safe configuration materialization. | -| `internal/domaininput`, `internal/glossary` | Shared input-schema validation and Narratio's selected vocabulary projections/composition. | -| `internal/stage` | Fixed stage contracts, stage execution and resume semantics, sub-stage reconciliation, and stage-owned semantic fingerprints. | -| `internal/adapters/*` | Narratio-owned external contracts and HTTP, subprocess, notification, or object-store implementations. Shared subprocess supervision and credential handling have a dedicated owner. | -| `internal/manifest`, `internal/artifactmodel`, `internal/artifactpolicy` | Durable progress records/persistence, shared product models, and source/destination vocabulary and validation. | -| `internal/artifacts` | Canonical paths and local store/locking, runtime availability and evidence, artifact resolution, remote commit/current-state models, and remote locks. | -| `internal/audio`, `internal/previouscache` | Verified S3 audio materialization and selection of committed previous-session inputs. | -| `internal/preflight` | Downstream readiness assessment over supplied targets and adapter reports. Application code selects targets and coordinates probes. | -| `internal/pathsafe`, `internal/fileops` | Path confinement, ordinary workspace modes, bounded reads, replacement/deletion mechanics, and the diagnostic-view behavior discussed below. | -| `internal/contracts`, `internal/notariusref`, `internal/logging`, `internal/doccheck` | Focused bounds/selector contracts, reporting interfaces, and repository validation support. | - -The actual import graph respects the main direction: the executable imports -`app`; `app` composes stages and implementations; stages consume Narratio-owned -adapter contracts and support services. Stages do not import `app`. Locating -an interface in an adapter package does not itself leak an SDK or subprocess -protocol into its consumers. - -The five findings below concern responsibility allocation within that generally -sound structure. Several refine existing audit findings and should be addressed -as the same work rather than counted as additional runtime defects. - -## BN-01 — P3: Diagnostic-view layout policy is embedded in file-operation mechanics - -Status: Open - -**Relevant implementation.** -[fileops/attempt_views.go](../../../internal/fileops/attempt_views.go): -`BeginAttemptViews`, `attemptTarget`, `existingManagedView`, -`InspectManagedAttemptViews`, `RemoveManagedAttemptViews`, and `AttemptViews.Revert`. -[artifacts/paths.go](../../../internal/artifacts/paths.go): -`SessionInvocationProbeDir`, `SessionRunLogsDir`, `SessionRunDebugDir`, and the -latest-view path helpers. -[stage/run_local.go](../../../internal/stage/run_local.go): `resolveRunStageLayout`. - -**Basis.** Fileops knows Narratio's `runs///{logs,debug}` grammar, -the corresponding latest-attempt links, and reserved `.preflight`/`.validation` -identities. It constructs and recognizes those paths independently of the -canonical path owner. This is application workspace/navigation policy, beyond -writing, replacing, or removing a caller-selected file. Changing the attempt -layout or probe convention requires coordinated changes in fileops, artifacts, -and stage/application callers. - -The application correctly decides when to advance or revert a view in -`executeSelectedStage`; restore uses the same fileops operation, and cleanup -removes recognized views. The ownership issue is the location of the layout -grammar, not those callers' lifecycle decisions. - -**Remediation options.** Prefer moving the existing diagnostic-view operation -to the canonical layout owner, currently `internal/artifacts`, and making it -consume the same path model. Keep root-scoped directory creation, permissions, -and ordinary replacement/deletion mechanics in fileops. Move the operation -without introducing a generalized symlink-management framework. - -An alternative is a focused `internal/workspace` owner containing the canonical -local path model, session locking, and attempt views. That gives the broad -artifacts package a clearer boundary, but requires a larger interface/import -change. Establishing one owner for attempt layout is useful independently of -whether that broader extraction is worthwhile. - -**Supporting tests and tradeoffs.** -[Fileops view tests](../../../internal/fileops/attempt_views_test.go), including -`TestAttemptViewsAdvanceAndRestoreManagedTargets`, and -[application attempt tests](../../../internal/app/attempt_views_test.go), -`TestAttemptViewsTrackAttemptsFailureSkipAndReuse`, protect advancement, -failed-attempt visibility, self-skip reversion, and reuse without an empty run. -Keep those behaviors and root-confinement rules. The runner still decides -whether an attempt exists; cleanup still chooses authorized targets. A package -move should not add retention, locking, or filesystem guarantees. - -## BN-02 — P3: Notarius output-protocol translation partly lives in stage orchestration - -Status: Open - -**Relevant implementation.** -[stage/notarius_lanes.go](../../../internal/stage/notarius_lanes.go): -`notariusLanePath` (line 23) and `stageRequiredNotariusLanes`. -[stage/extract.go](../../../internal/stage/extract.go): `resolveExecutable` -(line 317) and its extraction caller. -[stage/extract_preflight.go](../../../internal/stage/extract_preflight.go): -`BuildNotariusReadiness`. -[adapters/notarius/runner.go](../../../internal/adapters/notarius/runner.go): -`RunRequest` and `RunResult`; -[subprocess.go](../../../internal/adapters/notarius/subprocess.go): -completion decoding and bundle discovery. - -**Basis.** The adapter owns CLI arguments, completion decoding, and bundle-root -discovery, but returns only the bundle root rather than locations of requested -native outputs. The stage therefore implements Notarius's lane-ID sanitization -and `lanes/.json` mapping itself. This mapping changes with the external -output protocol, not Narratio's stage policy. Executable discovery through -`exec.LookPath` also lives in the stage and is used by execution and readiness, -although process launch belongs to the adapter/shared subprocess boundary. - -The source mapping is directly protected by -[TestNotariusLanePath](../../../internal/stage/notarius_lanes_test.go), with -native filename expectations in the stage package. -[TestNativeExtractionRejectsMappedLaneCollisions](../../../internal/stage/extract_native_test.go) -also exercises the external sanitization collision. These tests demonstrate -where the external contract currently resides. - -**Remediation options.** Prefer making the existing Notarius adapter own the -lane-to-native-path translation, through a narrow resolver or requested-lane -result contract. The stage supplies required lane IDs and receives their -locations, then applies Narratio's staging, checksum, canonical-name, and -promotion policy. Pass executable selection through the adapter/shared process -runner or production composition, retaining the same operator override semantics. - -A smaller alternative moves only lane-path resolution into an exported helper -in the existing Notarius adapter package. That fixes the clearest misplaced -responsibility without redesigning `Runner`. A separate shared contract package -is warranted only if another actual consumer needs the same protocol. - -**Tradeoffs.** Keep Narratio's canonical filename selection and collision rules -outside the downstream protocol resolver. Confined paths, bounded valid JSON, -verification before replacement, and manifest evidence remain Narratio -responsibilities. Typed adapter results do not eliminate those checks. Move -native naming fixtures with their owner while retaining stage tests that prove -the correct configured lanes are promoted. This is distinct from decomposing -the large extraction function in CX-03 of the -[complexity audit](03-complexity.md). - -## BN-03 — P3: Machine-consumed publication metadata lacks a shared contract owner - -Status: Open - -**Relevant implementation.** -[stage/publish.go](../../../internal/stage/publish.go): `publishMetadata`. -[stage/publish_output_plan.go](../../../internal/stage/publish_output_plan.go): -`publishOutputStatus` and `publishOutputOutcomeMetadata` (line 245). -[stage/cleanup_plan.go](../../../internal/stage/cleanup_plan.go): -`validateCleanupPublishEvidence` (line 84). -[app/artifact_inspection.go](../../../internal/app/artifact_inspection.go): -`committedPublishOutputOutcomes` (line 41) and `isPublishOutputOutcome`. - -**Basis.** Publish serializes completion identity and per-source outcomes into -`StageRecord.Metadata`. Cleanup independently reconstructs completion fields and -checks their meaning. App inspection independently knows the outcome keys and -repeats the producer's five status strings. Its parser handles both -`[]map[string]any` and JSON-decoded `[]any`. A producer change can compile while -silently changing cleanup eligibility or operator reporting. - -These values are shared control/reporting evidence, even though they currently -share a map with arbitrary diagnostics. Manifest persistence supplies a common -container, but does not own the meaning of publication fields. Stage-private -types also cannot be the sole contract for independent app consumers. - -**Remediation options.** Prefer small typed publication completion/outcome -values and map encoding/decoding helpers under an existing shared owner, such -as `internal/artifacts` alongside its remote publication identities. Have the -producer and consumers use that contract while preserving the existing JSON -shape. Keep cleanup eligibility in cleanup and presentation decisions in app. - -An alternative is a focused publication package if remote commit, lock, and -publication evidence responsibilities are extracted together. That creates a -stronger domain boundary at the cost of a larger change. A generic metadata -framework or new manifest schema is unnecessary for the immediate issue. - -**Supporting tests and tradeoffs.** -[TestCommittedPublishOutputOutcomesRecognizesAllStates](../../../internal/app/restore_commit_test.go) -checks the app-side vocabulary. -[Cleanup plan tests](../../../internal/stage/cleanup_plan_test.go), notably -`TestBuildCleanupPlanRejectsInvalidPublishEvidenceWithoutExecutablePlan`, -exercise the safety gate. Retain direct and persisted-round-trip coverage. -Tolerant display parsing and authoritative cleanup checks have different -failure policies; a shared decoder should not silently make them equally -strict. Arbitrary diagnostic metadata can remain flexible. - -This is the publication part of CX-06 in the -[complexity audit](03-complexity.md), with a concrete ownership recommendation. -Typed evidence does not resolve FC-02's carried-output/manifest coherence issue. - -## BN-04 — P3: Audio discovery is owned independently by preparation and inspection - -Status: Open - -**Relevant implementation.** -[stage/prepare.go](../../../internal/stage/prepare.go): -`resolveLocalAudioFiles` (line 311), `resolveAudioInputs`, and -`localAudioDestinations`. -[app/operator_inspection.go](../../../internal/app/operator_inspection.go): -`inspectLocalAudioPresence`, `resolveLocalInspectionAudioPaths` (line 207), -and remote-audio inspection. -[audio/s3_audio.go](../../../internal/audio/s3_audio.go): -`MaterializeS3Audio`, the existing audio-focused domain helper. - -**Basis.** Both app and stage own explicit-list/directory selection, relative -resolution, FLAC filtering, duplicate handling, and deterministic ordering. -There is no shared read-only source-selection owner. Their policies have already -diverged: preparation rejects duplicate resolved source paths and supports -distinct same-basename recordings; inspection accepts repeated identical paths -and rejects distinct paths with the same basename. File eligibility checks also -differ: preparation's `requireFile` rejects directories, while inspection -requires a regular file. - -The same-basename reporting defect is already CX-01 in the -[complexity audit](03-complexity.md), including its dynamic evidence. This audit -does not recount it as a new defect; it identifies the missing ownership seam. - -**Remediation options.** Prefer a read-only audio-source discovery operation in -the existing `internal/audio` package. Supply explicit selection and source-base -values and return sources or remote identities. Preparation retains copying, -canonical destination naming, and manifest updates; app retains reporting. -Storage adapters continue to receive explicit bucket-relative prefixes. - -A narrow separate source-selection package is viable if it materially avoids -dependencies on audio materialization. The existing audio owner is the smaller -starting point. Share discovery and filters rather than turning operator -inspection into a preparation-stage invocation. - -**Supporting tests and tradeoffs.** -[Preparation tests](../../../internal/stage/prepare_test.go) cover explicit -lists, directory enumeration, and duplicate source rejection. -[TestLocalAudioDestinationsPreserveDistinctRecordings](../../../internal/stage/audio_destinations_test.go) -protects disambiguation and source preservation. Keep inspection read-only and -retain the separately selected S3 basename rules. Resolve current eligibility -differences explicitly against the existing contract rather than adopting the -strictest implementation merely to simplify sharing. CX-01's correctness fix -retains its original priority. - -## BN-05 — P3: Configured-artifact graph operations are fragmented across domain owners - -Status: Open - -**Relevant implementation.** -[config/artifact_dependencies.go](../../../internal/config/artifact_dependencies.go): -`resolveArtifactDependencies` derives the concrete edge union and origin data. -[config/validate_scriptorium.go](../../../internal/config/validate_scriptorium.go): -`ValidateScriptoriumArtifactDependencies` rebuilds adjacency and validates it. -[stage/analyze_fingerprint.go](../../../internal/stage/analyze_fingerprint.go): -`normalizedAnalyzeDependencyKeys` and `orderConfiguredAnalyzeArtifacts`. -[stage/analyze_plan.go](../../../internal/stage/analyze_plan.go): -`AnalyzeTargetClosure`. -[stage/analyze.go](../../../internal/stage/analyze.go): -`staleAnalyzeDependentClosure`. -[artifacts/previous_requirements.go](../../../internal/artifacts/previous_requirements.go): -`CollectPreviousArtifactRequirements` consumes the selected target set. - -**Basis.** Configuration owns the concrete graph, while stage code owns its -normalization, work ordering, prerequisite closure, and reverse-edge rebuilding. -Artifact services expose an effective selection that is targets-only; consumers -must know when to expand it. These are different views of one domain relation, -with no single query boundary for its mechanics. The earlier FC-01 missing -previous-input closure illustrates the resulting cross-package ambiguity. - -**Remediation options.** Prefer exposing dependency queries from the existing -derived `config.ArtifactCatalog` owner: validated adjacency, dependency-first -order, prerequisite closure, and dependent traversal. Make selected targets and -required work separate explicit results. Preparation and restore can then ask -for inputs of the work closure without depending on analyze-stage internals. -Stage code retains force, reuse, fingerprint payloads, and invalidation decisions. - -A lower-level artifact-graph package taking keys and edges is a viable -alternative if needed to keep dependencies acyclic. Preserve configuration's -source-origin diagnostics at its boundary. A generic workflow engine would -serve a different problem. - -**Supporting tests and tradeoffs.** Configuration dependency tests, -[fingerprint ordering tests](../../../internal/stage/analyze_fingerprint_test.go), -and [work-plan tests](../../../internal/stage/analyze_plan_test.go) protect -normalization, invalid-graph rejection, deterministic ordering, disabled -prerequisites, and target-only force. Preserve those distinctions. -`config.ArtifactCatalog` describes derived definitions; the runtime -`artifacts.ArtifactCatalog` additionally tracks manifest-backed availability. -Those responsibilities remain distinct even if their graph queries are shared. -The fixed stage-invalidation relation also remains separate. - -This refines CX-05 in the [complexity audit](03-complexity.md) and EQ-03 in the -[equivalence audit](10-equivalence.md); implement it as their shared remediation. - -## Proportionate Follow-Up - -Address BN-01 and BN-02 as focused ownership corrections. Fold BN-03 through -BN-05 into the cited existing work rather than parallel refactors. The -equivalence audit's transcript predicate and sibling-temp recommendations are -additional small shared-helper opportunities under existing owners. - -The review does not recommend splitting app or stage by file count, merging -configuration definitions with runtime availability, moving stage execution -policy into persistence, or creating an umbrella package for every contract. -Native configuration acquisition, input-schema validation, vocabulary -composition, process supervision, typed checkpoint persistence, and -pointer-selected remote-state verification already have useful boundaries. -Preserve these owners and the fixed pipeline while correcting the narrower -allocation problems above. diff --git a/docs/roadmap/audit/12-deadcode.md b/docs/roadmap/audit/12-deadcode.md deleted file mode 100644 index 7f46910..0000000 --- a/docs/roadmap/audit/12-deadcode.md +++ /dev/null @@ -1,309 +0,0 @@ -# Dead Code And Obsolete Functionality Audit - -Reviewed: 2026-11-30 - -Baseline: `bd8e8a0627e7dfe0425e380212e82f00c79aa1d2` - -## Scope And Method - -The review examined repository-owned functions, helpers, constants, structs, -interfaces, configuration/defaulting paths, conditional branches, and retained -compatibility behavior. It followed supported command entry points and checked -tests, registrations, interface calls, reflection, build constraints, and -documented retention purposes before classifying candidates. - -Codebase-memory-mcp supplied discovery, source snippets, and caller searches. -Its same-named Go method and constant-reference indexing is incomplete; graph -degree alone was not used to establish deadness. Source searches and the -following tools supplied independent evidence: - -- `deadcode` from `golang.org/x/tools v0.52.0`, built with Go 1.27.4, analyzed - `./cmd/narratio` for Linux amd64, Linux arm64, and macOS arm64. Each produced - the same 88 unreachable-function candidates, including legitimate test fakes - and library/test entry points. -- `deadcode -test ./...` on Linux amd64 reduced that list to 12 functions: - six in production files and six in test files. DD-01 records those confirmed - orphaned functions. Results were filtered to Narratio's module. -- Staticcheck 2026.2.2 (`honnef.co/go/tools v0.8.2`) with `-checks=U1000` - reported the same ten unused unexported helpers on Linux amd64 and macOS - arm64. The additional exported wrapper and its helper were found by - `deadcode`. `-checks=U1000,SA4*,SA9*` also reported DD-06's unused assignment. -- A temporary standard-library `go/ast` scan counted references to declarations - in `config/defaults.go` across all repository Go source under `cmd/` and - `internal/`, including tests and platform files. Six constants occurred only - at their declarations; source searches confirmed the DD-02 candidates. - -Analyzer binaries, their build module, and the small AST diagnostic were kept -outside the repository. Project dependencies were unchanged. Cross-target -analysis is source/type-analysis evidence, not native macOS or arm64 execution. -Analyzer diagnostics were reviewed as candidates rather than automatic deletion -instructions. - -`go test -count=1 ./...` and `go vet ./...` passed with Go 1.27.4 on Linux. -`go test -count=1 ./internal/doccheck` passed after writing this report. -Staticcheck's nonzero exit reflects the findings above. No production code, -tests, or functionality were changed, and no live providers or object storage -were used. - -## Current Architecture - -Narratio is a fixed-stage orchestrator: -`prepare → transcribe → merge → polish → normalize → trim → render → extract → analyze → publish → notify → cleanup`. -The application owns command composition, invocation/session lifecycle, -planning, and restore. Stages own execution and semantic resume decisions; -adapters own external interactions. Manifests and typed speaker/artifact -collections provide durable progress. Artifact services provide identities, -evidence, canonical paths, and committed remote-state resolution. ConfigKit owns -configuration resolution, with Narratio's domain derivation after handoff. - -The main supported paths are connected. The findings are focused remnants and -redundant machinery rather than an abandoned pipeline subsystem. - -## DD-01 — P3: Completely orphaned helper functions remain in production and tests - -Status: Open - -### Code And Evidence - -The following production functions remain unreachable even when all test -executables are included: - -| File | Functions | Evidence | -| --- | --- | --- | -| [Notarius subprocess adapter](../../../internal/adapters/notarius/subprocess.go) | `resolveRegularFile` (line 244), `requireRegularFileTree` (line 273) | U1000 and reachability analysis agree. The first calls the second, but neither has an external caller. Current bundle and lane validation use other paths. | -| [Cleanup target validation](../../../internal/app/cleanup_targets.go) | `validateCleanRoot` (line 69) | U1000 and reachability analysis agree; supported cleaning uses `validateScopedTarget`. | -| [Configuration validation helpers](../../../internal/config/validate_helpers.go) | `validatePathWithinRoot` (line 41) | U1000 and reachability analysis agree; current product-destination validation is implemented elsewhere. | -| [Effective pipeline helpers](../../../internal/config/effective_pipeline.go) | `NormalizedConfigurationPath` (line 32), `normalizedProvenancePath` (line 65) | The exported wrapper has no callers, including tests; its private path helper is used only by that wrapper. `deadcode -test` reports both. | - -Six test helpers also have no callers; both analyzers report them: - -- [Notarius adapter tests](../../../internal/adapters/notarius/subprocess_test.go): - `cloneMap` (line 557). -- [Application command tests](../../../internal/app/commands_test.go): - `writeManifestPathForExecute` (line 509). -- [Configuration command tests](../../../internal/app/config_commands_test.go): - `writeInspectionOverlays` (line 48). -- [Path test helpers](../../../internal/app/paths_test_helpers_test.go): - `mustPreviousArtifactPathForCampaign` (line 9). -- [Extraction tests](../../../internal/stage/extract_test.go): - `stringPointerForExtractTest` (line 957). -- [Preparation tests](../../../internal/stage/prepare_test.go): - `assertManifestInputsSorted` (line 766). - -Source inspection found no registration, reflective lookup, build-tag consumer, -or documented future/compatibility purpose for these helpers. In particular, -the Notarius pair is a disconnected helper chain, not a live security check -that merely lacks a direct call edge in the graph. The functions are in -internal packages rather than a supported external Go library API. - -### Removal Approach And Cautions - -Remove the orphaned declarations and any newly unused imports. Delete a helper -file if it becomes empty. Keep live Notarius directory/file checks, current -cleanup confinement, and current product-destination validation intact. -Removing the unused sorting assertion does not imply removing the active -preparation ordering assertions. - -No replacement abstraction is needed. Re-run the analyzers and focused package -tests after removal; do not replace these declarations with forwarding shims. - -## DD-02 — P3: Unused constants and retired workspace paths advertise obsolete concepts - -Status: Open - -### Code And Evidence - -Six constants in [config/defaults.go](../../../internal/config/defaults.go) -have no Go identifier references beyond their declarations, including tests -and alternate-platform files: - -- `DefaultScriptoriumArtifactOutputRoot`; -- `PathTranscriptBase`, `PathTranscriptPolished`, and `PathTranscriptFinal`; -- `S3ManifestFile` and `S3RunIDFile`. - -Their exported names do not establish use. The active transcript vocabulary is -in `artifactmodel`; remote publication selects immutable commit declarations -through the current pointer. No supported source or documentation consumer of -these particular aliases/constants was found. Removing an unused name does not -remove the corresponding live transcript path or manifest/run identity. - -Separately, [artifacts/paths.go](../../../internal/artifacts/paths.go) declares -`SessionPaths.ReportsDir` and `ConfigDir` (lines 25–26) and assigns -`/reports` and `/config` in `buildSessionPathsFromRoot` -(lines 239–240). Neither field is read elsewhere. Their only path constants, -`PathReportsDirSegment` and `PathConfigDirSegment`, feed those unused assignments. -`LocalStore.ensureLayout` does not create these directories. - -The [operator layout](../../operations.md#local-state-layout) places actual -attempt diagnostics under `runs/` and exposes latest logs/debug links. Prepared -configuration belongs in `inputs/`; the retained top-level path fields describe -an earlier organization without providing a live layout capability. - -### Removal Approach And Cautions - -Remove the six disconnected constants, the two unused `SessionPaths` fields, -their assignments, and their two now-unnecessary directory constants. Keep the -canonical artifact-model vocabulary and current remote commit/key helpers. - -This is code-model cleanup. It should not delete existing session directories, -alter physical layout, migrate sessions, or add a default artifact output path. -In particular, reconnecting an unused constant by inventing a new fallback would -change behavior instead of removing dead code. - -## DD-03 — P3: Extraction still carries descriptor fields that the current model discarded - -Status: Open - -### Code And Evidence - -[stage/extract.go](../../../internal/stage/extract.go), `fingerprintOutput` -(lines 261–268), retains `MediaType`, `SchemaID`, `SchemaVersion`, and -`ModuleKey`. All four have `json:"-"` tags. `extractionFingerprint` constructs -only key, lane ID, and filename; nothing writes or reads the four excluded -fields. They cannot affect the fingerprint's serialized payload. - -[artifacts/extraction_evidence.go](../../../internal/artifacts/extraction_evidence.go) -also retains `ExtractionEvidenceOutput.Contract`. Its sole production -construction supplies path, checksum, and size but never a contract. The nil -field is passed by `HydrateExtractionArtifacts` to -`markAvailableFromExtractManifest` in -[catalog.go](../../../internal/artifacts/catalog.go), where it is cloned back -to nil. There is no non-nil producer along this path. - -The current configured extraction definition contains only lane, pipeline, and -filename. [TestNotariusNativeControlsAndOutputs](../../../internal/config/product_destinations_test.go) -expressly rejects the retired `media_type` output descriptor. Extraction -execution and resume validate the configured JSON products and provenance -without resurrecting those old descriptor fields. - -### Removal Approach And Cautions - -Remove the four JSON-excluded fingerprint fields. Remove the always-nil -extraction evidence field and its extraction-only parameter/copy plumbing. -Keep shared `CatalogEntry.Contract`, manifest contract metadata, and the -analyze-generated contract path: they have live consumers and different roles. - -The existing fingerprint JSON and digest can remain unchanged because the -discarded fields are already excluded. This does not require a fingerprint or -manifest schema migration, stricter lane validation, or reintroduction of -retired configuration options. Retain current extraction/resume and dependent -input-identity coverage. - -## DD-04 — P3: Manual cleaning retains a file-target mode unavailable through its CLI - -Status: Open - -### Code And Evidence - -[app/clean_command.go](../../../internal/app/clean_command.go), -`cleanSelectedSession`, passes `directory=true` for both supported target -choices: one entire session or the whole session-work tree for `--all`. -Its `appendTarget` closure forwards that boolean to `cleanScopedTarget` and -then to [validateScopedTarget](../../../internal/app/cleanup_targets.go). - -Only [cleanup target unit tests](../../../internal/app/cleanup_targets_test.go) -request the false/file branch through -[validateScopedFile](../../../internal/app/clean.go). The sibling -`validateScopedDir` wrapper is likewise test-only, while production bypasses -both wrappers. This preserves an artificial two-mode validation API for a -directory-only command. - -The [documented cleanup contract](../../operations.md#cleanup) provides whole -local-session deletion and a separate publication-gated run-history stage. -Neither accepts individual file targets. No future file-clean command or -compatibility caller is documented. DD-01 separately covers the fully unused -`validateCleanRoot` helper in the same area. - -### Removal Or Consolidation Approach - -Make the manual-clean validation path explicitly directory-oriented. Eliminate -the forwarded directory boolean, the false-only branch, and `validateScopedFile`. -Use one live directory validation entry point from commands and tests rather -than preserving test-only wrappers around the implementation. - -Retain directory/root/traversal/symlink checks, missing-target behavior, -dry-run behavior, and the selected command's deletion scope. Consolidate the -unit tests onto that live contract, removing file-only cases. General file -operations used elsewhere remain available. This cleanup does not resolve or -replace CN-01's separate session-locking remediation. - -## DD-05 — P3: A superseded publish-default mutation helper survives only in a no-op test call - -Status: Open - -### Code And Evidence - -[config/validate_publish.go](../../../internal/config/validate_publish.go), -`applyMissingPublishDestinations` (line 36), directly writes destinations into -its input configuration. Its only caller is -`TestProductDestinationsPreserveExplicitRemotePaths` in -[product_destinations_test.go](../../../internal/config/product_destinations_test.go). -That fixture already supplies a destination, so `deriveMissingPublishDestinations` -returns no entries and the call performs no mutation. - -The production path in -[pipeline_configkit.go](../../../internal/config/pipeline_configkit.go), -`resolvePipelineConfig` (lines 191–199), uses the shared derivation directly -and records actual defaults through native `configkit.Normalize`. Reachability -analysis therefore reports the old writer as absent from the production -command graph while retaining it when tests are roots. - -### Removal Or Consolidation Approach - -Remove the unused writer. Keep `deriveMissingPublishDestinations` and the -native ConfigKit resolution path. Preserve explicit-destination testing through -the production loader/domain boundary; the current validator assertion can -also remain without the irrelevant helper call. - -The [configuration ownership decision](../../adr/0003-assign-configuration-ownership.md) -already assigns resolution to ConfigKit's supported hooks. No new configuration -semantics or stricter destination policy is needed, and this finding does not -claim the obsolete writer currently mutates an authoritative runtime result. - -## DD-06 — P3: Input hashing stores a normalized path that is never consumed - -Status: Open - -[stage/analyze_input_identity.go](../../../internal/stage/analyze_input_identity.go), -`hashAnalyzeInputFile` (line 262), assigns the normalized result back to -`relative`, then uses only `err` and opens the previously resolved `target`. -Staticcheck reports this assignment as SA4006. The original `filepath.Rel` -result is used as the normalization input; only the normalized return value -is discarded by all later code. - -Use a blank identifier for that unused return value, or an equivalently clear -error-only validation form. Keep the normalization call and its error check: -they enforce the existing relative-path confinement rule. Removing the entire -call to silence a dead-value diagnostic would remove live validation. This is -a small mechanical cleanup, not a new path-resolution abstraction or a change -to accepted input paths. - -## Deliberately Retained Behavior And Limits - -- The fixed registry and stage interfaces make stage methods reachable without - direct concrete calls. ConfigKit callbacks such as `pipelineConfigDefaults` - and validation hooks are explicitly registered function values. The - `deadcode -whylive` result also retained the defaults callback, but its - conservative reflection path is a static approximation rather than a runtime - trace; the native definition's callback registration supplies the direct - source evidence. -- Fakes, test entry points, and loader conveniences with actual test consumers - are not dead merely because the CLI does not call them. The documented - package-internal compatibility form of `config.Load` is not proposed for - removal. Future-facing aliases were not classified solely from production - reachability. -- No-op notification is an explicit supported mode. The documented one-time - regeneration of aggregate-only transcription state also has a live recovery - purpose. Neither is an obsolete feature to delete in this audit. -- Build-tagged locking and process-tree code was evaluated in the supported - target configurations. Lack of an edge in one platform's graph does not - establish deadness. No blanket deletion of alternate/unsupported-platform - implementations is recommended; unsupported platforms were not build gates. -- Native YAML/JSON bindings, embedded schemas, and reflective semantic-type - validation were considered. A missing direct field read is insufficient for - bound configuration options. No operator-facing configuration option is - recommended for removal merely because it is optional or indirectly consumed. - -The recommended changes remove disconnected symbols, inert data, and -superseded internal variants. They preserve the current supported workflow, -selected compatibility behavior, and deliberate test seams. diff --git a/docs/roadmap/audit/13-documentation.md b/docs/roadmap/audit/13-documentation.md deleted file mode 100644 index 94fcb1c..0000000 --- a/docs/roadmap/audit/13-documentation.md +++ /dev/null @@ -1,361 +0,0 @@ -# Documentation Consistency Audit - -Reviewed: 2026-12-01 - -Baseline: `1b7742cd385c8852e058898ba1e25b928bc4eb9d` - -## Scope And Evidence - -The review compared current-facing documentation with the implemented code, -focused tests, accepted ownership decisions, and the -[documentation policy](../../policy/documentation.md). It covered the root and -examples READMEs, CLI and configuration references, operations and -troubleshooting, internal and integration documents, package/API comments, -maintained YAML examples, development instructions, and the release/deployment -instructions and automation. Narratio has no separate maintained container or -service deployment recipe in this baseline. - -The policy's current-behavior, canonical-owner, example-validity, and upstream -documentation rules informed the findings. Code discovery used the knowledge -graph, supplemented by source inspection where Go receiver-method indexing was -incomplete. No production code, tests, configuration examples, or documents -under review were changed. - -Verification used Go 1.27.4 on Linux: - -- Fresh `go test -count=1 ./...` passed, including maintained-example loading, - documentation-link checks, and release/workflow checks. -- `go vet ./...` and a temporary CLI build passed. -- The production/testing walkthrough's validate, show, sources, diff, and - artifact-catalog commands succeeded against the maintained local fixtures. - Help for the root, plan, preflight, cleanup, and regeneration commands agreed - with their documented command paths and installed selectors. -- Native inspection of the minimal pipeline confirmed the documented effective - defaults, including the empty Audita output-schema selector and ordinary - publish defaults. An explicit configuration in another example is not a - different application default. -- A read-only check inspected 148 local Markdown fragment links. Its only - apparent missing heading was an old profile heading linked from the - historical v2.0.0 release note. Current-facing local targets passed the - existing link test and this additional check. The existing test checks file - existence, not heading existence or prose accuracy. - -Commands used no live providers, paid APIs, remote publication, destructive -cleanup, or release publication. Tests establish their exercised behavior; -passing them does not validate every prose claim. External URLs were treated as -references, not as evidence that current upstream services or tools were tested -live. - -Historical release notes were read as records of their tagged versions. -Accepted ADR context and consequences were distinguished from current behavior -references; the policy permits a decision to precede implementation. Existing -audit records describe pending findings. None of these were treated as a claim -that historical or proposed behavior must be implemented now. - -## Current Architecture - -Narratio is a fixed-stage Go orchestrator: -`prepare → transcribe → merge → polish → normalize → trim → render → extract → analyze → publish → notify → cleanup`. -Notify is currently a no-op. The application owns CLI composition, acquisition, -session locking, planning, execution, and restore. ConfigKit owns configuration -resolution through its final handoff; Narratio derives separate domain catalogs -and plans. CommandKit and ckconfig provide native CLI and inspection behavior. - -Stages coordinate WhisperX HTTP transcription, Seriatim transcript operations, -Audita polishing, Notarius extraction, and Scriptorium bounds/analysis. Typed -speaker and analysis checkpoints share a manifest persistence boundary. -Manifest-backed product identities govern reuse and resolution. Completed -products occupy flat transcript/artifact locations; run-local attempts retain -diagnostics and expose latest-attempt views. Publication uploads immutable -objects and a commit before advancing the current pointer. Restore verifies -declared objects and installs the manifest last; authorized cleanup separately -removes local run history. ReleaseKit owns native release mechanics. - -## DOC-01 — P2: Recovery examples publish before the stated inspection step - -Status: Open - -**Documentation.** [Troubleshooting](../../troubleshooting.md), lines 690–696, -instructs operators recovering an unsupported manifest to run an unbounded -`narratio run`, then force publish. The following sentence says to inspect the -regenerated records and publish explicitly. Its publish-failure section also -places `run ... --stage publish --force` in the **Diagnostics** block -(lines 884–889), alongside inspection commands. - -**Implementation and discrepancy.** -[BuildFullPlan](../../../internal/app/planner.go), line 127, and -[the canonical registry](../../../internal/stage/placeholders.go), line 61, -include publish, notify, and cleanup in an unbounded run. The command can -therefore advance remote current state before the proposed inspection, and can -remove run diagnostics when automatic cleanup is enabled. The subsequent force -publish is a second publication attempt. The command in the diagnostics block -also performs publication rather than inspection. These effects agree with the -[CLI](../../cli.md#run) and -[operations guide](../../operations.md#publish-workflow), but not the recovery -sequence implied by the troubleshooting text. The assembled full-run test -checks the complete canonical order. - -**Correct behavior and remediation.** If inspection before publication is the -intended recovery workflow, bound regeneration through `analyze`, inspect the -results, and then publish explicitly. Move the forced publish command from -diagnostics to the repair/retry step, identifying its remote mutation. A viable -alternative is to retain the full-run recovery example and explicitly describe -its publication and possible cleanup effects, removing the claim that -inspection precedes publication. This finding calls for truthful instructions, -not an additional CLI confirmation or publication restriction. - -## DOC-02 — P3: Operator guidance incorrectly requires force after enablement - -Status: Open - -**Documentation.** [Operations](../../operations.md), lines 196–201, says that -successful no-output render, publish, and analyze results are reused on later -runs and tells operators to force the stage after enabling or configuring it. -This contradicts the same document's semantic-resume explanation and the -focused [render](../../internal/stage-render.md), -[publish](../../internal/stage-publish.md), and -[analyze](../../internal/stage-analyze.md) documents. - -**Implementation and discrepancy.** Render enablement is included by -`renderStage.SemanticConfigFingerprint` in -[semantic_contracts_refinement.go](../../../internal/stage/semantic_contracts_refinement.go), -line 130. Publish enablement/upload policy is likewise fingerprinted in -[semantic_contracts_delivery.go](../../../internal/stage/semantic_contracts_delivery.go). -The sensitivity tests cover these changes. Analysis -[resume reconciliation](../../../internal/stage/analyze_resume.go), line 13, -plans newly selected or newly enabled missing artifacts. The shared -[execution decision](../../../internal/app/run_control.go), line 45, runs a -succeeded stage when its resume evidence is non-current without requiring force. - -**Correct behavior and remediation.** An ordinary invocation selecting the -affected stage detects these observable configuration changes. Force remains -appropriate for intentional replacement of current results or private upstream -changes Narratio cannot observe. Correct the operator paragraph and link to the -focused evidence descriptions. Alternatively, replace the repeated enablement -explanation with a short link to that resume contract. Preserve the distinction -between successful no-output results and explicit self-skips. - -## DOC-03 — P3: Internal resume summaries describe obsolete fingerprint inputs - -Status: Open - -**Documentation and implementation.** Three related descriptions have drifted: - -- [Analyze](../../internal/stage-analyze.md), lines 79–83, includes effective - render-debug behavior in the artifact fingerprint. The payload and artifact - structs in [analyze_fingerprint.go](../../../internal/stage/analyze_fingerprint.go), - lines 49–63, contain no debug selection. The explicit - `TestAnalyzeFingerprintIgnoresRenderDebugSelection` test in - [analyze_fingerprint_test.go](../../../internal/stage/analyze_fingerprint_test.go), - line 136, verifies that toggling it preserves product identity. -- [Prepare](../../internal/stage-prepare.md), lines 67–73, includes stable-input - ownership and a party mode in its fingerprint description. - [semantic_contracts_initial.go](../../../internal/stage/semantic_contracts_initial.go), - lines 19–40 and 98–168, records stable input kind/presence and the players - schema, not source ownership or a selectable party mode. Its source comment - expressly keeps ownership as provenance. The sensitivity test verifies that - changing source ownership or relocating equivalent sources preserves the - fingerprint. -- [Manifest](../../internal/manifest.md), lines 275–289, lists extraction, - analysis, and cleanup validators and describes prepare reuse as an aggregate - fingerprint alone. Prepare also implements - [ValidateResume](../../../internal/stage/prepare_resume.go), line 36, checking - current sources and durable prepared files. The nearby transcribe row already - acknowledges its speaker reconciliation; the overview should distinguish - these validators consistently. - -**Correct behavior and remediation.** Debug selection and stable-input -ownership alone do not change these product fingerprints. Prepare combines -semantic configuration with content/source validation; its fingerprint alone -does not establish reuse. Update the summaries from these current typed -payloads and validator implementations. A smaller alternative is to remove -duplicated field inventories from the manifest overview and link to each stage's -corrected resume section. Do not change fingerprint contracts or add -invalidation to satisfy the obsolete prose. - -## DOC-04 — P3: Seriatim reports are documented as canonical artifact outputs - -Status: Open - -**Documentation.** The output lists in -[merge](../../internal/stage-merge.md), line 16, and -[normalize](../../internal/stage-normalize.md), line 14, advertise -`artifacts/seriatim.report.json` and -`artifacts/seriatim.normalize.report.json`. - -**Implementation and discrepancy.** -[merge.go](../../../internal/stage/merge.go), line 82, selects the run-local -logs directory for its report, and -[normalize.go](../../../internal/stage/normalize.go), lines 74–80, does the same. -Each stage returns only its canonical transcript as `Outputs`; an enabled report -is included in `Logs`. The reports are available through the corresponding -latest-attempt log view and follow run-history retention. They are not promoted -into the flat canonical artifact directory. The existing descriptions also -conflict with the content classification in -[ADR 0001](../../adr/0001-classify-session-content.md) and the -[workspace reference](../../operations.md#local-state-layout). - -**Correct behavior and remediation.** List the transcript as the substantive -stage output and describe the optional report as a diagnostic. Link to the -operations owner for physical placement and retention. Alternatively, give -outputs and diagnostics separate subsections with that same ownership link. -Moving report files back into canonical artifacts would reverse the selected -workspace design and is not a documentation fix. - -## DOC-05 — P3: Annotated example comments retain obsolete contracts and defaults - -Status: Open - -**Documentation.** [pipeline.full.annotated.yml](../../../examples/pipeline.full.annotated.yml) -contains three misleading annotations despite being valid executable YAML: - -- Line 210 says configured-artifact input sources require matching authored - `depends_on` membership. -- Line 27 labels `OBJECT_STORAGE_KEY_ID` and `OBJECT_STORAGE_KEY` as defaults. -- Line 7 describes cleanup as removing a run-scoped work directory, omitting - its current whole-session run-history scope. - -**Implementation and discrepancy.** -[resolveArtifactDependencies](../../../internal/config/artifact_dependencies.go), -line 17, infers dependencies from configured-artifact inputs and unions them with -explicit ordering edges. The -[dependency tests](../../../internal/config/artifact_dependencies_test.go) and -the maintained split bundle exercise input-only edges. These inputs do not -require a duplicate authored `depends_on` entry. - -S3 credential references default to absent. The -[S3 constructor](../../../internal/adapters/storage/s3_backend.go), line 77, -uses explicit captured static values only when the pair is configured; -otherwise the default provider chain is retained. The names in the example are -operator-selected references, not automatically recognized defaults. - -[buildCleanupPlan](../../../internal/stage/cleanup_plan.go), line 27, targets -the session's entire runs directory after authorization. This includes earlier -failed attempts and diagnostics, as correctly described in -[operations](../../operations.md#cleanup). - -**Correct behavior and remediation.** Correct these comments and link to the -configuration and cleanup owners where details are needed. An alternative is -to remove volatile explanatory comments and retain only short labels plus those -links. Example-loading tests validate the YAML and effective domain values; -they cannot detect incorrect natural-language annotations. No new dependency, -credential alias, or cleanup contract is needed. - -## DOC-06 — P3: Internal credential ownership descriptions predate native bootstrap - -Status: Open - -**Documentation.** [File operations](../../internal/fileops.md), lines 37–39, -assigns credential mode policy and environment precedence to `internal/app`. -[Adapters](../../internal/adapters.md), lines 85–88, says application-owned -object-store construction loads filesystem secrets before invoking the factory. - -**Implementation and discrepancy.** -[configurationAcquisition.Pipeline](../../../internal/app/configuration_acquisition.go), -line 65, prepares the selected source before its typed load. The production -dependency in [command_dependencies.go](../../../internal/app/command_dependencies.go), -lines 29–36, delegates this to -`configkit.LoadSecretsIntoEnvironmentFromConfig`. -[Object-store construction](../../../internal/app/object_store.go), lines 11–29, -only invokes the configured factory with already-resolved configuration; it -does not load or inspect credential files. Permission requirements are operator -policy in [operations](../../operations.md#workspace-permissions). - -The stale descriptions assign implementation responsibilities to Narratio that -the native integration deliberately moved upstream. They disagree with -[ADR 0003](../../adr/0003-assign-configuration-ownership.md), the -[configuration reference](../../config.md#secrets-handling), and -[configuration internals](../../internal/configuration.md). - -**Correct behavior and remediation.** Describe invocation acquisition as the -caller of ConfigKit's configured startup, and the storage factory as a consumer -of resolved values. Link to ConfigKit for bootstrap/precedence behavior and to -operations for local credential permissions. Removing credential-policy prose -from the generic file helper document is a viable simpler alternative. This -does not call for restoring Narratio-side bootstrap, file-mode enforcement, or -upstream configuration inspection. - -## DOC-07 — P3: Internal glossary inventories omit the combined prepared document - -Status: Open - -**Documentation.** [Manifest](../../internal/manifest.md), line 377, describes -four prepared glossary kinds. [Publish](../../internal/stage-publish.md), line 64, -and [restore](../../internal/command-restore.md), line 40, likewise describe -four prepared glossary documents carried across publication and restore. - -**Implementation and discrepancy.** Preparation produces five envelopes: -party, campaign, setting, spells, and combined. The inventory in -[prepare resume](../../../internal/stage/prepare_resume.go), line 57, verifies -all five. [collectPublishPreparedInputs](../../../internal/stage/publish_sources.go), -line 31, includes both the four individual descriptors and the combined -descriptor. The -[prepared-input publication test](../../../internal/stage/publish_prepared_test.go), -line 61, checks all five remote declarations. The -[committed restore test](../../../internal/app/restore_commit_test.go), line 46, -includes and restores `glossaries/combined.yml`. - -The [configuration reference](../../config.md#glossary-inputs), prepared source -inventory, and prepare output list already describe the combined product. It is -important to distinguish five retained inputs from the four individual -glossaries intentionally passed to Audita. - -**Correct behavior and remediation.** Update the manifest/publish/restore -summaries to include the combined prepared input. Prefer linking to the -prepared-input inventory instead of repeating counts in multiple documents. -Explicitly listing five names in each location is viable but increases drift -risk. Keep Audita's four-file invocation description unchanged. - -## DOC-08 — P3: Logging package documentation advertises a removed responsibility - -Status: Open - -**Documentation.** [logging/doc.go](../../../internal/logging/doc.go), line 1, -says the package provides structured logger construction. - -**Implementation and discrepancy.** -[logging.go](../../../internal/logging/logging.go) defines the `Reporter` -interface and nil-safe Info/Warn/Debug/Progress forwarding helpers. It exposes -no logger constructor. Invocation presentation is supplied through the native -CommandKit boundary. The current -[internal overview](../../internal/overview.md) describes the small reporting -interface correctly. - -**Correct behavior and remediation.** Update the package summary to identify -the reporting interface and helpers. Alternatively, use a short reference to -the implemented reporting owner. No logger factory or new logging abstraction -is required; this is a stale GoDoc comment. - -## Existing Implementation Gaps And Audit Boundaries - -Some documentation/implementation mismatches already have implementation -findings. They remain pending rather than becoming additional prose fixes: - -- EH-01 in the [error-handling audit](06-error-handling.md): identified domain - configuration failures can exit 1 instead of the documented input status 2. - Preserve the selected exit-status contract when fixing classification. -- CN-03 in the [concurrency audit](04-concurrency.md): the exceptional late-reap - path can return before ownership settles, contrary to the documented - subprocess lifecycle. Do not erase that selected ownership boundary merely - to match the defective branch. -- FC-01/FC-02 in the [correctness audit](01-correctness.md) and CX-01 in the - [complexity audit](03-complexity.md) cover previous-input dependency closure, - carried-publication/restore authority, and inconsistent audio discovery. - Those need their recorded implementation decisions and tests, not a general - weakening of current manifest or input contracts. - -The reviewed release runbook agrees with the module-selected ReleaseKit tool, -release profile, CI toolchain, three build targets, delivery token mapping, and -source-tag completion boundary. The maintained CLI command tree and native -inspection walkthrough are current. No additional platform support, live -upstream compatibility result, historical-note rewrite, or stronger runtime -guarantee is proposed by this audit. - -## Review Outcome - -Eight documentation findings warrant follow-up. Prioritize DOC-01's recovery -sequence because it changes the consequences of copying the instructions. -The remaining findings correct stale behavior, path, inventory, example, and -ownership descriptions. Use the canonical owners and existing behavioral tests -when updating them; no production-code changes are required to resolve these -eight documentation findings. diff --git a/docs/roadmap/audit/catalog.md b/docs/roadmap/audit/catalog.md deleted file mode 100644 index 713f4c5..0000000 --- a/docs/roadmap/audit/catalog.md +++ /dev/null @@ -1,1094 +0,0 @@ -# Consolidated Audit Catalog - -Catalogued: 2026-12-01 - -Repository baseline: `191bd4342bc75246caf8bd3d65f33fb8f5f0b8df`. - -## Scope And Use - -This catalog accounts for **53 findings across all 11 audit reports** in this -directory, consolidated into **43 entries: one P1, twelve P2, and thirty P3**. -Every original finding belongs to one catalog entry. Original-entry links retain -the detailed code references, evidence, alternatives, and qualifications. - -The original source reports retain their historical open statuses and evidence. -The catalog records subsequent verified remediation without changing those reports. -Only audit documents changed between the first audit's code baseline and this -review's baseline. The original evidence therefore concerns the same application -code as it stood at the audit baseline; its limits still apply: source-established hazards are distinct from -dynamically reproduced failures, and green tests do not disprove unexercised -conditions. - -Entries are ordered first by the highest source priority and then by likely -consequence and breadth: data safety and lifecycle integrity, valid-workflow -failures/resource pressure, followed by maintainability and smaller hygiene -corrections. Ordering within a priority is a review judgment, not a new severity -assessment or a measured production-impact ranking. - -This is an inventory, not a staged implementation plan. Directions summarize the -audits' possible remedies without closing unresolved operational choices. -Required regression work is included with its associated production finding; -the independent S3-upload test gap remains separate. Related entries identify -shared change surfaces, not extra prerequisites. - -## Remediation Ownership And Remaining Decisions - -Published-artifact import is implemented; [Restore Internals](../../internal/command-restore.md) -describes its behavior. The [audio-inputs roadmap](../audio-inputs.md) records -shared audio discovery and the approved multi-format extension of CAT-12. -Disposition notes below relate findings to these features without expanding -their scope. Unless assigned otherwise, a finding remains independent audit -remediation. Shared code does not make a refactoring a prerequisite or assign -the whole finding to a roadmap. - -Forty-three entries are closed by the safety, transfer, audio discovery, S3 -planning, prerequisite-history, publication-import, CLI classification, -inspection aggregation, test maintenance, dead-code removal, and associated -documentation work; none remain open. **Planned** identifies -an agreed remedy awaiting implementation. **Potentially eliminated** requires verification that the offending -lifecycle is removed. **Coordinate** identifies shared changes, not a commitment -that a related feature implements the entire finding. Findings close only after their -relevant behavior or code removal is verified. Original audit reports, finding -identities, priorities, and source links remain unchanged. - -The final integration review checked all 25 roadmap coverage rows against their -implementations and behavioral tests, confirmed removal of the listed dead code -and preservation of supplied-product and analysis contracts, and verified the -original audit reports remain unchanged. The uncached full suite, race-enabled -suite, vet, and build pass with Go 1.27.4. - -Directions for CAT-01, CAT-02, CAT-04, CAT-05, and CAT-09 reflect subsequent agreed choices. -CAT-12 also reflects the approved audio selection and naming decisions. -Other direction paragraphs retain the audit's candidate remedies; agreed -choices and roadmap ownership are identified by the disposition notes. - -Decisions on [audio generation/size handling](discussion.md#4-keep-downloaded-audio-and-its-source-identity-together), -[subprocess completion](discussion.md#5-finish-subprocess-shutdown-before-releasing-its-files), -[publication source lifetimes](discussion.md#6-open-publication-sources-as-they-are-needed), -and [audio selection and naming](discussion.md#7-give-preparation-and-inspection-the-same-audio-selection-rules) -are agreed and implemented. Topic 1 -records cancellation-aware workspace lock waiting, now implemented. Remote checkpoint timing and -failure handling are deferred, not decisions blocking publication import. - -## Consolidation Decisions - -- Production defects and their matching test gaps share entries: CN-01/TE-04, - FC-02/TE-02, CN-03/TE-05, FC-01/TE-03, and EH-01/TE-06. -- Repeated ownership findings share entries: CX-01/BN-04, CX-02/EQ-04, - CX-05/EQ-03/BN-05, and CX-06/BN-03. The last entry retains CX-06's broader - extraction-evidence consideration as well as publication. -- Related but distinct problems remain separate: graph ownership versus - repeated reverse-index construction; prerequisite selection versus history - hydration; extraction protocol ownership versus large-function decomposition; - transfer-size enforcement versus sibling-temp reuse; and manual-clean safety - versus its dead file-target branch. -- Cross-references in audit summaries are not counted again. Deliberately - retained behavior, rejected generalizations, and areas with no actionable - finding are outside this catalog. - -## Architecture Context - -Narratio remains a fixed-stage orchestrator. The application coordinates -invocations, locks, plans, stages, and restore; adapters own external transports. -ConfigKit supplies completed configuration, CommandKit/ckconfig supply native -CLI/inspection, and Narratio derives separate domain catalogs. Manifest-backed -speaker/artifact checkpoints and valid supplied records govern product reuse. -Publication selects immutable inventories through a current pointer, restore -saves a merged local baseline last, -and cleanup has a separate authorization/lifecycle. See the -[implemented overview](../../internal/overview.md) and -[architecture policy](../../policy/architecture.md). - -## Prioritized Findings - -### CAT-01 — P1: Coordinate whole-session deletion with active invocations - -Status: Closed - -**Closure.** The stable workspace lock and command wiring are covered by `internal/artifacts/local_test.go` and `internal/app/clean_lock_test.go`. -Acquisition-path progress reporting and its command-level regression were -completed in `89c8e5d`; the review follow-up is resolved. - -**Disposition / owner.** Independent locking remediation — the [agreed direction](discussion.md#1-coordinate-destructive-cleanup-with-other-work) -permits one workspace-wide lock. [Restore](../../internal/command-restore.md) uses -that coordination; locking remains a separate remediation. Cancellation-aware -waiting is implemented and verified. - -Original findings: [CN-01](04-concurrency.md#cn-01--p1-whole-session-cleaning-bypasses-and-can-dismantle-session-exclusion), -[TE-04](08-testing.md#te-04--p2-whole-session-cleanup-tests-never-contend-with-an-active-invocation). - -**Original issue.** Manual `session clean` and `--all` bypass session locking and can -delete the in-tree lock pathname while a run, restore, or preflight still holds -its inode. A new invocation can then lock a replacement inode and overlap the -original writer. Existing cleanup tests never combine manual deletion with an -active invocation. - -**Agreed remedy.** Use a stable coordination identity or admission gate that survives -deletion, including admission of new sessions during `--all`. Use -cancellation-aware waiting and identify the lock being waited on. Add real-lock, -controlled-interleaving coverage for deletion, a second contender, and cancellation -while waiting. The already-locked final cleanup stage is a different operation. - -Related: [CAT-39](#cat-39--p3-simplify-manual-clean-to-its-live-directory-only-contract). - -### CAT-02 — P2: Make restored carried products agree with manifest authority - -Status: Closed - -**Closure.** Inventory-based import records validated local supplied products -without installing remote execution evidence. The publish–lock–generate–republish -round trip for a transcript and configured artifact, downstream source resolution, -and republishing are covered by -[`import_workflow_test.go`](../../../internal/app/import_workflow_test.go). -[Restore Internals](../../internal/command-restore.md#installation-and-local-baseline) -describes the implemented product-import model. - -Original findings: [FC-02](01-correctness.md#fc-02--p2-carried-publication-bytes-conflict-with-restored-manifest-evidence), -[TE-02](08-testing.md#te-02--p2-publication-and-restore-tests-do-not-prove-carried-output-authority-is-coherent). - -**Issue.** After publishing A, locking its source, generating B locally, and -republishing, the remote commit carries A while its session-manifest snapshot -retains B's completion evidence. Restore can succeed with A's bytes and B's -checksum/fingerprint authority; normal resolution then rejects the restored -product. Separate publish/restore tests miss this interaction. - -**Direction.** Use publication import and locally synthesized -completion instead of restoring historical execution evidence. Retain -publish–lock–regenerate–republish–restore–resolve round trips for built-in and -configured outputs, verifying usable restored products without reconstructing -their historical generation fingerprints or provenance. - -Related: [CAT-20](#cat-20--p3-share-typed-publication-control-evidence-across-producer-and-consumers). - -### CAT-03 — P2: Enforce non-forced session creation at the write boundary - -Status: Closed - -**Closure.** Exclusive local creation and conditional remote upload are covered by `internal/app/session_init_conflict_test.go`. - -Original findings: [CN-02](04-concurrency.md#cn-02--p2-session-initializations-no-overwrite-check-is-not-atomic). - -**Original issue.** Local stat-then-write and remote Exists-then-unconditional-upload allow -concurrent `session init` calls to overwrite a destination without `--force`. Both -can report success; local writes can also truncate or mix content. - -**Agreed remedy.** Use exclusive local creation and the existing remote absence -precondition for non-forced writes. Keep deliberate forced replacement separate -and test competing creators. A preliminary existence check may inform diagnostics -but cannot authorize the later write. - -### CAT-04 — P2: Bind prepared S3 audio bytes to their observed generation - -Status: Closed - -**Closure.** Response-bound audio identity, replacement, reuse, and rollback are covered by `internal/audio/s3_audio.go` and `internal/stage/prepare_test.go`. - -**Disposition / owner.** Independent audio-acquisition remediation — [discussion topic 4](discussion.md#4-keep-downloaded-audio-and-its-source-identity-together) -selects accepting the raw-audio generation actually downloaded; this is implemented -and verified. This is separate from the -[audio-inputs roadmap's discovery changes](../audio-inputs.md#relationship-to-other-work). -[Publication import](../../internal/command-restore.md) -relaxes generation-history requirements for imported products, not source identity -for local audio reuse. - -Original findings: [CN-04](04-concurrency.md#cn-04--p2-s3-audio-provenance-can-combine-two-object-generations). - -**Original issue.** Preparation records listing metadata from generation A but can download -same-sized generation B. Its checksum then describes B while source provenance -describes A, allowing incorrect reuse after a remote rollback. - -**Agreed remedy.** Retain metadata from the same opened response as the streamed body. -Accept and record that observed raw-audio generation when the download passes -existing acquisition checks, even if it differs from the earlier listing. -Test replacement between listing and reading, including rollback/reuse. This -corrects per-object consistency without a whole-session snapshot guarantee or -automatic retries until sources stop changing. - -Related: [CAT-06](#cat-06--p2-stop-known-size-downloads-before-oversized-bodies-exhaust-staging-space). - -### CAT-05 — P2: Retain subprocess and stream ownership through delayed completion - -Status: Closed - -**Closure.** Waiter joining and delayed output ownership are covered by `internal/adapters/subprocess/execution.go` and `execution_test.go`. - -**Disposition / owner.** Independent subprocess remediation — [discussion topic 5](discussion.md#5-finish-subprocess-shutdown-before-releasing-its-files) -selects joining process/output completion after bounded termination escalation, -before releasing resources; this is implemented and verified. Publication import -does not remove downstream process ownership. - -Original findings: [CN-03](04-concurrency.md#cn-03--p2-the-exceptional-subprocess-reap-timeout-releases-ownership-too-early), -[TE-05](08-testing.md#te-05--p2-subprocess-lifecycle-tests-do-not-exercise-a-delayed-reap-after-escalation). - -**Original issue.** The exceptional final reap timeout can return without receiving the -wait result. `ProcessState` inspection, redactor flushing, diagnostic closure, and -caller-owned result-file closure can then overlap a still-active waiter or stream -copier. Current tests exercise ordinary shutdown or pre-populated completion, not -delayed completion beyond escalation. - -**Agreed remedy.** Retain bounded graceful-to-forceful escalation, then join process -and output completion before reading process state, flushing/closing diagnostics, -or returning resource ownership to callers. Add a controlled delayed-wait/stream -test for release ordering and preserved error causes. Exceptional I/O delays can -outlast escalation timers; no absolute return-time guarantee or early-return -ownership handoff is required. - -### CAT-06 — P2: Stop known-size downloads before oversized bodies exhaust staging space - -Status: Closed - -**Closure.** Bounded response streaming and consumer regressions are covered by `internal/adapters/storage/stream_test.go`, `internal/app/restore_commit_test.go`, and `internal/stage/prepare_previous_test.go`. - -**Disposition / owner.** Coordinate — [restore](../../internal/command-restore.md#installation-and-local-baseline) -uses verified downloads. Transfer-size enforcement remains a separate audit -remediation across all listed callers. [Discussion topic 4](discussion.md#4-keep-downloaded-audio-and-its-source-identity-together) -approves bounded known-size streaming with existing unknown-size behavior; this -is implemented and verified. - -Original findings: [RS-02](05-resources.md#rs-02--p2-known-size-downloads-consume-the-full-response-before-rejecting-oversize). - -**Original issue.** Restore, previous-input hydration, S3 audio, and immutable-object -verification can know the expected size yet copy the entire body before rejecting -oversize. Invalid responses can fill temporary storage and hold the session lock -unnecessarily. - -**Agreed remedy.** Enforce the existing known size during transfer, with correlated -response metadata and size-plus-one detection, then close/remove failed staging. -Retain checksum/generation checks and installation ordering. Test early rejection -and destination preservation; a declared zero size is known. Unknown-size audio -needs no newly invented universal cap. - -Related: [CAT-04](#cat-04--p2-bind-prepared-s3-audio-bytes-to-their-observed-generation), [CAT-21](#cat-21--p3-share-closed-sibling-temporary-file-creation-mechanics). - -### CAT-07 — P2: Correct recovery instructions that publish before inspection - -Status: Closed - -**Closure.** Inspection-first regeneration and the mutating retry are corrected in `docs/troubleshooting.md`; documentation checks pass. - -**Disposition / owner.** Coordinate documentation — [recovery guidance](../../troubleshooting.md) -reflects publication import. Explicitly verify the inspection-before-publication -sequence; a restore documentation rewrite alone does not close this finding. - -Original findings: [DOC-01](13-documentation.md#doc-01--p2-recovery-examples-publish-before-the-stated-inspection-step). - -**Original issue.** Troubleshooting's unsupported-manifest recovery invokes a full run, -then force publish, while describing inspection before explicit publication. The -first command can already publish and run authorized cleanup. A separate -diagnostics block also includes a mutating forced publish. - -**Agreed remedy.** For inspection-first recovery, bound regeneration through analyze, -inspect, and then publish. Alternatively, describe the full run's -publication/cleanup effects accurately. Move publication retries out of the -inspection-only diagnostics sequence. This is a documentation correction, not a -new command confirmation or publication restriction. - -### CAT-08 — P2: Stream local audio copies instead of buffering whole recordings - -Status: Closed - -**Closure.** Streaming atomic input copying and replacement behavior are covered by `internal/stage/prepare.go` and `prepare_copy_test.go`. - -**Disposition / owner.** Independent copy-resource remediation — coordinate with the -[audio-inputs roadmap](../audio-inputs.md#reuse-and-transport-verification), which -reuses the copy path. Multi-format discovery does not remove whole-file buffering. - -Original findings: [EF-01](02-efficiency.md#ef-01--p2-local-audio-copying-buffers-the-complete-recording). - -**Original issue.** The changed/missing local-copy path hashes a recording, reads all its -bytes into memory, then writes them atomically. One large speaker file therefore -requires recording-sized auxiliary RAM despite sequential processing. - -**Agreed remedy.** Use the existing streaming artifact/file-copy mechanism while -preserving unchanged-destination checks, naming, workspace modes, atomic -visibility, and recorded checksums. The improvement is O(1) auxiliary buffering -relative to file size, not asymptotically faster I/O. No new audio-size limit is -required. - -### CAT-09 — P2: Bound publication's simultaneously open source descriptors - -Status: Closed - -**Closure.** Sequential confined source transfers, same-handle uploads, and pointer preservation are covered by `internal/stage/publish_transfer.go` and `publish_lifetime_test.go`. - -**Disposition / owner.** Independent publication-resource remediation — coordinate with the -[publication's snapshot removal](../../internal/stage-publish.md#outputs). -Removing one manifest source does not bound the remaining descriptors; -[discussion topic 6](discussion.md#6-open-publication-sources-as-they-are-needed) -selects sequential source opening, verification, upload, and closure, accepting -late-source failure after unselected uploads. This is implemented and verified. - -Original findings: [RS-01](05-resources.md#rs-01--p2-publication-retains-one-open-descriptor-per-source). - -**Original issue.** Publication retains descriptors for every run file, previous-cache -source, selected output, and committed manifest until its final defer, although -uploads are sequential. Valid larger inventories can exhaust lower process -descriptor limits before transfer begins. - -**Agreed remedy.** Plan identities, destinations, and rules upfront; then open, -verify, upload, and close sources one at a time. Preserve confined regular-file -opening, checksum checks, and hashing/uploading through the same descriptor. -Validating every source before any upload is no longer required. A late invalid -source may leave an unselected attempt, while pointer-last publication preserves -the current selection on failure. No artifact-count cap, source-snapshot system, -or new cleanup subsystem is needed. - -Related: [CAT-14](#cat-14--p3-close-temporary-committed-manifest-cleanup-gaps). - -### CAT-10 — P2: Hydrate previous inputs for the full analysis prerequisite closure - -Status: Closed - -**Closure.** The shared closure and prerequisite-inclusive history collector were -implemented in [a057ce3](https://forge.maximumdirect.net/eric/narratio/commit/a057ce3) -and [7a25a50](https://forge.maximumdirect.net/eric/narratio/commit/7a25a50). -Preparation-to-analysis and semantic resume regressions landed in -[76f9918](https://forge.maximumdirect.net/eric/narratio/commit/76f9918), with -restore, status, and preflight coverage in -[663e02e](https://forge.maximumdirect.net/eric/narratio/commit/663e02e). -[Reference preparation](../../internal/stage-prepare.md) -retains its separate acquisition and workflow boundaries. - -Original findings: [FC-01](01-correctness.md#fc-01--p2-previous-session-hydration-omits-analysis-prerequisites), -[TE-03](08-testing.md#te-03--p2-previous-session-hydration-coverage-stops-short-of-dependency-closure). - -**Original issue.** Preparation and previous-cache restore collected history requirements -from enabled/explicit targets only, while analyze separately scheduled -prerequisites. A prerequisite's required history could remain unavailable despite an -available remote product; optional history could disappear silently. Existing tests -covered these mechanisms separately. - -**Implemented direction.** A shared prerequisite-inclusive requirements view feeds -preparation, semantic evidence, store composition, and restore. Explicit targets -remain separate for force and publication. Regression tests cover selected children -and disabled prerequisites, required and optional history, unrelated-work exclusion, -and restore. - -Related: [CAT-17](#cat-17--p3-centralize-configured-artifact-dependency-queries). - -### CAT-11 — P2: Verify the bytes supplied to the production S3 upload adapter - -Status: Closed - -**Closure.** SDK-boundary upload bytes and reader failures are covered by `internal/adapters/storage/s3_backend_test.go`. - -Original findings: [TE-01](08-testing.md#te-01--p2-s3-upload-tests-do-not-verify-the-transmitted-content). - -**Original issue.** The SDK fake records upload requests without consuming their bodies. -Replacing the production body with unrelated fixed bytes survived the full suite; -higher-level storage fakes bypass that mapping. This is a demonstrated protection -gap, not a finding that the unmodified adapter sends wrong bytes. - -**Agreed remedy.** Consume and compare upload bytes in the narrow SDK fake for file -and conditional-reader uploads, retaining key/precondition assertions and -appropriate stream-error coverage. A local HTTP SDK test is an alternative; live -S3 is unnecessary. - -### CAT-12 — P2: Share audio discovery and accept valid same-basename recordings in inspection - -Status: Closed - -**Disposition / owner.** Implemented and verified under the -[audio-inputs roadmap](../audio-inputs.md) and -[discussion topic 7](discussion.md#7-give-preparation-and-inspection-the-same-audio-selection-rules). - -**Closure.** `internal/audio` owns local and S3 selection, prepared names, and -speaker-ID collision checks. Preparation, reuse, and inspection consume these -selections; transcription accepts manifest-selected files and uses the shared -filter for fallback. Audio discovery and real preparation/inspection tests cover -same-basename and mixed-format selection; transcription retry and WhisperX HTTP -and replay tests cover durable reuse and byte-preserving transport. Full tests, -race tests, vet, and build pass on Go 1.27.4. - -Original findings: [CX-01](03-complexity.md#cx-01--p2-audio-discovery-is-duplicated-and-inspection-rejects-valid-inputs), -[BN-04](11-boundaries.md#bn-04--p3-audio-discovery-is-owned-independently-by-preparation-and-inspection). - -**Issue.** Preparation and operator inspection independently implement source -resolution, filtering, eligibility, duplicates, and ordering. Preparation -preserves distinct same-basename recordings with unique prepared names; inspection -rejects them. The audits also identify differing duplicate-path and -file-eligibility handling. - -**Direction.** Give read-only audio selection a shared owner, preferably -`internal/audio`. Keep materialization and checkpoint transitions in preparation -and reporting in app. Apply the approved regular-file requirement and the -roadmap's shared case-insensitive filter for automatic discovery; explicit local -file selections and manifest-registered audio remain extension-agnostic. Preserve -duplicate-resolved-source rejection, existing local prepared-name disambiguation, -and the separately selected S3 basename rule. Retain stem-based speaker IDs and -reject remaining cross-extension stem collisions during discovery, identifying -both sources after existing disambiguation. Verify consistent mixed-format -selection, downstream acceptance, transport, and local retry across consumers -without imposing backend codec guarantees. - -Related: [CAT-13](#cat-13--p2-give-s3-session-planning-the-evidence-needed-for-truthful-reuse-decisions). - -### CAT-13 — P2: Give S3 session planning the evidence needed for truthful reuse decisions - -Status: Closed - -**Disposition / owner.** Implemented and verified under the -[planning/preflight decision](discussion.md#3-inspect-s3-when-planning-and-preflighting). - -**Closure.** Planning supplies the object store to the shared preparation -validator for eligible S3 reuse. Unavailable evidence reports an unverified -source and preserves the normal rerun. The application regressions in -[`plan_s3_test.go`](../../../internal/app/plan_s3_test.go) and -[`session_readiness_test.go`](../../../internal/app/session_readiness_test.go) -cover observed reuse, change, access failure, and preflight cancellation; -[`prepare_resume_test.go`](../../../internal/stage/prepare_resume_test.go) -covers unavailable and insufficient identity evidence. Full tests, race tests, -vet, and build pass on Go 1.27.4. - -Original findings: [FC-03](01-correctness.md#fc-03--p2-session-planning-reports-reusable-s3-preparation-as-changed). - -**Original issue.** The planning projection omits the object store needed to inspect S3 -audio identities. Resume converts that missing collaborator into 'inputs changed', -so plan can predict prepare reruns and dependent invalidation while actual -execution reuses identical evidence. - -**Direction.** Supply read-only remote identities to the shared planning decision, -or explicitly report conditional/unverified evidence if remote inspection is -intentionally unavailable. Test unchanged, changed, and unavailable identities -while proving no workspace mutation. Keep this distinct from local audio discovery -disagreement. - -Related: [CAT-12](#cat-12--p2-share-audio-discovery-and-accept-valid-same-basename-recordings-in-inspection). - -### CAT-14 — P3: Close temporary committed-manifest cleanup gaps - -Status: Closed - -**Closure.** Publication no longer creates or uploads a temporary session -execution-manifest snapshot; the inventory commit is encoded and written by -[`publish_commit.go`](../../../internal/stage/publish_commit.go). The removed -temporary-file lifecycle and its ownership gap no longer exist. Publication -tests verify that no execution ledger is emitted. - -Original findings: [RS-03](05-resources.md#rs-03--p3-publications-temporary-manifest-has-cleanup-gaps-before-ownership-transfer). - -**Issue.** Publication can orphan a system-temp committed-manifest file when -writing/closing fails or opening it fails before the transfer collection accepts -ownership. These files are outside run-history cleanup. - -**Direction.** Make the creator own removal immediately, and retain caller cleanup -until transfer ownership is explicit. Exercise write/close/handoff failure paths. -Straightforward deferred cleanup suffices; this is distinct from intentionally -retained attempt diagnostics. - -Related: [CAT-09](#cat-09--p2-bound-publications-simultaneously-open-source-descriptors), [CAT-21](#cat-21--p3-share-closed-sibling-temporary-file-creation-mechanics). - -### CAT-15 — P3: Preserve input-error classification for resolved domain validation - -Status: Closed - -**Closure.** Explicit storage/audio and product-destination rejections retain a -cause-preserving `config.DomainInputError`, recognized by the existing CLI -classifier. Loading and environmental errors retain their ordinary types. -[`domain_validation_test.go`](../../../internal/app/domain_validation_test.go) -exercises real-command rejection of both reported conflicts and invalid product -placement, valid local/S3 and destination counterparts, missing configuration, -and joined operational/cancellation precedence. Existing native and catalog -classification regressions remain passing. See -[configuration internals](../../internal/configuration.md#resolved-domain-validation). - -Original findings: [EH-01](06-error-handling.md#eh-01--p3-domain-configuration-failures-lose-the-cli-input-classification), -[TE-06](08-testing.md#te-06--p3-cli-classification-tests-omit-real-resolved-domain-rejections). - -**Issue.** Cross-document storage/audio conflicts and product-destination -collisions return ordinary errors, so commands exit 1 instead of the documented -identifiable-input status 2. Existing tests check rejection or synthetic markers -but do not carry these real failures through the CLI. - -**Direction.** Use a narrow cause-preserving domain input marker at the -rejection/classification boundary, or integrate suitable checks with native -validation diagnostics. Add real-command cases for both conflicts, valid -counterparts, and joined operational/cancellation precedence. Environmental -failures stay operational; no new validation rule is needed. - -### CAT-16 — P3: Flatten inspection-error aggregation - -Status: Closed - -**Closure.** Publication and enclosing session inspection collect ordered errors and -join once. `TestPublishedOutputInspectionRetainsMultipleLookupFailures` verifies -partial rows, ordered messages, and retained error causes. - -Original findings: [EF-05](02-efficiency.md#ef-05--p3-publication-inspection-errors-form-a-quadratic-formatting-tree). - -**Issue.** Repeated `errors.Join(previous, next)` creates a left-nested -publication-inspection error tree. Formatting F bounded-size failures takes -quadratic cumulative copying and linear nesting, particularly during storage -outages. - -**Direction.** Collect ordered failures and join once. Preserve per-output -details, partial results, and `errors.Is`/`errors.As` causes. Existing preflight -collectors provide a local pattern. - -Related: [CAT-25](#cat-25--p3-separate-inspectionreadiness-collection-assessment-and-presentation). - -### CAT-17 — P3: Centralize configured-artifact dependency queries - -Status: Closed - -**Closure.** The derived catalog owns the shared artifact dependency graph; -configuration validation, prerequisite selection, ordering and analysis -planning use its mechanics. Focused configuration, artifact, stage and app -tests verify selection, origins, supplied boundaries and history. - -**Disposition / owner.** Independent dependency-refactoring owner — [restore coverage](../../internal/command-restore.md#installation-and-local-baseline) -uses a fixed stage/output coverage mapping, not this configured-artifact graph. -Do not make graph consolidation a prerequisite; coordinate only where existing -artifact reconciliation is actually changed. - -The CAT-10 work moved the existing prerequisite closure, ordering, and dependency -normalization to `internal/artifacts`; broader graph ownership and dependent -queries remain open. - -Original findings: [CX-05](03-complexity.md#cx-05--p3-artifact-dependency-semantics-span-several-representations-and-owners), -[EQ-03](10-equivalence.md#eq-03--p3-configured-artifact-dependency-mechanics-have-multiple-owners), -[BN-05](11-boundaries.md#bn-05--p3-configured-artifact-graph-operations-are-fragmented-across-domain-owners). - -**Issue.** One derived edge relation has separately maintained normalization, -validation adjacency, topological ordering, prerequisite traversal, and -reverse-edge mechanics. Targets-only selection is easily confused with required -work, as the history-hydration defect illustrates. - -**Direction.** Expose a small validated dependency view alongside the derived -artifact catalog, or a narrow key/edge package if dependency direction requires -it. Share deterministic order, closure, and dependent queries while retaining -origin diagnostics and caller-owned force/reuse/invalidation policy. Keep -configuration definitions, runtime availability, and the fixed stage relation -distinct. - -Related: [CAT-10](#cat-10--p2-hydrate-previous-inputs-for-the-full-analysis-prerequisite-closure), [CAT-18](#cat-18--p3-reuse-the-analysis-reverse-dependency-index-within-an-invocation). - -### CAT-18 — P3: Reuse the analysis reverse-dependency index within an invocation - -Status: Closed - -**Closure.** Analysis reuses its operation-owned graph for success and failure -invalidation, including eligibility barriers. Analyze and checkpoint tests pass. - -Original findings: [EF-02](02-efficiency.md#ef-02--p3-analysis-rebuilds-the-same-dependency-index-after-each-completion). - -**Issue.** Each new/changed completion rebuilds and sorts the unchanged reverse -graph. Independent artifacts still incur quadratic setup work. This performance -issue can be fixed independently of broader graph ownership. - -**Direction.** Construct the immutable reverse index once and reuse it for -success/failure invalidation. Preserve traversal ordering, eligibility, and -invalidation timing. Complete-collection checkpoint costs remain separate. - -Related: [CAT-17](#cat-17--p3-centralize-configured-artifact-dependency-queries). - -### CAT-19 — P3: Describe stable prepared products once for materialization and reuse - -Status: Closed - -**Closure.** Stable product descriptions drive materialization, resume source -matching and semantic presence selection. Preparation, resume, configuration -and app tests cover snapshots, relocated inputs, glossaries, and supplied work. - -**Disposition / owner.** Coordinate — [reference preparation](../../internal/stage-prepare.md) -supports imported products and reuse. Review the shared stable-product description -there to avoid another parallel inventory; the import feature does not itself perform -this consolidation or replace evidence for locally prepared products. - -Original findings: [CX-02](03-complexity.md#cx-02--p3-prepared-stable-inputs-have-parallel-materialization-and-resume-definitions), -[EQ-04](10-equivalence.md#eq-04--p3-preparation-and-resume-separately-describe-the-same-stable-products). - -**Issue.** Preparation, party/player writing, resume reconstruction, managed-kind -matching, and semantic presence repeat stable-product inventories and dependency -mappings. Existing renderers and source descriptors are already shared, but -callers can omit different products. - -**Direction.** Use a small stage-owned read-only product description backed by -current descriptors, with separate write and expected-evidence projections. -Preserve snapshot normalization, combined-glossary dependencies, source -relocation, ConfigKit immutability, and bounded presence-only fingerprinting. Keep -audio and previous acquisition explicit and retain independent literal -inventory/corruption tests. - -Related: [CAT-34](#cat-34--p3-include-the-combined-glossary-in-prepared-input-documentation). - -### CAT-20 — P3: Share typed publication control evidence across producer and consumers - -Status: Closed - -**Closure.** Shared publication and extraction codecs retain typed control -evidence across direct and JSON-decoded metadata. Cleanup, inspection, -extraction, resume, and fallback tests pass. - -**Disposition / owner.** Coordinate — [inventory-based import](../../internal/command-restore.md) -changed publication consumers and extraction availability. Typed local control -evidence remains a separate simplification; neither snapshot removal nor import -completion automatically centralizes the remaining codecs. - -Original findings: [CX-06](03-complexity.md#cx-06--p3-unstructured-metadata-carries-cross-package-control-evidence), -[BN-03](11-boundaries.md#bn-03--p3-machine-consumed-publication-metadata-lacks-a-shared-contract-owner). - -**Issue.** Publish writes map-based completion/outcome evidence; cleanup and app -inspection independently reconstruct keys, status strings, types, and in-memory -versus JSON-decoded collection shapes. Extraction has a related producer/reader -metadata boundary. - -**Direction.** Start with narrow typed publication values and codecs under an -existing shared owner, preserving the JSON shape. Keep cleanup authorization and -tolerant display policy at their callers. Apply the same treatment to extraction -evidence where useful; leave free-form diagnostics flexible. Test direct and -persistence-round-trip use. Typing does not resolve carried-product authority. - -Related: [CAT-02](#cat-02--p2-make-restored-carried-products-agree-with-manifest-authority). - -### CAT-21 — P3: Share closed sibling-temporary-file creation mechanics - -Status: Closed - -**Closure.** Download callers share closed sibling temporary-file creation; -fileops and consumer tests cover failure cleanup, validation, and retry. - -**Disposition / owner.** Coordinate — [restore](../../internal/command-restore.md#installation-and-local-baseline) -retains staging and validation before installation. Reassess the common mechanics -across the surviving download callers; helper extraction remains separate from -both product import and CAT-06's transfer bounds. - -Original findings: [EQ-02](10-equivalence.md#eq-02--p3-verified-downloads-duplicate-sibling-temporary-file-ownership). - -**Issue.** Audio, previous-input hydration, and ordinary restore repeat creating, -writing, closing, and error-cleaning a sibling temporary file before -domain-specific verification and installation. - -**Direction.** Use a small `internal/fileops` helper returning an owned closed -temporary path, or a narrowly scoped cleanup callback. Keep selection, -cancellation, validation, root confinement, and installation with callers. Atomic -reader-copy helpers that install before validation are not substitutes. Retain -representative consumer failure/retry tests. - -Related: [CAT-06](#cat-06--p2-stop-known-size-downloads-before-oversized-bodies-exhaust-staging-space), [CAT-14](#cat-14--p3-close-temporary-committed-manifest-cleanup-gaps). - -### CAT-22 — P3: Share the minimal transcript-envelope predicate - -Status: Closed - -**Closure.** Adapters, stage validation and artifact resolution share the minimal -transcript envelope predicate; literal shape and boundary tests pass. - -Original findings: [EQ-01](10-equivalence.md#eq-01--p3-four-boundaries-repeat-the-same-minimal-transcript-shape-validator). - -**Issue.** Seriatim, Audita, stage acceptance, and artifact resolution -independently implement the same JSON top-level `segments` array check. Their -surrounding filesystem and diagnostic rules legitimately differ. - -**Direction.** Prefer a byte-oriented predicate in existing `internal/contracts`, -leaving acquisition, bounds, file eligibility, and contextual errors at each -boundary. Preserve empty arrays and unrelated members; do not impose segment IDs -or a universal downstream schema. Keep independent literal fixtures and -representative adapter/consumer tests. - -### CAT-23 — P3: Move Notarius native output mapping and executable lookup to their boundary - -Status: Closed - -**Closure.** The Notarius adapter resolves native lane paths and executable -selection; stage promotion, collision and readiness tests remain in place. - -Original findings: [BN-02](11-boundaries.md#bn-02--p3-notarius-output-protocol-translation-partly-lives-in-stage-orchestration). - -**Issue.** Stage code implements Notarius lane-ID sanitization and native bundle -filenames, and performs executable discovery shared by execution and readiness. -These are external-protocol/launch details rather than Narratio product policy. - -**Direction.** Move native mapping to the existing adapter through a narrow -resolver or requested-output result contract; route executable selection through -adapter/composition. Stages retain required-lane selection, canonical names, -collisions, confinement, bounded JSON checks, checksums, and promotion. This -ownership correction is distinct from decomposing the large stage functions. - -Related: [CAT-24](#cat-24--p3-separate-trimextract-invocation-phases-from-product-acceptance). - -### CAT-24 — P3: Separate trim/extract invocation phases from product acceptance - -Status: Closed - -**Closure.** Extraction shares resolved invocation options with readiness and -separates acceptance and promotion. Trim separates bounds generation, selection, -execution and final acceptance; focused stage and app tests pass. - -Original findings: [CX-03](03-complexity.md#cx-03--p3-trim-and-extraction-mix-invocation-mechanics-with-product-acceptance). - -**Issue.** Large stage entry points interleave layout, disabled branches, debug -rendering, native execution, validation, promotion, and metadata. Extraction -readiness and execution also repeat resolved invocation options. - -**Direction.** Extract cohesive typed operations and shared invocation options, -keeping explicit orchestration and one final acceptance path where behavior is -shared. Preserve validation before promotion, post-call reference verification, -and failure diagnostics. Avoid a generic stage framework or helpers that only -relocate statements. - -Related: [CAT-23](#cat-23--p3-move-notarius-native-output-mapping-and-executable-lookup-to-their-boundary). - -### CAT-25 — P3: Separate inspection/readiness collection, assessment, and presentation - -Status: Closed - -**Closure.** Prompt interpretation, session inspection collection, preparation -assessment and tool readiness operations are separated from report projection. -Preflight, app and stage tests cover partial failures and cancellation. - -**Disposition / owner.** Coordinate — [publication import](../../internal/command-restore.md) -supports inspection and readiness for supplied inputs. The broader separation of -collection, assessment, and presentation retains independent audit ownership; -do not require it before adding coverage-aware decisions. - -Original findings: [CX-04](03-complexity.md#cx-04--p3-inspection-and-readiness-combine-collection-policy-and-presentation). - -**Issue.** Operator entry points mix local/remote evidence acquisition, -independent probes, preparation outcomes, cancellation, policy interpretation, and -report mutation. Scriptorium discovery interpretation is interleaved with -transport iteration. - -**Direction.** Collect cohesive typed results, isolate tool-specific readiness and -pure requirements interpretation, then project the existing reports. Preserve -partial findings, independent work after ordinary failures, preparation-blocked -checks, cancellation, read-only inspection, and preflight effects. No check -registry or stronger readiness rule is required. - -Related: [CAT-16](#cat-16--p3-flatten-inspection-error-aggregation). - -### CAT-26 — P3: Place diagnostic-view layout grammar with canonical workspace paths - -Status: Closed - -**Closure.** Managed attempt views now use the artifact workspace path owner; -fileops retains confined directory mechanics. View, cleanup, stage and app tests pass. - -Original findings: [BN-01](11-boundaries.md#bn-01--p3-diagnostic-view-layout-policy-is-embedded-in-file-operation-mechanics). - -**Issue.** Fileops constructs and recognizes Narratio-specific -run/stage/log/debug/probe paths independently of the canonical path owner. A -layout change therefore spans file mechanics and multiple domain callers. - -**Direction.** Move the existing view operation to `internal/artifacts` and its -path model, or consider a focused workspace owner if the broader extraction is -justified. Keep ordinary root-scoped file mechanics in fileops and attempt/cleanup -decisions in callers. Retain advancement, failure, self-skip, reuse, and -confinement coverage. - -### CAT-27 — P3: Index repeated previous-input and prepared-record lookups - -Status: Closed - -**Closure.** Previous publication declarations and optional absence use -operation-local indexes; prepared and previous input resolution share an -input-snapshot lookup retaining ordered candidates and verifying file contents. -The previous-cache, artifact, stage, and app package tests pass, including -snapshot replacement and content revalidation coverage. - -**Disposition / owner.** Coordinate — [inventory-based import](../../internal/command-restore.md) -changed previous-input discovery and prepared-record consumers. Reassess the -surviving scans after those changes; inventory-only selection does not by itself -remove repeated linear lookups. - -Original findings: [EF-03](02-efficiency.md#ef-03--p3-previous-session-metadata-is-repeatedly-searched-as-a-list). - -**Issue.** Requirement resolution repeatedly scans remote commit declarations, -local input identities are repeatedly selected from manifest lists, and -optional-absence reporting repeatedly searches skipped names. - -**Direction.** Build phase-local source/kind indexes and skipped-name membership -sets (or use appropriate sorted lookup). Keep one selected commit, candidate -multiplicity, ambiguity checks, deterministic result order, and content -verification. Index selection rather than caching payloads across invocations. - -### CAT-28 — P3: Index restore report action updates - -Status: Closed - -**Closure.** Restore reports index action identities privately while retaining -the first matching action, report order and counters. Restore execution tests -cover duplicate keys and unmatched updates as well as existing workflows. - -**Disposition / owner.** Coordinate — [restore reporting](../../internal/command-restore.md#reporting-and-ownership) -remains implemented. Carry or index action identity if that path is changed; -new manifest construction alone does not fix quadratic report updates. - -Original findings: [EF-04](02-efficiency.md#ef-04--p3-restore-reporting-performs-a-full-search-after-each-install). - -**Issue.** Each restored object's success/failure searches the report's full -action list, yielding quadratic bookkeeping when all actions download. - -**Direction.** Use a private composite-key-to-report-index map or carry the -original index with execution actions. Preserve report order and shape and the -separate manifest-last installation order. - -### CAT-29 — P3: Correct force-after-enablement guidance - -Status: Closed - -**Closure.** [Operations](../../operations.md#stage-execution-and-continuation-behavior) explains -automatic reassessment of observable enablement/configuration changes, explicit -force for current-result replacement or private changes, and independent supplied -coverage. - -Original findings: [DOC-02](13-documentation.md#doc-02--p3-operator-guidance-incorrectly-requires-force-after-enablement). - -**Issue.** Operations says newly enabled/configured render, publish, or analyze -requires force, contradicting current fingerprints and reconciliation. - -**Direction.** Explain automatic reruns for observable configuration changes when -the affected stage is selected. Reserve force guidance for intentional -current-result replacement or private upstream changes. Link to canonical resume -descriptions rather than repeating stale behavior. - -### CAT-30 — P3: Correct internal resume and fingerprint descriptions - -Status: Closed - -**Closure.** The focused [analyze](../../internal/stage-analyze.md), -[prepare](../../internal/stage-prepare.md), and [manifest](../../internal/manifest.md) -descriptions now distinguish diagnostic render-debug, provenance-only input -ownership, and prepare's durable-copy and current-source checks. - -Original findings: [DOC-03](13-documentation.md#doc-03--p3-internal-resume-summaries-describe-obsolete-fingerprint-inputs). - -**Issue.** Analyze prose incorrectly includes debug selection in fingerprints; -prepare prose includes source ownership/party mode; the manifest overview omits -prepare's durable source/content validator. - -**Direction.** Describe the current typed payloads and prepare's combined -semantic/content checks, or shorten the overview to links to focused stage owners. -Preserve diagnostic-only debug selection and provenance-only ownership. Correct -prose without changing fingerprints to match it. - -### CAT-31 — P3: Correct annotated-example dependency, credential, and cleanup claims - -Status: Closed - -**Closure.** Annotated pipeline comments describe inferred dependencies, -operator-selected secret references and session run-history cleanup. The -comments were reviewed and example configuration validation passes. - -Original findings: [DOC-05](13-documentation.md#doc-05--p3-annotated-example-comments-retain-obsolete-contracts-and-defaults). - -**Issue.** Comments require redundant authored `depends_on` edges, label example -S3 secret-reference names as defaults, and understate cleanup as one run's work -directory. - -**Direction.** State inferred input dependencies, operator-selected credential -references, and whole-session run-history cleanup accurately. Link to the -configuration/operations owners. YAML-loading tests cannot detect incorrect -comments. - -### CAT-32 — P3: Document Seriatim reports as diagnostics - -Status: Closed - -**Closure.** Merge and normalize documentation identifies canonical transcripts -as products and optional reports as run-local diagnostics. Documentation checks pass. - -Original findings: [DOC-04](13-documentation.md#doc-04--p3-seriatim-reports-are-documented-as-canonical-artifact-outputs). - -**Issue.** Merge and normalize output lists advertise canonical `artifacts/` -report files, while implementation retains reports in run-local logs and returns -only canonical transcripts as substantive outputs. - -**Direction.** Separate products from diagnostics and link to the -workspace/retention owner. Keep the selected content taxonomy; moving reports back -to canonical artifacts is not a prose fix. - -### CAT-33 — P3: Align credential-ownership descriptions with native ConfigKit startup - -Status: Closed - -**Closure.** File operations no longer claim credential policy; adapter and -storage documentation identifies ConfigKit startup at acquisition and resolved -value consumption, with upstream and operator-permissions links. Documentation checks pass. - -Original findings: [DOC-06](13-documentation.md#doc-06--p3-internal-credential-ownership-descriptions-predate-native-bootstrap). - -**Issue.** Internal fileops/adapter prose assigns credential precedence/mode -responsibility to app and describes bootstrap during object-store construction. -Actual acquisition delegates configured startup to ConfigKit before typed loading, -and storage consumes resolved values. - -**Direction.** Describe native startup at acquisition and link upstream for its -semantics; link operations for operator-managed permissions. Remove stale -credential-policy prose from file helpers. Do not restore duplicate bootstrap or -filesystem enforcement in Narratio. - -### CAT-34 — P3: Include the combined glossary in prepared-input documentation - -Status: Closed - -**Closure.** [Manifest](../../internal/manifest.md#prepared-glossary-evidence), -[publication](../../internal/stage-publish.md), and -[restore](../../internal/command-restore.md) documentation include the combined -document alongside the four individual envelopes. The manifest description -retains Audita's four-envelope input distinction. - -Original findings: [DOC-07](13-documentation.md#doc-07--p3-internal-glossary-inventories-omit-the-combined-prepared-document). - -**Issue.** Manifest/publish/restore summaries count four retained glossaries, -omitting the combined fifth envelope that is prepared, committed, and restored. - -**Direction.** Include combined alongside party/campaign/setting/spells, -preferably linking to one inventory instead of repeating counts. Audita -intentionally receives four individual envelopes; keep that distinct. - -Related: [CAT-19](#cat-19--p3-describe-stable-prepared-products-once-for-materialization-and-reuse). - -### CAT-35 — P3: Remove assertions on incidental serialization and validation order - -Status: Closed - -**Closure.** Metadata tests compare decoded JSON members and omissions; the native campaign -validation test locates its diagnostic without requiring its position. - -Original findings: [TE-07](08-testing.md#te-07--p3-some-assertions-freeze-incidental-serialization-or-validation-order). - -**Issue.** A metadata test freezes JSON object-member order and a campaign test -with multiple invalid conditions freezes the first diagnostic. Valid internal -reorderings fail despite equivalent contractual results. - -**Direction.** Assert JSON structure/omissions and the intended validation -condition without prescribing irrelevant order. Retain canonical-byte assertions -where bytes actually define fingerprints or remote contracts; do not delete -meaningful boundary tests. - -### CAT-36 — P3: Remove confirmed orphaned production and test helpers - -Status: Closed - -**Closure.** The listed orphan helpers and their unused imports were removed after a source -reference check; focused package tests and `go vet ./...` pass. - -Original findings: [DD-01](12-deadcode.md#dd-01--p3-completely-orphaned-helper-functions-remain-in-production-and-tests). - -**Issue.** Reachability analysis and source review identify six disconnected -production helpers and six unused test helpers across Notarius, cleanup, -configuration, and fixtures. - -**Direction.** Remove the exact source-listed declarations and newly unused -imports/files. Retain live path/bundle validation, supported callbacks, and -independent preparation assertions. Verify current references before deletion; no -replacement abstraction or compatibility shim is needed. - -### CAT-37 — P3: Remove unused constants and retired workspace path fields - -Status: Closed - -**Closure.** The listed unused constants and retired session path fields were removed; -active layout and publication defaults remain covered by package tests. - -Original findings: [DD-02](12-deadcode.md#dd-02--p3-unused-constants-and-retired-workspace-paths-advertise-obsolete-concepts). - -**Issue.** Six disconnected constants and unused -`SessionPaths.ReportsDir`/`ConfigDir` fields, assignments, and directory constants -preserve obsolete names without providing runtime capabilities. - -**Direction.** Delete only the listed inert model elements. Keep active artifact -vocabulary and commit/path helpers. This does not authorize deleting session -directories, changing layout, migrating sessions, or inventing an output fallback. - -### CAT-38 — P3: Remove inert extraction descriptor fields and nil-only plumbing - -Status: Closed - -**Closure.** JSON-excluded fingerprint fields and nil-only generated extraction -contract plumbing were removed. Artifact, stage, and configuration tests pass; -supplied and analysis contracts remain. - -Original findings: [DD-03](12-deadcode.md#dd-03--p3-extraction-still-carries-descriptor-fields-that-the-current-model-discarded). - -**Issue.** Four extraction fingerprint fields are JSON-excluded and unused. An -extraction evidence contract field has no non-nil producer and is passed through -redundant extraction-only plumbing. - -**Direction.** Remove those fields and extraction-only parameters/copies while -retaining live analyze/catalog/manifest contracts. Existing fingerprint bytes can -remain unchanged. No schema migration, stricter lane check, or retired -configuration descriptor is needed. - -### CAT-39 — P3: Simplify manual clean to its live directory-only contract - -Status: Closed - -**Closure.** Manual clean now validates directories through one entry point; -focused clean, cleanup, confinement, and lock tests pass. - -Original findings: [DD-04](12-deadcode.md#dd-04--p3-manual-cleaning-retains-a-file-target-mode-unavailable-through-its-cli). - -**Issue.** Both CLI cleaning modes always pass `directory=true`; file-target -behavior and wrapper variants survive only through unit tests. - -**Direction.** Use one live directory validation path and remove the forwarded -mode, file-only branch, and obsolete wrappers/tests. Preserve confinement, -symlink/root/traversal checks, dry runs, missing targets, and deletion scope. This -simplification is separate from the workspace-lock remediation in CAT-01. - -Related: [CAT-01](#cat-01--p1-coordinate-whole-session-deletion-with-active-invocations). - -### CAT-40 — P3: Remove the superseded publish-default mutation helper - -Status: Closed - -**Closure.** The obsolete publish-default writer and its no-op test call were removed; -ConfigKit derivation and explicit-destination tests remain. - -Original findings: [DD-05](12-deadcode.md#dd-05--p3-a-superseded-publish-default-mutation-helper-survives-only-in-a-no-op-test-call). - -**Issue.** `applyMissingPublishDestinations` has only a test caller whose explicit -destination makes the call a no-op. Production uses native ConfigKit normalization -and the shared derivation directly. - -**Direction.** Remove the obsolete writer and irrelevant call; retain derivation -and explicit-destination protection through the live boundary. Do not alter -configuration ownership or introduce new destination semantics. - -### CAT-41 — P3: Remove the duplicate normalized-transcript test - -Status: Closed - -**Closure.** The duplicate analysis test was removed; the manifest-authoritative source test -remains. - -Original findings: [TE-08](08-testing.md#te-08--p3-two-normalized-transcript-tests-are-exact-duplicates). - -**Issue.** Two differently named analyze tests have identical bodies and -assertions for the same manifest-authoritative normalized source. - -**Direction.** Keep one authority test and delete its exact duplicate. Retain -neighboring source-kind and missing-input cases, which protect different behavior. - -### CAT-42 — P3: Discard the unused normalized-path result while retaining validation - -Status: Closed - -**Closure.** Input hashing discards the unused normalized value while retaining the -confinement check; stage tests pass. - -Original findings: [DD-06](12-deadcode.md#dd-06--p3-input-hashing-stores-a-normalized-path-that-is-never-consumed). - -**Issue.** Input hashing reassigns a normalized relative path that is never used -afterward; only the validation error matters. - -**Direction.** Discard the unused return value explicitly. Preserve the -normalization call and error check, which enforce live path confinement. - -### CAT-43 — P3: Correct the logging package summary - -Status: Closed - -**Closure.** Package documentation describes Reporter and forwarding helpers -and assigns presentation to CommandKit. - -Original findings: [DOC-08](13-documentation.md#doc-08--p3-logging-package-documentation-advertises-a-removed-responsibility). - -**Issue.** GoDoc advertises structured logger construction, but the package -supplies a Reporter interface and nil-safe forwarding helpers, with presentation -supplied by CommandKit. - -**Direction.** Update the package summary or link to the implemented reporting -owner. No logger constructor or new logging abstraction is needed. diff --git a/docs/roadmap/audit/discussion.md b/docs/roadmap/audit/discussion.md deleted file mode 100644 index eca41a9..0000000 --- a/docs/roadmap/audit/discussion.md +++ /dev/null @@ -1,486 +0,0 @@ -# Audit Remediation Discussion - -Status: Decisions agreed; assigned safety, transfer, and feature work implemented - -## Purpose - -Work through the seven topics raised in the catalog review before preparing a -remediation roadmap. Section numbers match that review and the operator's -responses. They are discussion topics, not implementation stages or catalog IDs. - -The [catalog](catalog.md) remains the findings inventory. Its original audit links -own the detailed evidence. This document records decisions, explains consequences, -and distinguishes recommendations from approved scope. No remediation has been -implemented by this document. - -Problem descriptions below record the original audit baseline. The catalog owns -current finding status and closure evidence; consult it for remaining work. - -The operator has settled the direction for all seven topics, including -cancellation-aware waiting for lock contention. [Publication import](../../internal/command-restore.md) -and the [audio-inputs feature](../audio-inputs.md) are implemented. The catalog -retains the remaining independent work and its closure evidence. - -## 1. Coordinate destructive cleanup with other work - -Status: Implemented and verified - -Finding: [CAT-01](catalog.md#cat-01--p1-coordinate-whole-session-deletion-with-active-invocations). - -### What goes wrong today - -A run holds a lock inside its session directory. Manual whole-session cleanup -can delete that directory, including the lock's filename, while the run is still -active. Another run can create a replacement lock file and start working against -the same paths. The first process still owns its original lock, but it no longer -coordinates access to the replacement file. - -The final pipeline cleanup stage is different: it already runs under invocation -locking and preserves the session root. - -### Agreed direction - -Concurrent sessions are not a goal or known use case. Use one workspace-wide lock -if that is the simplest design. Serializing work on different sessions is -acceptable. A shared/exclusive admission hierarchy and per-session concurrency -are unnecessary for this scope. - -The coordination file must survive the directory deletions it protects. All -participating operations must use the same identity, including whole-workspace -session cleanup and creation of a new session's working state. This is local -process coordination for a workspace, not a distributed lock across machines. - -### Agreed contention behavior - -Use cancellation-aware waiting, consistent with existing invocation locking, -and identify the lock being waited on. A contending invocation waits for the -workspace lock and can be cancelled while waiting. - -The roadmap should identify the mutating command participants explicitly. Pure -inspection and unrelated workspaces need no new serialization requirement. - -Operator response: - -_Approved: use cancellation-aware waiting for the workspace lock. CAT-01 is -closed, including the acquisition-diagnostic review follow-up._ - -## 2. Import published artifacts and retain local resume - -Status: Publication import implemented; remote execution checkpoints deferred - -Finding: [CAT-02](catalog.md#cat-02--p2-make-restored-carried-products-agree-with-manifest-authority). - -### Separate publication from execution recovery - -Publication and remote execution recovery are independent capabilities: - -1. Store completed artifacts for publication and later use. Publication locks - preserve selected published files. -2. Store execution checkpoints so a saved session can later be restored and - resumed, retaining its manifest, fingerprints, and applicable provenance. - -The operator has selected publication import for this development scope and -deferred remote execution checkpoints. Local execution checkpoints and ordinary -resume remain supported. - -The current session manifest is Narratio's local progress ledger. It records -completed work and evidence used to decide whether that work can be reused. -The remote publication commit separately identifies published files. The current -restore flow combines these records in a way that can mix different generations. - -### Concrete example - -1. Generate transcript A and publish it. -2. Lock the published transcript because A is the distributed, canonical copy. -3. Regenerate locally, producing transcript B. The local manifest describes B. -4. Publish again. The lock correctly keeps A in the remote publication. -5. Restore that publication into an empty workspace. - -The audit reproduced this result: - -| Item | Restored value | -| --- | --- | -| Transcript file | A | -| Manifest's recorded transcript checksum | Checksum of B | -| Manifest's completion evidence | Generation B | -| Restore command | Reports success | -| Subsequent normal transcript resolution | Rejects the checksum mismatch | - -The lock correctly retained A. The failure comes from combining publication's A -with execution's manifest describing B. - -### Agreed direction: published artifacts - -Published artifacts are finished products available for consumption. They can be -imported as inputs to a subsequent session or a fresh run of the same session. - -Publication import uses file identity and location to select the requested -product. Transfer-integrity checks, such as verifying downloaded bytes against -a checksum, are separate from generation history. - -Generation fingerprints, historical inputs, prompts, models, settings, and -generation provenance are irrelevant to using these published products. Import -does not require reconstructing historical completion records or evaluating -whether the original producer would be reusable under today's configuration. -An imported artifact is a supplied input; it does not assert that its producer -executed in the receiving workspace. - -Published products may come from different generations. This direction adds no -requirement for a publication-wide coherent pipeline generation. - -### Agreed operator workflows - -The immediate scope supports three distinct workflows: - -- Start from original sources: supply campaign/session configuration and raw - audio in a fresh workspace, then generate transcripts and artifacts. -- Start from published products: select and import finished transcripts or - artifacts as supplied inputs, then execute the downstream work that consumes - them. This starts new execution rather than recovering historical execution. -- Continue local work: rerun against the existing workspace and use its local - manifest and files to retain completed speaker/artifact work and retry unfinished - work under normal resume checks. - -For the failed-transcription example, the existing local workspace already -preserves completed speaker work. Remote backup is unnecessary for that ordinary -retry. Recovering unpublished progress after workspace loss or moving execution -to another machine is a separate capability without an established immediate -operational need. - -The import workflow is a real gap. Previous-session published-artifact consumption -already exists, but starting a fresh same-session execution from a published -transcript needs explicit support. Current bounded starts require preceding -manifest stage records; copying files into place and selecting a downstream range -does not provide the agreed workflow. Imported inputs should enable their consuming -work without inventing upstream stage-completion history. - -In the A/B example, publication import retrieves A and makes it usable as a -supplied input. The local workspace containing B can continue independently -through normal local resume. Recovering B's execution after losing that workspace -is deferred. - -### Consequences for remediation - -Use the publication inventory to select imported products and verify their -transfer, independently of a remotely saved execution manifest. The earlier -proposal to reconstruct historical producer evidence for publication import is -superseded by this decision. - -Current remote-state loading, restore, status, and previous-session acquisition -depend on the uploaded session-manifest snapshot. The roadmap should remove that -coupling for publication consumption and review which snapshot-publication and -execution-recovery machinery becomes unnecessary. Preserve the configuration -inputs needed for the selected workflow. Previous-session artifact selection -already uses the publication inventory and should follow the import semantics -above. - -Physical layout, command syntax, and storage formats remain implementation-planning -matters. This discussion does not select a new CLI or treat the current mixed -restore behavior as the target contract. - -This decision preserves local execution checkpoints and normal resume behavior. -It adds no requirement for publication imports to carry or satisfy the original -producer's fingerprints or generation provenance. - -### Deferred capability: remote execution checkpoints - -Remote checkpoint upload and recovery are outside the immediate scope. Upload -timing, cancellation behavior, transfer-failure handling, and retry machinery are -therefore deferred rather than open decisions blocking this remediation. - -If a future operational need warrants remote checkpoints, design that recovery -workflow separately from publication import. A resumable checkpoint would need -the saved execution ledger and matching files, with ordinary resume validation; -a publication lock could not substitute an older product for a checkpoint output. - -Operator response: - -_Approved: defer remote execution checkpoints, retain local resume, and focus on -importing published artifacts._ - -## 3. Inspect S3 when planning and preflighting - -Status: Implemented and verified - -Finding: [CAT-13](catalog.md#cat-13--p2-give-s3-session-planning-the-evidence-needed-for-truthful-reuse-decisions). - -### What goes wrong today - -Execution can compare current S3 audio identities with preparation's recorded -identities. The planning projection omits that storage collaborator and can -translate its absence into "inputs changed." It can therefore predict work that -execution would correctly reuse. - -### Agreed direction - -Planning should make a read-only S3 check. Preflight should make the relevant -read-only S3 check as well. Use existing storage capabilities and share the -identity interpretation with execution where practical. - -The S3 identity check is read-only. This decision does not redefine the entire -preflight command as read-only. The current -[preflight workflow](../../operations.md#prompt-requirements-preflight) prepares -or reuses inputs, may download files and update the manifest, and checks downstream -providers. Preserve those responsibilities unless separately changed. - -### Follow-through for the roadmap - -Verify which S3 checks preflight already performs through preparation and reuse -that work rather than adding redundant calls. Observe unchanged, changed, and -unavailable sources through both commands. An access or connectivity failure -should be identified as such rather than reported as proven content change. -Use existing command failure/reporting conventions where they fit. The lookup -does not guarantee that S3 remains unchanged between planning and execution. - -### Completion - -The [source diagnostic](https://forge.maximumdirect.net/eric/narratio/commit/c0c8a95f7c93a2908cbe82c53f31119bd23da468), -[planning composition](https://forge.maximumdirect.net/eric/narratio/commit/11de2262a0d7b3f17118b00fa26a6ca85ae5479e), -and [preflight verification](https://forge.maximumdirect.net/eric/narratio/commit/c1f43de5f98a0b8cda0fe9e97e791b72d940a838) -implement the decision. The [catalog closure](catalog.md#cat-13--p2-give-s3-session-planning-the-evidence-needed-for-truthful-reuse-decisions) -links the regression coverage and validation. - -Operator response: - -_Read-only S3 checks approved; no further product choice identified here._ - -## 4. Keep downloaded audio and its source identity together - -Status: Both decisions implemented and verified - -Findings: [CAT-04](catalog.md#cat-04--p2-bind-prepared-s3-audio-bytes-to-their-observed-generation) -and [CAT-06](catalog.md#cat-06--p2-stop-known-size-downloads-before-oversized-bodies-exhaust-staging-space). - -### Concrete example - -Narratio lists a speaker recording in S3 and sees version A. Before the download, -an ordinary uploader replaces that key with version B of the same size. Narratio -downloads B but records A's listed source identity alongside B's checksum. - -If S3 later contains A again, Narratio can conclude that its local copy is current: -the remote identity matches the recorded A identity, and the local bytes match -the recorded B checksum. Both checks pass individually, but they describe -different versions. Narratio can reuse the wrong recording. - -Here "version" means an observed object generation/identity; this does not -require enabling S3 bucket versioning. The existing read operation already -provides metadata associated with the returned body. The audio download path -currently loses that association. - -### Agreed direction: audio source identity - -Use the metadata returned with the actual download as the identity of the bytes -accepted. If B is a valid recording satisfying the acquisition rules, record B -and continue. This accommodates ordinary uploads without claiming that the -earlier directory listing froze all the session's audio. - -If the observed response cannot satisfy the applicable checks, fail clearly. -The earlier listing does not require rejecting an otherwise acceptable replacement. -This adds no automatic retry-until-stable loop or session-wide snapshot protocol. - -### Agreed direction: known-size transfers - -Restore and other downloads already reject content that differs from a known -expected size, but only after writing the complete response. Stop an oversized -response during transfer instead. This applies an existing acceptance condition -earlier; it introduces no universal maximum recording size. - -Use a bounded streaming transfer: for an expected N bytes, reading at most N plus -one byte distinguishes an exact-sized response from an oversized one. Retain -existing short-response and checksum validation. On failure, close the response, -remove partial staging, preserve the canonical destination, and identify the -responsible transfer and expected size in the error. - -For committed products, the committed size is authoritative. If audio adopts B -instead of A, the response identity and size boundary must both describe B. -The byte count remains checked rather than trusting response metadata alone. -Unknown-size input retains its existing behavior and remains distinct from a -known zero-byte declaration. The change does not reserve disk space or prevent -every disk-full condition. - -For raw audio, the observed download supplies the accepted identity. For published -products, the selected publication inventory supplies the expected identity; -different content is rejected rather than silently adopted. Transfer verification -is separate from historical generation provenance for imported products. - -Operator response: - -_Approved: accept and record the raw-audio generation actually downloaded, using -metadata from the same response; enforce known expected sizes while streaming, -without a universal audio-size cap. CAT-04 and CAT-06 are closed._ - -## 5. Finish subprocess shutdown before releasing its files - -Status: Implemented and verified - -Finding: [CAT-05](catalog.md#cat-05--p2-retain-subprocess-and-stream-ownership-through-delayed-completion). - -### What goes wrong today - -When a downstream command times out or is cancelled, Narratio requests graceful -termination and then forceful termination. A separate waiter observes process -exit and completion of output copying. - -On an exceptional path, the final wait timer expires before that waiter finishes. -Narratio can return an error and start closing log or result files while the -waiter or output copier still uses them. Issuing a kill request is not the same -as observing completion of every resource user. - -The audit established this ordering from source. It did not reproduce a dynamic -race. Normal cancellation and subprocess tests passed. - -### Agreed direction - -Keep the bounded graceful-to-forceful escalation, then join process/output -completion before releasing the associated resources or returning their ownership -to callers. Read process state and flush/close diagnostics after completion is -joined. Preserve the original timeout or cancellation cause. Exercise the -delayed-completion branch with a controlled test of resource-release ordering. - -Ordinary cancellation should still terminate promptly. In an exceptional blocked -filesystem write or kernel operation, resource completion can take longer than -the escalation windows. The invocation may remain in shutdown and continue -holding its workspace lock while resource ownership completes. - -Document the timeout as starting command shutdown, not guaranteeing that every -resource is released at that instant. Retain bounded escalation without an -absolute return-time guarantee for arbitrary blocked I/O. Use the existing -supervisor and standard process-waiting mechanisms; an early-return ownership -handoff or background cleanup service is unnecessary for this fix. - -Operator response: - -_Approved: retain bounded termination escalation, then wait for process and output -completion before releasing resources, even when exceptional I/O delays outlast -the escalation timers. CAT-05 is closed._ - -## 6. Open publication sources as they are needed - -Status: Implemented and verified - -Finding: [CAT-09](catalog.md#cat-09--p2-bound-publications-simultaneously-open-source-descriptors). - -### What goes wrong today - -Publication opens every selected local source before uploading and keeps all -those handles open until the stage ends. Each open file consumes an operating -system descriptor. A large inventory can exhaust that resource even though -uploads occur one at a time. Closing the handles at the end prevents an ordinary -leak but does not prevent excessive simultaneous use. - -The audit established this scaling from source; it did not reproduce exhaustion -or establish a failure threshold for a production deployment. - -### Why the current approach exists - -Opening and validating sources up front catches invalid sources before uploading. -Retaining a verified handle also avoids substituting a later pathname lookup for -the file that was checked. Those are separate concerns from retaining every handle -throughout the entire attempt. - -Remote publication becomes current only when the final pointer is updated. -An earlier failure may already leave immutable uploads that were never selected -as current. Preserving the old current pointer is the important existing commit -boundary; failure does not promise that no remote bytes were uploaded. - -### Agreed direction - -Keep complete destination planning, then open, verify, upload, and close each -source in sequence using a bounded number of handles. Retain confinement, -regular-file and checksum checks, and use the verified handle for hashing and -transfer. Close each source when its transfer and verification finish rather -than retaining all sources until the stage ends. - -An invalid later source may be discovered after earlier immutable uploads. -Such a failure leaves the prior publication current; the new attempt is not -selected. On a first publication, failure leaves no newly selected publication. -Keep the current-pointer write last, after all required publication work succeeds. - -This explicitly relaxes the documented all-sources-rejected-before-upload behavior. -Planning identities, destinations, and rules remains upfront; opening and validating -every source before any upload is no longer required. - -Use the existing sequential transfer mechanism. This decision adds no artifact-count -cap, descriptor-limit tuning, disk-backed source snapshots, or upload-concurrency -framework. Unselected objects from unsuccessful attempts do not require a new -cleanup subsystem as part of this fix. Existing publication locks retain their -semantics, including carrying locked remote products without opening their local -replacements. - -Verify bounded source-handle lifetimes with a growing inventory and a late-source -failure that leaves current publication unchanged. Retain the existing source -validation and pointer-ordering coverage. - -Operator response: - -_Approved: plan destinations upfront, then open, verify, upload, and close one -source at a time. A later invalid source may leave an unselected remote attempt; -the current publication must remain unchanged on failure. CAT-09 is closed._ - -## 7. Give preparation and inspection the same audio selection rules - -Status: Implemented and verified - -Finding: [CAT-12](catalog.md#cat-12--p2-share-audio-discovery-and-accept-valid-same-basename-recordings-in-inspection). - -Roadmap owner: [Multi-Format Audio Inputs and Shared Discovery](../audio-inputs.md). - -### Concrete example - -At the audit baseline, the operator selects `first/speaker.flac` and -`second/speaker.flac`. Preparation accepts these distinct recordings and gives the prepared copies distinct names. -Inspection rejects them because their basenames match. A status command can -therefore report unavailable audio for a session preparation can process. - -The duplicate implementations also differ on selecting the exact same file twice -and on file eligibility. Preparation's initial file check rejects directories; -inspection requires a regular file. A named pipe or device can pass the former -check but fail the latter. The audit does not establish successful end-to-end -support for those non-regular sources. - -### Agreed direction - -Share read-only selection rules. Accept distinct local recordings with matching -basenames and retain preparation's rejection of duplicate resolved source paths. -Keep materialization and checkpoint transitions with preparation and reporting -with inspection. Preserve the existing prepared-name disambiguation and keep -the separately selected S3 basename rule distinct from local selection. - -Local recording sources must resolve to regular files. This supports repeated -reading, hashing, and resume. Existing path and symlink rules remain separate. - -Accept multiple audio formats. Automatic directory and S3-prefix scans use one -shared, broad, case-insensitive extension filter; nonmatching sidecars are -ignored. The [roadmap](../audio-inputs.md#broad-extension-filtering-for-automatic-discovery) -owns the extension set and its application to preparation, inspection, reuse, -and transcription fallback. Explicit local file selections and manifest-registered -audio remain extension-agnostic. Backend decoding determines actual codec support; -selection adds no transcoding or format-probing requirement. - -Preserve stem-based speaker IDs. After existing prepared-name disambiguation, -reject remaining same-stem collisions across extensions during shared discovery, -identify both sources, and ask the operator to select one encoding or rename the -recordings. Distinct same-full-basename local recordings remain supported. This -moves the existing transcription ambiguity failure earlier without adding -automatic cross-extension renaming or content-based deduplication. - -The roadmap extends CAT-12's shared-discovery remediation with the subsequently -approved multi-format behavior. Audio generation identity and transfer bounds -remain the separate corrections agreed under topic 4. Publication import is -independent of raw-audio discovery; the implemented features have separate scopes. - -Operator response: - -_Approved: regular-file selection, shared broad audio-extension filtering for -automatic discovery, extension-agnostic explicit inputs, and early rejection of -unresolved speaker-stem collisions. CAT-12 is closed after implementation -and verification._ - -## After Discussion - -Prepare remediation plans for the catalog's remaining open entries. Distinguish -agreed behavior changes from internal refactoring, retain the audit evidence -links, and include focused regression coverage. Build on the completed safety, -transfer, publication-import, and audio-input work. Recording an approved -direction alone does not close its finding; pending work still requires -implementation and verification. diff --git a/internal/doccheck/doccheck_test.go b/internal/doccheck/doccheck_test.go index 2002cd1..4f0ac75 100644 --- a/internal/doccheck/doccheck_test.go +++ b/internal/doccheck/doccheck_test.go @@ -271,13 +271,6 @@ func walkDocumentationLinks(t *testing.T, root, directory string) { } resolved := filepath.Clean(filepath.Join(filepath.Dir(path), target)) if _, err := os.Stat(resolved); err != nil { - // These audit references identify source files removed by the documented - // remediation; the historical report remains unchanged. - if relativeToRoot(root, path) == "docs/roadmap/audit/12-deadcode.md" && - (relativeToRoot(root, resolved) == "internal/app/paths_test_helpers_test.go" || - relativeToRoot(root, resolved) == "internal/app/clean.go") && os.IsNotExist(err) { - continue - } t.Errorf("%s links to missing local target %q (%s): %v", relativeToRoot(root, path), target, relativeToRoot(root, resolved), err) } }