Remove completed audit and planning documents
All checks were successful
ci/woodpecker/push/verify Pipeline was successful
All checks were successful
ci/woodpecker/push/verify Pipeline was successful
This commit is contained in:
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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=<temporary-file> ./...`
|
||||
passed. `go tool cover -func=<temporary-file>` 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=<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.
|
||||
@@ -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.
|
||||
@@ -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/<run>/<stage>/{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/<name>.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.
|
||||
@@ -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
|
||||
`<session>/reports` and `<session>/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.
|
||||
@@ -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.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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.
|
||||
Reference in New Issue
Block a user