357 lines
22 KiB
Markdown
357 lines
22 KiB
Markdown
# Dedicated Preflight Command: Implementation Plan
|
||
|
||
Status: Ready for implementation.
|
||
|
||
Implement the target in [Dedicated Preflight Command](preflight-command.md).
|
||
That roadmap owns the behavior and policy choices; this document defines the
|
||
ordered work for a Luna coding agent. Reviewed baseline:
|
||
`604ae631b39b48c5ab80871ffcd76cdf8db6e108`.
|
||
|
||
## Execution and scope
|
||
|
||
Execute Stage 1 through Stage 8 in order during one end-to-end sprint.
|
||
Intermediate stages need not compile. Update internal callers and tests directly;
|
||
remove obsolete paths rather than building temporary compatibility wrappers.
|
||
Run focused tests once the relevant path is complete, followed by final validation.
|
||
Follow `docs/development.md` and its applicable agent, architecture, testing and
|
||
documentation policies. Use graph-first discovery before editing code.
|
||
|
||
Deliver standalone `preflight`, default-on structured-output smoke diagnostics,
|
||
shared local preparation consumed by processing, and `run` as an alias of
|
||
`process`. Preserve the existing domain algorithms, correction resilience,
|
||
configuration semantics and publication behavior except for the explicitly
|
||
selected earlier normalization/chunking boundary. No dependency upgrades,
|
||
application schema changes, retained preflight artifacts, persisted plans,
|
||
provider-specific prompts, releases or sibling-repository changes are needed.
|
||
|
||
The plan is invocation-local and consumed once. It is not an externally supplied
|
||
or reusable execution contract. Do not add serialization, digests, cache keys,
|
||
plan authenticity checks, extra filesystem guarantees or a general workflow
|
||
framework. Local readiness remains provider-independent in the expressly named
|
||
`internal/framework/preflight` package; native provider diagnostics belong in the
|
||
LLM adapter after local readiness, consistent with ADR 0002's separation.
|
||
|
||
## Code map and selected design
|
||
|
||
| Responsibility | Starting points |
|
||
| --- | --- |
|
||
| Shared flags, registration and native alias | `internal/cli/process_command.go`, `app_wiring.go`; CommandKit `Alias("run", "process")` |
|
||
| Acquisition, source paths, bootstrap and output selection | `internal/cli/process_inputs.go`, `app_wiring.go` |
|
||
| Current readiness/output coupling | `internal/framework/preflight/preflight.go` |
|
||
| Normalization currently performed after output initialization | `internal/cli/process.go`; existing core normalizer |
|
||
| Chunk planning currently performed inside execution | `internal/framework/runner/runner.go`: `RunInput`, `Run`, `chunkWorkingTranscript`; core chunker |
|
||
| Destination checks, staging and publication | `internal/core/diagnostics/output_session.go` and its output-session/stream tests |
|
||
| Processing role clients and retained evidence | `internal/cli/process_pipeline.go`, `process_output.go`, framework LLM runtime |
|
||
| Native provider diagnostics | PromptKit v0.25.0 `Engine.SmokeTest`, `SmokeTestRequest`, `SmokeTestReport` |
|
||
|
||
Use these small internal values; names may follow local conventions while their
|
||
ownership and handoff remain as specified:
|
||
|
||
- A checked-destination value in `core/diagnostics` holds the existing display
|
||
paths, resolved publication paths and destination kinds, without open handles.
|
||
Both write probes and processing output sessions consume that value.
|
||
- `preflight.Plan` holds resolved configuration, stage specs/prepared glossary
|
||
context, normalized transcript and summary, fixed `[]chunking.Section`, and
|
||
ordered distinct selected profile IDs. It contains no native PromptKit types
|
||
or output-resource lifecycle.
|
||
- A CLI prepared-invocation value combines acquired configuration/runtime/source
|
||
evidence, the domain plan and checked destinations. Together these are the
|
||
complete processing handoff, including intended destinations.
|
||
- The LLM adapter returns per-profile verification results retaining the native
|
||
report and error, with a small success/negative/unsupported/inconclusive
|
||
classification. Native observations do not enter domain configuration.
|
||
|
||
## Stage 1: Separate checked destinations from output resources
|
||
|
||
**Completed.**
|
||
|
||
Work:
|
||
|
||
1. Extract the checking work in `diagnostics.SelectOutput` into a check operation
|
||
returning the checked-destination value. Keep current canonicalization,
|
||
symlink/hard-link comparisons, target-type rules, input protection, in-place
|
||
transcript allowance, report placement and inactive-output behavior.
|
||
2. Add output-session construction from checked destinations. Move no file opens,
|
||
report initialization or publication into the checker. Keep real preparation,
|
||
initialization, finalization and cleanup in the existing output-session owner.
|
||
Update callers directly and retire the old combined checking/construction API
|
||
once replaced; do not maintain two implementations of path policy.
|
||
3. Keep the existing late destination checks at actual preparation/publication
|
||
where they protect changed stream/file types. A checked value records what
|
||
was checked, not a guarantee against later filesystem changes.
|
||
4. Adapt output-session tests to the new entry points. Preserve existing evidence
|
||
for collisions, in-place replacement, parent requirements, symlink publication,
|
||
devices/pipes, partial failures and cleanup. Do not assert the new private
|
||
representation or create another complete path-policy matrix.
|
||
|
||
Acceptance: checking acquires no output handles or files; ordinary output sessions
|
||
retain their existing publication and cleanup behavior when constructed from it.
|
||
|
||
## Stage 2: Add temporary write-readiness probes
|
||
|
||
**Completed.**
|
||
|
||
Work:
|
||
|
||
1. Add a context-aware probe operation in the output adapter that accepts checked
|
||
destinations and visits active regular-file targets in the existing transcript,
|
||
errors, recoveries, Markdown order. Include nonexistent regular-file targets
|
||
whose checked parents exist. Skip stdout and stream/device targets; disabled
|
||
reports have no targets to probe.
|
||
2. For each target, use `os.CreateTemp` in the resolved publication parent, close
|
||
the temporary file, and remove it. Its name must differ from the intended
|
||
destination. Do not open/truncate the final path, create missing parents,
|
||
initialize a report, write to a pipe/device, simulate permission bits, or add
|
||
fsync/durability requirements. A successful writable temporary file open is
|
||
the selected readiness check; no transcript-sized write is needed.
|
||
3. Attempt removal after a close error and cleanup after cancellation. Preserve
|
||
create/close/remove failures and cancellation with contextual paths and normal
|
||
error wrapping/joining. Observe cancellation between targets and after a probe;
|
||
cleanup itself must still be attempted when the context is canceled. Return
|
||
failure rather than silently treating an unremoved probe as success.
|
||
4. Use a small package-private probe-operation seam for deterministic create,
|
||
close and remove failures in tests. Keep real filesystem collaborators for
|
||
normal checks; no general virtual filesystem or public injection framework.
|
||
5. Cover successful creation/removal with existing target contents unchanged,
|
||
representative create/close/remove failures and cancellation, disabled reports,
|
||
missing parents, and stream targets not being opened. Verify path/type/collision
|
||
checks precede probes. Reuse Stage 1 coverage for unchanged policy.
|
||
|
||
Acceptance: required file destinations are probed without acquiring a processing
|
||
session; all temporary resources receive cleanup attempts and failures are visible.
|
||
This is present readiness, not a guarantee that a later write will succeed.
|
||
|
||
## Stage 3: Build the domain preparation plan once
|
||
|
||
**Completed.**
|
||
|
||
Work:
|
||
|
||
1. Refactor `framework/preflight` into the provider-independent local planning
|
||
owner. Replace the current `Prepare` operation that initializes outputs with
|
||
preparation returning `preflight.Plan`. Move output/debug lifecycle structs
|
||
and operations to the CLI/output-adapter boundary; retain this named package.
|
||
2. Reuse `ProcessingPlan`'s complete-pipeline glossary/profile readiness checks,
|
||
stage selection, profile/backend inspection deduplication and prepared-context
|
||
reuse. Preserve collection instructions, protection, profile fallback, and
|
||
disabled-repair behavior. Select profile IDs in first-use stage order, with
|
||
proposal then validation then enabled correction repair, deduplicating by ID
|
||
with a set and retaining an ordered slice. Distinct IDs remain distinct even
|
||
when they use one backend. Empty pipelines yield an empty profile list.
|
||
3. Move the existing canonicalization/normalization call and summary production
|
||
from `runProcess` into preparation. Build chunks using the existing core
|
||
chunker and effective configuration; do not change normalization, token
|
||
estimation, balancing or chunk identity algorithms.
|
||
4. Move the configured chunk-planning responsibility out of the runner. Internal
|
||
runner tests that relied on its nil-config convenience path should prepare
|
||
explicit sections with test helpers rather than retaining a production
|
||
fallback that silently rechunks. Update tests/callers as this API changes.
|
||
5. Keep errors at their owners: infeasible user-requested chunk counts are input
|
||
failures, just as unusable processing selections are. Cancellation and
|
||
operational collaborator errors remain operational. Use a focused typed
|
||
preparation error or existing selection-error wrapping without making every
|
||
preparation failure an input error. Preserve causes and phase context.
|
||
6. Test the assembled plan for normalized content/summary, feasible fixed chunks,
|
||
selected stage guidance and ordered profile deduplication. Include an empty
|
||
pipeline, disabled repair profiles and infeasible section count. Use real
|
||
normalizer/chunker; reuse their algorithm tests rather than duplicating them.
|
||
|
||
Acceptance: preparation returns the complete domain plan without an output
|
||
session or model call, and processing can consume it without repeating this work.
|
||
|
||
## Stage 4: Make processing consume the prepared invocation
|
||
|
||
**Completed.**
|
||
|
||
Work:
|
||
|
||
1. Factor shared CLI acquisition/local preparation out of `loadProcessInputs`
|
||
and `prepareProcess`. Retain the current main selection, bootstrap reporting,
|
||
runtime glossary source protection, native diagnostic classification and
|
||
runtime assembly. Factor the quiet destination check so both commands use it
|
||
before configuration/transcript acquisition.
|
||
2. Keep normal configuration and credential behavior: engine creation and native
|
||
inspection still perform their existing checks. Do not add a special local-only
|
||
credential bypass or force new credential/provider preparation checks where
|
||
the existing local path does not perform them.
|
||
3. Assemble the domain plan, then derive/check destinations with the existing
|
||
report-directory rules from `prepareProcess`. Return the prepared-invocation
|
||
value. Processing uses checking without the standalone temporary probe pass:
|
||
its real output preparation establishes write readiness.
|
||
4. Only after local preparation succeeds, allocate the processing run ID and
|
||
reporting session, build initial/failed report renderers, prepare outputs,
|
||
initialize reports, and optionally create debug artifacts. Preserve source,
|
||
normalized transcript, normalization-summary and effective-config debug
|
||
evidence, writing the already-computed values rather than recomputing them.
|
||
5. Change `runner.RunInput` to consume the prepared domain plan instead of
|
||
independently supplied configuration/transcript/specs. Update `executePipeline`
|
||
and internal tests directly. `Runner.Run` starts from its prepared sections,
|
||
preserves fixed initial metadata and the current per-stage mutation/commit
|
||
behavior, and never calls the chunker. Keep ownership invocation-local; do not
|
||
add a reusable/immutable-plan guarantee or redundant whole-plan deep copies.
|
||
6. Preserve role-client setup, proposal/validation/repair execution, cancellation,
|
||
partial success, ordered reporting and transcript encoding/publication. Ordinary
|
||
processing makes no smoke calls. Early normalization/chunking failure now occurs
|
||
before a reporting session and need not produce failed report files.
|
||
7. Adjust affected runner, preflight, CLI and report tests around this handoff.
|
||
Prove that chosen chunks reach execution and remain fixed as text evolves.
|
||
Preserve output initialization/publication failure tests; update expectations
|
||
that required artifacts for failures now deliberately preceding initialization.
|
||
|
||
Acceptance: `process` executes the shared plan, produces the existing transcript
|
||
and report/debug contracts on execution, and does not repeat stage resolution,
|
||
normalization or chunk planning. No temporary compatibility path remains.
|
||
|
||
## Stage 5: Share argument bindings and add the command routes
|
||
|
||
**Completed.**
|
||
|
||
Work:
|
||
|
||
1. Extract the current processing flags and transcript argument into reusable
|
||
typed binding builders. Use a shared invocation input for the existing
|
||
options; add the `Smoke` field and flag only to the preflight command binding.
|
||
Bind `--smoke` as a boolean with default true. `process` does not gain that flag.
|
||
2. Reuse all current process option parsers and explicit-override presence rules,
|
||
including runtime glossary ordering, profiles, collections, output/report/debug
|
||
settings and normalization/chunking controls. Preflight accepts the same
|
||
intended settings without triggering their processing lifecycle.
|
||
3. Register `preflight` with the shared bootstrap reporting invocation feature.
|
||
Register `commandkit.Alias("run", "process")` alongside the existing canonical
|
||
process declaration, rather than creating a second processing command.
|
||
Preserve native help, completion, reporting and usage-feature integration.
|
||
4. Implement standalone local-only orchestration through the shared preparation
|
||
helper, followed by Stage 2 probes. It must not generate a run ID for retained
|
||
artifacts, initialize reports, construct a disposable processing output
|
||
session, execute the runner, or emit corrected transcript JSON.
|
||
5. Route preparation errors through a shared CLI outcome adapter extracted from
|
||
`runProcess` where useful. Keep native load diagnostic distinctions, selection
|
||
and chunk-feasibility input failures at status 2, and cancellation/output
|
||
failures at status 1. Do not reintroduce blanket input classification by phase.
|
||
6. Test shared bindings with an overlay and runtime glossary, local-only success,
|
||
quiet without an output, `/dev/null`, help without acquisition, and one `run`
|
||
alias processing invocation. Test the alias against canonical behavior without
|
||
copying the whole process test suite. Default smoke execution is completed in
|
||
Stages 6–7; no intermediate stub should remain in the final implementation.
|
||
|
||
Acceptance: the routes and shared bindings represent one processing contract,
|
||
with a standalone local path that leaves final files and processing artifacts alone.
|
||
|
||
## Stage 6: Implement native structured-output verification
|
||
|
||
Work:
|
||
|
||
1. Add a focused adapter in `internal/framework/llm` using the already captured
|
||
runtime engine. Call `Engine.SmokeTest` with
|
||
`SmokeTestRequest{Kind: SmokeTestStructuredOutput, ProfileID: id}`. Keep
|
||
`TransientRetries` nil (v0.25.0 diagnostic default: zero), and leave `Execution`,
|
||
direct credentials and prompt selection unset so native effective profile
|
||
settings/defaults apply. Do not apply per-stage retry/deadline values to one
|
||
shared profile check, add outer retries, or invent an aggregate timeout.
|
||
2. Retain the report and error together, including partial reports on cancellation.
|
||
Add a small pure outcome adapter with this positive-result predicate:
|
||
no error; nonnil report for the requested structured-output kind; supported;
|
||
applicability positively true; completed; native failure is none; and
|
||
`GenerationCompleted`, `ValidJSON` and `SchemaMatched` are each positively true.
|
||
Nil mandatory facts are inconclusive, not false or success.
|
||
3. Distinguish unsupported/inapplicable results, concluded negative results,
|
||
inconclusive/incomplete observations and successful results for diagnostics.
|
||
Native execution failures remain failures even if some positive facts exist.
|
||
Do not require HTTP status, reachability/authentication facts, expected-text
|
||
matching or other ancillary observations to establish structured generation.
|
||
Keep additional facts as native evidence; the diagnostic does not establish
|
||
provider enforcement or compatibility with every production prompt/schema.
|
||
4. Check the plan's distinct profiles sequentially in their established order.
|
||
Continue after an ordinary negative result/error to report the remaining
|
||
selected profiles, retaining all causes. Stop further calls on parent
|
||
cancellation/deadline and retain completed/partial results. No parallel
|
||
scheduler, backend deduplication or new capacity control is needed.
|
||
5. Add outcome-adapter tests using native report values for positive, nil-error
|
||
negative, unsupported/inapplicable, unknown facts, incomplete, execution-error
|
||
and canceled results. Cover a positive report with HTTP facts absent. Test
|
||
orchestration with a narrow fake smoke boundary for distinct-ID selection and
|
||
cancellation; use one real-engine controlled transport case to verify native
|
||
request wiring, without copying the private smoke prompt into production code.
|
||
|
||
Acceptance: success requires positive generation/schema evidence for each selected
|
||
profile. Native requests, credentials, retries/admission and observations remain
|
||
upstream-owned. The domain preflight package contains no provider types.
|
||
|
||
## Stage 7: Finish preflight reporting and provider orchestration
|
||
|
||
Work:
|
||
|
||
1. After all shared local checks and destination probes succeed, call verification
|
||
by default. `--smoke=false` skips only verification. An empty profile list
|
||
succeeds without provider work and reports that there were no selected profiles.
|
||
Never dispatch smoke requests after a local failure.
|
||
2. Report local-preparation progress and each selected profile through CommandKit.
|
||
Emit a concise completion summary distinguishing local-only from local-plus-smoke
|
||
scope. For failures, identify the profile and unsupported/negative/inconclusive
|
||
result, preserving available native causes and partial observations. Do not
|
||
include transcript content, credentials or raw provider bodies in summaries.
|
||
3. Use CommandKit outcomes/reporters for quiet, progress and failure delivery.
|
||
Quiet requires the intended `--output` and suppresses optional summaries;
|
||
failures remain visible. No preflight JSON/YAML file, ordinary processing report,
|
||
debug run directory or new stable machine-report contract is introduced.
|
||
4. Retain existing ckprompt usage integration and context rather than computing
|
||
local token/cost totals. Native smoke usage is carried in each native report;
|
||
present that per-profile usage alongside its result, retaining native
|
||
known/completeness information and labeling it as smoke usage.
|
||
Do not synthesize execution events or imply the ordinary execution-observer
|
||
summary necessarily accounts for smoke calls. Unknown usage is not zero usage.
|
||
5. Cover default-on verification, explicit local-only mode, local failure preceding
|
||
provider calls, distinct models on one backend, omitted disabled repair roles,
|
||
and cancellation with partial diagnostics. Use controlled reports for outcome
|
||
combinations and an HTTP stub for a representative assembled command; never
|
||
call live providers. Check no final transcript/report/debug artifacts appear
|
||
and existing file contents survive both success and failure.
|
||
|
||
Acceptance: standalone preflight reports the checked scope truthfully and exits
|
||
0 only when that scope succeeds; unsuccessful provider verification exits 1.
|
||
`process`/`run` retain their existing execution behavior without smoke requests.
|
||
|
||
## Stage 8: Complete documentation and final validation
|
||
|
||
Work:
|
||
|
||
1. Update the canonical owners with implemented behavior:
|
||
- `docs/cli.md`: `preflight`, default-on `--smoke`, local-only invocation,
|
||
shared arguments, `run` alias and outcomes.
|
||
- `docs/operations.md`: temporary probes, secrets/provider side effects,
|
||
non-destructive final-destination checks and the earlier preparation/report
|
||
boundary. Explain stdout/stream/report/debug distinctions without duplicating
|
||
the command reference.
|
||
- `docs/integrations/subprocess.md`: Narratio-style readiness invocation,
|
||
exit interpretation and the limits of a check before a separate later run.
|
||
- Internal pipeline, CLI/config and diagnostics docs: plan handoff, fixed chunks,
|
||
expressly named local preflight owner, provider adapter, and output lifecycle.
|
||
Update architecture's implementation description only if needed; preserve
|
||
ADR 0002's provider-independent local-readiness decision.
|
||
2. Add one small domain-neutral example under `examples/`, preferably extending
|
||
an existing project. Include local-only use and explain default live-smoke use;
|
||
link the canonical native diagnostic docs. Keep D&D recipe and Narratio adapter
|
||
changes outside this sprint. Do not duplicate upstream diagnostic manuals.
|
||
3. Run focused tests for touched packages as their wiring completes. On the final
|
||
implementation, run `go test ./...` and
|
||
`go build -o ./bin/audita ./cmd/audita` with the documented supported Go toolchain.
|
||
Validate affected examples/local links, Go formatting and `git diff --check`.
|
||
Reuse tests for unchanged algorithms; no performance study or live API gate.
|
||
4. Review final coverage for the specific risks: preserved final files; probes
|
||
attempted in quiet/nonquiet and local/default modes; failures during create,
|
||
close, removal or cancellation; disabled reports; stream targets never opened;
|
||
chunking failures before smoke/output initialization; processing report cleanup
|
||
and publication after the refactor; prepared guidance retained through execution.
|
||
Prefer narrow boundary tests over duplicating the full cross-product at CLI level.
|
||
5. Remove obsolete preparation code/test helpers and update roadmap status to
|
||
actual completion. Commit completed units under agent policy. Do not publish a
|
||
release or introduce new release gates as part of this feature sprint.
|
||
|
||
Acceptance: the final source build and offline suite pass, canonical documentation
|
||
matches delivered behavior, and no obsolete duplicated preparation path remains.
|
||
|
||
## Open Questions
|
||
|
||
None. Product decisions are settled in the feature roadmap; the design choices
|
||
above specify the implementation handoffs and native diagnostic success criteria.
|