Retire completed preflight planning documents

This commit is contained in:
2026-11-28 16:23:29 +00:00
parent 460d368d8e
commit 2be1716520
5 changed files with 5 additions and 1173 deletions

View File

@@ -5,12 +5,6 @@ configuration, operations, internal, and integration docs. This backlog records
proposed extensions to that implementation. Items below are ordered roughly by
value and specificity, not as committed release dates.
## Feature Context And Implementation
- [Pipeline Preflight](preflight.md): accepted feature context for invocation
preparation, native provider checks, and readiness reporting; its
[implementation plan](implementation.md) records sequencing and completion.
## Near-Term D&D Pipeline
### Evaluate Spell Extraction And Normalization

View File

@@ -1,556 +0,0 @@
# Pipeline Preflight Implementation Plan
## Purpose And Execution Instructions
Implement the accepted [Pipeline Preflight Feature Roadmap](preflight.md).
That document owns product scope, readiness semantics, side effects, and consumer
policy. This document owns the implementation sequence. The original
[Narratio request](narratio-feature-request.md) is background; the accepted feature
roadmap governs where it refines that request.
Each numbered stage is one implementation prompt for a Luna coding agent.
Execute stages in order as one end-to-end sprint. Intermediate stages may leave
incomplete wiring or compilation errors; do not add temporary compatibility
layers or duplicate implementations merely to make an intermediate stage green.
Attach focused behavioral tests to their owning stage, and run them as soon as
the affected code is executable. The final stage requires a coherent, verified
repository. Follow the repository's commit discipline for completed units.
Before implementation, read [Development](../development.md),
[Agent Policy](../policy/agents.md), [Architecture](../policy/architecture.md),
and [Testing Policy](../policy/testing.md). Read
[Documentation Policy](../policy/documentation.md) before canonical documentation
changes. Prefer graph-based code discovery as directed by `AGENTS.md`.
This is application orchestration work, not a kit upgrade. Use the selected
PromptKit v0.25.0, CommandKit v0.8.0, ckprompt v0.12.0, and ConfigKit v1.4.0 APIs.
Do not change dependency versions or implement provider mechanics locally.
If a required native operation proves unavailable, describe the concrete API gap
before expanding scope; do not silently replace native resolution with a private
resolver or weaken the accepted preflight behavior.
## Current Baseline And Intended Seams
The reviewed baseline is commit `714d4456d9e8cb36fd3e039cdadb7ae7f23f568b`.
Verify current source before editing; names below locate owners, not required new
filenames or private helper names.
| Area | Current implementation and intended change |
| --- | --- |
| Command composition | `internal/cli/application.go` installs pipeline commands and the native `run` alias. Add another domain command and native alias, retaining lazy help/version construction. |
| Invocation selection | `run_input.go`, `execution_overrides.go`, and `pipeline_run.go` contain run flags, supplied values, configuration selection, reference selectors, resolution, and construction. Share these rather than copy the run handler. |
| Offline validation | `internal/preflight/preflight.go` inspects known dependencies of resolved modules and validators without input reads, construction, or network activity. Preserve `pipeline validate` at that boundary. |
| Domain preparation | `MaterializeReferences` and `pipeline.Prepare` materialize references and construct the complete typed implementation set. Constructors already validate many domain references. Keep those checks with their owners. |
| Source parsing | `prepareRunSource` in `runner_boundaries.go` parses through the prepared adapter, validates the generic document, and builds the run's source index inside execution. Extract the parsing/validation portion for preflight reuse without chunking. |
| Native resource declarations | `ModuleSpec.Prompts` lists initial and correction dependencies together; validator specs list assessment prompts. Resource existence is not the same as execution-target selection. Distinguish continuation-only dependencies when discovering targets. |
| Capture and outcomes | `run_debug.go`, `run_capture.go`, `pipeline_run.go`'s `finish`, and `run_result.go` implement early capture, retained causes, and native reporting. Reuse lifecycle mechanisms, not artifact-publication state. |
Use the selected native [smoke API][smoke-api], [inspection API][inspection-api],
[consumer guide][promptkit-consumer], and [CommandKit reporting guide][reporting]
as upstream contracts. Native `SmokeTestRequest` accepts profile/prompt/backend
selection, an execution override, and an optional transient-retry count.
`SmokeTestReport` retains support/applicability, completion, effective target,
facts, failure, attempts, and usage. A nil Go error is not a positive verdict.
Smoke evidence is separate from ordinary execution-observer totals.
## Cross-Stage Decisions
- Share ordinary helpers with explicit arguments/results. Keep configuration
loaders free of destination allocation and provider calls. Do not create a
generic preparation framework, persisted prepared-invocation record, or new
execution ledger.
- Keep all source/domain validation with the input adapter, pipeline framework,
or owning module. The CLI coordinates checks and presents their results.
- Local preparation and destination checks finish before paid diagnostics.
Construction failures still precede source parsing. Run does not acquire an
implicit online preflight or parse its source twice.
- Readiness covers the supplied input. A synthetic transcript is not a special
mode or proof about a future real transcript.
- Cache auto/refresh never read or alter accepted entries during preflight.
Bypass needs no access; cache problems only warn. Deterministic selected work
does not acquire provider checks or unnecessary cache probes.
- Preserve native supplied-value semantics, provider defaults, failure causes,
cancellation, diagnostic routing, and report-delivery outcomes. No new retry
loop, exit-code family, capability checklist, or readiness guarantee is added.
- Use stable resolved traversal order for checks. Stop on a dependency-blocking
local failure or failed required smoke check; retain performed results. Cache
warnings do not stop checks. No exhaustive/unperformed-check inventory is
required. Check counts on the successful path protect paid-probe deduplication.
## Stage 1: Share Invocation Selection And Local Composition
**Status:** Complete.
**Goal:** Run and the future preflight handler can select exactly the same work.
**Inspect:** `internal/cli/{run_input,execution_overrides,pipeline_run,configkit_load,
reference_selectors}.go`,
`internal/core/config`, and the existing pipeline-run/reference/override tests.
**Work:**
1. Reuse the typed run input, flag declarations, required pipeline operand, and
input checker for both commands. Rename private helpers only where clarity
warrants it. Retain native resource/execution flag builders.
2. Factor the run prefix into small invocation-local helpers: load the selected
application result/runtime settings, then resolve reference actions, effective
pipeline, shared engine when required, and offline resource dependencies.
Keep a handoff between loading and later preparation so each caller can start
requested capture before resolution/engine failures.
3. Reuse materialization, complete typed construction, input byte reading, and
session selection through the same local preparation path. Pass a capture
collaborator/context explicitly where needed. Do not allocate output/cache
state or run smoke tests in these helpers.
4. Keep run-specific cache creation, runner execution, domain publication, and
completion reporting in the run owner. Preserve existing error categories,
paths, diagnostics, supplied empties, and reference precedence.
5. Retain current loader/result/engine reuse. Do not re-load configuration or
mutate it to apply request-scoped execution overrides.
**Evidence and acceptance:** Existing run selection, explicit-empty session and
profile behavior, CLI/config reference origins, binding/unbinding, generated
reference conflicts, and lazy help/inspection behavior remain intact. Add only
missing behavioral coverage; do not test private helper arrangement.
**Validation:** `go test ./internal/cli ./internal/core/config ./internal/preflight`
when the refactor compiles. This stage fits one prompt; defer parsing/domain
extraction to Stage 2.
## Stage 2: Expose Shared Source And External-Reference Checks
**Status:** Complete.
**Goal:** Preflight can validate actual local inputs without running a pipeline.
**Inspect:** `internal/framework/pipeline/{prepare,references,runner_boundaries}.go`,
input contracts, the Seriatim adapter, production module constructors and registry
resolvers, and preparation/source/reference tests.
**Work:**
1. Extract the adapter parse plus `source.ValidateDocument` work from
`prepareRunSource` into a small pipeline-owned operation accessible through
the already constructed `PreparedPipeline`. Accept the existing parse data
and context; return the generic source document. Keep the adapter private.
2. Make the runner use that operation, retaining source debug evidence and one
source-index construction. Preflight will call the same operation after
module construction. Do not add a second parse to the run CLI or a new
persistent prepared-source object.
3. Review every selected production reference consumer. Reuse domain constructor
checks already reached by `pipeline.Prepare`, including registry decoding and
effective spell catalog validation. Where a required external-reference
check only occurs inside substantive execution, extract that specific pure
check into its domain owner and call it from shared preparation and execution.
Do not add a universal validator interface without a demonstrated need.
4. Preserve binding/unbinding and media/type requirements. Validate generated
dependencies using existing wiring/order/kind compatibility, not fabricated
generated content or empty stand-in artifacts. Generated content validation
remains at execution time.
5. Preserve caller cancellation and adapter/domain error causes. Shared checking
must not call chunk/extract/merge/normalize operations, configured candidate
validators, or output encoding to simulate preparation.
**Evidence and acceptance:** Invalid transcript data and malformed required
external references are rejected locally; valid generated handoffs need no
same-run artifacts yet. Complete module construction precedes parsing. Standalone
runner and CLI run paths keep their existing source behavior and index sharing.
**Validation:** `go test ./internal/framework/pipeline ./internal/modules/seriatim/...`
and focused tests for changed D&D reference owners. This stage is one prompt;
limit domain changes to checks needed by the accepted local-preparation contract.
## Stage 3: Discover Selected Initial Targets Without Executing Work
**Status:** Complete.
**Goal:** Produce scoped, deduplicated profile/backend selections for preflight.
**Inspect:** `ModuleSpec`, `ValidatorSpec`, resolved pipeline/validator structures,
`internal/preflight/preflight.go`, all production model declarations and their
initial request builders, and native inspection/requirements APIs.
**Work:**
1. Add a domain-neutral target inventory operation under `internal/preflight`
using the resolved selection, catalog, and shared engine. Reuse the existing
traversal of input, chunk, ordered extract/merge/normalize roles, output, and
all selected validator chains. Skip deterministic roles, unused profiles,
and unselected lanes, not selected roles whose results may be cached.
2. Distinguish initial execution prompts from continuation-only dependencies.
The current flat module `Prompts` list is insufficient to infer that role.
Add a small declarative initial-prompt selection to module specs, reusing the
constants used by request builders, and carry it only where discovery needs
it. Validator `Prompts` already denotes assessment requests. Preserve the
complete existing prompt dependency list for offline validation. Do not infer
roles from slice position, filename, or a correction prompt's default profile.
3. Resolve the actual profile through native inspection: a resolved binding's
profile selection wins; otherwise use its initial prompt's native default.
Use exact native identities. Continuation inherits its origin's target and
adds no probe; keep checking its prompt dependency. Verify the production
request builders match these declarations. A concrete custom independent
target, if present, must be represented rather than silently omitted.
4. Deduplicate by exact profile identity, retaining all associated pipeline
binding scopes. Inspect profiles for their associated backend IDs; deduplicate
those IDs and retain a first-use representative profile for native access
checks. Native smoke calls, not local merging, complete target settings.
5. For an endpoint-only profile, retain that profile as its own access-check
scope and use native profile-targeted diagnostics. Do not invent a backend ID,
group endpoints heuristically, compare credentials, or build fingerprints.
6. Return selection failures with their original native causes and meaningful
binding scope. Do not reject partial profiles in ordinary offline validation
just because online preflight will require a concrete usable target.
An unresolved model target cannot silently disappear from online readiness:
report that required check as unsuccessful. This does not make dynamic
selection invalid for ordinary run or offline dependency inspection.
**Evidence and acceptance:** A real catalog/engine fixture covers initial prompt
defaults, explicit run-wide profile selection, selected validator profiles,
shared profiles/backends, endpoint-only profiles, and an unused profile.
A correction-only different default is inspected as a dependency but not probed.
No input fabrication or provider call is needed to discover targets.
**Validation:** `go test ./internal/preflight ./internal/framework/pipeline` and
focused changed module registration tests. This stage fits one prompt; resource
metadata edits are mechanical, and smoke execution belongs to Stage 4.
## Stage 4: Orchestrate Native Smoke Checks And Interpret Observations
**Status:** Complete.
**Goal:** Convert applicable native diagnostics into a correct readiness decision.
**Inspect:** Native `SmokeTestRequest`, `SmokeTestReport`, facts and reason GoDoc,
and the Stage 3 inventory. Use a local HTTP server for built-in HTTP behavior;
an injected client alone cannot exercise native reachability/authentication.
**Work:**
1. Add a small orchestration operation under `internal/preflight`. Run
reachability and available authentication once per backend/access scope,
using its representative selected profile and supplied execution overrides.
Then request one `SmokeTestStructuredInference` per distinct profile.
Use a sequential loop; no new scheduler is needed. Do not add text inference,
full suites per operation, or a Notarius retry/admission layer.
2. Forward the same request-scoped execution override used by run. In particular,
backend probes must retain representative profile-level settings rather than
only passing `BackendID`. Every profile generation test uses its own profile,
so differing profile settings still reach native resolution.
3. Preserve omitted transient retries as nil, retaining native smoke defaults.
Forward an explicitly supplied supported count, including zero, to
`SmokeTestRequest.TransientRetries`. Producer turn, mode, structural repair,
and other execution-only controls do not manufacture smoke work.
4. Interpret returned observations, including partial reports on errors:
| Observation | Readiness treatment |
| --- | --- |
| Native operation error, cancellation, or reported execution failure | Failed required check; preserve the cause and any gathered evidence. |
| Diagnostic unsupported or known inapplicable, without an independent execution error | No readiness check entry, warning, missing-coverage claim, or replacement test. |
| Supported/applicable check unfinished, or its required result is unknown | Failed required check, not success based on nil error. |
| Reachability | Requires completed diagnostic and affirmative `EndpointReachable`. An HTTP response is reachability, not authentication success. |
| Available authentication | Requires completed diagnostic and affirmative `CredentialsAccepted`. Merely supplying credentials is insufficient. |
| Structured generation | Requires completed generation and affirmative `GenerationCompleted`, `ValidJSON`, and `SchemaMatched`. Do not require unrelated HTTP or text-inference facts. |
5. Keep native reports/attempts/usage available for debug capture separately from
the small public checks. Preserve native typed error identity. A negative
factual result with nil Go error needs an application outcome cause/message,
not provider-response prose parsing. Strict/permissive mode never changes
these verdicts.
**Evidence and acceptance:** Native HTTP/client fixtures prove successful probe
deduplication, actual request override propagation, nil-error negative/unknown
facts, unavailable capability handling, and cancellation with partial evidence.
Use independent literal verdicts and exact paid call counts where contractual;
do not reproduce PromptKit's provider test suite.
**Validation:** `go test ./internal/preflight`. This stage fits one prompt and
does not include filesystem destinations or command/report wiring.
## Stage 5: Implement Destination Access Probes
**Status:** Complete.
**Goal:** Check only invocation-relevant filesystem access, without cache effects.
**Inspect:** Existing output/file helpers, cache-mode resolution, configured roots,
`run_debug.go`, `debugbundle`, and cache/state tests.
**Work:**
1. Add an ordinary CLI-owned helper using existing creation conventions and the
standard library: create the selected output root if needed, create a temporary
access-probe file, close it, and remove it. Do not allocate a domain output run
directory or publish files. Surface creation/write/close/cleanup failure as
failed output access, retaining its cause.
2. Apply the same temporary-file pattern to the cache root only if selected work
can use it. Resolve cache behavior from actual selected bindings and overrides;
all-bypass or genuinely deterministic work needs no cache access. Auto and
refresh probe identically. Classify cache access/cleanup problems as actionable
warnings, without preventing readiness or initializing a cache store.
3. Reuse the real requested-debug allocation lifecycle, not a separate fake probe.
Stage 7 wires that allocation early in the handler and finalizes it. Debug
failures are required failures, not cache-style warnings.
4. Preserve existing directory permissions/ownership and path conventions.
Newly created destination roots may remain. Add no permission convergence,
new host-access restrictions, or claims about future access persistence.
**Evidence and acceptance:** Temporary roots verify cleanup, preserved accepted
cache bytes under auto/refresh, absence of cache access in bypass, and distinct
output failure versus cache warning behavior. Use deterministic filesystem
failures such as a non-directory ancestor; do not depend on chmod denial when
tests may run with elevated privileges. Requested debug is covered in Stage 7.
**Validation:** Focused `go test ./internal/cli` access-probe tests. This stage fits
one prompt; no new configuration or report-storage options are needed.
## Stage 6: Install The Command And Small Native Readiness Report
**Status:** Complete.
**Goal:** Both command spellings expose the complete non-capture preflight flow.
**Inspect:** `application.go`, pipeline command declarations, Stage 1 helpers,
Stage 2 parsing, Stages 3–5 operations, native reporting/outcomes, and existing
run report/delivery tests.
**Work:**
1. Install `pipeline preflight` and a native top-level `preflight` alias to that
declaration, using the shared pipeline operand, required input, flags, and
checker. Preserve all run inputs. Construction/help must remain lazy.
2. Compose local selection, reference/materialization and complete construction,
source validation, and destination checks before smoke execution. The run
path still performs no automatic smoke work. Do not call `Runner.Run` from
preflight or instantiate an accepted-result store for this command.
3. Define one command report with `pipeline`, `ready`, `checks`, and optional
`debug_directory`. Each check has `id`, structured `scope`, `result` (`passed`,
`failed`, or `warning`), human-readable `message`, and an optional stable
finding `code` where consumers distinguish reasons. Scope identifies the
relevant input/reference/binding/backend/profile/destination. Include multiple
binding associations for shared target checks without duplicate probes.
Keep native reports, credentials, and unrelated effective settings out of
this public report. Emit an empty checks collection as a collection, not a
second report variant.
4. Choose concise, stable check-class IDs; distinguish instances through scope.
Preserve those selected public field meanings in consumer tests and docs,
not incidental prose or private helper structure. Do not add an envelope,
report file, separate failures/warnings arrays, or third readiness state.
5. Accumulate performed local and provider results. A failed required check or
incomplete required work makes `ready` false; cache warnings alone do not.
Preserve existing actionable configuration/materialization diagnostics without
promoting ordinary quality signals to warnings or adding new severity policy.
6. Deliver an available assessment even when not ready, then return the proper
unsuccessful native outcome with retained causes. Early argument/loading
failures without an assessment use existing native errors. Preserve native
configuration/input versus operational categories; do not invent exit codes.
7. Supply concise default text (summary, failures, warnings), successful details
at verbose visibility, and native JSON/YAML serialization of the same value.
Let CommandKit own quiet/mode/format behavior and delivery evidence. Failed
report output must not be treated as operational success or trigger probes
again.
**Evidence and acceptance:** Both spellings share behavior. Decode successful
and failed JSON/YAML assessments, check default/verbose/quiet native behavior,
and verify malformed arguments need no inputs/state/provider calls. Required
local failures cause no paid probes; deterministic selection needs no engine
diagnostic. Existing `pipeline validate` remains offline.
**Validation:** `go test ./internal/cli ./internal/preflight`. This stage fits one
prompt by using earlier helpers; requested capture/final failure joining follows.
## Stage 7: Complete Debug Lifecycle And Failure Preservation
**Status:** Complete.
**Goal:** Requested capture records preparation and smoke evidence, with native
cancellation and independent delivery outcomes intact.
**Inspect:** `run_debug.go`, `run_capture.go`, `runInvocation.finish`, debugbundle
and recorder helpers, native smoke observation ownership, and capture/recovery tests.
**Work:**
1. Start requested debug after the configuration needed to locate its root is
available and before module resolution, engine creation, source/reference
preparation, or destination/provider checks can fail. Reuse run identity,
start-time `latest`, enable/disable precedence, and the real capture lifecycle.
2. Capture useful selected configuration through the existing secret-aware
capture helper, invocation/source/reference context, performed smoke reports,
and terminal failure/readiness. Preserve native credential omissions. Debug
names/layout remain private; do not add a preflight receipt or artifact index.
3. Finalize once on every post-allocation exit. If allocation partially succeeds,
retain the available path. Reuse mechanisms for sticky write failures and
joined operation/capture causes. Do not reuse run's publication claims or
construct extraction/output metadata simply to fit its finish method.
4. Finish capture before report delivery. A failed capture can make the command
unsuccessful independently of a completed positive assessment; a report with
`ready: true` does not override nonzero process status. Failed allocation is
itself a required debug-destination check failure when an assessment exists.
5. Pass the inherited invocation context throughout. Preserve cancellation and
native causes with any capture failure, and do not restart/continue provider
work on cancellation or retry report delivery as another preflight run.
6. Keep native smoke usage in its own retained reports. PromptKit intentionally
excludes it from ordinary execution events; do not synthesize those events,
add smoke totals to ckprompt's ordinary execution group, or introduce custom
usage flags/accounting. Native usage/report controls stay installed normally.
**Evidence and acceptance:** Cover early preparation capture, failed debug
allocation, start-time `latest`, capture disabled/explicit-empty distinctions,
cancellation plus a capture failure, and report-delivery failure without repeated
finalization/probes. Assert retained causes and useful locations, not private
capture filenames or serialization snapshots.
**Validation:** `go test ./internal/cli ./internal/core/debugbundle ./internal/framework/debug`.
This stage fits one prompt focused on lifecycle rather than probe policy.
## Stage 8: Verify The Assembled Consumer Workflow
**Status:** Complete.
**Goal:** Close cross-boundary gaps using real application composition and
simulated external providers, not another implementation-level test matrix.
**Inspect:** Existing native executable, assembled pipeline, run/reference,
recovery, and schema-loading tests; maintained D&D complete configuration and
its reference/input contracts.
**Work:**
1. Add a representative assembled command test with real ConfigKit loading,
production registries, input adapter, reference selectors, and native report
rendering. Use an ordinary valid synthetic transcript and required reference
files, as Narratio will. A local server simulates provider behavior. Adapt
maintained configuration with temporary overlay/provider settings rather
than changing production assets or requiring credentials.
2. Exercise preflight then run as separate invocations. Preflight publishes no
extraction artifacts or accepted entries; run still parses its actual input
and executes normally. A changed/invalid real input after successful fixture
preflight is still rejected by execution.
3. Cover successful shared-profile/backend counts, selected semantic validator
coverage, one representative native override including a supplied zero/empty
where supported, and exclusion of unselected work. Reuse lower-level coverage
for the remaining selection cases instead of multiplying flag combinations.
4. Verify supported/applicable negative observations, no warning for unavailable
capabilities, cache warning with readiness true, failed readiness report plus
unsuccessful exit, and native alias behavior through the assembled route.
Reuse Stage 4/6 tests where they already prove a behavior at the right boundary.
5. Review every verification row in feature-roadmap Section 5 and map it to
existing or newly added test evidence. Add tests only for consequential gaps.
Retain normal offline `pipeline validate` and ordinary run regression coverage.
**Evidence and acceptance:** Tests are deterministic, offline, secret-free, and
independent of installed live providers. Successful preflight is not asserted to
guarantee later model/domain acceptance. No live API or Narratio subprocess test
is required for the default suite or release gates.
**Validation:** `go test ./internal/cli ./internal/preflight ./internal/framework/pipeline`.
This stage fits one prompt devoted to assembled verification, not documentation.
## Stage 9: Document Commands And Consumer Operation
**Status:** Complete.
**Goal:** Document the implemented product surface for operators and consumers.
**Work and canonical owners:**
| File | Update |
| --- | --- |
| `docs/cli.md` | Command and alias; shared run inputs and preflight-specific effects; affirmative readiness checks; report/check fields, failed assessments, native statuses, and one implementation-checked structured example. Keep offline validate distinct. |
| `docs/consumers/subprocess.md` | First-class preflight-then-run invocation with references; synthetic versus real input; process status plus optional report decoding on failure. Preserve the successful-run completion protocol separately. |
| `docs/consumers/dnd-pipeline.md` | Brief optional preflight workflow using the maintained full pipeline; link to CLI and generic consumer owners rather than duplicate their contracts. |
| `docs/operations.md` | Provider contact/cost, output/cache temporary probes, cleanup, cache bypass/refresh behavior, requested debug, and remaining destination roots. Link elsewhere for syntax and report fields. |
Cross-check documentation against the assembled command/help and tests. Use
affirmative user-facing descriptions of performed checks; do not add an unsupported
capability/coverage disclaimer catalogue. Narratio's original request remains
background, with its existing link to the accepted design.
**Evidence and acceptance:** The structured report example matches the actual
serializer. Consumers can distinguish failed readiness with an available report
from early native errors, and always use process status. The preflight example
and run example preserve identical selections/references without claiming that
a fixture establishes readiness of a future transcript.
**Validation:** Run both command help routes, inspect the Stage 8 report fixtures,
verify changed local links, and run `git diff --check`. No live-provider run is
needed to verify documentation. Four focused public docs fit one prompt.
## Stage 10: Align Internal Documentation And Architecture Boundaries
**Status:** Complete.
**Goal:** Document the implemented shared preparation/native smoke boundaries in
their existing canonical homes, with narrow architecture wording changes.
**Work and canonical owners:**
| File | Update |
| --- | --- |
| `docs/internal/cli.md` | Shared selection/preparation, separate execution/smoke handoffs, command outcomes and capture ownership. |
| `docs/internal/pipeline.md` and `docs/internal/modules.md` | Shared parse/domain-check seam and small initial-target declaration, only where implementation changed. |
| `docs/internal/state.md` and `docs/internal/llm.md` | Capture/probe lifecycle and the application-specific use of native smoke results; smoke evidence remains separate from ordinary observations. |
| `docs/internal/overview.md` | Update the preflight component row and execution map to reflect implemented boundaries, without creating an architecture policy here. |
| `docs/integrations/pkg-promptkit.md` and `docs/integrations/pkg-commandkit.md` | Briefly identify the application integration of native smoke/reporting APIs and link their selected canonical upstream docs. Do not write a copy of the library manuals. |
| `docs/policy/architecture.md` | Retain offline rules for `pipeline validate` and dependency inspection; distinguish explicit online preflight, its allowed input/probe/capture effects, and pipeline-owned readiness interpretation. Revise the broad statement that capture belongs only to run. Preserve provider/config/CLI ownership and all unrelated constraints. |
Update only affected sections, keeping these changes concise. No new ADR is
needed for this explicit command within the existing native-kit ownership
decisions. Link upstream for native APIs and keep invocation syntax/report
contracts in `docs/cli.md` rather than repeating them in internal guides.
**Evidence and acceptance:** Current implementation maps, offline inspection
language, capture ownership, and target-selection declarations are accurate.
Architecture still permits input-free/provider-free offline validation and
shared storage-free loaders, while explicitly permitting the accepted online
preflight effects. No unrelated invariant or safety contract is strengthened.
**Validation:** Review changed passages against their actual code owners and
tests; check affected local links and `git diff --check`. This is one prompt of
narrow cross-document edits, not a rewrite of the documentation suite.
## Stage 11: Verify End-To-End Completion
**Status:** Complete.
**Goal:** Complete the sprint with full code, documentation, and scope verification.
Review every requirement in `preflight.md` against implementation and test
evidence. In `docs/roadmap/future.md`, point feature context to `preflight.md` and
sequencing to this plan. Update implementation status only after successful
verification; do not delete planning documents unless requested.
Run the final checks using the selected Go toolchain and normal repository setup:
```sh
go test ./...
go vet ./...
go build ./cmd/notarius
go run ./cmd/notarius help pipeline preflight
go run ./cmd/notarius preflight --help
go run ./cmd/notarius pipeline validate dnd-session --config examples/dnd-complete/config.yml
```
The last command stays offline; do not run the maintained configuration's new
online preflight against a real provider as a mandatory check. Verify local
Markdown links in changed documents, run `git diff --check`, and inspect
`git status --short` for accidental binaries, captures, credentials, or generated
data. Remove only build outputs created by this sprint when appropriate.
**Final acceptance:** All feature-roadmap requirements have corresponding code
and verification evidence; both command spellings work; ordinary run and offline
validation retain their contracts; native target/override/fact semantics are
honored; no accepted cache state is consulted or changed by preflight; capture,
cancellation, and delivery failures retain causes; current documentation matches
the implementation. Record remaining concrete gaps instead of declaring the
feature complete on partial test evidence. This final stage is one prompt.
## Open Questions
None. The accepted product decisions are complete. Private helper names, capture
layout, and check-class identifiers may be selected during implementation within
the contracts above; they do not require another product-design decision.
[smoke-api]: https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/smoke_diagnostics.go
[inspection-api]: https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/resource_inspection.go
[promptkit-consumer]: https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/consumers/pkg-promptkit.md
[reporting]: https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.8.0/docs/consumers/guide.md#invocation-reporting

