Files
narratio/docs/roadmap/implementation.md

366 lines
22 KiB
Markdown
Raw Normal View History

# Standalone Session Preflight Implementation Plan
2026-11-30 15:13:41 +00:00
Status: In progress.
## Scope And Working Instructions
Implement the target in [Standalone Session Preflight](preflight.md). That
roadmap owns product scope and policy choices; this document owns the ordered
implementation work. The baseline is commit `07e6fae`, including the session
probe locking fix in `826369c`.
The audience is a Luna coding agent implementing one stage per prompt, in order,
within one end-to-end sprint. Intermediate stages may leave callers or tests
temporarily incomplete. Complete the final integrated behavior rather than
adding transitional APIs or duplicate implementations to keep every stage green.
Update each stage's status when its work is complete and record actual checks.
Commit completed units with plain English messages under the agent policy.
Start with [Development](../development.md) and read the applicable
[Agent](../policy/agents.md), [Architecture](../policy/architecture.md),
[Testing](../policy/testing.md), and
[Documentation](../policy/documentation.md) policies. Follow `AGENTS.md` for
code discovery. Each stage below identifies its focused starting points; expand
reading when a concrete dependency requires it.
Planning authorizes documentation only. Implementation begins in subsequent
prompts. No dependency upgrade, release, tag, push, or CI monitoring is part of
this sprint.
## Implementation Decisions
- Register top-level `preflight SESSION` and remove `session validate`. Reuse
`run`'s configuration/session selectors, including `--previous-session-id`,
through existing acquisition helpers. Keep native CommandKit reporting and
ConfigKit error semantics. Stage ranges, force, and artifact filters are
outside this command's initial surface.
- Standalone selection covers enabled capabilities and the existing prompt
prerequisite closure, including reusable outputs. Automatic selection stays
based on projected execution. Share downstream checking and request setup.
- Execute a prepare-only bounded plan with ordinary resume and invalidation,
followed by standalone checks inside the same locked invocation. Use one
acquisition and one authoritative prepared manifest. Preparation success is
durable even when later readiness fails.
- Extract a small private locked-lifecycle wrapper and the existing selected
stage loop. The normal runner and standalone workflow supply their operation
bodies to that wrapper. This is reuse of two concrete workflows, not a stage
engine, plugin system, or collection of lifecycle hooks.
- Report coarse check groups: configuration, preparation, workspace/storage,
prompt requirements, Audita, Notarius, and publication locks as applicable.
Use `succeeded`, `failed`, and `blocked` check outcomes; omit inapplicable
groups or explain their non-applicability informationally. Keep preparation's
ordinary `completed`, `reused`, `failed`, or `not_attempted` outcome separate.
Findings retain existing severity and useful target context. A group can
succeed with warnings, including incomplete Scriptorium discovery.
- Use actual preparation/resume evidence for stable inputs, audio, and required
or optional previous-session inputs. Keep the existing configured-storage and
remote-lock inspections where preparation does not supply that evidence.
Required failures or blocked required checks prevent readiness success;
optional omissions and observed publication locks retain their current
non-fatal treatment.
- Continue independent standalone checks after ordinary failures while context
remains active. Prepared-input probes require successful persisted preparation.
Cancellation stops new work. Use ordinary errors and native classifications;
readiness creates neither a manifest stage nor a reusable success record.
- Use existing invocation-scoped probe helpers under `runs/` for both workflows.
Probe outputs remain disposable diagnostics. Leave canonical products,
latest processing-attempt views, and authorized cleanup semantics unchanged.
## Stage 1: Factor Native Check Operations And Preserve Findings
2026-11-30 15:13:41 +00:00
Status: Complete. Verified with `GOTOOLCHAIN=go1.27.4 go test ./internal/preflight ./internal/adapters/audita ./internal/adapters/notarius` and `git diff --check`.
Read `internal/preflight/{types,check,downstream}.go`, their tests, and
[Preflight Internals](../internal/preflight.md). Inspect the Audita and Notarius
adapter preflight contracts and focused tests where needed.
1. Factor the Audita operation out of `CheckDownstream` into a small named
checker alongside existing Scriptorium `Check` and `CheckNotarius` operations.
Keep adapter invocation and native result interpretation in their current
owners. The application will sequence these operations and record group
outcomes without reinterpreting private downstream reports.
2. Preserve Scriptorium binding/variable checks, prerequisite context, warning
severity, and partial findings. Preserve Audita provider-smoke behavior and
Notarius inspection completeness, selected pipeline, required lanes, native
failure causes, warnings, and synthetic-input descriptions.
3. Preserve errors with wrapping/joining and honor cancellation. Successful
checks need not manufacture findings for every successful upstream detail;
the application can record a successful group from a successful operation.
4. Remove the old combined wrapper once its callers migrate in Stage 2; avoid
leaving two maintained implementations of the same checks.
Verification: adapt existing `internal/preflight` tests for success, warnings,
failure findings, partial results, and cancellation. Use existing adapter
contract tests rather than repeating subprocess parsing at this layer.
Done when each downstream check has one explicit callable owner and existing
severity/error behavior is preserved.
## Stage 2: Share Downstream Request Construction And Execution
Status: Complete. Verified with `GOTOOLCHAIN=go1.27.4 go test ./internal/app ./internal/preflight` and `git diff --check`.
Read `internal/app/{runner_preflight,preflight_targets}.go`,
`internal/stage/{polish_context,extract_preflight}.go`, and
`internal/app/{runner_preflight,runner_downstream,notarius_preflight,preflight_targets}_test.go`.
1. Introduce a narrow application helper for downstream readiness, taking
explicit targets, the current invocation environment/paths/manifest, probe
identity, and the existing transcript/force controls. Return group outcomes,
contextual findings, and an error. Keep the report data small and local to
this feature; no generic check registry or dependency graph is needed.
2. Lazily construct only targeted adapters through invocation dependencies and
retain them in the invocation environment for later production reuse. Build
Audita requests through `stage.BuildPolishRequest` and Notarius requests
through `stage.BuildNotariusReadiness`. Verify Notarius reference snapshots
after the native call, including failure paths. Surface request-construction
or adapter-initialization failures as the affected group's failure.
3. Use `artifacts.SessionInvocationProbeDir` with the invocation's run identity
and existing output/log/debug subpaths. Pass the same configuration,
credentials, overlays, timeouts, reference selections, and applicable cache
controls as production. Standalone requests use ordinary non-forced controls;
automatic forced extraction keeps its current refresh behavior.
4. Sequence the three independent tool checks directly. Preserve collected
findings when another tool fails; stop starting checks on cancellation.
Prepared-evidence failure blocks only probes that require that evidence.
A failed checker still prevents automatic processing from starting.
5. Migrate `inspectInvocationRequirements` to the shared helper. Keep its work
projection, empty-target shortcut, `executionDownstreamTargets`,
`currentTranscriptUsableForNotarius`, and warning/progress presentation.
Keep standalone target selection as a distinct function, renaming the
validation-named selector to describe enabled capabilities when callers move.
Verification: retain automatic checks-after-prepare, reused-work suppression,
artifact prerequisite closure, forced refresh, synthetic/current input choice,
and invocation-owned adapter reuse tests. Add only missing coverage for
independent tool failures and request-building failures; use fakes at adapters.
Done when automatic preflight uses the shared path and standalone orchestration
can call it without rebuilding requests or acquiring a second lock.
## Stage 3: Extract The Runner's Locked Invocation Lifecycle
Status: Pending.
Read `internal/app/{runner,runner_runtime,runner_stage_execution,runner_finalization,runner_composition,runner_dependencies}.go`,
[Workspace Internals](../internal/workspace.md), and runner cancellation,
terminal-failure, partial-result, bounded-prerequisite, and cleanup-reuse tests.
1. Extract the existing lifecycle shell from `executePlanWithDependencies` into
a private helper accepting one operation body. Preserve prerequisite checks,
unsupported-manifest handling before layout changes, layout creation,
context-aware session locking, locked initialization, restore protection,
terminal persistence, partial summaries, and lock-release error propagation.
2. Extract the selected-stage loop, including stage-result bookkeeping and its
automatic preflight boundary, into one private operation. The normal runner
uses the shared lifecycle with that operation and keeps its public executor
contract unchanged.
3. Allow the standalone body to execute that same loop with a prepare-only
bounded plan, inspect the outcome, and check readiness before returning to
shared finalization. A prepare-only selection does not trigger automatic
downstream checks, so standalone invokes them once through its own selection.
4. Hold the same lock continuously from locked manifest initialization through
preparation, readiness request construction, native calls, report reading,
reference verification, and terminal persistence. Finalize before releasing
it. Do not call another public command, reacquire the lock, or reload config.
5. Retain lazy run-directory creation, ordinary stage invalidation, and existing
cancellation-detached terminal persistence. Keep all operation errors intact
when persistence or release also fails.
Verification: run the existing runner lifecycle, failure, bounded-run,
cancellation, and cleanup tests as the refactor becomes integrated. Preserve
their behavioral assertions rather than locking tests to new helper ordering.
Done when normal execution retains its behavior and a second concrete operation
can share the full lifecycle without copying stage transitions or finalization.
## Stage 4: Implement The Standalone Prepare-And-Check Operation
Status: Pending.
Read `internal/app/{session_inspection_command,operator_inspection,operator_findings,configuration_acquisition,command_dependencies}.go`,
[Preparation](../internal/stage-prepare.md), and existing session preflight tests.
1. Add the application operation behind standalone preflight. Acquire the domain
configuration once with `newConfigurationAcquisition`, apply the existing
previous-session assertion, validate through the ordinary path, and close the
acquisition on every exit. Pass that same configuration and reporter to the
shared locked lifecycle with `BuildBoundedPlan("prepare", "prepare")` and
normal non-forced options.
2. Adapt command-owned adapter/storage factories into the invocation's existing
dependency seams. Reuse an already composed object store where available;
construct configured storage through the ordinary factory when needed for
lock inspection. Avoid global test hooks and duplicate configuration loads.
3. Run or reuse prepare through the shared stage loop. Derive preparation
outcome from its stage result and durable save outcome, not merely a prior
succeeded manifest record. Required writes must succeed before prepared-input
probes run. A failed replacement must not probe old preparation as current.
4. Map successful preparation/resume evidence to input/audio/previous-input
readiness findings. Preserve optional missing previous artifacts as optional.
Remove redundant validation-only live-input/download setup; keep inspection
helpers used by status, planning, or other commands. Use existing remote-lock
inspection without simulating uploads or requiring future outputs to exist.
5. Select all enabled downstream capabilities and prompt prerequisites regardless
of output reuse. Call the shared downstream helper once. After successful
preparation, use the existing pure work projection for the normal transcript
producer range and `currentTranscriptUsableForNotarius` to determine whether
upstream work would rerun. This suitability assessment does not narrow the
standalone target set or persist projection decisions. Permit a real input
only when that assessment and existing trimmed-artifact resolution support
it; otherwise use the synthetic fallback. This covers semantic changes to
transcript stages even when their older files and success records remain.
Do not run transcript producers to obtain a probe input.
6. On preparation failure, report prepared-input checks as blocked. Continue
configuration-based Scriptorium requirements inspection and available remote
lock inspection when practical and uncanceled. If acquisition, locked
initialization, or cancellation prevents a usable operation, return the
available failure/partial assessment and do not manufacture successes.
7. Build the standalone report as ordinary application data: `campaign`,
`session_id`, optional `session_source`/`run_id`, `preparation` (outcome and
reason), `ready`, `checks` (group, outcome, message), and `findings` with
existing severity/context. Keep its data shape common to all output formats.
Finalize `ready` after acquisition-close, persistence, and release errors are
known. Native report delivery failure retains CommandKit's own failed outcome.
8. Readiness failure leaves persisted preparation succeeded and retains normal
session terminal-failure reporting. It does not fail a processing stage or
independently invalidate its evidence. Only ordinary prepare transitions can
stale descendants. Stop before processing, publishing, notify, or cleanup.
Verification: add focused application behavior tests for fresh preparation,
reused preparation with repeated checks, provider failure after prepare success,
and a preparation failure with blocked probes and independent findings. Use real
temporary input/workspace files and fake providers/storage. Verify substantive
state and error causes; exact incidental diagnostic wording is not contractual.
Done when the operation works without prior prepare, has meaningful partial
results, and uses production preparation and readiness owners throughout.
## Stage 5: Replace The CLI Command And Integrate Native Reporting
Status: Pending.
Read `internal/app/{commands,session_inspection_command,execution_command,command_reporting,command_outcome}.go`,
the command boundary tests, and the existing session validation command tests.
1. Register top-level `preflight SESSION` using native CommandKit declarations
and shared configuration flags. Include the existing overlay, campaign,
campaign-file, party-file, session-file, and previous-session selectors.
Help must state that preparation writes state/downloads inputs and checks may
contact providers. Keep help/completion discovery free of configuration loads.
2. Emit one final report through `Reporter().Report` and return
`reportOperationOutcome`, preserving joined causes and native classifications.
Use native text, YAML, JSON, automatic format selection, and visibility;
preparation/check progress belongs on stderr. Retain substantive failed or
blocked findings in reports under quiet/terse settings.
3. Remove `session validate` registration, its command-only types, and obsolete
orchestration. Reuse the shared inspection spec for other commands where
appropriate. Remove validation-only probe helpers if no caller remains;
retain helpers with other live users. Add no compatibility alias.
4. Migrate command callers and relevant tests to `preflight`, retaining native
malformed-config versus operational-failure coverage. Leave `config`,
`session plan`, `session status`, and artifact inspection semantics unchanged.
Verification: exercise a representative successful and failed CLI workflow,
JSON/YAML report decoding, text/auto reporting, quiet failure visibility,
selection mapping, config failure, and removal/discovery of commands. Reuse
existing native boundary coverage instead of testing every upstream formatting
combination or reproducing CommandKit's test suite.
Done when the new command is discoverable, the old command is absent, and native
reporting accurately presents preparation and readiness outcomes.
## Stage 6: Protect Resume, Probe Locking, And Cleanup Interactions
Status: Pending.
Read `internal/app/{session_preflight,session_validation_lock,notarius_preflight,preflight_targets,runner_downstream,cleanup_orchestration}_test.go`
and the application tests added in earlier stages.
1. Replace obsolete no-workspace/no-manifest-mutation validation assertions with
the selected prepare-and-check behavior. Preserve tests for native findings,
optional sources, disabled prerequisites, cancellation, and error causes.
2. Verify a changed stable input triggers normal prepare invalidation, while a
probe failure alone retains successful preparation and previously current
processing authority. Verify a later ordinary run reuses preparation and
still performs applicable automatic preflight before processing.
3. Verify standalone checks include reusable enabled targets while automatic
checks omit reused targets. Keep production request parity, prerequisite
closure, and stale-transcript fallback covered at their narrowest owners.
4. Migrate the `826369c` lock regression tests to the new workflow. With each
provider probe held at a test-controlled boundary, verify the shared lock
excludes concurrent cleanup until all probe work has finished. Verify lock
waiting honors cancellation and no provider starts before acquisition. Cover
preparation-to-probe continuity through the shared lifecycle; avoid sleeps
that guess when a race has occurred.
5. Verify authorized subsequent cleanup removes finished run-local probe
evidence while durable prepared inputs remain reusable. Repeated preflight
can recreate probe space. Preflight itself does not perform cleanup or rotate
processing-stage diagnostic views.
6. Cover representative preparation-save, terminal-save, cancellation, and
release failures through existing injectable boundaries. Confirm partial
results never claim overall readiness or preparation reuse without adequate
evidence. Reuse existing lifecycle tests when they already cover a risk.
Verification: run focused application tests and their race-enabled variants.
All default tests remain offline and credential-independent; external calls use
fakes and filesystem behavior uses `t.TempDir()`.
Done when the changed workflow retains recovery and cleanup safety without
duplicating the suite or introducing stricter readiness rules.
## Stage 7: Update Canonical Documentation And Verify The Sprint
Status: Pending.
Read the affected sections of [CLI](../cli.md), [Operations](../operations.md),
[Troubleshooting](../troubleshooting.md), [Internal Overview](../internal/overview.md),
[Preflight Internals](../internal/preflight.md),
[Workspace Internals](../internal/workspace.md),
[Audita Integration](../integrations/audita.md), and the architecture policy.
1. Update CLI command inventory, examples, and public report-field reference for
`preflight`. Update operations to replace the separate prepare/validate
sequence with preflight and explain mutable preparation, full-capability
checking, provider calls, diagnostic lifetime, and successful-prepare reuse
after readiness failure. Keep automatic preflight's different selection clear.
2. Replace live troubleshooting commands and obsolete validation descriptions.
Explain synthetic-input limits and actionable failures without implying a
successful preflight guarantees later processing or publication success.
3. Update internal ownership/lifecycle descriptions and architecture policy's
standalone-validation paragraph to match implemented prepare-and-check
behavior. State the policy affirmatively and concisely. Preserve existing
ownership boundaries and the canonical pipeline stage set.
4. Update affected integration summaries, links/anchors, and roadmap baseline
links when the old CLI section is removed. Keep upstream feature definitions
linked to canonical upstream documentation. Keep versioned release-note
preparation for the documented release workflow; retain the command-removal
migration reminder in the feature roadmap for that follow-up.
5. Remove unused validation orchestration, imports, fixtures, and helpers left
by the migration. Review the cumulative diff against the feature roadmap:
no new config resolver, health framework, stage, success cache, subprocess
internals validator, or additional readiness restrictions should remain.
6. Run the normal completion checks with the maintained Go toolchain:
```sh
GOTOOLCHAIN=go1.27.4 go test ./...
GOTOOLCHAIN=go1.27.4 go test -race ./...
GOTOOLCHAIN=go1.27.4 go vet ./...
GOTOOLCHAIN=go1.27.4 go build ./...
GOTOOLCHAIN=go1.27.4 go test ./internal/doccheck
git diff --check
```
Format changed Go code and fix relevant failures. Review staged changes,
update plan statuses with verification results, and commit the completed
work. Do not publish a release or wait for CI as part of completion.
Done when all seven stages satisfy the feature roadmap, normal verification
passes, current documentation describes implemented behavior, and the worktree
is clean after commits.
## Open Questions
None. The feature's scope and behavior are decided. Internal names and file
placement may follow the simplest idiomatic organization within the owners
identified above; those choices do not alter the selected operator contract.