diff --git a/docs/cli.md b/docs/cli.md index e9080cd..df3fad3 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -217,12 +217,13 @@ narratio session restore SESSION --dry-run narratio session restore SESSION --force --include-audio ``` -Uses pointer-selected committed state and returns actions/conflicts. Dry runs -make no local directory or mode changes. Actual restore preserves confined -replacement, transition locking, incomplete-restore recovery markers, and -manifest-last installation. `--force` permits replacement only of eligible -regular files. The public report is separate from the persisted restore -execution report. See [restore operations](operations.md#restore-workflow). +Imports products from the pointer-selected publication and returns actions, +conflicts, and projected work. Dry runs make no local directory or +mode changes. Actual restore merges verified products with local progress under +the workspace lock and saves the local manifest last. `--force` permits +replacement only of eligible regular files; it does not force pipeline work. +Interrupted imports retain a recovery marker. Remote execution-checkpoint +recovery is deferred. See [restore operations](operations.md#restore-workflow). ## Session clean @@ -349,7 +350,7 @@ manifests, resolved credentials, or internal dependency containers. | Status/artifacts | Identities/source, `local_manifest`, `stages`, `artifacts`, optional `remote`, configuration provenance, audio/previous-artifact readiness, `findings` | | Init | `campaign`, `session_id`, `destination`, `remote`, `written` | | Locks | Identities, `operation`, `result`, `complete`, optional `source`, `locks` | -| Restore | Identities/run, `dry_run`, `complete`, `status`, `downloaded`, `conflicts`, `actions` | +| Restore | Identities/run, `dry_run`, `complete`, `status`, `downloaded`, `conflicts`, `actions`, projected satisfied/remaining work | | Clean | Optional identities, `all`, `dry_run`, `complete`, `cache`, `actions`, optional `error` | Preflight preparation outcomes are `completed`, `reused`, `failed`, or @@ -372,7 +373,8 @@ artifact entries identify key, optional family/character, role, reason, and force. Publication actions identify source, destination, required, and selected. Remote status outputs retain source, destination, required, state, lock state, declared destination/key, origin run, and error. Restore -actions carry kind, relative local path, remote key, status, optional reason/error. +actions carry kind, optional product source, relative local path, remote key, +status, and optional reason/error. Clean actions carry path, status (`would_delete`, `deleted`, `missing`, `empty`, `failed`), and optional error; cache records whether it was preserved, requested, processed, or not applicable. Lock rows include source, reason, creation time, diff --git a/docs/internal/artifacts.md b/docs/internal/artifacts.md index 8540773..ef394dc 100644 --- a/docs/internal/artifacts.md +++ b/docs/internal/artifacts.md @@ -189,13 +189,9 @@ restore, status and validation checks, and previous-cache planning. `LoadCurrentInventory` reads and verifies the pointer-selected commit without fetching an execution snapshot. Status, publication inspection, and session configuration acquisition and previous-session acquisition use that inventory. -The existing restore path still uses the snapshot reader until its cutover. - -The selected session manifest is accepted only with -`schema_version: narratio.session-manifest.v2` and complete stage identity. -An unsupported local or downloaded manifest must be replaced by regeneration, -verified restore, or republication; artifact resolution never fills in missing -authority markers. +Restore uses the same inventory. Obsolete execution-snapshot declarations are +ignored without reading their contents; unsupported local progress must be moved +aside before creating a new local baseline. For a new-protocol current state, the pointer-selected immutable commit is the complete restore authority. Callers receive its declared object identities and @@ -207,10 +203,9 @@ Only this declaration type may refer to an earlier run; other declared objects remain confined to the selected commit's run. The reader opens each small control object directly and enforces owner-specific -limits before decoding: 64 KiB for the mutable commit pointer, 4 MiB for the -immutable commit manifest, and 8 MiB for the selected session manifest. These -are exposed as `MaxCurrentCommitPointerBytes`, -`MaxRemoteCommitManifestBytes`, and `MaxRemoteSessionManifestBytes`. +limits before decoding: 64 KiB for the mutable commit pointer and 4 MiB for the +immutable commit manifest. These are exposed as `MaxCurrentCommitPointerBytes` +and `MaxRemoteCommitManifestBytes`. Each read uses the generation and size metadata returned with its opened body. Actual bytes remain subject to a limit-plus-one read even if size metadata is diff --git a/docs/internal/command-restore.md b/docs/internal/command-restore.md index 46bbd6d..b1403d4 100644 --- a/docs/internal/command-restore.md +++ b/docs/internal/command-restore.md @@ -2,129 +2,69 @@ ## Purpose -Explain the implemented restore discovery, planning, installation, and -reporting flow in `internal/app`. User invocation belongs in -[CLI](../cli.md#session-restore), and the operator recovery procedure and -physical restore scope belong in -[Operations](../operations.md#restore-workflow). +Restore imports products declared by the selected publication inventory into a +local session. The [CLI](../cli.md#session-restore) describes invocation and +[Operations](../operations.md#restore-workflow) describes operator recovery. +The session progress manifest stays local; publication is not a checkpoint backup. -Restore separates remote authority, local conflict policy, and filesystem -mutation so each remains testable independently. +## Discovery and planning -The public command supplies production defaults to one private, -invocation-scoped dependency value. Discovery, planning, and execution use that -same value, so focused sequencing tests can replace one boundary without -mutable package hooks. +`internal/artifacts` validates the current pointer and its immutable commit, +including campaign, session, run, checksum, size, generation, and namespace. +Discovery binds the plan to that inventory. Obsolete execution-snapshot +declarations are ignored without reading their bodies. Authored session YAML +remains a separate configuration input. -## Discovery Contract +The planner maps each recognized published source through the built-in product +registry or current concrete configured definitions. Local products use flat +canonical paths regardless of remote destination names. Exact immutable keys, +checksums, sizes, and generations remain attached to actions, including products +carried from earlier publications by locks. Supported prepared documents and, +with `--include-audio`, audio retain their input paths. Prepared glossary inputs +include the four individual envelopes and the combined glossary. Previous-session +requirements use the shared prerequisite-inclusive collector and exact +published-output declarations; execution diagnostics and remote progress +snapshots are not imported. -Discovery delegates current-state pointer and manifest loading to -`internal/artifacts`, then validates the result against the resolved request: +Each target is classified as `download`, `skip_same`, or `conflict` beneath the +session root. Symlinked or non-regular ancestors and leaves remain conflicts; +`--force` authorizes replacement of differing regular files only. Duplicate +local destinations fail planning. Dry runs perform no durable session writes and +report imports plus projected work using the normal read-only assessment for +preserved local progress. Product coverage is conditional on successful +verification of planned downloads; unavailable local assessment is conservative. -- campaign must match; -- session ID must match. -- run ID must match the pointer-selected committed run. +## Installation and local baseline -Restore treats any missing or invalid remote current state as a command error. +A non-dry run acquires the same workspace lock used by runners before loading +local state and classifying files. It writes an incomplete-restore marker before +installation. Transfers use confined sibling temporary files and verify the +inventory's content and object identity before replacement. Installed products +are checked against their canonical paths, content rules, sizes, and checksums. -## Planning Contract +Restore merges accepted products into a clone of local state and saves the local +manifest last. Identical content with valid local generation evidence keeps that +authority. Other accepted products receive typed supplied records. Changed +products invalidate dependent local work using the existing stage relations; +unrelated checkpoints and locally recorded diagnostics remain. Co-published +products need no shared generation history. The resulting coverage satisfies +work without inventing intermediate files or successful publish, notify, or +cleanup execution. -Restore planner action kinds: +Failure leaves the marker and any already-installed files. A retry reclassifies +those files, verifies them, and saves the merged baseline; the marker is removed +after that save succeeds. This is not a whole-workspace rollback guarantee. -- `download`; -- `skip_same`; -- `conflict`. +## Reporting and ownership -Planner behavior: +Reports identify publication identity, actions, counts, and failures. Actual +attempts persist under the restore run's logs. `restore --force` governs file +replacement and is independent of pipeline force. -- prepared campaign, session, party, and all four glossary inputs are restored - from declared immutable run objects to their canonical local input paths; -- a new-protocol restore uses only the selected commit's declared artifact set; - each action carries that artifact's immutable key, checksum, size, and - generation; -- remote-to-local mapping is traversal-safe; -- actions are sorted by local relative path and then remote key; -- planning opens the selected session root and inspects every target by its - normalized session-relative path. Missing ancestors produce a missing target; - an ancestor or leaf symlink is a non-regular conflict and is never opened for - hashing; -- force converts differing eligible regular files from conflicts to downloads; - directories, symlinks, and other non-regular targets remain conflicts. - -For a non-dry-run restore, planning/classification happens only after acquiring -the workspace lock. Runner manifest/reuse checks acquire that same lock first. - -Restore uses the default enabled targets and their full prerequisite closure to -collect previous requirements as described in [Artifact Internals](artifacts.md#previous-requirement-collection). -Previous-cache readiness is resolved through `previouscache.Resolve` for restore, -prepare, status, and validation. Each requirement selects the unique -`published_output` for its canonical source in the pointer-selected commit, -then strips only that run's immutable `published/` prefix for its safe local -cache path. It never probes candidate objects or derives paths from manifests, -configuration, or basenames. - -## Execution Contract - -Execution order and safety: - -- non-manifest downloads happen before manifest install; -- `manifest.json` installs last; -- downloads use sibling temp files, validate the complete object, then use an - atomic rename; -- manifest replacement is validated before rename; -- each committed object is verified against its declared checksum, size, and - generation before installation; -- installation reopens the selected session root, creates only validated - missing directory components with workspace modes, and rejects symlinked or - non-regular ancestors and leaves before replacement; -- a committed manifest already verified during discovery is retained for the - matching restore action and revalidated before installation, avoiding a - second body transfer; -- failed installs do not roll back files already written in the same execution. -- a durable `.restore-incomplete.json` marker is written before installation. - It blocks runners until a restore retry completes all verified installs and - the local manifest replacement, at which point it is removed. -- restored manifest local references are rebased beneath the selected local - session root. Unsafe relative references and producer-machine absolute paths - outside the manifest's producer session root are rejected; producer-local - run-local diagnostic references are not restored as - authority. Cleanup remains ordinary restored stage state and is not reset or - synthesized by restore. - -Audio restore path: - -- uses `audio.MaterializeS3Audio`; -- restores selected audio directly into the prepared session audio directory; -- reuses a prepared copy only when manifest identity and its content checksum - match; otherwise downloads to a verified temporary sibling before installation. - -## Reporting Contract - -- dry-run mode prints a summary, performs no durable session writes, and may - read remote current-state or object-identity data to produce that summary; -- execution mode persists the canonical restore report described in - [Operations](../operations.md#restore-workflow); -- report includes plan counts, per-action status, and execution failures. - -## Invariants - -- restore uses committed remote current state as authority; -- one restore or status inspection observes the single pointer-selected commit - loaded at discovery; later pointer changes cannot add objects or substitute a - different run into its plan; -- a verified `current/commit-pointer.json` and its selected immutable commit - establish remote commitment; when absent, republish the session; -- restore does not execute pipeline stages. - -## Implementation And Tests - -- Discovery: `internal/app/restore_discovery.go` -- Planning: `internal/app/restore_plan.go`, `internal/previouscache` -- Execution: `internal/app/restore_execute.go` -- Reporting and command coordination: `internal/app/restore_report.go`, - `internal/app/restore.go` -- Tests: `internal/app/restore_discovery_test.go`, - `internal/app/restore_plan_test.go`, - `internal/app/restore_execution_test.go`, - `internal/app/restore_recovery_test.go`, - `internal/app/restore_workflow_test.go` +Discovery is in `internal/app/restore_discovery.go`, planning and coverage in +`internal/app/restore_plan.go`, transfers in `internal/app/restore_execute.go`, +local baseline installation in `internal/app/restore_manifest_paths.go`, and +command coordination/reporting in `internal/app/restore_command.go` and +`internal/app/restore_report.go`. The restore, import-workflow, artifact, and +recovery tests cover source mapping, identity, conflicts, preservation, retry, +and carried products. diff --git a/docs/internal/manifest.md b/docs/internal/manifest.md index 7fc1277..6a0875d 100644 --- a/docs/internal/manifest.md +++ b/docs/internal/manifest.md @@ -25,10 +25,10 @@ structure; artifact helpers check the recorded path and actual content. A separate coverage helper derives transcript work satisfied by valid supplied transcripts without creating records for absent intermediate products. Planning and execution use that coverage to reuse satisfied transcript work without -historical producer evidence. Restore installation is described in its roadmap -until the inventory cutover is implemented. +historical producer evidence. Restore merges verified records into local progress +as described in [restore internals](command-restore.md). -Session, campaign, and run identities in local and downloaded manifests must be +Session, campaign, and run identities in local manifests must be portable opaque segments. Unsafe legacy identities are rejected with migration guidance rather than being normalized into a different workspace or remote namespace. @@ -43,8 +43,8 @@ cleanup entry in `stages`. Every persisted session manifest has a non-nil `stages` map. Each entry is non-nil and its embedded `name` exactly matches its map key; loading never invents either marker. A missing or unsupported schema version, or incomplete -stage identity, is unsupported local state: move it aside before regenerating it -or restoring a supported committed snapshot when that is authoritative. +stage identity, is unsupported local state: move it aside before regenerating +or importing published products into a new local baseline. Prepare records independent `party` and `players` input checksums. In canonical party mode, the party record retains its campaign source identity while the @@ -175,7 +175,7 @@ be non-successful, but every completed artifact checkpoint remains reusable. ## Remote Commit Manifest -`artifacts.RemoteCommitManifest` is a separate, versioned remote snapshot +`artifacts.RemoteCommitManifest` is a separate, versioned publication inventory contract. It is not a serialized session manifest and contains no local post-publication assertion such as `current_pointer_written`. A remote commit identifies one campaign, session, and run and declares its immutable artifact @@ -189,7 +189,7 @@ unknown fields, version mismatches, pointer/commit identity mismatches, and objects that do not match their declaration. An absent commit pointer means no remote state is published. Republish to -establish a current immutable snapshot. +establish a current immutable publication. ## Persistence Semantics @@ -302,7 +302,7 @@ evidence and focused durable validators: | Work | Reuse authority | Focused owners | | --- | --- | --- | -| prepare | aggregate semantic fingerprint | [prepare](stage-prepare.md) | +| prepare | aggregate semantic fingerprint plus durable-copy and current-source validation | [prepare](stage-prepare.md) | | transcribe speakers | aggregate semantic fingerprint plus per-speaker input/output reconciliation | [transcribe](stage-transcribe.md), [WhisperX](../integrations/whisperx.md) | | merge | aggregate semantic fingerprint | [merge](stage-merge.md), [Seriatim](../integrations/seriatim.md) | | polish | aggregate semantic fingerprint | [polish](stage-polish.md), [Audita](../integrations/audita.md) | @@ -370,7 +370,8 @@ where the last session transition can require operator interpretation. ## Invariants - stage resume/skip decisions are session-manifest driven. -- semantic fingerprint comparison precedes stage-specific resume validation. +- ordinary local semantic fingerprint comparison precedes stage-specific resume + validation; valid supplied coverage is assessed independently. - only successful and intentional-skipped results promote current semantic evidence. - running, failed, and self-skipped stages do not retain result payloads from @@ -394,9 +395,9 @@ where the last session transition can require operator interpretation. ## Prepared Glossary Evidence -Preparation records four distinct glossary input kinds with canonical paths, -checksums, sizes, and provenance. Polish records the resolved glossary identity -evidence used for its result; preflight itself records no stage success. Publish -and restore carry the prepared inputs using their declared manifest identities. +Preparation records the party, campaign, setting, spells, and combined glossary +documents with canonical paths, checksums, sizes, and provenance. Audita's polish +request consumes the four individual envelopes. Publish includes recorded +prepared documents, and restore selects their declared immutable objects. See [prepare](stage-prepare.md), [polish](stage-polish.md), and [artifact internals](artifacts.md). diff --git a/docs/internal/stage-analyze.md b/docs/internal/stage-analyze.md index 586fad5..0f5b303 100644 --- a/docs/internal/stage-analyze.md +++ b/docs/internal/stage-analyze.md @@ -78,10 +78,11 @@ Supported source families: JSON payload and no map serialization. Configured artifacts are fingerprinted in deterministic dependency order. - fingerprints the normalized artifact key, prompt and profile identifiers, - effective render-debug behavior, session-relative output identity, sorted + session-relative output identity, sorted dependency keys, ordered input declarations and semantic identities, validated current dependency-output identities, and sorted effective Scriptorium variables (including Narratio's sticky session variable). + Render-debug is diagnostic and does not affect the fingerprint. - provides read-only reconciliation that classifies each configured record as supplied, current, stale, missing, failed, or otherwise non-resumable, and separately identifies manifest records removed from current configuration. @@ -193,8 +194,8 @@ Supported source families: visible only inside Scriptorium—such as a file privately loaded by its config path—requires an explicit forced regeneration. - output provenance and metadata are deterministic per execution. -- a canonical file without current per-artifact manifest evidence is never - promoted to current state. +- a canonical file without current per-artifact evidence or a validated + supplied-product record is never promoted to current state. - an ordinary retry after interruption or partial failure reuses every valid earlier checkpoint and schedules only failed, stale, missing, or otherwise non-current work in dependency order. diff --git a/docs/internal/stage-extract.md b/docs/internal/stage-extract.md index d9f7506..4c97a23 100644 --- a/docs/internal/stage-extract.md +++ b/docs/internal/stage-extract.md @@ -20,6 +20,11 @@ recording success. The original bundle and optional domain auxiliaries stay in the producing run until authorized cleanup removes run history. Positive native fallback counts are recorded and reported. +An imported lane is individually available from its validated supplied record +without historical Notarius metadata. Extraction is satisfied by supplied +products only when all configured lanes are available. Executing a missing +bundle regenerates the complete configured set and retires its supplied records. + ## Resume Validation Resume checks the direct transcript identity, configured pipeline and lane diff --git a/docs/internal/stage-prepare.md b/docs/internal/stage-prepare.md index 2d32084..c41ad6f 100644 --- a/docs/internal/stage-prepare.md +++ b/docs/internal/stage-prepare.md @@ -67,7 +67,8 @@ cache path, then validates the committed checksum, size, and generation. ## Invariants -- only `prepare` hydrates canonical `inputs/previous/` state. +- prepare and restore hydrate canonical `inputs/previous/` state from exact + declared previous-session products. - managed previous artifacts are stored under `inputs/previous/artifacts/**` without duplicate `artifacts/artifacts/` nesting. - managed `inputs/previous/` state represents only the current requirement set. @@ -77,13 +78,13 @@ cache path, then validates the committed checksum, size, and generation. Prepare records a versioned semantic-configuration fingerprint for the resolved campaign/session selection, local-versus-S3 audio mode and canonical -audio names, stable-input ownership/presence, previous-session identity, and -the party mode plus canonical players projection version, and the effective +audio names, stable-input presence, previous-session identity, the canonical +players projection version, and the effective previous-artifact requirement set. A change reruns prepare and stales its fixed descendants. Existing successful records without this evidence rerun once when selected. -Workspace placement are not semantic when logical selection, +Source ownership and workspace placement are not semantic when logical selection, canonical names, and effective bytes are equivalent. The fingerprint deliberately does not read or rehash large audio. Prepared input checksums remain the content provenance. Before reusing success, prepare diff --git a/docs/internal/stage-publish.md b/docs/internal/stage-publish.md index e766eeb..4ec4e22 100644 --- a/docs/internal/stage-publish.md +++ b/docs/internal/stage-publish.md @@ -6,7 +6,7 @@ Upload run/session outputs to object storage and atomically advance remote curre ## Inputs -- successful preceding stages from the [canonical stage set](overview.md#pipeline-stage-set) +- ordinary preceding stage evidence or valid supplied product availability - declared run-local diagnostic files - resolved publish output rules - independent per-source remote lock objects read at planning start @@ -44,7 +44,8 @@ supports remote loading when no authored session override is available. The the session manifest records success. Enablement and upload policy are fingerprinted, so changing either automatically makes the prior result non-resumable. -- validates prerequisite stage success and object-store availability. +- validates ordinary prerequisites or valid supplied availability and requires + an object store. Every selected source is independently resolved and checked. - derives a deterministic run-archive allowlist from the session manifest's declared current-run outputs, logs, and generated configurations. References outside the current run root, including canonical session files and prior-run @@ -57,12 +58,13 @@ supports remote loading when no authored session override is available. The the same confinement and regular-file checks. - resolves publish output sources through runtime artifact catalog and manifest-aware resolution. Configured Scriptorium outputs are publishable - only from validated `current` per-artifact analyze evidence; an incidental + from validated `current` per-artifact analyze evidence or a valid supplied + product; an incidental canonical file, aggregate output, stale/failed/unselected record, or mismatched path, size, or checksum remains unavailable. Built-in and - extraction sources likewise require their own current manifest evidence. -- includes the four manifest-backed prepared glossary documents with their - declared input identities for restore; + extraction sources likewise require their own current local or supplied evidence. +- includes the four individual prepared glossary documents and the combined + glossary with their declared input identities for restore; - publishes extraction lanes only through explicit configured output rules; original Notarius bundles are not scanned or uploaded wholesale. Historical run-local references are not required for later publication. diff --git a/docs/internal/stage-render.md b/docs/internal/stage-render.md index 58027cb..34ad5e8 100644 --- a/docs/internal/stage-render.md +++ b/docs/internal/stage-render.md @@ -22,12 +22,12 @@ records that may consume rendered transcripts. - uses `pipeline.render` settings (enabled/variants/format/title/booleans). - resolves and renders only selected variants; duplicate selections have no effect. -- resolves inputs only from verified manifest output evidence. +- resolves inputs from verified local output evidence or supplied records. - writes run-local outputs first, then materializes canonical session outputs. - records input provenance, output paths, adapter metadata, logs, and generated config refs. - when `pipeline.render.enabled=false`, completes successfully with no outputs - and records explanatory metadata. This is not an explicit self-skip: both - manifests record success. Because enablement is fingerprinted, enabling + and records explanatory metadata. This is not an explicit self-skip: the + local manifest records success. Because enablement is fingerprinted, enabling render later automatically makes the prior result non-resumable. ## Failure Semantics diff --git a/docs/operations.md b/docs/operations.md index 4e9ce38..9fde4b1 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -62,9 +62,9 @@ version 3 configuration and Notarius its version 6 configuration. Consult the [Audita](integrations/audita.md) and [Notarius](integrations/notarius.md) contracts for their upstream guides. -Move unsupported local state aside before regenerating it; restore only a -supported committed session manifest, or regenerate and republish. Do not edit -state markers manually. Products now use flat session paths and diagnostics use +Move unsupported local state aside before regenerating or importing published +products into a new local baseline. Do not edit state markers manually. +Products now use flat session paths and diagnostics use latest-attempt views; explicit remote destinations remain independent. Review cleanup and separately configured subprocess caches before removing old state. This guidance does not create a release or publish any changes. @@ -202,7 +202,10 @@ An explicit self-skip is a durable `skipped` stage outcome that later runs reconsider. It differs from successful no-output execution: disabled `render` and `publish`, and absent or no-executable `analyze`, record `succeeded` with metadata and no outputs. Ordinary later runs reuse those successful results; -force the affected stage after enabling or configuring it. Optional artifact +when the observable enablement or configuration changes, selected work is +reassessed and reruns as needed. Use force to replace a current result or for +private upstream changes Narratio cannot observe. Supplied products are assessed +independently of historical producer configuration. Optional artifact inputs are omitted only from the consuming artifact invocation and do not make the stage self-skip. @@ -231,9 +234,11 @@ prerequisite rebuilds, scheduled execution, and current reuse. This lets a coarsely stale aggregate analyze stage show zero artifact executions when its selected artifact evidence is still semantically current. -Before a bounded run or plan whose range starts after `prepare`, every excluded -prefix stage must already have a session-manifest status of `succeeded` or -`skipped`. Narratio reports the first absent, pending, running, failed, stale, +Before a bounded run or plan whose range starts after `prepare`, excluded +prefix work needs local success/skip evidence or applicable supplied-product +coverage. With a supplied transcript, prepare and independent render/extract +work do not automatically block downstream selections; required consumer inputs +must still exist. Narratio reports the first unsatisfied absent, pending, running, failed, stale, or interrupted prerequisite without creating a run-local directory or changing session state. Widen `--from` to include that stage, or recover it explicitly before retrying. Excluded prefix stages are not resume-validated or repaired as @@ -293,8 +298,8 @@ identifier is unchanged, but older strict-decoding Narratio binaries may reject a manifest after current Narratio writes the additive speaker fields; retain a backup or complete the upgrade before relying on downgrade. -Restoring a manifest does not implicitly publish or restore every raw speaker -file. If a recorded canonical transcript is absent locally, ordinary +Importing published products does not restore every raw speaker file. If a +recorded canonical speaker transcript is absent locally, ordinary reconciliation schedules that speaker again. Removing run directories does not remove canonical checkpointed transcripts and does not by itself invalidate them. @@ -597,7 +602,7 @@ source; they do not reconstruct a current-run key or scan the session prefix. Other artifact types remain confined to the selected commit's own run. When the pointer is absent, remote state is not published; republish the -session to establish a committed snapshot. Remote commit state does not carry +session to establish a committed publication. Remote commit state does not carry local `current_pointer_written` metadata. ## Publish Locks @@ -658,9 +663,10 @@ narratio session restore 2026-04-04 remote current state and may read object identity/content needed to classify the plan, so it is not a network-free operation. The inventory-based preview maps published source identities to current canonical local product paths; the remote -destination name does not choose the local filename. Its projected satisfied and -remaining work describes product coverage assuming planned downloads pass -content verification. It does not certify that an import or pipeline run occurred. +destination name does not choose the local filename. Projected satisfied and +remaining work combines conditional product coverage with the read-only +assessment of preserved local evidence. Planned downloads must still pass +content verification; the preview does not certify an import or pipeline run. Default restore scope: @@ -717,9 +723,9 @@ Remote audio is downloaded to a temporary sibling and verified before replacing its single prepared `audio/` copy. Restore follows the same layout. Subprocess cache and state locations are configured separately in those applications. -Only `narratio.session-manifest.v2` is supported. Move older local state aside -and regenerate it, or restore a supported committed snapshot; republish after -regeneration when remote state is incompatible. Do not edit old markers by hand. +Only `narratio.session-manifest.v2` is supported locally. Move older local state +aside and regenerate it or import published products into a new baseline. Do not +edit old markers by hand. ### Workspace Permissions @@ -785,7 +791,8 @@ cleanup. See [cleanup internals](internal/stage-cleanup.md). ## Operational Caveats - Local and S3 audio modes are mutually exclusive. -- Publish requires prerequisite stages through `render` and `analyze` to be succeeded. +- Ordinary publication checks prerequisite stage success; a supplied-product + baseline permits publication of individually validated selected sources. - Markdown publish defaults require render outputs (`transcripts/final.md` and `transcripts/final.trimmed.md`). - Restore requires configured object storage and committed remote current state. - Each reached pipeline acquisition applies its configured startup before typed diff --git a/docs/policy/architecture.md b/docs/policy/architecture.md index 27eb0cb..b55861e 100644 --- a/docs/policy/architecture.md +++ b/docs/policy/architecture.md @@ -166,14 +166,20 @@ leave an empty run directory. Restore treats the pointer-selected publication inventory as its authority. It must plan deterministically, confine remote-to-local paths, protect local conflicts, and save a merged local baseline after accepting restored products. +Valid supplied records represent actual local products and may satisfy the +fixed work they cover without asserting that their historical producers ran +locally. Imported products are independent of one another; publication does +not require common generation history. Local generation keeps its ordinary +checkpoint and freshness rules. Import alone must not record successful +publication, notification, or cleanup execution. The physical workflow and recovery procedures belong in [Operations](../operations.md). Restore and runner transitions for one session use the same local lock. A durable incomplete-restore marker blocks runner reuse after a partial restore; safe retry, rather than rollback of arbitrary local effects, is the recovery -mechanism. Restored manifest-local references must be confined to the selected -local session root, never trusted as producer-machine absolute paths. +mechanism. Imported product paths must be confined to the selected local +session root and derived from current source definitions, not producer paths. For the immutable remote-commit protocol, a restore or status operation binds to one pointer-selected commit and only its declared object identities. A force diff --git a/docs/roadmap/audit/catalog.md b/docs/roadmap/audit/catalog.md index 18cbd5b..a4c1e55 100644 --- a/docs/roadmap/audit/catalog.md +++ b/docs/roadmap/audit/catalog.md @@ -41,8 +41,9 @@ their scope. Unless assigned otherwise, a finding remains independent audit remediation. Shared code does not make a refactoring a prerequisite or assign the whole finding to a roadmap. -Twelve entries are closed by the safety, transfer, audio discovery, S3 -planning, and prerequisite-history work; 31 remain open. **Planned** identifies +Seventeen entries are closed by the safety, transfer, audio discovery, S3 +planning, prerequisite-history, publication-import, and associated documentation +work; 26 remain open. **Planned** identifies an agreed remedy awaiting implementation. **Potentially eliminated** requires verification that the offending lifecycle is removed. **Coordinate** identifies shared changes, not a commitment that the roadmap implements the entire finding. Findings close only after their @@ -84,8 +85,9 @@ Narratio remains a fixed-stage orchestrator. The application coordinates invocations, locks, plans, stages, and restore; adapters own external transports. ConfigKit supplies completed configuration, CommandKit/ckconfig supply native CLI/inspection, and Narratio derives separate domain catalogs. Manifest-backed -speaker/artifact checkpoints govern product reuse. Publication selects immutable -snapshots through a current pointer, restore installs manifest authority last, +speaker/artifact checkpoints and valid supplied records govern product reuse. +Publication selects immutable inventories through a current pointer, restore +saves a merged local baseline last, and cleanup has a separate authorization/lifecycle. See the [implemented overview](../../internal/overview.md) and [architecture policy](../../policy/architecture.md). @@ -124,12 +126,15 @@ Related: [CAT-39](#cat-39--p3-simplify-manual-clean-to-its-live-directory-only-c ### CAT-02 — P2: Make restored carried products agree with manifest authority -Status: Open +Status: Closed -**Disposition / owner.** Planned — the [restore roadmap](../session-restore.md#build-and-consume-restore-defined-completion) -owns this remedy. Its publication-import and synthesized-completion model -supersedes historical producer-evidence reconciliation; implementation and the -original round-trip regression outcomes remain outstanding. +**Closure.** Inventory-based import records validated local supplied products +without installing remote execution evidence. The publish–lock–generate–republish +round trip for a transcript and configured artifact, downstream source resolution, +and republishing are covered by +[`import_workflow_test.go`](../../../internal/app/import_workflow_test.go). +The [restore roadmap](../session-restore.md#build-and-consume-restore-defined-completion) +owns the implemented product-import model. Original findings: [FC-02](01-correctness.md#fc-02--p2-carried-publication-bytes-conflict-with-restored-manifest-evidence), [TE-02](08-testing.md#te-02--p2-publication-and-restore-tests-do-not-prove-carried-output-authority-is-coherent). @@ -445,12 +450,13 @@ Related: [CAT-12](#cat-12--p2-share-audio-discovery-and-accept-valid-same-basena ### CAT-14 — P3: Close temporary committed-manifest cleanup gaps -Status: Open +Status: Closed -**Disposition / owner.** Potentially eliminated — the [restore roadmap](../session-restore.md#decouple-remote-discovery-from-execution-snapshots) -removes unnecessary execution-snapshot publication. Close only after verifying -that the temporary-manifest creation and ownership gaps disappear; repair any -retained lifecycle rather than assuming snapshot removal fixes it. +**Closure.** Publication no longer creates or uploads a temporary session +execution-manifest snapshot; the inventory commit is encoded and written by +[`publish_commit.go`](../../../internal/stage/publish_commit.go). The removed +temporary-file lifecycle and its ownership gap no longer exist. Publication +tests verify that no execution ledger is emitted. Original findings: [RS-03](05-resources.md#rs-03--p3-publications-temporary-manifest-has-cleanup-gaps-before-ownership-transfer). @@ -752,12 +758,12 @@ separate manifest-last installation order. ### CAT-29 — P3: Correct force-after-enablement guidance -Status: Open +Status: Closed -**Disposition / owner.** Coordinate documentation — the [restore roadmap](../session-restore.md#align-policies-and-canonical-documentation) -adds render selection and supplied-baseline reuse. Correct the existing -render/publish/analyze enablement guidance explicitly while distinguishing -ordinary local semantic reuse from restore-defined completion. +**Closure.** [Operations](../../operations.md#stage-execution-and-continuation-behavior) explains +automatic reassessment of observable enablement/configuration changes, explicit +force for current-result replacement or private changes, and independent supplied +coverage. Original findings: [DOC-02](13-documentation.md#doc-02--p3-operator-guidance-incorrectly-requires-force-after-enablement). @@ -771,12 +777,12 @@ descriptions rather than repeating stale behavior. ### CAT-30 — P3: Correct internal resume and fingerprint descriptions -Status: Open +Status: Closed -**Disposition / owner.** Coordinate documentation — the [restore roadmap](../session-restore.md#align-policies-and-canonical-documentation) -rewrites resume descriptions. Check each original mismatch for locally generated -work as well as documenting the new baseline; do not change fingerprints to -match obsolete prose. +**Closure.** The focused [analyze](../../internal/stage-analyze.md), +[prepare](../../internal/stage-prepare.md), and [manifest](../../internal/manifest.md) +descriptions now distinguish diagnostic render-debug, provenance-only input +ownership, and prepare's durable-copy and current-source checks. Original findings: [DOC-03](13-documentation.md#doc-03--p3-internal-resume-summaries-describe-obsolete-fingerprint-inputs). @@ -836,12 +842,13 @@ filesystem enforcement in Narratio. ### CAT-34 — P3: Include the combined glossary in prepared-input documentation -Status: Open +Status: Closed -**Disposition / owner.** Coordinate documentation — the [restore roadmap](../session-restore.md#align-policies-and-canonical-documentation) -changes prepared-input/publication descriptions. Verify the retained combined -input inventory explicitly; execution-snapshot removal does not make the four -individual Audita inputs a five-input invocation. +**Closure.** [Manifest](../../internal/manifest.md#prepared-glossary-evidence), +[publication](../../internal/stage-publish.md), and +[restore](../../internal/command-restore.md) documentation include the combined +document alongside the four individual envelopes. The manifest description +retains Audita's four-envelope input distinction. Original findings: [DOC-07](13-documentation.md#doc-07--p3-internal-glossary-inventories-omit-the-combined-prepared-document). diff --git a/docs/roadmap/audit/discussion.md b/docs/roadmap/audit/discussion.md index 24d6819..4bf8cc7 100644 --- a/docs/roadmap/audit/discussion.md +++ b/docs/roadmap/audit/discussion.md @@ -1,6 +1,6 @@ # Audit Remediation Discussion -Status: Decisions agreed; safety and transfer work complete; feature work pending +Status: Decisions agreed; assigned safety, transfer, and feature work implemented ## Purpose @@ -67,7 +67,7 @@ closed, including the acquisition-diagnostic review follow-up._ ## 2. Import published artifacts and retain local resume -Status: Scope agreed; remote execution checkpoints deferred +Status: Publication import implemented; remote execution checkpoints deferred Finding: [CAT-02](catalog.md#cat-02--p2-make-restored-carried-products-agree-with-manifest-authority). diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 703a01d..d4b2c28 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -1,6 +1,6 @@ # Import Published Products: Implementation Plan -Status: Pending +Status: Complete ## Scope and working rules @@ -25,9 +25,9 @@ code may connect stages, but remove the old execution-snapshot workflow by completion. Intermediate commits are not a finished release. Update owned current-behavior documentation when each capability becomes implemented. -This is a planning document. This pass changes no application code or policy. -Implementation commits use plain-English messages under agent policy; pushing -and releasing require separate authorization. +This document records the staged implementation. Implementation commits use +plain-English messages under agent policy; pushing and releasing require separate +authorization. ## Implementation decisions @@ -430,7 +430,7 @@ Validation: run focused workflow tests uncached, then `go test ./...`. ## Stage 13: Align policy, documentation, and audit disposition -Status: Pending +Status: Complete 1. Finalize and check the Stage 1 architecture policy adaptations: completion can express executed work or satisfaction by supplied products; product diff --git a/docs/roadmap/session-restore.md b/docs/roadmap/session-restore.md index 8428450..4ad3773 100644 --- a/docs/roadmap/session-restore.md +++ b/docs/roadmap/session-restore.md @@ -1,6 +1,6 @@ # Session Restore from Published Artifacts -Status: Agreed scope; implementation pending +Status: Implemented and verified ## Goal @@ -20,7 +20,7 @@ agreement to synthesize stage completion using a small stage/output mapping. That agreement supersedes earlier suggestions that restore must reconstruct historical producer evidence or avoid marking covered upstream stages complete. -## Current Baseline +## Historical Baseline Reviewed against `d8bc99b17efdddd0a728ef519b2e5a1d25f85fa9`. @@ -125,8 +125,8 @@ Illustrative coverage: This mapping is about satisfaction, not reconstruction. A final trimmed transcript can cover earlier stages even though their intermediate files are -absent. The manifest records actual imported files and marks covered stages -complete without inventing output records for files that do not exist. +absent. The manifest records actual imported files; validated supplied records +express covered work without inventing output records for files that do not exist. Keep independent products independent. A transcript does not prove that extraction, analysis, or rendering completed. Render and extract remain sibling @@ -380,8 +380,8 @@ Use focused offline behavioral tests and representative assembled workflows: baseline-save, and partial-restore retry coverage. Choose tests for observable risks, not exact helper structure or incidental wording. -The implementation plan should select checks proportionately under the -[testing policy](../policy/testing.md). This planning pass implements no behavior. +The implementation and its focused and assembled tests follow the +[testing policy](../policy/testing.md). ## Scope Boundaries diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index c6f08e2..3c670c3 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -69,10 +69,9 @@ Safe fix: - align config with [Configuration](./config.md) and the [maintained examples](../examples/README.md). -- for a manifest schema error, move the unsupported local state aside and - regenerate it; restore a verified current committed snapshot or republish - healthy regenerated state when appropriate. Do not add version or stage - markers by hand. +- for a manifest schema error, move unsupported local state aside and regenerate + it or import verified published products into a new local baseline. Do not add + version or stage markers by hand. - if an older manifest is rejected for its retired cleanup-obligation field, finish outstanding cleanup with the pre-upgrade binary. Otherwise verify the remote commit, move aside or regenerate the incompatible manifest, and use @@ -667,8 +666,7 @@ Safe fix: Symptom: - Narratio rejects a local session manifest because `schema_version` is missing - or unsupported; or -- restore rejects a committed remote session manifest for the same reason. + or unsupported. Likely causes: @@ -680,10 +678,8 @@ Likely causes: Safe fix: -- for unsupported local state, move the old manifest aside and regenerate, or - restore a verified current committed snapshot when one is authoritative; -- for unsupported committed remote state, regenerate healthy local state as - needed and republish the session; and +- for unsupported local state, move the old manifest aside and regenerate or + import products from a verified current publication; and - for a downgrade rejection, return to the current binary or restore a verified pre-upgrade backup. Do not delete only the speaker fields by hand. @@ -854,7 +850,7 @@ Relevant reference: [Operations: Restore Workflow](./operations.md#restore-workf Symptom: -- restore cannot find current pointer or current manifest. +- restore cannot find the current pointer or its selected publication inventory. Likely causes: diff --git a/examples/README.md b/examples/README.md index 6f1c417..a784e29 100644 --- a/examples/README.md +++ b/examples/README.md @@ -67,6 +67,11 @@ with the sample campaign and a compatible local- or S3-audio session. relative resources follow the file that supplies each value. - [Local-audio session](session.local-audio.yml) and [S3-audio session](session.s3-audio.yml) are concrete session files. +- [Published-products session](session.published-products.yml) omits audio for + downstream work after import. Configure the needed references, and use + `render.variants: [trimmed]` when only the final trimmed transcript is + available. Transcription and forced transcription still require audio; see + the [restore workflow](../docs/operations.md#restore-workflow). - [Session template](session.template.yml) and the campaign-local equivalent demonstrate the narrow placeholder syntax consumed by `session init`; they are templates, not runtime session files. diff --git a/examples/session.published-products.yml b/examples/session.published-products.yml new file mode 100644 index 0000000..187be66 --- /dev/null +++ b/examples/session.published-products.yml @@ -0,0 +1,5 @@ +# Start downstream work after importing this session's published products. +# Add an audio source if transcription or forced transcription is selected. +session_id: 2026-05-03 +date: 2026-05-03 +title: Sample Session diff --git a/internal/app/config_loader.go b/internal/app/config_loader.go index c118ca2..ce5b5dd 100644 --- a/internal/app/config_loader.go +++ b/internal/app/config_loader.go @@ -108,7 +108,7 @@ func findRemoteSessionConfig(ctx context.Context, store storage.ObjectStore, ses } var selected *artifacts.RemoteArtifact if !authored { - current, err := artifacts.LoadCurrentInventory(ctx, store, sessionPrefix, artifacts.CurrentStateValidation{ExpectedCampaign: campaign, ExpectedSessionID: sessionID, ValidateRunID: true}) + current, err := artifacts.LoadCurrentInventory(ctx, store, sessionPrefix, artifacts.CurrentStateValidation{ExpectedCampaign: campaign, ExpectedSessionID: sessionID}) if err == nil { for _, item := range current.Commit.Artifacts { if item.Type == artifacts.RemoteArtifactTypeRunFile && item.Source == "run:prepare/inputs/session.yml" { diff --git a/internal/app/import_workflow_test.go b/internal/app/import_workflow_test.go index f5266ac..fef5d0b 100644 --- a/internal/app/import_workflow_test.go +++ b/internal/app/import_workflow_test.go @@ -156,16 +156,24 @@ func TestLockedProductsRemainUsableAfterImportAndRepublish(t *testing.T) { if _, err := artifacts.ResolveSessionArtifactWithCatalog(importedPaths, imported, artifacts.ConfiguredArtifactSourceID("session_recap"), catalog); err != nil { t.Fatalf("carried configured product unavailable: %v", err) } + downstream := &scriptorium.FakeRunner{} + result, err := executePlan(ctx, cfg, mustBoundedPlan(t, "analyze", "analyze"), RunOptions{Force: true, SelectedArtifacts: []string{"player_handout"}, Env: &Env{Scriptorium: downstream}}) + if err != nil { + t.Fatalf("consume carried product in downstream work: %v", err) + } + if len(downstream.RunRequests) != 1 || downstream.RunRequests[0].InputPaths["recap"] != filepath.Join(importedPaths.ArtifactsDir, "session_recap.md") { + t.Fatalf("downstream work did not reuse the carried recap: %#v", downstream.RunRequests) + } + imported, err = (&manifest.LocalStore{}).Load(ctx, result.ManifestPath) + if err != nil { + t.Fatal(err) + } for _, rule := range rules { if err := artifacts.RemoveRemoteLock(ctx, fake, prefix, rule.Source); err != nil { t.Fatal(err) } } - imported.RunID = "20260521T010203Z-a1b2c3d4" - imported.LocalWorkDir = artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, imported.Campaign, imported.SessionID, imported.RunID) - if err := os.MkdirAll(imported.LocalWorkDir, 0755); err != nil { - t.Fatal(err) - } + publishedRun := imported.RunID env.ArtifactStore = artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) if _, err := publish.Run(ctx, env, imported); err != nil { t.Fatalf("republish imported products: %v", err) @@ -174,6 +182,7 @@ func TestLockedProductsRemainUsableAfterImportAndRepublish(t *testing.T) { t.Fatal(err) } imported.RunID = "20260522T010203Z-a1b2c3d4" + imported.S3RunPrefix = artifacts.S3RunPrefix(prefix, imported.RunID) imported.LocalWorkDir = artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, imported.Campaign, imported.SessionID, imported.RunID) if err := os.MkdirAll(imported.LocalWorkDir, 0755); err != nil { t.Fatal(err) @@ -182,7 +191,7 @@ func TestLockedProductsRemainUsableAfterImportAndRepublish(t *testing.T) { t.Fatal("republish accepted a tampered required product") } current, err := artifacts.LoadCurrentInventory(ctx, fake, prefix, artifacts.CurrentStateValidation{}) - if err != nil || current.RunID != "20260521T010203Z-a1b2c3d4" { + if err != nil || current.RunID != publishedRun { t.Fatalf("failed republish changed current publication: %#v, %v", current, err) } } @@ -222,6 +231,18 @@ func TestImportedPartialExtractionRegeneratesCompleteBundle(t *testing.T) { if artifacts.SuppliedExtractionComplete(paths, before, artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius)) { t.Fatal("partial extraction was treated as complete") } + definitions := artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius) + catalog := artifacts.NewArtifactCatalog() + if err := catalog.RegisterExtractionArtifacts(definitions); err != nil { + t.Fatal(err) + } + catalog.HydrateExtractionArtifacts(paths, before, definitions) + if _, err := artifacts.ResolveSessionArtifactWithCatalog(paths, before, artifacts.ExtractionArtifactSourceID("npc_registry"), catalog); err != nil { + t.Fatalf("imported extraction product unavailable: %v", err) + } + if _, err := artifacts.ResolveSessionArtifactWithCatalog(paths, before, artifacts.ExtractionArtifactSourceID("encounters"), catalog); err == nil { + t.Fatal("missing extraction product became available") + } runner := &materializingNotariusRunner{cfg: cfg.Pipeline.Notarius} result, err := executePlan(ctx, cfg, mustBoundedPlan(t, "extract", "extract"), RunOptions{Env: &Env{Notarius: runner}}) if err != nil { diff --git a/internal/app/operator_helpers_test.go b/internal/app/operator_helpers_test.go index 1693f60..dad78c0 100644 --- a/internal/app/operator_helpers_test.go +++ b/internal/app/operator_helpers_test.go @@ -1169,7 +1169,7 @@ func TestExecutePublishIgnoresRetiredSharedLockObject(t *testing.T) { if storeInitCalls != 1 { t.Fatalf("object store initialization calls = %d, want 1", storeInitCalls) } - current, err := artifacts.LoadCurrentInventory(context.Background(), fake, sessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true}) + current, err := artifacts.LoadCurrentInventory(context.Background(), fake, sessionPrefix, artifacts.CurrentStateValidation{}) if err != nil { t.Fatalf("LoadCurrentState() error = %v", err) } diff --git a/internal/app/reference_preparation_test.go b/internal/app/reference_preparation_test.go index c51f386..d076fd8 100644 --- a/internal/app/reference_preparation_test.go +++ b/internal/app/reference_preparation_test.go @@ -5,6 +5,7 @@ import ( "context" "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -99,7 +100,14 @@ func TestFullRunWithSuppliedTranscriptPreparesAndRendersSelectedVariant(t *testi if _, err := restoreSessionState(context.Background(), cfg, RestorePlanOptions{}, normalizeCommandDependencies(restoreCommandDependencies(fake))); err != nil { t.Fatal(err) } - plan := mustBoundedPlan(t, "", "analyze") + baseline, err := (&manifest.LocalStore{}).Load(context.Background(), manifestPathFor(cfg)) + if err != nil { + t.Fatal(err) + } + if baseline.Stages["publish"] != nil || baseline.Stages["cleanup"] != nil { + t.Fatalf("import fabricated publication or cleanup: %#v", baseline.Stages) + } + plan := mustBoundedPlan(t, "", "") effective, err := resolveEffectiveArtifacts(cfg, nil) if err != nil { t.Fatal(err) @@ -131,6 +139,17 @@ func TestFullRunWithSuppliedTranscriptPreparesAndRendersSelectedVariant(t *testi } } } + current, err := discoverRemotePublication(context.Background(), cfg, fake) + if err != nil { + t.Fatal(err) + } + restorePreview, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{DryRun: true}) + if err != nil { + t.Fatal(err) + } + if !slices.Contains(restorePreview.Satisfied, "render") || slices.Contains(restorePreview.Remaining, "render") { + t.Fatalf("restore preview did not preserve reusable local render: %#v", restorePreview) + } forced := mustBoundedPlan(t, "transcribe", "transcribe") input := &executionInput{plan: forced} input.Force.Value = true diff --git a/internal/app/restore_baseline_test.go b/internal/app/restore_baseline_test.go index 4945be3..ff75c01 100644 --- a/internal/app/restore_baseline_test.go +++ b/internal/app/restore_baseline_test.go @@ -24,12 +24,22 @@ func TestInventoryImportInstallsValidatedBaselineAndRetriesSave(t *testing.T) { if err != nil { t.Fatal(err) } + paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) + if err := os.MkdirAll(paths.Root, 0755); err != nil { + t.Fatal(err) + } + if err := writeRestoreMarker(paths); err != nil { + t.Fatal(err) + } if _, err := executeRestorePlan(ctx, cfg, current, plan, nil, fake); err != nil { t.Fatal(err) } if err := installInventoryBaseline(ctx, cfg, plan, &failingRestoreManifestStore{}); err == nil { t.Fatal("expected final manifest save to fail") } + if err := requireCompleteRestore(paths); err == nil { + t.Fatal("failed save did not retain the incomplete-restore marker") + } path := artifacts.SessionManifestPathForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) if _, err := os.Stat(path); !os.IsNotExist(err) { t.Fatalf("failed save installed manifest: %v", err) @@ -41,11 +51,13 @@ func TestInventoryImportInstallsValidatedBaselineAndRetriesSave(t *testing.T) { if err := installInventoryBaseline(ctx, cfg, retry, &manifest.LocalStore{}); err != nil { t.Fatal(err) } + if err := clearRestoreMarker(paths); err != nil { + t.Fatal(err) + } loaded, err := (&manifest.LocalStore{}).Load(ctx, path) if err != nil { t.Fatal(err) } - paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) if !artifacts.SuppliedTranscriptCoverage(paths, loaded.SuppliedProducts)["trim"] { t.Fatalf("trimmed transcript unavailable after retry: %#v", loaded.SuppliedProducts) } diff --git a/internal/app/restore_manifest_paths.go b/internal/app/restore_manifest_paths.go index 5d1afe9..c1e71df 100644 --- a/internal/app/restore_manifest_paths.go +++ b/internal/app/restore_manifest_paths.go @@ -30,7 +30,16 @@ func installInventoryBaseline(ctx context.Context, cfg *config.Config, plan *Res if err := artifacts.ValidateSuppliedProduct(paths, action.SourceID, action.LocalRelativePath, record); err != nil { return fmt.Errorf("validate imported product %q: %w", action.SourceID, err) } - if priorSourceChecksum(plan.baseline, action.SourceID) == action.SHA256 { + } + if err := invalidateImportedDependencies(plan.candidate, plan.baseline, plan.Actions); err != nil { + return err + } + return store.Save(ctx, paths.ManifestPath, plan.candidate) +} + +func invalidateImportedDependencies(candidate, baseline *manifest.Manifest, actions []RestoreAction) error { + for _, action := range actions { + if action.SourceID == "" || action.Kind == RestoreActionConflict || priorSourceChecksum(baseline, action.SourceID) == action.SHA256 { continue } producer := importedProductProducer(action.SourceID) @@ -38,14 +47,14 @@ func installInventoryBaseline(ctx context.Context, cfg *config.Config, plan *Res return fmt.Errorf("unknown imported product source %q", action.SourceID) } at := time.Now().UTC() - if existing := plan.candidate.Stages[producer]; existing != nil && existing.Status == manifest.StatusSucceeded { - plan.candidate.MarkStageStale(producer, at, staleReasonChangedResult) + if existing := candidate.Stages[producer]; existing != nil && existing.Status == manifest.StatusSucceeded { + candidate.MarkStageStale(producer, at, staleReasonChangedResult) } - if _, err := invalidateDependentSucceededStagesWithReason(plan.candidate, producer, at, staleReasonChangedResult); err != nil { + if _, err := invalidateDependentSucceededStagesWithReason(candidate, producer, at, staleReasonChangedResult); err != nil { return err } } - return store.Save(ctx, paths.ManifestPath, plan.candidate) + return nil } func importedProductProducer(source string) string { diff --git a/internal/app/restore_plan.go b/internal/app/restore_plan.go index 486e74e..1a71e1d 100644 --- a/internal/app/restore_plan.go +++ b/internal/app/restore_plan.go @@ -137,7 +137,7 @@ func buildInventoryRestorePlan(ctx context.Context, cfg *config.Config, current }) plan := &RestorePlan{Actions: actions} - if err := projectInventoryCoverage(ctx, cfg, plan); err != nil { + if err := projectInventoryCoverage(ctx, cfg, plan, store); err != nil { return nil, err } for _, action := range actions { @@ -157,7 +157,7 @@ func buildInventoryRestorePlan(ctx context.Context, cfg *config.Config, current // projectInventoryCoverage describes completion if all accepted transfers // validate successfully. It never treats a declaration as verified content. -func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *RestorePlan) error { +func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *RestorePlan, store storage.ObjectStore) error { manifestPath := artifacts.SessionManifestPathForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) local, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, manifestPath) if err != nil { @@ -261,12 +261,34 @@ func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *Res } covered["extract"] = covered["extract"] || complete } - if cfg.Pipeline.Render == nil || cfg.Pipeline.Render.Enabled == nil || *cfg.Pipeline.Render.Enabled { - names = append(names, "render") - } - if cfg.Pipeline.Notarius != nil && cfg.Pipeline.Notarius.Enabled { - names = append(names, "extract") + // Reuse the normal read-only stage projection for preserved local work. + // Proposed downloads have not been installed, so the supplied coverage above + // remains conditional and local validation may conservatively schedule work. + if local != nil { + model, cloneErr := cloneManifestForPlan(plan.candidate, cfg) + if cloneErr != nil { + return cloneErr + } + if err := invalidateImportedDependencies(model, plan.baseline, plan.Actions); err != nil { + return err + } + effective, effectiveErr := resolveEffectiveArtifacts(cfg, nil) + selection, selectionErr := BuildBoundedPlan("", "") + if effectiveErr == nil && selectionErr == nil { + projection, _ := projectSelectedWork(ctx, cfg, selection, false, nil, effective, artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root), store, model) + if err := ctx.Err(); err != nil { + return err + } + if projection != nil { + for _, item := range projection.Stages { + if item.Decision.action == stageActionSkip && recordedStageStatus(local, item.Name) == manifest.StatusSucceeded { + covered[item.Name] = true + } + } + } + } } + names = []string{"prepare", "transcribe", "merge", "polish", "normalize", "trim", "render", "extract", "analyze", "publish", "notify", "cleanup"} for _, name := range names { if covered[name] { plan.Satisfied = append(plan.Satisfied, name) diff --git a/internal/app/restore_workflow_test.go b/internal/app/restore_workflow_test.go index 1ad4830..2166914 100644 --- a/internal/app/restore_workflow_test.go +++ b/internal/app/restore_workflow_test.go @@ -77,6 +77,17 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) { if beforeAnalyze.Stages["trim"] != nil { t.Fatal("import invented a trim execution") } + selected := []string{"player_handout"} + effective, err := resolveEffectiveArtifacts(cfg, selected) + if err != nil { + t.Fatal(err) + } + input := &executionInput{plan: mustBoundedPlan(t, "analyze", "analyze")} + input.Force.Value = true + preview, err := buildSessionPlan(context.Background(), cfg, input, selected, effective, commandDependencies{}) + if err != nil || len(preview.Stages) != 1 || preview.Stages[0].Action != "run" || preview.Stages[0].Analysis == nil || len(preview.Stages[0].Analysis.Reuse) != 1 { + t.Fatalf("bounded analysis preview = %#v, %v", preview, err) + } stdout.Reset() stderr.Reset() diff --git a/internal/artifacts/current_state.go b/internal/artifacts/current_state.go index 5696953..f8663c2 100644 --- a/internal/artifacts/current_state.go +++ b/internal/artifacts/current_state.go @@ -37,7 +37,6 @@ type CurrentStateValidation struct { ExpectedCampaign string ExpectedSessionID string ExpectedRunID string - ValidateRunID bool } // LoadCurrentInventory reads the selected publication identity and declarations diff --git a/internal/artifacts/remote_commit_test.go b/internal/artifacts/remote_commit_test.go index 78294d6..ffdead4 100644 --- a/internal/artifacts/remote_commit_test.go +++ b/internal/artifacts/remote_commit_test.go @@ -166,7 +166,6 @@ func TestLoadCurrentStateReadsVerifiedRemoteCommit(t *testing.T) { state, err := LoadCurrentInventory(context.Background(), store, testCurrentSessionPrefix(), CurrentStateValidation{ ExpectedCampaign: commit.Campaign, ExpectedSessionID: commit.SessionID, - ValidateRunID: true, }) if err != nil { t.Fatalf("LoadCurrentInventory() error = %v", err) diff --git a/internal/config/load_validate_test.go b/internal/config/load_validate_test.go index f9ed29d..96a68f0 100644 --- a/internal/config/load_validate_test.go +++ b/internal/config/load_validate_test.go @@ -320,6 +320,7 @@ func TestExamplesLoadAndValidate(t *testing.T) { sessionFile string }{ {name: "catalog pipeline with local audio session", pipelineFile: "pipeline.catalog.yml", sessionFile: "session.local-audio.yml"}, + {name: "minimal pipeline with published products", pipelineFile: "pipeline.minimal.yml", sessionFile: "session.published-products.yml"}, { name: "minimal pipeline with local audio session", pipelineFile: "pipeline.minimal.yml", diff --git a/internal/previouscache/previouscache.go b/internal/previouscache/previouscache.go index cac4d2e..070a206 100644 --- a/internal/previouscache/previouscache.go +++ b/internal/previouscache/previouscache.go @@ -99,7 +99,6 @@ func Resolve( current, err := artifacts.LoadCurrentInventory(ctx, store, previousSessionPrefix, artifacts.CurrentStateValidation{ ExpectedSessionID: previousSessionID, ExpectedCampaign: campaign, - ValidateRunID: true, }) if err != nil { var pointerMissing *artifacts.CurrentCommitPointerMissingError diff --git a/internal/stage/publish_commit.go b/internal/stage/publish_commit.go index efad54c..8ff3f3a 100644 --- a/internal/stage/publish_commit.go +++ b/internal/stage/publish_commit.go @@ -13,7 +13,7 @@ import ( func loadPriorPublishCommit(ctx context.Context, store storage.ObjectStore, sessionPrefix, campaign, sessionID string) (*artifacts.RemoteCommitManifest, error) { current, err := artifacts.LoadCurrentInventory(ctx, store, sessionPrefix, artifacts.CurrentStateValidation{ - ExpectedCampaign: campaign, ExpectedSessionID: sessionID, ValidateRunID: true, + ExpectedCampaign: campaign, ExpectedSessionID: sessionID, }) if errors.Is(err, artifacts.ErrCurrentCommitPointerMissing) { return nil, nil diff --git a/internal/stage/publish_test.go b/internal/stage/publish_test.go index 150eb4d..93d574e 100644 --- a/internal/stage/publish_test.go +++ b/internal/stage/publish_test.go @@ -795,7 +795,7 @@ func TestPublishCarriesLockedRequiredOutputAndCommits(t *testing.T) { t.Fatalf("carried published output metadata = %#v", outcome) } - state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true}) + state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{}) if err != nil { t.Fatal(err) } @@ -971,7 +971,7 @@ func TestPublishFailurePreservesPreviousCommittedSnapshotAndRetryIsDeterministic if got := fake.Objects[pointerKey].Data; !reflect.DeepEqual(got, priorPointer) { t.Fatalf("current pointer changed after failed publication: %q", got) } - state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true}) + state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{}) if err != nil { t.Fatalf("LoadCurrentState() error = %v", err) } @@ -992,7 +992,7 @@ func TestPublishFailurePreservesPreviousCommittedSnapshotAndRetryIsDeterministic if len(fake.Uploads) == 0 || fake.Uploads[len(fake.Uploads)-1].Key != pointerKey { t.Fatalf("retry uploads = %#v, want pointer as final mutation", fake.Uploads) } - state, err = artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true}) + state, err = artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{}) if err != nil { t.Fatalf("LoadCurrentState() after retry error = %v", err) } @@ -1051,7 +1051,7 @@ func TestPublishDoesNotSelectCommitWhenLockAppearsAtCommitPoint(t *testing.T) { if _, exists := fake.Objects[commitKey]; !exists { t.Fatalf("immutable attempt commit %q missing after final lock appeared", commitKey) } - state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true}) + state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{}) if err != nil || state.RunID != oldRunID { t.Fatalf("current state after lock loss = %#v, %v; want old run %q", state, err, oldRunID) }