Files
narratio/docs/roadmap/implementation.md

307 lines
18 KiB
Markdown
Raw Normal View History

# Multi-Format Audio Inputs Implementation Plan
Status: Ready for implementation
Baseline: `0288111c721ed49f19aade68370f30f92017d581`.
## Scope and Working Instructions
Implement the agreed target in [audio-inputs.md](audio-inputs.md). That roadmap
owns the extension set, selection policy, naming decisions, and scope boundaries.
This plan owns implementation sequencing for a Luna coding agent.
The sprint addresses [CAT-12](audit/catalog.md#cat-12--p2-share-audio-discovery-and-accept-valid-same-basename-recordings-in-inspection)
and the approved multi-format extension of that finding. Preparation and
inspection must share read-only discovery, and transcription must accept the
selected recordings without a second extension gate. Keep the completed safety,
transfer-size, response-identity, streaming-copy, and workspace-lock behavior.
CAT-13's S3 planning/preflight collaborator fix, the session-restore redesign,
and other catalog refactorings remain separate work. Wiring an existing consumer
to shared discovery does not close those findings. No new dependency or upstream
application change is needed.
Follow Stages 1–7 in order, one focused Luna prompt per stage. This is a single
end-to-end sprint: intermediate stages may temporarily fail to compile or test
while consumers migrate. Avoid temporary compatibility APIs or duplicate paths
whose only purpose is making intermediate stages independently releasable.
Stage 7 must leave a coherent, verified repository.
Read `docs/development.md` and applicable agent, architecture, testing, and
documentation policies. Use graph tools for code discovery. Focused audit evidence
is in `audit/03-complexity.md`, lines 49–97 (CX-01), and
`audit/11-boundaries.md`, lines 215–262 (BN-04). Those unchanged historical reports
describe FLAC-only behavior; the feature roadmap's later decisions govern the
target. Other audit reports need not be read in full for this sprint.
Preserve these boundaries throughout:
- Automatic scans use the roadmap's one shared, case-insensitive extension set.
Explicit local files and manifest-registered audio are extension-agnostic.
Discovery selects candidates; the backend decides whether it can decode them.
- Local recordings must resolve to regular files. Preserve existing path rules;
no blanket symlink rejection, inode/hard-link deduplication, recursive local
discovery, or new filesystem-hardening contract is requested.
- Keep existing local prepared-name disambiguation, case-sensitive speaker-ID
comparisons, and S3 duplicate-basename policy. Reject remaining stem ambiguity
after deriving prepared names; do not silently choose an encoding or generate
new names for cross-extension collisions.
- Preserve file bytes, meaningful suffixes, source identity, checkpoints, force
behavior, and ordinary evidence-based reuse. No transcoding, MIME registry,
local codec probe, new audio cap, configurable extension knob, S3 per-object
selector, or manifest-version migration is in scope.
- Inspection stays read-only. Share discovery rather than invoking preparation
from the application or moving materialization/state transitions into discovery.
Use real temporary files and existing storage/transcription fakes or local HTTP
servers. Placeholder bytes test selection and transport, not codec decoding.
Keep tests offline and credential-free. Commit completed focused units according
to agent policy; this sprint does not authorize pushing or releasing.
## Stage 1: Centralize read-only candidate selection
Read the roadmap's selection sections, the focused audit evidence above, and
current `resolveLocalAudioFiles`, `resolveLocalInspectionAudioPaths`,
`listS3AudioObjects`, and `inspectRemoteAudioPresence`.
Work:
1. Put shared source selection in existing `internal/audio`. Use small explicit
parameters for the session-file base directory and local file/directory
selections, and an explicit bucket-relative prefix plus object-store boundary
for S3 listing. Do not pass a stage environment or execute stage code.
2. Keep the roadmap's complete discovery extension set in one discoverable
package-level definition. Provide one membership operation shared by all
automatic scans. Extension matching ignores case; it does not rewrite names.
3. Preserve local path resolution: trim authored path whitespace, resolve relative
selections against the session document directory, and clean paths using the
current rules. Explicit file selection takes precedence as it does today.
Reject repeated cleaned/resolved source paths, not distinct paths merely
because their basenames match. Do not add symlink canonicalization or content
equivalence as a new definition of duplicate input.
4. Explicit local selections bypass suffix filtering. Local directory enumeration
remains non-recursive: skip directory entries, filter candidate suffixes, and
require selected entries to resolve to regular files using ordinary stat
semantics and existing read-path rules. Missing/unreadable sources and
selected non-regular entries remain clear failures. Nonmatching sidecars are
ignored rather than submitted to transcription.
5. S3 selection lists the explicit prefix, trims keys, ignores empty keys and
directory markers, applies the same extension predicate, and sorts by key.
Use slash-based object-key basenames. Preserve rejection of distinct keys
with identical full basenames; local basename disambiguation does not become
a remote naming policy. Return complete selected object metadata, unchanged
apart from the existing key normalization.
6. Keep existing configured-source empty-selection errors, replacing FLAC-only
wording with audio-candidate wording. Do not make exact wording/order a test
contract. Stage 5 retains transcription's own existing no-input outcome.
Acceptance: focused package tests cover explicit unfamiliar/extensionless paths,
case-insensitive automatic candidates, ignored sidecars, regular-file eligibility,
relative resolution, deterministic order, duplicate resolved paths, S3 directory
markers, and existing S3 duplicate-basename behavior. Discovery creates no
workspace directories, copies no files, and writes no manifest.
## Stage 2: Share prepared-name and speaker-identity calculation
Read `localAudioDestinations`, `buildTranscribeJobs`, and
`internal/stage/audio_destinations_test.go`.
Work:
1. Move the pure local prepared-basename calculation into the shared audio owner,
preserving its existing algorithm: leave unique full basenames unchanged;
disambiguate identical full basenames with the existing cleaned-source-path
hash and occupied-name suffix handling, preserving the original extension.
Preparation still chooses the canonical directory and performs installation.
2. Have local discovery return each original resolved path with its derived
prepared basename (a narrow source record is sufficient). Consumers must not
maintain a second naming implementation or independently recompute a slightly
different collision policy.
3. Derive speaker ID by stripping the final extension from the prepared basename,
exactly as current transcription does. Share this operation and the uniqueness
check with transcription. Preserve existing empty-stem rejection and ID case.
4. After existing basename disambiguation, detect duplicate derived speaker IDs
during shared local/S3 discovery. Errors identify both original source paths
or keys and direct the operator to choose one encoding or rename recordings.
S3 prepared basenames remain the selected object basenames. Do not fix this
case by automatically appending codec names or selecting one recording.
Acceptance: distinct `first/speaker.flac` and `second/speaker.flac` remain valid
with their established deterministic names. `speaker.mp3` and `speaker.wav`
fail early with both sources identified. Test generated-name occupancy as well:
checking original stems alone must not reject a pair the existing disambiguation
resolves, and checking full filenames alone must not miss a remaining stem clash.
Use observable names/mappings and a small preservation case for the established
hash algorithm, not broad snapshots of private helper structure.
## Stage 3: Wire preparation and its reuse inventory to shared discovery
Read `internal/stage/prepare.go`, `prepare_resume.go`, and preparation's source
selection/destination tests. Inspect the completed S3 audio materialization and
local streaming-copy paths before changing their callers.
Work:
1. Replace preparation's local and S3 selection loops with Stage 1–2 operations.
Keep source-mode/configuration checks and session/S3 prefix construction at
existing Narratio boundaries, using canonical artifact/path helpers. Storage
continues receiving explicit bucket-relative prefixes.
2. Materialize each selected local path under its shared prepared basename.
Keep copying, destination policy, workspace locking, and manifest updates with
preparation. Continue using streaming local copies and their installed-byte
checksums; do not reintroduce recording-sized allocations.
3. Feed selected S3 objects to existing `audio.MaterializeS3Audio`. Preserve
response-bound generation metadata and known-size transfer behavior. Record
the identity actually returned by materialization, not stale listing evidence.
4. Migrate `currentPrepareAudioSourceInputs` to the same selections and names.
Retain its normal hashing, S3 identity checks, and expected-input projection.
Remove obsolete selection/naming loops and FLAC helpers as their callers move;
thin caller-specific adaptation is fine, duplicated policy is not.
5. Replace MP3-rejection and FLAC-only enumeration tests with the chosen contract.
Add local and S3 mixed-format preparation/reuse cases. Retain regular existing
FLAC fixtures, unchanged source names, source replacement/rollback tests,
failed-staging preservation, and unaffected stable-input tests.
Acceptance: selection and resume reconstruction agree on ordered identities and
destinations. Unchanged existing FLAC inputs retain their normal reuse evidence;
newly discovered supported files change the inventory through ordinary rules.
Unresolved speaker ambiguity fails before audio materialization or transcription
dispatch. This stage does not repair CAT-13's missing planning collaborator.
## Stage 4: Make operator inspection consume the same selections
Read `internal/app/operator_inspection.go` and its local/remote inspection tests.
Work:
1. Replace local inspection discovery with the shared result. Report original
resolved source paths through the existing local report shape. Prepared names
can be described through existing reporting where needed; no new public
report schema or command family is requested.
2. Replace remote prefix/list/filter/basename handling with the shared S3
selection. Preserve the current checked/prefix/keys/error reporting and
caller-owned error context. Keep prefix construction with Narratio's existing
path helpers and respect cancellation/storage errors.
3. Remove inspection-only FLAC predicates and audio-specific duplicate path
logic. Leave generic path/file helpers used by non-audio inputs intact.
4. Add a cross-consumer regression using the real preparation stage and operator
inspection with distinct same-basename files. Also compare explicit mixed
formats, directory scans, and fake S3 listings. Confirm both consumers accept
or reject the same source sets, including repeated paths and stem clashes.
5. Demonstrate inspection on a fresh workspace does not create managed files or
manifests and performs only read-only remote operations. Reuse existing
inspection non-mutation tests where they already establish that boundary.
Acceptance: status/inspection no longer rejects the valid same-basename local
recordings preparation supports. It does not invoke preparation, hash audio
merely to decide eligibility, or acquire a mutation lock to discover sources.
## Stage 5: Remove transcription's second extension gate
Read `internal/stage/transcribe.go`, `transcribe_reconciliation.go`,
`transcribe_resume.go`, and their discovery/checkpoint tests.
Work:
1. Keep manifest audio inputs authoritative when present. Resolve their paths
through existing manifest/path helpers and validate regular files and duplicate
paths without applying the automatic extension filter. Unknown suffixes and
extensionless selected files must reach job construction.
2. When no manifest audio inputs are available, enumerate the prepared audio
directory with the shared automatic filter and regular-file check. Preserve
the existing directory scope and transcription no-input/failure behavior;
do not fall back to directory scanning to hide invalid manifest-selected audio.
3. Build jobs with Stage 2's stem/uniqueness operation using the actual prepared
filenames. Already materialized or manifest-selected files must not undergo
local-source basename renaming again. Keep the final collision guard for
supplied manifests/fallback inputs that did not pass current preparation.
4. Retain raw transcript paths, speaker mappings, worker dispatch, force semantics,
and reconciliation/fingerprint payloads. Additional codecs alone require no
checkpoint version bump, migration, or new fingerprint field.
5. Test manifest-selected non-FLAC and unusual/extensionless audio, filtered
fallback candidates, invalid selected inputs, and duplicate stems before any
transcription call. Preserve ordinary FLAC identities and mapping behavior.
Acceptance: a recording accepted during preparation is not rejected later solely
by its suffix. Missing/invalid selected files remain errors; unlisted prepared
sidecars are not accidentally promoted into manifest-selected audio.
## Stage 6: Verify partial retry and byte-preserving transport
Read existing per-speaker checkpoint tests and WhisperX multipart/replay tests,
especially `TestTranscribeFailureCheckpointsEarlierSpeakersAndRetryRunsOnlyRemaining`
and `TestMultipartBodyReplayUsesIdenticalFraming`.
Work:
1. Extend representative assembled preparation-to-transcription coverage to a
mixed-format set. Include the naming flow for distinct same-basename local
sources and an explicit unfamiliar suffix or extensionless recording.
2. Use controlled transcription success/failure to durably checkpoint an initial
subset, fail a remaining speaker, persist/reload the manifest, and retry.
Verify completed speakers are not resubmitted and unfinished work completes.
Reuse existing test machinery; sequential test concurrency can make the
failure order deterministic without changing production concurrency.
3. Verify changed selected bytes still invalidate the affected speaker through
ordinary reconciliation, and existing unambiguous FLAC checkpoints remain
reusable. Keep aggregate-completion and explicit-force protections intact.
4. Use representative local and fake S3 preparation cases to assert byte and
suffix preservation. At the HTTP adapter boundary, check the multipart file
part's actual filename and bytes for non-FLAC/unfamiliar selections, including
transport replay. Keep existing generic content type and replay machinery.
5. Retain a representative unsupported/malformed-audio backend error as a visible
transcription failure. Selection tests must not claim a decoder accepted their
placeholder bytes or force the adapter to classify codecs locally.
Acceptance: mixed-format selection works through preparation, job creation,
upload, failure, and durable local retry. No paid/live backend, transcoder,
decoder toolchain, or new performance gate is needed.
## Stage 7: Align documentation and verify the final sprint state
1. Update `docs/config.md` as the canonical owner of source-selection semantics
and the extension set. Explain automatic versus explicit selection, current
S3 prefix behavior, and the operator action for unresolved speaker-stem
collisions. Link to it rather than copying the full suffix list elsewhere.
2. Update operations, `docs/internal/stage-prepare.md`,
`docs/internal/stage-transcribe.md`, affected workspace/input descriptions,
and `docs/integrations/whisperx.md` where needed. Explain shared discovery,
prepared-name/ID behavior, and backend codec ownership at their appropriate
boundaries. Remove inaccurate FLAC-only claims; FLAC examples remain valid.
3. In `examples/README.md`, describe the existing sample audio as a placeholder
to replace with a real supported recording. Keep valid sample filenames and
configured paths unless an example actually needs changing; do not add binary
audio fixtures or mechanically rename every FLAC test/example.
4. Review remaining production extension checks: only the shared automatic
discovery predicate should implement audio-suffix selection. Verify no
manifest-selected validation, reuse inventory, or inspection path retains an
independent FLAC gate or a divergent suffix list. Retain unrelated filename
uses and diagnostics that merely name a FLAC fixture.
5. Run the maintained end-state checks from repository root:
```sh
GOTOOLCHAIN=go1.27.4 go test ./...
GOTOOLCHAIN=go1.27.4 go test -race ./...
GOTOOLCHAIN=go1.27.4 go vet ./...
GOTOOLCHAIN=go1.27.4 go build ./...
git diff --check
```
During development, use focused tests for `internal/audio`, `internal/stage`,
`internal/app`, `internal/adapters/whisperx`, and `internal/doccheck`. Tests
should protect selected behavior and important interactions, not incidental
diagnostic wording or helper choreography.
6. Close CAT-12 in `audit/catalog.md` only after verifying both original discovery
disagreement and the complete approved multi-format behavior. Record concise
code/test evidence and update status counts. Update discussion topic 7 and
the feature roadmap's implementation status. Keep original audit reports
unchanged; CAT-13 and the other pending findings remain open.
7. Mark these stages complete with brief evidence, inspect the final diff for
new restrictions/guarantees, and commit completed work with plain-English
messages. Leave a clean workspace; do not push, tag, or release.
Completion requires the roadmap's selection, naming, transport, retry, and
documentation outcomes together. The feature roadmap already separates desired
behavior from staging, so it needs no restructuring in this planning pass.
No product decisions remain open for this scope.