diff --git a/docs/roadmap/cleanup.md b/docs/roadmap/cleanup.md index 1046b6e..a3b4f25 100644 --- a/docs/roadmap/cleanup.md +++ b/docs/roadmap/cleanup.md @@ -68,30 +68,29 @@ partial cleanup can remove some diagnostics before failing. A retry must finish the remaining work without requiring republishing. Missing run directories and already-removed managed links are successful, idempotent conditions. -## Implementation Work +## Required Changes -1. **Establish durable reuse.** Audit stage reuse, artifact resolution, extraction - validation, publication, and recovery for dependencies on run-local paths. - Retain required semantic evidence in canonical products or manifest state. - Historical provenance may describe a removed attempt, but must not be treated - as a live file dependency. Missing diagnostics must not invalidate products. -2. **Simplify cleanup.** Replace published-run pruning and retained-bundle - exceptions with session-wide run deletion and managed-view removal. Remove - retention-only markers, traversal logic, and checks that are no longer needed. - Account for all run material, including attempts created after an earlier - successful cleanup, when deciding whether cleanup has work to do. -3. **Complete lifecycle handling.** Verify writer shutdown, cleanup retry, - cleanup-only invocation, and final reporting using the existing orchestration - paths. Use ordinary stage status and errors; avoid a second cleanup scheduler - or retention framework. -4. **Update documentation with implementation.** Update the - [operations guide](../operations.md), [configuration reference](../config.md), - affected internal documentation, and the - [architecture policy](../policy/architecture.md). In particular, replace the - policy's published-run target restriction with the selected session's run - history scope. Explain diagnostic loss and how to retain diagnostics by - disabling automatic cleanup. Record the changed retention behavior in release - documentation. +Stage reuse, artifact resolution, extraction validation, publication, and recovery +use canonical products and manifest-held semantic evidence. Historical provenance +can describe removed attempts. Missing diagnostics do not invalidate products. + +Session-wide deletion and managed-view removal replace published-run pruning and +retained-bundle exceptions. Retention-only markers and protected-tree traversal +are removed. Cleanup's reuse decision accounts for all remaining run material +and managed views, including attempts created after an earlier cleanup. + +The existing stage and invocation lifecycle coordinates writer completion, +manifest persistence, retry, and final reporting. Run-local directories are +created on demand for actual work. Cleanup-only and fully reused invocations can +leave an already-clean session without recreating `runs/`. + +The operations guide, configuration reference, affected internal and integration +documentation, and architecture policy describe the resulting retention behavior. +Architecture policy reflects session-wide cleanup scope and diagnostic lifetime. +Release documentation explains diagnostic loss and retaining diagnostics by +disabling automatic cleanup. + +The [implementation plan](implementation.md) owns sequencing and validation steps. ## Verification @@ -113,10 +112,3 @@ path-safety and publication tests unnecessarily: - New attempts after a successful cleanup are removed by the next authorized cleanup. Cleanup and final reporting leave `runs/` absent and managed views consistent. - -## Open Decisions - -None for the intended retention policy. During implementation planning, identify -any required product or reuse evidence currently available only in a run-local -bundle and specify its durable destination before enabling complete deletion. -This is a dependency audit, not a reason to retain run history by default. diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md new file mode 100644 index 0000000..1ce94b6 --- /dev/null +++ b/docs/roadmap/implementation.md @@ -0,0 +1,383 @@ +# Durable Session Cleanup Implementation Plan + +Status: Planned; implementation has not started. + +## Scope And Execution + +Implement [Durable Session Cleanup](cleanup.md). That roadmap owns the retention +policy and operator intent; this document owns implementation order and checks. +The separate [standalone preflight proposal](preflight.md) remains pending and is +outside this sprint. + +The audience is a Luna coding agent. Execute Stage 1 through Stage 7 in order. +Each stage is sized as one focused implementation prompt. This is one end-to-end +sprint: intermediate commits may temporarily fail to compile or contain tests +awaiting a later stage. Avoid temporary compatibility paths just to make each +intermediate stage independently deployable. The final sprint must satisfy all +completion criteria below. + +Start with [development guidance](../development.md) and read the applicable +[agent](../policy/agents.md), [architecture](../policy/architecture.md), +[testing](../policy/testing.md), and [documentation](../policy/documentation.md) +policies. Apply the cleanup-policy changes specified here when implementing the +new behavior. Preserve unrelated work and commit completed, nonempty units with +short, plain-English messages. This plan does not authorize pushing or releasing. + +Use real temporary directories and existing manifest, artifact, and runner +collaborators. Fake subprocesses and object storage at their external boundaries. +Keep checks offline and independent of credentials. Reuse existing behavioral +tests where they protect the same risk; revise tests that encode the deliberately +replaced retention policy. + +## Baseline And Implementation Decisions + +Planning baseline: `39ad49e` (following cleanup proposal `3b64491`). Recheck the +current worktree before implementing; the following are the relevant owners: + +| Concern | Current implementation | Planned treatment | +| --- | --- | --- | +| Cleanup authorization | `internal/stage/cleanup_plan.go`, especially `validateCleanupPublishEvidence` | Preserve successful-upload, run/commit/pointer, and configured campaign/session checks. Publication authorizes deleting the selected session's run history. | +| Cleanup target and reuse | `internal/stage/cleanup.go`, `cleanup_plan.go`, `cleanup_retained_bundle.go` | Target the complete canonical session `runs/` directory. Replace protected-subtree pruning with ordinary confined deletion and managed-view removal. | +| Diagnostic views | `internal/fileops/attempt_views.go` | Reuse strict managed-link recognition; inspect and remove owned stage/restore links without following their targets. | +| Layout creation | `internal/artifacts/local.go`, `internal/app/runner_runtime.go` | Remove eager `runs/` creation from ordinary layout initialization. Actual attempts and probes create their directories on demand. | +| Extraction reuse | `internal/stage/extract_resume.go`, `internal/artifacts/extraction_evidence.go` | Existing proof uses canonical lane bytes, transcript/reference identity, and manifest metadata. Keep that authority; original bundle existence is unnecessary. | +| Extraction retention | `internal/stage/extract.go`, `internal/artifacts/paths.go` | Remove the retention marker and retention-only metadata/helper. Keep bundle/report paths as historical provenance where useful. | +| Invocation completion | `internal/app/runner.go`, `runner_stage_execution.go`, `runner_finalization.go` | Keep ordinary stage transitions, session-manifest persistence, error propagation, and native invocation reporting. Completion must work after run-local deletion. | +| Publication and restore | `internal/stage/publish_sources.go`, `publish_commit.go`, `internal/app/restore_manifest_paths.go` | Preserve the remote protocol and restore scope. Use canonical products/prepared inputs; old run-local references are historical diagnostics. | + +The retained evidence already has durable owners: + +- Prepared input, audio, glossary, previous-session, and reference-snapshot + identities live in session inputs and manifest records. +- Speaker completions bind prepared audio to canonical raw transcripts through + the existing transcribe collection. +- Combined transcripts, rendered transcripts, and bounds are canonical products + with their existing producer records and semantic evidence. +- Extraction identity is recorded in the manifest; selected lane products live + in flat `artifacts/`. Optional chunk maps and evidence context remain disposable + bundle contents. +- Analysis completions bind canonical configured products to existing artifact + fingerprints and checkpoint records. + +These observations are starting points for Stage 1's focused dependency check, +not a request to add new validators to otherwise unchanged stages. Preserve the +existing manifest schema and output/checkpoint authority. Historical producer +IDs, `local_workdir`, log/configuration references, archive paths, and native +completion paths may name removed attempts; their presence does not require +those files to exist. Cleanup need not rewrite all historical references. + +Keep the existing default `workspace.cleanup_after_publish=false`, stage order, +range selection, force behavior, and manual `session clean` scope. Cleanup is a +local operation and does not contact remote storage to reauthorize deletion. +Subprocess state/cache settings and remote objects remain unchanged. Preserve +ordinary workspace permission handling. No new retention controls, archive, +schema migration, generic cleanup framework, transactional deletion, or stronger +filesystem/concurrency guarantees are part of this work. + +## Stage 1: Make Run-Bundle Disposal Explicit + +Status: Pending. + +Read `internal/stage/extract.go`, `extract_resume.go`, `extract_references.go`, +`extract_native_test.go`, `internal/artifacts/extraction_evidence.go`, +`extraction_catalog.go`, `analyze_evidence.go`, and `paths.go`. Follow concrete +references into `internal/app/semantic_resume.go`, stage semantic providers, +artifact resolution, and publication/restore only where needed to check reuse. + +1. Confirm the durable evidence inventory above against actual readers. Identify + any operational read of a run-local file after stage completion. Distinguish + substantive product reads from optional diagnostic/provenance references. + If a required identity is only in a native report, record the necessary + bounded identity in existing stage metadata; if a required product is only + staged, promote that product through the existing canonical path machinery. + Preserve existing evidence validation rather than treating file presence as + completion. Do not copy reports or whole bundles into durable inputs. +2. Stop writing `notarius-retention.json`. Remove `bundle_retention_role`, + `retention_path`, and `SessionRunNotariusRetentionPath` plus dead imports and + comments. Keep native bundle/diagnostic paths and completion metadata that + remain useful provenance. Arbitrary old metadata need not be migrated or + specially decoded. +3. Keep available producer files and diagnostics after extraction failure, as + today. A later authorized cleanup removes them; extraction failure itself + must not eagerly discard them. Disabling cleanup continues to retain original + bundles after successful extraction as well. +4. Replace the retention-marker tests with a focused test that records successful + extraction, removes its producing run, and proves resume validation and + catalog hydration still accept the canonical lanes. Assert that missing or + altered canonical products remain unavailable under existing rules. Keep + failure-evidence and partial-promotion regression coverage. + +Validation: focused extraction and artifact-evidence tests in `internal/stage` +and `internal/artifacts`. Delete obsolete marker-safety assertions with their +removed mechanism; existing path-safety tests retain ownership of confinement. + +Completion: selected extraction products and required identity remain reusable +without the native bundle, and extraction creates no retention marker. + +## Stage 2: Support Removal Of Managed Diagnostic Views + +Status: Pending. + +Read `internal/fileops/attempt_views.go`, `attempt_views_test.go`, `cleanup.go`, +`cleanup_test.go`, and `internal/stage/cleanup_retained_bundle.go`. + +1. Add narrow inspection/removal support alongside the existing attempt-view + helpers. Share `existingManagedView` recognition and existing root-confined + operations. Inspection must be non-mutating so cleanup reuse and planning can + call it. Return enough information to detect remaining managed views even + when their target directories have already disappeared. +2. Accept the explicit managed-name set from the stage owner: canonical stage + names from `stage.All()` plus `restore`. Consider both `logs` and `debug` and + every valid run identity, rather than filtering to the published run ID. + Missing category directories and missing links are successful absence. +3. Unlink only recognized managed leaves through an opened root/parent; do not + follow link targets. Retain existing rejection of unsafe category directories, + unexpected targets, and non-link conflicts at managed names. Leave unrelated + operator files, directories, and links untouched. Unlinking symlinks does not + belong in `RemoveFileUnderRoot`, whose regular-file contract remains intact. +4. Add focused real-filesystem tests for links spanning different runs, already + dangling recognized links, missing views/categories, repeat removal, unrelated + content preservation, and existing managed-name conflicts. Reuse existing + unsafe-link tests instead of duplicating their full matrix. + +Validation: `go test ./internal/fileops`. This stage may temporarily leave the +old pruning helper available until Stage 3 switches its callers. + +Completion: managed diagnostic views can be inspected and removed safely without +requiring the producing run to exist or touching operator-owned entries. + +## Stage 3: Replace Published-Run Pruning With Session-Wide Cleanup + +Status: Pending. + +Read `internal/stage/cleanup.go`, `cleanup_plan.go`, their tests, the Stage 2 +helpers, `internal/artifacts/paths.go`, and `internal/app/semantic_resume.go`. + +1. Preserve `buildCleanupPlan`'s disabled-policy behavior and all current publish + authorization and campaign/session checks. Derive the deletion destination + with `SessionRunsDirForCampaign` or the canonical `SessionPaths.RunsDir`, not + `SessionRunRootForCampaign`. Keep `published_run_id` as authorization/provenance, + distinct from the broader local deletion destination. +2. Remove recognized managed diagnostic views and delete the complete selected + session `runs/` tree using `fileops.RemoveAllUnderRoot` with an explicit + confining root. Preserve existing unsafe-root/target checks, error propagation, + and cancellation checks before destructive work. Check an existing runs root + as a real directory; do not traverse a substituted symlink. Reserved probe + directories, earlier failures, restore attempts, arbitrary run-local scratch, + and empty `runs/` are all inside the authorized deletion scope. +3. Make `ValidateResume` inspect the same target and owned views without mutation. + Cleanup is reusable only when `runs/` is absent and its managed views are + absent, with valid authorization. An empty runs directory is still pending + deletion. Newly created runs or leftover managed links make prior cleanup + non-resumable. Missing runs with dangling recognized views must still be + repairable. Propagate unsafe inspection errors rather than treating them as + clean. Keep `session plan` non-mutating through the existing shared decision + path. +4. Advance the cleanup semantic-contract version to reflect its changed scope; + keep the existing enabled/root inputs. Do not alter other stages' fingerprints + or introduce a session-manifest version change. +5. Delete `cleanup_retained_bundle.go` and obsolete protected-tree traversal and + retention-only tests. Remove `ManagedAttemptTargets` if no callers remain. + Keep the cleanup stage workspace-free, with ordinary result metadata and the + existing skipped/failed/succeeded transitions. +6. Rewrite cleanup behavior tests to cover multiple runs and owned views removed; + retained inputs/audio/transcripts/artifacts and another session unchanged; + subprocess state/cache sentinels untouched; disabled policy and invalid + publication evidence leaving targets intact; missing/empty targets; and new + runs or leftover links invalidating an earlier cleanup success. Preserve the + existing authorization/confinement tests with updated target expectations. + +Validation: focused cleanup tests in `internal/stage`, then +`go test ./internal/fileops ./internal/artifacts ./internal/stage` when the +combined stages compile. Inspection must not create directories or remove links. + +Completion: authorized cleanup removes the entire selected run history and +owned views, and its reuse decision observes all remaining cleanup work. + +## Stage 4: Complete The Invocation And Retry Lifecycle + +Status: Pending. + +Read `internal/artifacts/local.go`, `local_test.go`, `paths_model_test.go`, +`internal/app/runner.go`, `runner_runtime.go`, `runner_stage_execution.go`, +`runner_finalization.go`, `runner_preflight.go`, `cleanup_orchestration_test.go`, +and `attempt_views_test.go`. Inspect `internal/adapters/subprocess/run.go` and +stage adapter return boundaries only as needed to confirm writer completion. + +1. Remove `paths.RunsDir` from eagerly ensured session directories. Preserve the + path model and durable-directory creation. Actual stages, native readiness + probes, and restore already have explicit run-local creation paths; adjust + only callers that genuinely relied on the eager parent. Keep directory modes + and confinement at those creation boundaries. Update layout tests accordingly. +2. Verify that stage/subprocess writers are closed before cleanup starts and + nothing writes run-local files after deletion. Existing subprocess execution + waits and closes captured streams before returning. Keep that normal ownership + rather than adding a cross-stage writer registry. Session-manifest saves and + the final CommandKit summary must remain outside deleted run paths. +3. Exercise the real cleanup stage through the ordinary runner. On success, + require `runs/` absence after terminal persistence and final reporting, no + dangling managed views, and a readable succeeded cleanup record. Cover a + cleanup-only invocation, a reused invocation after cleanup, and another + authorized cleanup after later attempts create fresh run material. Use distinct + deterministic run IDs for successive invocations. +4. Replace the current invalid-retention-marker failure fixture. Exercise a real + cleanup error and retry through ordinary stage transitions. Include partial + progress, such as successfully removed views before a later deletion failure. + If deterministic I/O failure needs injection, use a small function seam at + the deletion boundary, not a new filesystem abstraction or configuration knob. + Verify the error reaches the caller, cleanup remains incomplete, publication + stays succeeded, and retry completes without another publish or remote access. + Already-deleted views and directories need no rollback. +5. Retain coverage for failed processing/publish/notify stopping before cleanup, + disabled cleanup, publish-only execution, and ranges ending before cleanup. + Do not add a finalizer that silently performs cleanup outside the selected + stage range. Preserve cancellation and terminal-save error handling. + +Validation: focused app cleanup/layout/view tests, then `go test ./internal/app`. +Assert observable state and outcomes, not exact logging text or an incidental +deletion order. Existing lock and subprocess tests own their respective mechanics. + +Completion: cleanup and retry work through the normal lifecycle, and successful +completion or reuse leaves no newly recreated `runs/` tree. + +## Stage 5: Prove Durable Reuse And Downstream Development After Cleanup + +Status: Pending. + +Read the existing reuse fixtures, stage semantic-resume tests, +`internal/app/restore_workflow_test.go`, and the Stage 1 extraction tests. Build +on Stages 1 and 4 rather than creating a second integration-test framework. + +1. Add a representative runner-level workflow using real canonical products, + persisted stage evidence, and fake external adapters. Execute processing and + authorized cleanup, reload the manifest, and run again with unchanged inputs. + Assert valid processing results are reused without reopening removed reports, + generated configs, staged outputs, or original Notarius bundles. Exercise the + transcribe/analyze completion collections where the existing fixture supports + them; Stage 1's focused evidence test supplies complementary extraction proof. +2. From the cleaned state, run forced analyze-only work with the existing + `run SESSION --stage analyze --force` selection. Verify transcript and extract + results remain reusable and analysis consumes canonical inputs. This bounded + command is expected to create new run diagnostics and leave them until an + authorized cleanup is selected later. + +Validation: relevant workflow tests in `internal/app` and extraction/evidence +tests from Stage 1. Use adapter invocation counts to prove required reuse; +content and manifest state prove product correctness. Consolidate overlapping +new cases when one workflow protects several outcomes. + +Completion: ordinary reuse and forced downstream development work from durable +evidence after historical run files are gone. + +## Stage 6: Verify Publication And Restore With Disposable Run History + +Status: Pending. + +Read `internal/stage/publish_sources.go`, `publish_commit.go`, +`internal/app/restore_manifest_paths.go`, `restore_workflow_test.go`, +`restore_execution_test.go`, and existing publish/restore test fixtures. Reuse +the cleaned-session fixture from Stage 5 where useful. + +1. Publish from retained products in a later invocation using fake object storage, + then clean again. Verify publication uses canonical source/checksum authority, + keeps existing locks and pointer-last semantics, and does not demand historical + diagnostics. Keep remote run archives limited to files belonging to the current + invocation under the existing protocol. Address only actual deleted-file + dependencies found by these workflows. +2. Extend existing restore coverage only where needed to show that deleted producer + runs are unnecessary for installing and consuming committed durable products. + Restore may create a fresh diagnostic attempt. Preserve the existing restore + inventory, local-conflict rules, manifest rebasing, incomplete-restore marker, + and prepared-reference regeneration behavior. Do not promise a byte-for-byte + restore of every retained local file or add remote publication of snapshots. + +Validation: focused publish/restore and cleanup-retry regressions in +`internal/stage` and `internal/app`. Use the real manifest and file operations +with fake object storage. Existing lock and commit tests continue to own their +protocol details; do not repeat their complete matrix in cleanup workflows. + +Completion: publication and restore consume their supported durable evidence +without depending on historical run files or changing remote inventory semantics. + +## Stage 7: Align Documentation And Verify The Completed Sprint + +Status: Pending. + +Read the affected canonical documents and the documentation policy. Update: + +- `docs/operations.md`: cleanup scope, diagnostic loss, original bundle lifetime, + local layout, and retry. Explain retaining diagnostics with + `workspace.cleanup_after_publish=false`, and that bounded development commands + do not implicitly clean their new attempts. +- `docs/config.md`: retain the current field/default and publish prerequisites; + describe the selected session's entire run-history scope. +- `docs/policy/architecture.md`: replace published-run-only target language; + qualify diagnostic durability by configured cleanup. Preserve the failure + evidence available before a later authorized cleanup and subprocess ownership. +- `docs/internal/stage-cleanup.md`, `workspace.md`, `fileops.md`, + `stage-extract.md`, `artifacts.md`, and relevant manifest/publish internals: + describe implemented owners, lazy layout, canonical reuse, view removal, and + ordinary stage retry. Remove retention-marker/protected-bundle descriptions. + Replace the obsolete publish-owned cleanup-obligation paragraph in + `docs/internal/manifest.md` with the ordinary selected cleanup-stage lifecycle. +- `docs/integrations/notarius.md`: distinguish promotion of selected products + from optional original bundle contents subject to Narratio cleanup, without + copying upstream contracts. Update troubleshooting only where its guidance + conflicts with the new behavior. + +Use concise affirmative wording and canonical-owner links. Accepted ADR decisions +remain unchanged: their content classification and ownership boundaries already +permit this retention policy. Published release notes remain historical records. +Keep the operator-visible diagnostic-loss summary ready for the next versioned +release note under `docs/release.md`; this sprint does not choose a release +version, rewrite an old note, tag, or publish. Mark this plan and the cleanup +roadmap complete after verification; preserve the pending preflight roadmap. + +Run the repository's existing final checks with the maintained toolchain: + +```sh +export GOTOOLCHAIN=go1.27.4 +go test ./... +go test -race ./... +go vet ./... +go build ./... +git diff --check +``` + +The default suite includes documentation-link and maintained-example checks. +Use focused `go test ./internal/doccheck` during documentation editing. Verify +the existing Linux amd64/arm64 and best-effort macOS arm64 build targets: + +```sh +cleanup_build_dir=$(mktemp -d) +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o "$cleanup_build_dir/narratio-linux-amd64" ./cmd/narratio +CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o "$cleanup_build_dir/narratio-linux-arm64" ./cmd/narratio +CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o "$cleanup_build_dir/narratio-darwin-arm64" ./cmd/narratio +``` + +These checks do not require native macOS execution, live providers, or CI +availability. No new permanent CI gates are required by this change. + +Before the final commit, inspect the complete diff and verify: + +- Authorized cleanup removes all session runs, including older failures, + original bundles, restore diagnostics, and readiness-probe directories. +- Retained session products and semantic/checkpoint evidence support the tested + reuse and downstream workflows; unrelated session content, operator diagnostic + entries, subprocess state/caches, and remote objects remain untouched. +- Managed views are removed even if their target run was already absent. +- Disabled/excluded cleanup and failures before cleanup preserve run material. +- Cleanup failure is visible and retryable without republishing; no transactional + deletion, new manifest ledger, or stronger filesystem contract was introduced. +- Final reporting and fully reused/cleanup-only invocations respect lazy run + creation, and no retention-only code or contradictory current documentation + remains. + +Commit the completed, verified work using the agent policy. Report checks and +any genuine validation limitations. Push and release require separate authority. + +## Open Questions + +None. The roadmap resolves the retention policy. The dependency inventory and +workflow checks above determine the necessary implementation without introducing +additional operator choices or retaining run history as a fallback.