View File

@@ -1,9 +1,10 @@
# Feature request: pipeline-aware preflight for Narratio
This is the original consumer request, retained as context. The accepted
[Pipeline Preflight Implementation Roadmap](preflight.md) owns the implementation
plan and subsequent design refinements, including native capability handling and
the simplified readiness report.
This is the original consumer request, retained as context for the completed
preflight work. The current [CLI contract](../cli.md#preflight) and
[subprocess guide](../consumers/subprocess.md#prepare-and-run) describe the
implemented behavior, including native capability handling and the simplified
readiness report.
## Purpose

View File

@@ -1,228 +0,0 @@
# Pipeline Preflight Feature Roadmap
## Purpose And Status
**Status:** Implemented and verified.
This roadmap defines the target behavior and accepted product decisions for
pipeline-aware preflight. There are no remaining open product decisions.
[Implementation Plan](implementation.md) owns sequencing and implementation tasks.
[Narratio's original feature request](narratio-feature-request.md) remains context.
The accepted design here governs implementation where it refines that request,
including the simpler treatment of native capabilities and readiness reporting.
Current behavior remains documented in [CLI Reference](../cli.md),
[CLI Internals](../internal/cli.md), and [Operations](../operations.md); this
roadmap records the accepted feature context; those canonical documents describe
the implemented command.
Private helper types, observer wiring, debug filenames, and exact check
identifiers remain implementation choices within the accepted contracts.
## Accepted Direction
- Notarius owns readiness for its selected pipeline, including relevant provider
targets and interpretation of native diagnostic observations. Narratio should
not reconstruct those decisions or supply a duplicate profile inventory.
- Add `notarius preflight PIPELINE_ID` with the same invocation inputs as `run`.
Provide `pipeline preflight` with the top-level spelling as a native alias.
Preserve defaults, precedence, path origins, and supplied-value distinctions.
- Keep `pipeline validate` as the existing offline configuration/dependency check.
New preflight explicitly permits input reads, destination probes, provider
contact, smoke inference costs, and requested debug capture.
- Share run declarations, selection, reference binding, and applicable preparation
logic. Do not run extraction and interrupt it as a substitute for preflight.
- Use native PromptKit diagnostics and CommandKit reporting/outcomes. Keep provider
mechanics upstream; consider an upstream addition if required observations or
target resolution cannot be obtained cleanly through native APIs.
- Do not publish extraction artifacts or populate, refresh, invalidate, or use
accepted cache entries as proof of present provider readiness.
- A supplied synthetic transcript is ordinary input. Readiness covers that input,
not a future real transcript; execution still validates its own input.
- A small machine-readable readiness report is the command's product, not a new
execution ledger, persisted receipt, or reporting sidecar system.
## 1. Required Checks And The Meaning Of Ready
Preflight validates that the selected pipeline is coherent and satisfied by the
supplied inputs, then runs the available, applicable native PromptKit smoke checks
against the backends/profiles implicated by that pipeline. This affirmative
contract is sufficient for user documentation; no catalogue of substantive
execution behavior outside preflight is needed.
| Area | Required check |
| --- | --- |
| Configuration and selected work | Valid effective selection, module options, lane selection, static prompt/profile dependencies, and binding compatibility. |
| Supplied input and external references | Readable input accepted by its input adapter; required external references accepted by their domain owners after run-equivalent binding/unbinding. |
| Generated dependencies | Valid producer/consumer wiring and compatibility. |
| Provider targets | Available, applicable native PromptKit smoke checks against the selected backends/profiles. |
| Output and requested debug | Practical access checks for destinations required by the invocation. |
A failed required check or inability to complete it, including cancellation,
produces unsuccessful readiness. Native diagnostic observations still require
interpretation: a diagnostic finishing without a Go error does not necessarily
mean its check passed.
An unavailable backend diagnostic capability is neither a failure nor an omission.
For example, absence of a native authentication check needs no compensating proof,
warning, or coverage disclaimer. Run the applicable checks PromptKit provides;
do not introduce a Notarius capability checklist that a backend must satisfy
beyond those native diagnostics.
Cache access problems warn rather than fail preflight, consistent with execution's
best-effort cache policy; bypass requires no cache access. Output and requested
debug destination failures remain failures.
Producer strict/permissive mode does not change the smoke-check verdict or turn
failed checks into success through fallback. Preflight performs its own defined
checks; producer fallback belongs to substantive pipeline execution.
## 2. Effective Target Discovery And Probe Coverage
Use the effective invocation to identify profiles implicated by selected work,
including model-backed chunking, extraction, normalization, validators, and any
other selected model roles. Build a deduplicated profile list and a deduplicated
list of their associated backends. Exclude unused configuration profiles and
unselected lanes; cached acceptance does not remove a selected profile from testing.
Run native reachability and available authentication checks once per backend,
then one native structured-generation test per distinct profile. Do not add a
separate text-generation test or run the full smoke suite per operation. Multiple
operations sharing a profile share its generation test; profiles sharing a backend
share backend access checks. Retain associations to the relevant pipeline bindings
for reporting. Unavailable checks follow Section 1's accepted semantics.
Use native PromptKit resolution and smoke APIs. Correction normally inherits its
originating execution target and adds no separate profile test; still validate its
prompt dependency. Any supported custom target change must be represented through
its actual selection. Endpoint-only profiles remain supported by native
profile-targeted diagnostics. Account for profile-level target settings through
native resolution rather than assuming all settings come from the named backend.
Avoid a general target-equivalence/fingerprint subsystem or credential comparisons.
Share the configuration result and invocation selections used by run. In the
current architecture, ConfigKit resolves configuration sources and configuration
assignments; ckprompt execution flags such as `--llm-model` and `--llm-endpoint`
remain request-scoped overrides, not mutations of that configuration. Forward
those same supplied overrides to native smoke requests so tests exercise the
intended invocation. Flag behavior follows Section 3.
Verify existing module declarations and selections during implementation. Reuse
existing information wherever sufficient; expose a small side-effect-free shared
target-selection operation only for concrete callers needing it. Do not fabricate
generated artifacts or execute substantive stages to discover targets. Escalate
concrete native target-resolution gaps upstream rather than duplicate resolution.
## 3. Shared Preparation, Input Validation, And Side Effects
Share ordinary local preparation between run and preflight: configuration and
invocation selection, lane/reference binding and module options, prompt/profile
dependency checks, module construction, input reading/parsing through its adapter,
and external-reference materialization/validation through its domain owners.
Extract reusable domain-owned checks where validation currently lives inside
execution; do not duplicate integration rules in the CLI. Validate generated
producer/consumer wiring and compatibility during preparation, and generated
content when execution produces it.
Use ordinary shared helpers with a clear handoff to pipeline execution or native
smoke orchestration. Complete local input, reference, and destination checks before
paid smoke checks. Shared preparation does not invoke smoke tests automatically
for run. No general preparation framework or persistent prepared-invocation record
is needed. Run continues to validate its own invocation and inputs.
| Destination | Preflight behavior |
| --- | --- |
| Output | Create the root if needed, write a temporary access-probe file, then remove it. Failure fails preflight. |
| Requested debug | Allocate a real debug session through the existing capture lifecycle. Failure fails preflight. |
| Cache used by selected work | Probe access with a temporary file; problems produce warnings. |
| Cache with bypass | No cache access. |
Probes clean up their own files; newly created destination directories may remain.
Auto and refresh have the same preflight access behavior, without reading or
modifying accepted cache entries. No cache-store initialization is needed merely
to probe access. Preflight publishes no extraction artifacts.
Share argument declarations and preserve defaults, precedence, and explicit-empty
distinctions. Configuration, input, lane, and reference controls select checked
work; profile and applicable execution overrides flow into native smoke requests;
output/cache controls select destinations and access behavior. Execution-only
controls remain accepted without manufacturing corresponding preflight work.
Formatting, verbosity, quiet mode, and usage reporting remain native. Preserve
PromptKit's smoke retry defaults when omitted and forward explicitly supplied,
supported overrides without another retry loop. Genuinely deterministic selected
work needs no provider calls.
Start requested debug capture early enough to record preparation failures, update
`latest` at session start, and finalize through the existing lifecycle. Capture
effective selection, useful input/reference diagnostics, native smoke results,
and failures. Reuse native observations for usage and preserve cancellation and
capture failure causes. Private capture filenames remain implementation choices.
## 4. Reports, Outcomes, And Consumer Contract
Emit one small command-specific readiness report through CommandKit, accompanied
by the ordinary process exit status:
| Field | Meaning |
| --- | --- |
| `pipeline` | Selected pipeline ID. |
| `ready` | Whether all required checks completed successfully. |
| `checks` | Results of performed checks, including actionable warnings. |
| `debug_directory` | Capture location when available. |
Each check has a stable identifier, relevant scope, a result (`passed`, `failed`,
or `warning`), and a human-readable message. Scope identifies the relevant input,
binding, backend, profile, or destination. Supply stable finding codes where
consumers need to distinguish failure reasons. Consumers need no prose parsing or
provider-specific interpretation to determine readiness. Keep native diagnostic
detail in debug capture; do not duplicate failures and warnings in separate lists.
Exact identifiers and field representation within checks remain implementation
choices consistent with this contract.
Readiness is true when all required checks complete successfully, and false when
any required check fails or cannot complete. Cache warnings do not prevent
readiness. Unavailable native capabilities add no invented check or warning.
Retain useful results gathered before failure without adding a hypothetical or
unperformed-check inventory. No third overall partially-ready state is needed.
When an assessment is available, report it even when readiness is false, then
return an unsuccessful outcome. Failures before an assessment can be constructed,
such as malformed arguments, use native error handling. Consumers check process
status, decode an available structured report for assessment details, and use
stderr for native explanations when no usable report is available. A ready report
does not override a nonzero status: capture or delivery can fail independently.
Preserve native exit classifications, cancellation, credential omissions, and
operation/delivery causes rather than adding preflight-specific exit codes.
Default text gives a concise ready/not-ready summary and actionable failures and
warnings; verbose presentation includes successful check details. JSON and YAML
serialize the same report value. Quiet mode and diagnostic routing remain native.
Do not introduce a schema-version envelope, saved receipt, mandatory sidecar, or
report-storage option. Consumers can save stdout when they need a record.
## 5. Verification And Documentation Requirements
Verify Notarius orchestration with real internal components and simulated
providers. Canonical documentation describes the feature when implemented;
the implementation plan owns that documentation handoff.
Use existing configuration loading, registries, input adapters, and temporary
files. Simulate external provider contact with a small fake provider or local HTTP
server. Default tests remain deterministic, offline, and credential-free. Optional
live-provider checks are manual verification, not ordinary test or release gates.
| Behavior | Required evidence |
| --- | --- |
| Selection equivalence | Run and preflight honor the same lane/reference selections, profile defaults, and supplied overrides, including explicit empty values where supported. |
| Target coverage and deduplication | Selected producer and validator profiles are covered; shared profiles/backends are checked once at their respective scope; unused targets are excluded. Unavailable native capabilities add no failure. |
| Native observations | Actual failed or incomplete required observations fail readiness even when the diagnostic returns no Go error. |
| Local preparation | Malformed supplied input or references fail before paid probes; generated dependencies are checked through wiring and compatibility. |
| Destinations and cache | Output/debug failures fail readiness, cache problems warn, bypass avoids cache access, temporary probes are cleaned up, and accepted entries remain unchanged under auto and refresh. No extraction artifacts are published. |
| Consumer outcomes | Successful and failed assessments produce the expected report and process outcome; early native errors, cancellation, and capture/delivery failures retain useful causes. |
| Assembled command | A representative command-level workflow exercises real composition and native rendering with simulated provider contact, including the native alias. |
Use independent expected outcomes and existing tests where sufficient. Assert
exact provider call counts where they protect the agreed deduplication of paid
checks. Test observable behavior rather than private helper structure, incidental
wording, or debug filenames. Do not duplicate upstream provider suites or build
an exhaustive matrix of every flag combination. Follow [Testing Policy](../policy/testing.md).

View File

@@ -1,379 +0,0 @@
# Pipeline Preflight Review Remediation
All five findings are implemented and individually verified. The audit text below
is retained as context; each finding's completion marker records its resolution.
## Scope And Overall Assessment
Reviewed implementation commit `c08e5ab` against all eleven stages of
[Implementation Plan](implementation.md) and the accepted
[Preflight Feature Roadmap](preflight.md).
A follow-up integration audit at `ab44543` reviewed those stages against the
existing run, configuration, source, reference, cache, capture, and reporting
paths. Findings 1 and 2 remain open; Finding 3 records the additional result.
An algorithmic audit at `3df1a53` adds Findings 4 and 5. It preserves algorithms
explicitly selected during planning and uses source-level complexity analysis,
not production measurements or latency estimates.
The intended architecture is in place. Run and explicit preflight share local
selection and construction; prepared adapters own source parsing; domain owners
validate references; `internal/preflight` discovers selected targets and
interprets native smoke evidence. The CLI owns destination probes, requested
capture, and native readiness reporting. Offline pipeline validation remains
offline. Preflight neither executes the substantive pipeline nor initializes
an accepted-result cache store.
Five follow-ups are warranted: consistent error propagation at the smoke observer
boundary, narrow documentation corrections, consistent handling of marked
sensitive runtime parameters in invocation capture, linear target association
building, and avoiding disabled-capture work. No unintended strengthening of
permissions policy, provider capability requirements, retry budgets, or readiness
guarantees was found. Keep the accepted scope unchanged while remediating.
## Finding 1: Preserve Smoke Observer Errors Independently Of Readiness
**Status: Complete.** Observer and diagnostic errors are joined consistently;
readiness now follows completed native checks independently of recording failure.
Focused smoke/preflight tests pass, including final/combined failures and stopping
before an unchecked profile.
Cancellation during the final observation is also retained at both the smoke
boundary and the command's readiness handoff, without altering the native verdict.
**Priority:** P2 — error handling and separation of responsibilities.
**Affected owners:**
[smoke orchestration](../../internal/preflight/smoke.go), particularly
`RunSmokeChecksObserved` lines 43–48, and the assessment/finalization handoff in
[the preflight command](../../internal/cli/pipeline_preflight.go).
Related plan stages: 4, 6, and 7.
The observer's error is returned only when the diagnostic itself succeeded and
another diagnostic remains. Consequently:
- A failing observer on the final successful diagnostic is silently discarded:
the helper returns a nil error.
- If a diagnostic and its observer both fail, the helper returns only the
diagnostic error, losing the observer error at this boundary.
An offline review test with one successful structured smoke request and an
observer returning a sentinel error reproduced the first case: one observation
was returned with `err == nil`. A final observer returning cancellation has the
same error-loss problem.
The current CLI's sticky recorder normally recovers capture failures during
`Finalize`; the existing capture tests confirm that those failures still yield
an unsuccessful command. This is not a claim that current CLI capture failures
silently succeed. The problem is that the generic smoke helper depends on a
particular caller's recorder behavior and discards an explicit callback error to
influence the caller's readiness calculation. That makes the error contract
surprising and couples orchestration to presentation/disposition.
### Required Change
- Retain errors returned by the observer consistently, including on the final
check and alongside a diagnostic failure. Ordinary wrapping or `errors.Join`
is sufficient; preserve `errors.Is`/`errors.As` identity.
- Keep the native diagnostic verdict on its observation distinct from errors
recording that observation. Retain the collected observations when returning
an error, and stop additional diagnostics when recording fails.
- Let the CLI determine assessment completion from performed diagnostic results
and whether required checks remain, separately from capture/command failure.
A completed positive assessment may still report `ready: true` with nonzero
command status when capture fails, as already agreed. An interrupted sequence
with required checks remaining must not claim readiness.
- Remove the need to suppress callback errors based on their position in the
sequence. No new retry loop, error hierarchy, persisted state, or public report
variant is needed.
### Verification
Add focused tests for a final observer failure and simultaneous diagnostic and
observer failures, checking original error identities. Retain the existing
early-capture-stop, cancellation/capture, and positive-assessment/failed-capture
tests. Verify that additional paid checks do not start after an observer
failure and that report delivery/finalization are not repeated.
## Finding 2: Correct Two Remaining Documentation Boundaries
**Status: Complete.** Capture ownership now names both commands, and substantive
acceptance/fallback guidance is again a subsection of the run lifecycle.
Heading hierarchy and affected link targets were reviewed; whitespace checks pass.
**Priority:** P3 — documentation accuracy and clarity.
Related plan stages: 9 and 10.
1. [Run State Internals](../internal/state.md), lines 131–133, still says that
the run path alone calls `debug.Start`. Explicit preflight now calls the same
allocation lifecycle through `startRunDebug`, as the preceding paragraph
correctly states. Describe both invocation owners and keep shared loaders
storage-free.
2. [Operations](../operations.md), lines 147–187, inserts the new top-level
`Preflight Lifecycle` section before the existing `Acceptance And Fallback`
subsection. This makes substantive run acceptance, semantic continuation, and
permissive artifact fallback appear to be part of preflight. Move the
preflight section after that run subsection, or otherwise restore the run
subsection's correct parent. Preserve the explicit distinction that producer
fallback does not change preflight's smoke verdict.
### Verification
Review the resulting heading hierarchy and capture-owner wording against the
implemented command. Check affected links and `git diff --check`; no prose
snapshot tests or additional upstream-library documentation are needed.
## Finding 3: Apply Existing Sensitive-Parameter Handling To Invocation Context
**Status: Complete.** Both commands use shared early context capture that omits
raw provider-parameter maps. Raw operation-request evidence uses the same
projection; target-aware native evidence still retains masked effective values.
Regression tests scan both commands' captures on success and early failure,
verify actual provider values are unchanged, and retain ordinary settings.
**Priority:** P2 — integration with the established capture contract.
Related plan stages: 1, 4, and 7.
**Affected owners:** Early context writing in
[the preflight command](../../internal/cli/pipeline_preflight.go), line 108,
and [the run command](../../internal/cli/pipeline_run.go), line 67, plus the shared
[capture helpers](../../internal/cli/run_capture.go).
Preflight copies the run path's direct serialization of
`input.Overrides.Execution` into `context.json`. This includes raw
`--llm-extra-params` values. That bypasses both ConfigKit's secret-aware effective
configuration writer and the selected-target masking used for native evidence.
A temporary offline regression test selected a profile with an `extra_params.token`
field marked sensitive by the existing definition, then supplied a different
synthetic value for that same field through `--llm-extra-params`. The provider
fixture confirmed that the intended runtime override was used. Capture contained:
| Capture surface | Result |
| --- | --- |
| Effective application configuration | Sensitive field redacted. |
| Native preflight smoke report | Sensitive runtime value redacted. |
| Preflight invocation context | Sensitive runtime value present verbatim. |
| Ordinary run invocation context | Same sensitive runtime value present verbatim. |
The assertion that the marked value is absent from retained context failed for
both commands. Thus this is a pre-existing run pattern propagated into the new
feature, rather than a defect in native smoke-report redaction. It affects
explicitly enabled debug capture, not the public readiness report.
The existing [architecture policy](../policy/architecture.md#state-output-and-safety)
already requires preserving marked-secret handling and native credential
omissions. This finding requests consistency with that contract, not a new
threat model or a claim that debug bundles sanitize arbitrary application data.
### Required Change
- Reuse a small common context-capture helper for run and preflight, so the two
invocation owners do not independently serialize raw runtime parameter maps.
- Keep early capture available before pipeline/target selection. Omit raw
`ExtraParams` values from that early record and retain supplied-state metadata
when useful. Detailed effective parameters can remain in the existing native
evidence, where selected-profile/backend marks are already applied.
- Preserve the existing native evidence path's redaction of marked parameters
and retention of ordinary non-sensitive settings. Do not mutate the values
passed to PromptKit or add provider calls/configuration loads to capture them.
- Use established sensitivity metadata; do not add heuristic scanning of source,
references, prompts, responses, arbitrary strings, or provider parameter names.
No new configuration restrictions, permission rules, or logging subsystem is
needed.
### Verification
Add a shared capture-boundary regression for both commands using synthetic
marked runtime parameters. Assert that the provider receives the intended
value while the retained context does not contain it; verify marked native
settings remain redacted and ordinary settings are still retained. Exercise an
early preparation failure as well as successful execution, since early capture
must not depend on later native evidence becoming available. Prefer content and
immutability assertions over full snapshots of the private capture layout.
## Finding 4: Build Target Associations With Ordered Sets
**Status: Complete.** Ordered scope slices now use companion membership sets;
invocation-local maps reuse prompt defaults and profile/access indexes. Association
insertion is expected-linear without changing native probe identity or ordering.
Tests cover distinct profiles sharing a backend, shared profiles, multiple initial
prompts, duplicate bindings, endpoint-only selections, and scoped failures.
**Priority:** P2 — scalability; plan Stage 3.
**Owner:** [Target discovery](../../internal/preflight/targets.go), especially
`DiscoverTargets` and `appendScope`.
Let `A` be the number of selected role/initial-prompt associations visited by
discovery, `P` the distinct selected profiles, and `K` the distinct access scopes.
The outer profile/backend lookup maps are appropriate, but `appendScope` scans
the complete accumulated binding slice on every insertion. For `B` distinct
bindings sharing one profile and backend, each slice performs
`0 + 1 + ... + (B-1)` comparisons. The two slices together perform `B(B-1)`
comparisons: **Theta(B²)** even though there are only Theta(B) associations to
return. The same backend-list problem exists when many distinct profiles share
one backend.
Discovery also calls native `InspectProfile` before consulting its existing
profile map, so a shared profile is inspected once per association rather than
once per profile. Repeated initial prompts without an explicit profile likewise
repeat `InspectPrompt`. These return detached resource views; that repeated
inspection/copy work is unnecessary for the invocation's fixed captured engine.
### Refactoring Opportunity
- Retain ordered result slices and companion membership sets keyed by the
comparable `BindingScope` value for each profile/access target. Insert into
the slice only when absent from its set. This gives expected **O(A)**
association-building time and **O(A + P + K)** bookkeeping space, preserving
exact deduplication and first-use ordering.
- Reuse successful profile selection/backend association data once each profile
is inspected. Memoize an initial prompt's default-profile lookup within this
discovery call where it repeats. Native inspection calls can then be bounded
by distinct selected resources rather than associations. Keep the small needed
identities/indexes, not an application-owned replacement resource registry.
- Preserve per-binding cancellation checks, error scope, endpoint-only behavior,
and the native provider-check schedule. Do not introduce process-global caches,
target fingerprints, altered profile equivalence, or different paid probes.
The roadmap specifies deduplicated targets and retained associations, not linear
slice scans as the required implementation. This optimization preserves the
accepted algorithmic policy. Native inspection's own cost is additional to the
association bound above; no upstream cost or real-world speedup is assumed here.
### Verification
Use independent expected ordered associations for shared-profile,
shared-backend/different-profile, and duplicate-binding/multiple-prompt cases.
Retain the existing target and native probe-deduplication tests. Verify the
complexity improvement by reviewing the map-based insertion path; wall-clock
thresholds and production benchmarks are unnecessary.
## Finding 5: Skip Evidence Preparation When Capture Is Disabled
**Status: Complete.** Disabled capture now passes a nil smoke observer and never
constructs the evidence writer or its mask indexes. Enabled capture retains the
same evidence lifecycle. Focused enabled/disabled command, capture-failure,
native-verdict, and provider-count tests pass.
**Priority:** P3 — avoidable work; plan Stage 7.
**Owner:** [Preflight command](../../internal/cli/pipeline_preflight.go), lines
180–190, and [evidence writer construction](../../internal/cli/run_capture.go).
`executePreflight` constructs `newRunEvidenceRecorder(capture, loaded.result)`
and supplies its observation callback unconditionally. With capture disabled,
the underlying recorder ultimately discards writes, but the work before that
no-op boundary still happens:
- Construction enumerates all `H` historical configuration paths and all `R`
configured profiles/backends, including unselected resources, to build masks.
This entails at least **Omega(H + R)** capture-specific traversal work and
temporary indexing, in addition to the native metadata API's own costs.
- Every smoke report still passes through target masking, which can copy
parameter maps for marked fields, even though none will be written. For `S`
reports with `M` matching top-level marks over `E` parameter entries, that
existing per-mark shallow-copy path can perform **O(S * M * E)** extra work.
The ordinary run path already avoids constructing this writer when capture is
disabled. The new preflight call site bypasses that guard.
### Refactoring Opportunity And Verification
Construct the evidence writer and install its callback only when capture is
enabled; otherwise pass a nil observer to `RunSmokeChecksObserved`. Its native
observations still return normally for readiness interpretation. This reduces
disabled-capture evidence preparation to **O(1)**, excluding required smoke
execution, report construction, and the earlier configuration load.
Keep active capture's masks, failure propagation, and native usage separation
unchanged, including Findings 1 and 3's required behavior. Do not change the
shared helper merely to forbid existing standalone/test uses of a nil recorder.
Use existing enabled/disabled preflight tests to verify identical readiness and
provider-call behavior with no debug files when disabled. No performance threshold
or new instrumentation framework is needed. This finding does not require
redesigning the pre-existing active-capture masking algorithm.
## Stage-By-Stage Review Evidence
| Plan stage | Review result |
| --- | --- |
| 1 — Shared invocation preparation | Both commands use the same flags, loading, reference selection, resolution, materialization, construction, input reads, and session selection. Run retains its execution/publication owner. Existing selection/regression tests pass. |
| 2 — Source and reference checks | `PreparedPipeline.ParseSource` is shared with the runner; document validation and cancellation remain adapter/framework-owned. The runner builds its index once. Constructors retain domain reference checks; a full configured D&D preflight accepts generated dependencies without fabricated artifacts. |
| 3 — Target discovery | Explicit initial-prompt declarations separate independently selected requests from correction dependencies. Native inspection selects profiles; exact identities deduplicate profile/backend scopes, retaining bindings. Endpoint-only profiles and selected validators are covered. |
| 4 — Native smoke orchestration | Access checks and structured generation are deduplicated, native overrides/retries are forwarded, and actual facts determine verdicts. Unsupported/inapplicable capabilities add no failed check or warning. Finding 1 concerns observer error propagation. |
| 5 — Destination probes | Standard-library temporary probes are cleaned up; output failure and cache warnings have different dispositions. Auto/refresh leave accepted entries unchanged; bypass/deterministic work avoids cache access. No permission convergence was added. |
| 6 — Command and report | Both native command spellings work. Text/JSON/YAML and unsuccessful assessments use CommandKit reporting; quiet/verbose and presentation failures retain native behavior. Assessment disposition needs the narrow adjustment described in Finding 1. |
| 7 — Capture and causes | Requested capture starts before selection/engine work, updates `latest`, and finalizes before reporting. Existing tests retain cancellation and sticky capture causes, including a positive assessment with failed capture. Finding 1 removes the lower helper's reliance on that sticky mechanism. Finding 3 addresses raw invocation context bypassing the existing sensitive-parameter treatment. |
| 8 — Assembled verification | Existing real-kit/local-provider tests pass. An additional temporary offline test exercised the unabridged maintained D&D pipeline, its ordinary transcript/reference inputs, generated handoffs, and selected target discovery; it passed with one shared-profile model call and no substantive execution. |
| 9 — Public documentation | Command/report and subprocess workflows are documented, including fixture scope and process-status handling. Finding 2 corrects the Operations hierarchy. |
| 10 — Internals and architecture | Native ownership, shared parsing, online versus offline boundaries, and smoke usage separation are documented. Finding 2 corrects the stale run-only capture sentence. No unrelated architecture restriction was introduced. |
| 11 — Final verification | Tests, vet, build, both help routes, and offline validation succeed. Correctness/documentation findings and the additional algorithmic opportunities above remain recorded for remediation. |
## Algorithmic Audit Coverage
| Plan stage | Algorithmic assessment |
| --- | --- |
| 1 — Shared preparation | The extraction preserves the prior configuration/selection/materialization algorithms; no additional nested scan was introduced by the shared handoff itself. These deliberately reused algorithms were not redesigned. |
| 2 — Parsing | Parsing/document validation is shared without a duplicate run parse; source-index construction remains once per run. No new algorithmic defect identified. |
| 3 — Discovery | Finding 4 identifies quadratic binding accumulation and repeated resource inspections; hash-indexed target lookup itself is appropriate. |
| 4 — Smoke checks | Sequential iteration is O(P + K) orchestration, excluding native calls and returned evidence. The agreed once-per-access/once-per-profile schedule and native retries are retained, not reconsidered. Finding 1 already covers the callback error issue. |
| 5 — Destinations | Cache-use detection is linear in selected lanes and temporary-file probes are bounded per destination. Repeated constant-count scans do not make this quadratic. The filesystem policy is unchanged. |
| 6 — Readiness report | Check accumulation and rendering use linear passes; serializing associated bindings is proportional to emitted data. No additional asymptotic issue identified. |
| 7 — Capture | Finding 5 removes work for disabled capture. Findings 1 and 3 retain the previously established correctness fixes; no new capture algorithm or security policy is proposed. |
| 8 — Tests | Existing tests express native verdicts, scopes, and probe counts. Future verification should protect these behaviors without timing assertions. |
| 9 — Public docs | No runtime algorithm introduced; the earlier documentation finding remains unchanged. |
| 10 — Internal docs/policy | No runtime algorithm introduced and no reconsideration of accepted native ownership or capability policy. |
| 11 — Verification | Source-level complexity analysis and focused tests suffice for these opportunities; no live-provider or real-world performance collection was needed. |
## Follow-Up Integration Audit Evidence
- Stages 1–2: Compared extracted loading/selection/preparation and parsing against
the original run path. Existing source-relative path, selector specificity,
unbinding, generated-reference, session/profile override, construction-order,
and source-index regression tests pass without cached test results.
- Stages 3–4: Checked initial/correction/validator target selection against actual
request builders and native override handling. Existing native smoke facts,
deduplication, endpoint-only profile, and typed-cause tests pass. No additional
target-resolution or provider-ownership conflict was found.
- Stage 5: An additional real-cache round trip ran a pipeline, performed both
auto and refresh preflight, and ran the pipeline again with auto reuse. Both
preflights left accepted cache bytes unchanged, each performed a smoke call,
and the subsequent run reused the original acceptance without new producer
calls. Output and cache file-placement helpers introduce no conflicting root
or permission treatment in these paths.
- Stages 6–7: Compared native outcome/delivery evidence and capture ownership
with ordinary run. Findings 1 and 3 identify the remaining error-propagation
and parameter-capture inconsistencies; no duplicate execution, publication,
or ordinary usage accounting was introduced.
- Stage 8: Ran the additional round-trip and marked-parameter reproduction tests
through a temporary Go overlay using real application configuration/registries
and a fake model client. Only the new sensitive-context assertion failed.
- Stages 9–11: Checked the new consumer/report guidance against the existing
subprocess protocol, configuration ownership, debug policy, and offline command
boundary. Finding 2 remains the narrow documentation correction; no additional
contract conflict was identified. The normal full test suite and vet pass.
## Checks Run During Review
- `go test ./...`
- `go test -count=1 ./internal/cli ./internal/preflight ./internal/framework/pipeline`
- `go test -race ./internal/preflight ./internal/cli -run 'TestPreflight|TestSmoke' -count=1`
- `go vet ./...`
- Built `./cmd/notarius` to a temporary path outside the repository.
- Exercised `help pipeline preflight`, `preflight --help`, and offline
`pipeline validate dnd-session --config examples/dnd-complete/config.yml`.
- Temporary Go-overlay tests exercised the full D&D preflight and the terminal
observer-error case without modifying application or permanent test files.
- The follow-up audit reran uncached tests for CLI, preflight, configuration,
pipeline, file I/O, debug allocation, and accepted-result cache packages, plus
`go test ./...` and `go vet ./...`.
- Additional temporary integration tests passed the run/preflight/cache round
trip and reproduced Finding 3 with a failing marked-context assertion in both
command paths. They used synthetic placeholders, not actual credentials.
- The algorithmic audit reran `go test ./internal/preflight ./internal/cli`
successfully. Findings 4 and 5 follow from source-level operation counts and
control flow; no benchmark or live-provider measurements were collected.
No live provider calls or real credentials were used. Artifacts and accepted cache
entries exercised by the round-trip tests were synthetic temporary fixtures;
no production state, application code, or permanent test files were modified.