426 lines
24 KiB
Markdown
426 lines
24 KiB
Markdown
# Safety and Transfer Remediation Implementation Plan
|
||
|
||
Status: Ready for implementation
|
||
|
||
Baseline: `074fe64e12d1b52a5d709469f4bced99be8740d8`.
|
||
|
||
## Scope and Authority
|
||
|
||
Implement the first two agreed work packages from the
|
||
[audit catalog](audit/catalog.md): safety fixes and baseline test protection,
|
||
then transfer correctness and resource use. The
|
||
[discussion](audit/discussion.md) records the approved operational choices.
|
||
Original audit reports remain historical evidence; subsequent agreed decisions
|
||
govern remedies where they differ from the original alternatives.
|
||
|
||
| Catalog entry | Outcome | Stages |
|
||
| --- | --- | --- |
|
||
| CAT-01 | Stable workspace exclusion, including destructive manual cleanup | 2–3 |
|
||
| CAT-03 | Non-forced initialization cannot overwrite an existing destination | 4 |
|
||
| CAT-04 | Downloaded audio and recorded source identity describe the same response | 6–7 |
|
||
| CAT-05 | Subprocess and output ownership continues until completion is joined | 5 |
|
||
| CAT-06 | Known-size downloads stop oversized responses during transfer | 6–8 |
|
||
| CAT-07 | Recovery documentation actually permits inspection before publication | 1 |
|
||
| CAT-08 | Local audio copies use streaming rather than recording-sized buffers | 9 |
|
||
| CAT-09 | Publication opens and closes sources sequentially | 10–11 |
|
||
| CAT-11 | Production S3 adapter tests verify uploaded bytes | 1 |
|
||
|
||
This sprint does not implement [session restore](session-restore.md),
|
||
[multi-format audio discovery](audio-inputs.md), prerequisite-history hydration,
|
||
S3 planning/preflight evidence changes, or the remaining P3 refactorings. Preserve
|
||
the existing restore protocol, local resume, publication locks, and pointer-last
|
||
publication. In particular, CAT-02 remains unresolved by this sprint.
|
||
|
||
## Instructions for the Implementing Agent
|
||
|
||
- Follow stages in integer order. Each is sized for one focused Luna prompt;
|
||
continue from the preceding stage's actual worktree.
|
||
- This is one end-to-end sprint. Intermediate stages may leave compilation or
|
||
tests temporarily broken when an interface migration spans stages. Do not add
|
||
temporary compatibility machinery or duplicate implementations solely to make
|
||
every intermediate stage independently releasable. Reach a coherent, verified
|
||
end state in Stage 12.
|
||
- Read `docs/development.md` and applicable policies before implementation:
|
||
agents, architecture, testing, and documentation. Use the repository's graph
|
||
discovery tools first for code. Follow focused evidence readings below rather
|
||
than reading every audit report on every prompt. Audit line ranges refer to
|
||
the unchanged original reports; named headings identify the same sections.
|
||
- Keep external transport in adapters, stage policy in stages/application, and
|
||
canonical paths in the existing path owner. Use standard library streaming and
|
||
existing fileops primitives. Add only narrow shared mechanics needed here.
|
||
- Choose behavioral tests with real temporary files/OS locks and controlled
|
||
external boundaries. Use channel/barrier coordination rather than sleeps to
|
||
manufacture races. Test watchdogs may detect hangs; they do not define public
|
||
timing guarantees. No live S3, paid services, or unkillable-process tests.
|
||
- Preserve existing path confinement, ordinary workspace modes, cancellation
|
||
causes, checksums, and verification before canonical installation. Preserve
|
||
explicit force behavior. The selected relaxations concern workspace concurrency
|
||
and upfront publication-source opening, not unrelated contracts.
|
||
- No new audio-size cap, disk reservation, artifact-count limit, distributed lock,
|
||
automatic source-stability retry, crash-durability promise, or absolute shutdown
|
||
return deadline is requested. Define any necessary internal timing constants in
|
||
their package's discoverable constants location; do not add user knobs here.
|
||
- Update affected canonical documentation as behavior lands. Record verified
|
||
closure in the catalog; keep original source reports unchanged. Commit completed
|
||
focused units under agent policy. Do not push or release during this sprint.
|
||
|
||
## Stage 1: Protect upload payloads and correct recovery instructions
|
||
|
||
Read:
|
||
|
||
- `audit/08-testing.md`, lines 70–101 (TE-01).
|
||
- `audit/13-documentation.md`, lines 74–106 (DOC-01).
|
||
- Current CLI run-range syntax and troubleshooting's unsupported-manifest and
|
||
publish-failure recovery sections.
|
||
|
||
Work:
|
||
|
||
1. In `internal/adapters/storage/s3_backend_test.go`, make the SDK-level
|
||
`fakeS3API.PutObject` consume the submitted body while the request is active
|
||
and retain its bytes for assertions. Propagate read errors through the fake.
|
||
2. Assert exact payload bytes for production file upload and conditional reader
|
||
upload, retaining existing key, content metadata, and write-condition checks.
|
||
Include a reader failure case at this boundary. Keep higher-level storage
|
||
fakes separate; they cannot prove the production SDK body mapping.
|
||
3. In `docs/troubleshooting.md`, bound the inspection-first regeneration example
|
||
through `analyze`, then inspect, then publish explicitly. Move forced publish
|
||
from diagnostics to a clearly identified mutating retry/repair step. Preserve
|
||
the existing supported command syntax and cleanup behavior.
|
||
|
||
Acceptance: replacing the production upload body with unrelated bytes would fail
|
||
the payload assertions. Recovery commands cannot publish or automatically clean
|
||
before the stated inspection. Run storage and documentation checks. No production
|
||
upload change is needed merely to improve these tests.
|
||
|
||
## Stage 2: Introduce one stable workspace lock
|
||
|
||
Read:
|
||
|
||
- `audit/04-concurrency.md`, lines 61–118 (CN-01).
|
||
- Discussion topic 1, including approved cancellation-aware waiting.
|
||
- `internal/artifacts` path and local lock implementations and existing lock tests.
|
||
|
||
Work:
|
||
|
||
1. Define the canonical coordination path as `<workspace.root>/.lock`, outside
|
||
`work/`, which manual `session clean --all` removes. Put its construction with
|
||
canonical workspace paths. The lock file remains present across release and
|
||
cleanup; release unlocks/closes its handle rather than deleting its pathname.
|
||
2. Reuse the existing OS advisory lock implementation and lock-handle lifecycle.
|
||
Provide a workspace-scoped acquisition operation that does not create a
|
||
campaign/session directory or call `EnsureLayoutFor` to find its lock.
|
||
3. Use context-aware contention waiting with the existing polling approach.
|
||
Identify the waited-on lock through existing diagnostics and preserve the
|
||
cancellation cause. No timeout, FIFO fairness promise, or new busy mode.
|
||
4. Replace the per-session coordination mechanism, including obsolete session
|
||
lock-path fields/usages as needed for this migration. Do not retain a second
|
||
per-session locking hierarchy. Keep changes confined to live lock machinery;
|
||
unrelated retired path fields are outside scope.
|
||
|
||
Acceptance: two sessions in the same workspace contend on the same real lock;
|
||
different workspaces do not. A cancelled waiter returns without ownership.
|
||
Release/process exit permits later acquisition, and deleting a session or the
|
||
`work/` tree cannot replace the coordination identity. Stage 3 completes wiring.
|
||
|
||
## Stage 3: Coordinate runners, restore, preflight, and manual cleanup
|
||
|
||
Read:
|
||
|
||
- `audit/08-testing.md`, lines 170–201 (TE-04).
|
||
- `internal/app/runner.go`, `runner_runtime.go`, `restore_command.go`,
|
||
`clean_command.go`, and standalone preflight's invocation path.
|
||
|
||
Work:
|
||
|
||
1. Acquire the workspace lock before creating/normalizing session layout or
|
||
mutating managed session state. Move runner layout preparation behind
|
||
acquisition; keep authoritative manifest/readiness rechecks under the lock.
|
||
Configuration acquisition and non-mutating path/identity calculation can
|
||
precede acquisition.
|
||
2. Use the same lock for run/resume and their aliases, standalone preflight,
|
||
restore's mutating transition, single-session manual clean, and `clean --all`.
|
||
Hold it through finalization/resource completion. Final pipeline cleanup
|
||
executes under its invocation's existing ownership without reacquiring it.
|
||
3. For `--all`, acquire before deletion and hold through its completion. New
|
||
sessions must acquire before creating managed state, so none can enter while
|
||
cleanup is deleting `work/`. Revalidate deletion targets after waiting.
|
||
4. Preserve pure inspection/dry-run behavior without adding serialization to
|
||
read-only status/plan operations. Retain existing restore dry-run controls.
|
||
Authored `session init` documents outside managed work do not need workspace
|
||
serialization; Stage 4 enforces their write-boundary safety. If initialization
|
||
writes inside managed work, coordinate that mutation with this same gate.
|
||
5. Add real-lock controlled-interleaving tests for active invocation versus each
|
||
manual clean mode, new-session admission during `--all`, and cancellation of
|
||
a waiting command without deletion. Exercise actual command wiring, not just
|
||
the lock helper. Reuse existing restore/preflight coverage with the new scope.
|
||
6. Update architecture, workspace/operations, and focused lock/cleanup/restore
|
||
docs to describe workspace serialization and cancellation-aware waiting.
|
||
|
||
Acceptance: no participating writer mutates a managed session tree before lock
|
||
ownership, and cleanup cannot dismantle active exclusion. Do not impose locks on
|
||
unrelated workspaces or add protection against external privileged deletion.
|
||
|
||
## Stage 4: Enforce initialization conflicts at the write boundary
|
||
|
||
Read `audit/04-concurrency.md`, lines 119–161 (CN-02), and
|
||
`internal/app/operator_helpers.go`, `session_init_command.go`, plus storage's
|
||
`WriteCondition`/`UploadConditional` contract.
|
||
|
||
Work:
|
||
|
||
1. For local non-forced initialization, use exclusive creation
|
||
(`O_WRONLY|O_CREATE|O_EXCL`) and normal write/close error handling and workspace
|
||
mode handling. Existing-file errors retain the command's conflict guidance.
|
||
Preserve the deliberate forced-replacement path.
|
||
2. For remote non-forced initialization, call existing `UploadConditional` with
|
||
`RequireAbsent: true`. A failed precondition is an already-exists/conflict
|
||
result, never authorization to retry unconditionally. Forced initialization
|
||
retains its overwrite behavior. Preliminary existence checks may remain for
|
||
diagnostics but do not decide write permission.
|
||
3. Test competing local creators and remote creators (or a remote insertion
|
||
between check and write). One succeeds, the other conflicts, and winner bytes
|
||
remain intact. Include existing destinations and explicit forced replacement.
|
||
Use the provider-condition fake rather than live storage.
|
||
|
||
Acceptance: neither a local workspace lock nor an earlier existence check is the
|
||
only protection. No distributed coordination, rollback protocol, or stronger
|
||
power-loss/partial-write guarantee is introduced.
|
||
|
||
## Stage 5: Join subprocess completion before releasing resource ownership
|
||
|
||
Read:
|
||
|
||
- `audit/04-concurrency.md`, lines 162–222 (CN-03).
|
||
- `audit/08-testing.md`, lines 202–232 (TE-05).
|
||
- Discussion topic 5 and subprocess execution, diagnostics, and result writers.
|
||
|
||
Work:
|
||
|
||
1. Keep bounded graceful then forceful escalation. After escalation, receive the
|
||
command waiter result before reading `ProcessState`, flushing redactors,
|
||
closing diagnostic writers, or returning caller-owned output destinations.
|
||
Timer expiry initiates/escalates shutdown; it does not establish completion.
|
||
2. Keep one supervisor and the existing standard process waiting/pipe machinery.
|
||
Preserve timeout/cancellation, wait, and cleanup causes with existing error
|
||
conventions. Do not add an early-return background ownership handoff.
|
||
3. Use a controlled waiter/output boundary that withholds completion past
|
||
escalation. Assert writers are not flushed/closed and callers do not regain
|
||
ownership until completion is released. Retain real-process normal timeout,
|
||
capture overflow, cancellation, and descendant disposal tests.
|
||
4. Update timeout/shutdown descriptions where they imply an absolute return
|
||
deadline. Exceptional blocked I/O may extend shutdown and workspace lock
|
||
ownership beyond escalation windows.
|
||
|
||
Acceptance: delayed completion cannot race resource closure or process-state
|
||
inspection; original causes remain identifiable. No real unkillable process or
|
||
new termination-time guarantee is required.
|
||
|
||
## Stage 6: Share metadata-preserving bounded object streaming
|
||
|
||
Read `audit/05-resources.md`, lines 117–183 (RS-02), discussion topic 4, and
|
||
storage's `Read`, `DownloadTo`, and bounded control-object read mechanisms.
|
||
|
||
Work:
|
||
|
||
1. Add a narrow streaming helper in the storage adapter layer using the existing
|
||
`ObjectStore.Read` result: metadata and body from the same response. Return
|
||
observed metadata to the caller and retain caller-owned destination handles.
|
||
No second metadata lookup or whole-body buffering.
|
||
2. Represent expected-size knowledge explicitly (for example, an optional size).
|
||
The caller selects either a fixed expected size for committed products or the
|
||
observed response size for newly downloaded raw audio. Missing response size
|
||
retains unknown-size streaming; a known zero must not mean unknown. Translate
|
||
existing unknown-size conventions at their boundaries without inventing a cap.
|
||
3. With known N, copy at most N bytes and probe at most one additional byte.
|
||
Reject short/oversized bodies, including a body exceeding its own reported
|
||
size. Avoid overflow in N+1 arithmetic, for example by copying N then probing.
|
||
Fixed expected-size metadata mismatch may reject before copying. Actual byte
|
||
counts remain checked even when metadata agrees.
|
||
4. Close the response on success, failure, and cancellation. Preserve meaningful
|
||
read/write/context/close errors. Errors include the object/transfer and known
|
||
expected byte count. Callers retain staging cleanup, checksums, confinement,
|
||
generation comparison, and canonical installation decisions.
|
||
5. Test exact, short, oversized, known-zero, and unknown-sized responses with
|
||
counting readers and inconsistent metadata. Verify early stop and closure,
|
||
plus read/write failure and cancellation. Use this primitive in Stages 7–8;
|
||
keep existing transport APIs only where their live callers still need them.
|
||
|
||
Acceptance: known-size paths never consume a complete oversized body simply to
|
||
reject it later. This bounds that transfer, not total disk consumption.
|
||
|
||
## Stage 7: Record the S3 audio generation actually downloaded
|
||
|
||
Read `audit/04-concurrency.md`, lines 223–274 (CN-04),
|
||
`internal/audio/s3_audio.go`, and preparation's S3 materialization/reuse paths.
|
||
|
||
Work:
|
||
|
||
1. Use Stage 6's response metadata with the audio body. For newly downloaded raw
|
||
audio, accept the observed generation B when acquisition checks succeed,
|
||
even when the earlier listing described A. Bound the transfer by B's known
|
||
size rather than rejecting a valid B using A's size.
|
||
2. Return the observed identity through `S3MaterializeResult` (or its narrow
|
||
equivalent) and persist its key, size, ETag and applicable existing identity
|
||
fields with the checksum of those accepted bytes. Do not rebuild downloaded
|
||
identity from the listing in stage code.
|
||
3. Preserve prepared-copy reuse: compare current listing identity with the prior
|
||
recorded identity and verify local content normally. Reused results must
|
||
retain their corresponding identity, not lose it in the new result shape.
|
||
4. Add preparation-to-manifest tests replacing listed A with same-sized B and
|
||
different-sized B before Read. Verify B is accepted and recorded; a later
|
||
rollback to A is not falsely reused as B. Cover unchanged reuse, malformed
|
||
transfer, cancellation, staging cleanup, and destination preservation using
|
||
representative existing tests where already adequate.
|
||
|
||
Acceptance: bytes/checksum and stored audio source evidence refer to one
|
||
response. No bucket versioning, cross-file snapshot, retry-until-stable loop,
|
||
extension-policy change, or new schema migration is required.
|
||
|
||
## Stage 8: Bound the remaining known-size download consumers
|
||
|
||
Read the RS-02 caller list in `audit/05-resources.md`, lines 117–183, and inspect
|
||
`restore_execute.go`, `prepare_previous.go`, and `publish_transfer.go`.
|
||
|
||
Work:
|
||
|
||
1. Apply Stage 6 to restore staging, previous-session artifact hydration, and
|
||
immutable-object verification. Include any live wrapper used by those paths;
|
||
do not stop after repairing the ordinary restore command alone.
|
||
2. For these consumers, the selected publication/local-source declaration's size
|
||
remains authoritative, including zero. Do not adopt different content merely
|
||
because Read returned different metadata. Retain existing checksum and
|
||
generation checks and validation-before-install ordering.
|
||
3. Keep body ownership in storage, temporary path ownership with its creator,
|
||
and installation policy with the consumer. A small shared sibling-temp helper
|
||
is permissible if directly useful, but broad CAT-21 consolidation is not a
|
||
sprint requirement. Do not install a streaming result before validation.
|
||
4. Prove each consumer actually uses the bound with a representative oversized
|
||
counting response. Check response closure, failed-staging removal, unchanged
|
||
existing destination, and original failure reporting. Retain short-body,
|
||
checksum, cancellation, and restore-retry tests rather than duplicating them
|
||
at every layer.
|
||
|
||
Acceptance: all four RS-02 paths, including Stage 7 audio, enforce applicable
|
||
known-size bounds. Restore's old execution-manifest semantics remain unchanged.
|
||
|
||
## Stage 9: Stream changed local audio copies
|
||
|
||
Read `audit/02-efficiency.md`, lines 20–48 (EF-01), and preparation's
|
||
`copyFileIfChanged`, artifact-store copy operations, and streaming fileops helpers.
|
||
|
||
Work:
|
||
|
||
1. Retain unchanged-destination checks, then replace recording-sized `os.ReadFile`
|
||
copying with existing `Store.CopyInputFor` or its underlying streaming
|
||
fileops operation. Keep preparation's destination names and recorded checksum.
|
||
2. Preserve workspace modes and atomic visibility. Do not introduce a parallel
|
||
custom writer or a new format/size restriction. Preserve any small-input
|
||
callers of the existing helper rather than accidentally changing their data.
|
||
3. Use temporary-file behavioral tests for changed/unchanged copies, content and
|
||
checksum, and failed replacement preserving the destination. Inspect the
|
||
actual production path to confirm streaming. A benchmark, RSS threshold, or
|
||
enormous audio fixture is unnecessary to establish bounded auxiliary memory.
|
||
|
||
Acceptance: auxiliary copy memory is independent of recording length; reuse and
|
||
installed content are unchanged. No claim of asymptotically faster I/O.
|
||
|
||
## Stage 10: Separate publication mapping from open source handles
|
||
|
||
Read `audit/05-resources.md`, lines 58–116 (RS-01), discussion topic 6, and
|
||
publication's run/previous/output source planning and transfer construction.
|
||
|
||
Work:
|
||
|
||
1. Build the complete deterministic identity/destination/lock plan using source
|
||
descriptors rather than retained `*os.File` handles. Descriptors identify the
|
||
confined root, relative path, expected content evidence, and destination needed
|
||
for later opening. Reuse existing types where possible.
|
||
2. Preserve complete upfront destination/rule/collision checks. Opening or hashing
|
||
every file before the first upload is no longer required. Any inventory hashing
|
||
still needed must open and close sources sequentially as well.
|
||
3. Cover every source class: current run archive, previous-cache files, canonical
|
||
outputs, and the generated committed-session-manifest snapshot. The snapshot
|
||
remains part of the current protocol until the later restore sprint.
|
||
4. Carried locked products use their remote declaration without opening the
|
||
corresponding local replacement. Keep all existing remote lock checks and
|
||
pointer selection policy; this is not a lock-protocol redesign.
|
||
|
||
Acceptance: planning retains no inventory-sized collection of open handles.
|
||
Stage 11 completes transfer wiring and regression coverage; do not add a temporary
|
||
second transfer implementation merely for an intermediate green build.
|
||
|
||
## Stage 11: Transfer and close publication sources sequentially
|
||
|
||
Continue RS-01 and inspect confined source opening, transfer preparation,
|
||
immutable-object verification, and publication finalization.
|
||
|
||
Work:
|
||
|
||
1. For each planned source, open through the existing root-confined regular-file
|
||
operation, validate/hash, rewind, upload or verify existing immutable content,
|
||
and close before advancing. Hash and upload from the same verified handle;
|
||
do not substitute a pathname-based upload after checking a descriptor.
|
||
2. Apply bounded handle lifetime to all Stage 10 source classes. Release handles
|
||
on success, failure, reuse, and cancellation; collect close errors through
|
||
existing error conventions. Do not defer all closures until the stage ends.
|
||
3. Write the immutable commit after accepted transfers, retain final lock
|
||
revalidation, and write the current pointer exactly once, last. A late invalid
|
||
source can leave unselected uploads; the prior current pointer remains
|
||
unchanged. A first failed publication selects no new current publication.
|
||
4. Use a controlled source-open seam or equivalent measurement with growing
|
||
inventories to prove active source handles stay bounded rather than scaling
|
||
with inventory. Include run, previous-cache, and output sources and a late
|
||
invalid source. Retain confinement/checksum/same-handle and pointer-order tests.
|
||
Do not rely on a host-specific descriptor limit or exhaust the real process.
|
||
5. Update publish internals and relevant architecture/operations claims to state
|
||
upfront destination planning followed by sequential source verification. Remove
|
||
the old all-invalid-sources-detected-before-upload claim. No source snapshots,
|
||
new artifact limit, concurrent uploader, or orphan-object cleanup service.
|
||
|
||
Acceptance: verified source lifetimes are bounded and pointer-last behavior is
|
||
preserved. CAT-14's pre-existing temporary-manifest cleanup gaps remain separately
|
||
tracked unless a directly changed lifecycle is demonstrably eliminated; do not
|
||
claim they are fixed merely by closing descriptors sooner.
|
||
|
||
## Stage 12: Verify the sprint end state and reconcile the audit catalog
|
||
|
||
Read this plan's scope table and affected canonical documentation. Use each
|
||
original finding's focused evidence section when checking closure.
|
||
|
||
1. Check every scoped outcome against implementation and regression tests.
|
||
Confirm workspace locking begins before managed layout mutation, initialization
|
||
guards writes, delayed subprocess completion retains ownership, all known-size
|
||
consumers are bounded, audio identity follows the response, local copies
|
||
stream, and every publication source class has bounded handle lifetime.
|
||
2. Run the maintained toolchain 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 implementation, use focused packages (`internal/app`,
|
||
`internal/artifacts`, `internal/adapters/storage`,
|
||
`internal/adapters/subprocess`, `internal/audio`, `internal/stage`, and
|
||
`internal/doccheck`) as appropriate. Record failures accurately; do not wait
|
||
for external CI or live service validation to establish these offline fixes.
|
||
3. Check command/help examples, lock scope and lifetime, timeout meaning, transfer
|
||
failures, and relaxed source-opening descriptions in their canonical owners.
|
||
Preserve unrelated contracts and link upstream library behavior rather than
|
||
duplicating it. Do not document the deferred roadmap features as implemented.
|
||
4. In `audit/catalog.md`, close only CAT-01, CAT-03, CAT-04, CAT-05, CAT-06,
|
||
CAT-07, CAT-08, CAT-09, and CAT-11 when their outcomes are verified. Record
|
||
concise implementation/test references and update the catalog's overall
|
||
status summary. All other entries remain open unless separately authorized
|
||
work supplies explicit closure evidence. Keep source reports immutable.
|
||
5. Mark these implementation stages complete with concise evidence, review the
|
||
final diff for scope creep, and commit all completed sprint work using focused
|
||
plain-English messages. Leave a coherent clean worktree. No release or push.
|
||
|
||
Completion requires all nine scoped outcomes and the repository-wide checks,
|
||
not completion of the other audit remediations. There are no remaining product
|
||
decisions required for this scope.
|