diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md deleted file mode 100644 index f04453d..0000000 --- a/docs/roadmap/implementation.md +++ /dev/null @@ -1,560 +0,0 @@ -# Scriptorium adoption implementation plan - -## Objective and Baseline - -Implement [the Scriptorium roadmap](scriptorium.md) in one end-to-end sprint. -The roadmap owns scope, target behavior, and inspection policy. This plan owns -the implementation sequence. Audita adoption and session workspace reorganization -remain separate pending work. - -Planning baseline: Narratio commit -`b9d56b89234bf52944b69e09029f63c44268872d`. Target the Scriptorium v0.16.0 -CLI at `0fa538c336fd64be51bc355fd53d3ca19f104d68`. Use the upstream links in -the roadmap for canonical CLI, configuration, and requirements contracts. -Scriptorium remains an independently installed subprocess; no PromptKit or -Scriptorium Go dependency is needed. - -Audience: a Luna coding agent implementing one numbered stage per prompt, in -order. Each stage is a bounded unit with its own reading and verification scope. -Intermediate stages may leave call sites or tests temporarily uncompilable. -Complete the native cutover directly; temporary compatibility APIs and dual CLI -paths are unnecessary. Record outstanding downstream call-site work accurately. -The final stage verifies the complete repository. - -## Working Rules - -- Start with `docs/development.md` and `docs/policy/agents.md`. Apply architecture, - testing, and documentation policy to the corresponding changes. Read each - stage's focused sources and tests rather than unrelated subsystems. -- Use the maintained Go 1.27.4 toolchain. Run the focused checks listed below - when the affected packages compile. A temporary compilation dependency on a - later stage is acceptable; report it and rerun the checks after integration. -- Use existing native library behavior and Narratio planners. ConfigKit continues - to own final configuration acquisition; Scriptorium owns its private prompt, - profile, backend, and resource resolution. -- Preserve source/binding identity distinctions, variable-based session routing, - stage output validation, atomic canonical promotion, per-artifact checkpoints, - force semantics, and manifest-authoritative reuse. -- Preflight checks intended bindings before generated files exist. It makes no - model calls. Its success does not certify future file contents or generation. -- `session plan` remains independent of subprocess inspection. Configuration - inspection, help, completion, and unrelated stage ranges retain their current - dependency behavior. -- Follow the existing commit policy for completed reviewable units. Finalize - temporary integration breakage within this sprint. Publishing, tagging, pushing, - live-provider checks, and deployment changes are outside this plan. - -## Stage 1: Add supervised stdout result capture - -**Status: Complete.** - -**Purpose:** Capture native stdout products without applying diagnostic -redaction or the diagnostic-size limit to their bytes. - -Read `internal/adapters/subprocess/run.go`, `diagnostics.go`, `execution.go`, -the supported process-tree implementation, and their focused tests. Read -`internal/adapters/scriptorium/subprocess.go` for the existing result-size guard. - -Implement: - -1. Add an optional caller-owned stdout result writer and byte budget to the - shared subprocess request. A request without a result writer keeps its - existing diagnostic-only behavior. This is a narrow extension to the existing - execution boundary, not another process runner. -2. In result mode, route stdout only to the result writer. Keep stderr on the - existing bounded, redacted diagnostic path. Result bytes do not enter stdout - diagnostic logs, tails, or error-message payloads. -3. Enforce the supplied result budget during streaming. Reuse Scriptorium's - existing `MaxOutputFileBytes` value at its call sites, including requirements - capture; add no separate configuration knob or report-specific numeric cap. - A result-limit error identifies the responsible adapter, stream, and limit. -4. Feed result-limit and writer failures into the existing owned-process abort - path. Preserve the originating failure even if the child exits concurrently. - Keep current cancellation, timeout, descendant cleanup, diagnostic limits, - and finalization behavior. Caller-owned files are closed by their caller. -5. Keep all other adapters on their existing capture mode. - -Verify with focused subprocess tests: byte-exact stdout, unchanged stderr -redaction, a result larger than the diagnostic cap, exact result-budget boundary -and overflow, writer failure, and termination on capture failure. Reuse existing -process-tree tests for mechanics already covered; add only the new result-mode -coverage needed. Test doubles use small budgets for boundary checks. - -Check: `go test ./internal/adapters/subprocess`. - -## Stage 2: Migrate Scriptorium generation - -**Status: Complete.** - -**Purpose:** Make native `run` deliver the artifact through Narratio's result -capture while retaining existing success and failure rules. - -Read `internal/adapters/scriptorium/{runner,subprocess,invocation}.go` where -present, adapter tests, the integration contract, and the upstream CLI migration -and subprocess guides linked by the roadmap. Locate invocation-record ownership -within the adapter if filenames differ. - -Implement: - -1. Build `run PROMPT_ID` with existing optional config/profile selections, - sorted repeated `--input-file NAME=PATH`, and repeated `--var KEY=VALUE`. - Preserve commas and additional equals signs as literal mapping values. -2. Select `--format text` for artifact-only stdout. Omit quiet, removed `--out`, - the old prompt flag, and the former duration-valued `--timeout`. -3. Keep the existing Narratio subprocess deadline. Pass the same duration to - generation's `--run-timeout` as the native operation budget. Leave native - per-attempt timeout selection to downstream configuration; add no new - Narratio field or duration-to-integer conversion. -4. Open the requested run-local output using ordinary workspace file conventions - and existing path-safety helpers, then use Stage 1 capture with - `MaxOutputFileBytes`. Propagate open, write, and close errors. Keep current - nonempty/regular-file/output validation. Canonical promotion remains in the - stage layer. -5. Classify completed content-validation failure at exit 4. Exit 2 is a native - usage/configuration error. Nonzero process or delivery outcomes remain errors - even if stdout produced bytes. Preserve native exit evidence and useful - redacted stderr context. -6. Update generated invocation records to describe actual arguments and the - Narratio-owned stdout destination. Retain credential names only. Do not copy - the product into an additional stdout diagnostic file or request an upstream - full-result report merely to recover artifact bytes. - -Verify the adapter with the existing subprocess helper, updated to emit product -bytes on stdout. Cover native file flags, binary-safe capture, status 4 versus 2, -empty output, partial output with failure, credentials, and invocation records. -Update obsolete assertions rather than retaining tests for the removed CLI. - -Check: `go test ./internal/adapters/scriptorium` when preview fixtures permit. - -## Stage 3: Migrate prepared preview and diagnostic references - -**Status: Complete.** - -**Purpose:** Preserve optional render-debug behavior through the native prepared -request command. - -Read the adapter's preview implementation, `internal/stage/trim.go`, -`internal/stage/analyze_artifact_execution.go`, their preview tests, and the -upstream prepared-preview contract. - -Implement: - -1. Replace `render --prompt` with `promptkit show prepared PROMPT_ID` and - `--format json`. Use repeated native file/variable flags and the same resource - selection as generation. Apply the Narratio supervisor deadline; preview - receives neither the removed timeout flag nor generation-only controls. -2. Capture native prepared JSON to the existing preview destination through - Stage 1. Retain current nonempty/JSON validation and debug failure behavior. - Preview remains diagnostic and uses the existing layout until workspace work - changes it. Do not rebuild the former render JSON shape. -3. Update command-mode provenance and generated invocation metadata to identify - the actual prepared command. Native command changes do not require changing - unrelated durable fingerprint or manifest schema versions. -4. Update trim/analyze diagnostic bookkeeping for both generation and preview: - record their actual stderr logs, invocation records, and preview results. - Stop advertising nonexistent stdout diagnostic files in metadata, errors, - and manifest log references. Keep raw stdout destinations separate from Logs. - Existing diagnostic files need no cleanup or migration in this scope. -5. Update fake/noop artifact and preview behavior and related fixtures to match - these result and diagnostic semantics. - -Verify optional preview enablement, valid native prepared JSON, malformed/failed -preview, accurate diagnostic paths, and preservation of canonical outputs when -generation fails. Reuse stage materialization tests where they already cover -the latter behavior. - -Check: `go test ./internal/adapters/scriptorium ./internal/stage`. - -## Stage 4: Add the native requirements adapter - -**Status: Complete.** - -**Purpose:** Inspect prompt requirements without input files, output paths, or -model execution. - -Read the upstream native requirements contract and Scriptorium subprocess guide, -plus `internal/adapters/scriptorium` and its test helper. - -Implement: - -1. Extend the existing Scriptorium runner boundary with `InspectRequirements` - and a request/result model. The request carries binary/config/prompt/profile, - applicable variables, captured credentials, working directory, and timeout. - It requires no input paths, output path, or persistent diagnostic destination. -2. Invoke `promptkit requirements show PROMPT_ID --format json`, forwarding - existing selectors and variable mappings through the same adapter helpers. - Use supervised stdout result capture into memory with the existing result - budget. Keep stderr bounded and redacted even when no log file is requested. -3. Decode one native report. Model exact input names, `kind`, `declared`, nullable - content type/description, variables and `supplied`, identities, `complete`, - and issues. Preserve false/empty/null distinctions in any local projection. - Ordinary unknown JSON fields are compatible with normal Go decoding; add no - custom envelope, schema version, diagnostic-prose parser, or strict extension - field rejection. -4. Reject missing/non-object reports, malformed/truncated JSON, and extra trailing - JSON documents. Require the native `prompt_id` string, `complete` boolean, - and `inputs`, `variables`, and `issues` inventories needed for interpretation; - accept their documented empty values and nullable input metadata. A partial - report with status zero is a valid inspection result. - Process, capture, or decode failure returns an error; JSON fragments emitted - by a failed process are not a successful inspection. -5. Extend the existing fake/noop runners and custom runner doubles to satisfy - the boundary. Fakes capture requests and can return reports/errors without - invoking generation. Do not add a production fallback that silently skips - inspection when a collaborator lacks the new operation. - -Verify complete and partial reports, nullable/empty metadata, empty supplied -variables, native invocation failure, malformed reports, credential forwarding, -and discovery with absent generated files. Assert no generation invocation in -these scenarios. - -Check: `go test ./internal/adapters/scriptorium`; compile affected test doubles. - -## Stage 5: Share effective Scriptorium request context - -**Status: Complete.** - -**Purpose:** Ensure discovery, preview, generation, and fingerprint variables -agree without resolving future artifact files. - -Read `internal/stage/scriptorium_vars.go`, `analyze.go` variable/timeout helpers, -`analyze_artifact_execution.go`, `analyze_fingerprint.go`, `trim.go`, and their -request-context tests. Review concrete family expansion through -`config.Config.ConcreteArtifacts()`. - -Implement: - -1. Extract the existing variable conversion, derived-session values, sticky - session override, and timeout selection into shared stage-owned helpers. - Expose narrow context builders for a configured analysis artifact and trim - bounds so application preflight can use the same production code. -2. Return a small context value with resource identifiers, effective vars, - credentials, binary/config path, and timeout. Put the common request value - at the existing Scriptorium boundary; keep configuration interpretation in - the stage-owned builders. Input-file resolution and output/log destinations - remain execution-only additions. -3. Wire trim, analysis preview/generation, and fingerprint variable calculation - through those helpers. Preserve current bool/string variable conversion, - explicit empty strings, per-artifact timeout inheritance, family-expanded - variables, and `session_id=narratio-session-` overriding configured - `vars.session_id`. Pass the template variable with `--var`; do not add a direct - native session-ID override. -4. Keep trim's one configured transcript binding and its existing variable - behavior. Analysis uses concrete artifact vars. Builders operate on final - domain configuration without changing it or loading downstream definitions. - -Verification compares discovery-ready context with preview/generation requests -for trim and an expanded character artifact, including derived variables and -the sticky override. Confirm existing fingerprint values remain stable for -unchanged effective semantics. Avoid duplicating upstream template tests. - -Check: `go test ./internal/stage ./internal/config`. - -## Stage 6: Extract reusable read-only planning and closure - -**Status: Complete.** - -**Purpose:** Reuse the existing projected plan for early inspection while keeping -actual execution authoritative. - -Read `internal/app/plan_command.go`, `plan.go`, stage decision helpers and their -tests, plus `internal/stage/analyze_{plan,resume,reconciliation}.go` and -`internal/stage/stage.go`. - -Implement: - -1. Factor the projection loop out of `buildSessionPlan` into an application-owned - helper that accepts the already-resolved configuration, selected bounded plan, - force/artifact selections, artifact store, and authoritative manifest snapshot. - Reuse existing clone, resume validation, pre-execution decision, and modeled - stage-transition helpers. Keep publication presentation outside the shared - projection when it is unnecessary for inspection. -2. Have `session plan` consume that helper and retain its existing public report - and state effects. The helper neither constructs adapters nor executes them. -3. Return stage decisions and the existing typed analysis execute/reuse summary. - Retain scheduled prerequisite work even when the prerequisite definition is - disabled. Preserve force-on-explicit-target semantics. Missing future inputs - can leave work non-current under the existing reconciler; they are not a new - prerequisite for requirements discovery. -4. Expose the existing analysis target-closure helper narrowly for validating - enabled definitions independently of current reuse. Use that same closure - implementation from the analysis work planner. Do not copy dependency walks - into application preflight or change the underlying graph semantics. - -Verify existing plan/run decision tests and read-only reconciliation tests. -Add focused coverage only for accepting an injected snapshot/store and returning -the scheduled keys needed by preflight. Preserve the original manifest and its -artifact collections while modeling earlier-stage invalidation on the clone. - -Check: `go test ./internal/app ./internal/stage`. - -## Stage 7: Build shared inspection targets - -**Status: Complete.** - -**Purpose:** Select the right prompts and intended bindings for each entry point. - -Read the roadmap's Inspection Policies, Stage 5 context builders, Stage 6 -projection/closure helpers, `internal/app/session_inspection_command.go`, and -`internal/artifacts/effective_set.go`. - -Implement: - -1. Add `internal/preflight` with simple target/result/finding types. A target - identifies stage and concrete artifact where applicable, the shared request - context, and intended input bindings with Narratio source IDs and optionality. - Names and source IDs remain distinct. Findings carry severity and context; - command-specific formatting stays in `internal/app`. -2. Add shared application target builders, rather than separate copies in run - and validate handlers. Execution derives targets from the Stage 6 projected - work: enabled trim only when projected to run, and each scheduled analysis - artifact in the selected closure. Skip reusable work established by that - projection and unrelated/disabled definitions outside the closure. -3. `session validate` targets enabled trim and enabled analysis definitions plus - their required configured prerequisites, including disabled prerequisites. - Validation checks this definition set regardless of existing output reuse; - it does not add artifact/range flags in this scope. -4. Build each target's context through Stage 5. Trim intends the configured - transcript input name. Analysis intends configured binding-map keys, including - optional bindings that may later be omitted. Use concrete family definitions - from the existing resolved catalog. -5. Describe required-prompt/optional-source bindings as potentially unavailable - when availability is unknown. A declaration-level warning that the optional - source may be omitted is sufficient. A new source-availability simulation, - artifact materialization, or remote fetch is unnecessary for these targets. -6. Keep ordering deterministic using canonical stage order and the existing - artifact work/closure order. An empty target list needs no Scriptorium process. - -Verify bounded selection, explicit artifact/family selection, required disabled -prerequisites, reused prerequisites, disabled trim, absent Scriptorium config, -and a fresh session with no generated transcripts. Exercise the shared builders -with existing planner/configuration collaborators rather than a second graph. - -Check the affected application and preflight tests as they become executable. - -## Stage 8: Implement shared requirements assessment - -**Status: Complete.** - -**Purpose:** Apply the agreed preflight policy identically for automatic execution -and explicit validation. - -Read Stage 4's native report types and Stage 7's target types. Read the roadmap's -Native findings and Inspection Policies sections. - -Implement a context-aware checker in `internal/preflight` using the Scriptorium -runner's inspection operation. It returns contextual findings and an error for -unsuccessful inspection or definite missing requirements. It does not import -`internal/app`, execute stages, mutate manifests, or acquire configuration. - -Apply these rules: - -| Native finding and intended binding | Narratio outcome | -| --- | --- | -| Required input has no exact binding-map key | Error identifying missing name and affected prompt/target. | -| Required input has a configured required-source binding | Binding is satisfied for discovery; future source resolution remains authoritative. | -| Required input has a configured optional-source binding | Warn that the source may be omitted when availability is unknown; preserve configured optionality. | -| Required variable has `supplied: false` | Error, including in an otherwise partial report. | -| Variable is explicitly supplied with an empty value | Respect native `supplied`; no added nonempty rule. | -| Conditional requirement, incomplete discovery, or discovery issue alone | Warning with native structured context; no failure solely for uncertainty. | -| Optional requirement or an extra configured binding | No new rejection. | -| Process/capture/decode failure | Error retaining the original cause and target context. | - -Inspect useful findings even when `complete` is false. Native issue descriptions -are display text; use fields rather than parsing prose. Avoid duplicating a -definite missing-variable error as a conflicting warning. No per-input schema or -media-type validation is inferred from discovery metadata. - -Check targets sequentially. Retain findings collected before a failure, stop -promptly on cancellation, and return a nonnil error when any definite failure -occurred. Ordinary target failures can be collected with `errors.Join` so explicit -validation can report more than one problem. No persistent cache is needed; -checking each target independently handles different character variable contexts. - -Verify the assessment table with small native report fixtures and an injected -inspector. Check partial success versus invocation failure, retained errors, -exact binding names, optional-source warnings, cancellation, and input maps that -reference absent future files. - -Check: `go test ./internal/preflight`. - -## Stage 9: Run preflight before stage attempts - -**Status: Complete.** - -**Purpose:** Catch actionable Scriptorium problems before expensive work while -preserving completed results on preflight failure. - -Read `internal/app/runner.go`, `runner_runtime.go`, `runner_composition.go`, -`runner_dependencies.go`, stage-attempt/invalidation helpers, and the existing -runner lifecycle and composition tests. - -Implement: - -1. Insert the hook between `initializeLockedInvocation` and - `composeInvocation`. The locked manifest and bounded prerequisite checks are - available there. Project selected work using Stage 6 and build execution - targets using Stage 7 before `executeSelectedStage`, `beginStageAttempt`, or - any pre-execution decision is applied to the live manifest. -2. For nonempty targets, reuse an injected `Env.Scriptorium` runner or compose - it through the existing invocation-owned Scriptorium factory. Pass it to - Stage 8. Reuse that collaborator for later generation; initialize no other - new integrations for requirements discovery. -3. Surface warnings through the existing reporter and propagate failures with - their causes. Return through the existing invocation finalization path. - Preflight failure leaves stage attempt counts, success records, artifact - authority, and completed output bytes unchanged. Ordinary invocation identity, - lock, and terminal-summary behavior need no new transactional guarantee. -4. Keep actual stage decisions and input resolution at execution time. Projected - future work can differ after earlier outputs are produced. Do not force - stages to follow a stale preflight prediction or add a reinspection loop. -5. All pipeline execution entry points, including bounded runs and artifact - regeneration aliases, receive preflight through this one runner hook. - Wholly reused invocations and ranges without projected Scriptorium work - invoke no inspector and retain lazy physical run-directory creation. - -Verify with injected external collaborators: inspection precedes the first stage -attempt; definite missing input and unavailable Scriptorium stop the run; -warnings allow it; `--force` preflight failure preserves previous outputs and -manifest authority; reusable/unrelated work invokes no inspector. Confirm that -no additional run directory is created solely for inspection. - -Check: `go test ./internal/app`, including lifecycle and composition suites. - -## Stage 10: Integrate explicit session validation - -**Status: Complete.** - -**Purpose:** Present the same prompt findings in the existing readiness report. - -Read `internal/app/session_inspection_command.go`, `operator_findings.go`, -`command_dependencies.go`, and their focused tests. Reuse Stages 7–8 directly. - -Implement: - -1. After obtaining valid final domain configuration and effective definitions, - build definition-validation targets. Keep other existing readiness checks and - their accumulated findings. A missing future transcript does not prevent the - requirements operation itself from running. -2. Add an invocation-owned Scriptorium factory seam to command dependencies, - using the same production constructor as execution. Default tests inject a - fake. Compose only when targets exist; avoid mutable package-level overrides. -3. Map shared finding severity/context into existing readiness findings. Both - entry points use the same checker. Validation may include additional - informational detail while preserving severity. -4. Preserve inspection and report-decoding errors in the returned error as well - as the report. Such failures and definite missing requirements make `Valid` - false and produce a non-successful native command outcome. Warnings alone do - not make the readiness result invalid. Existing unrelated readiness failures - continue to affect the overall result. -5. Use in-memory requirements capture and bounded redacted stderr evidence. - Validation creates no session workspace, run directory, execution lock, - persistent discovery report, or manifest update. Native child configuration - acquisition retains its own bootstrap semantics. - -Verify a valid session, missing binding, missing variable, successful partial -report, optional-source warning, inspector failure, malformed report, disabled -prerequisite, and no configured targets. Compare shared findings with automatic -preflight for the same targets and context. Assert returned failures remain -failures even when diagnostic presentation is quiet. - -Check: `go test ./internal/app -run 'Test.*(Validat|Preflight|SessionPlan)'` and -the focused validation tests under their final names. - -## Stage 11: Verify assembled workflows and remove superseded machinery - -**Status: Complete.** The full offline and race-enabled test suites pass. - -**Purpose:** Prove the integrated cutover and retain a proportionate test suite. - -Review the focused tests added in Stages 1–10 and existing plan, lifecycle, -artifact checkpoint, trim, and subprocess integration tests. - -Implement and verify: - -1. Add a representative offline application workflow with fresh future inputs, - trim plus analysis, and a required analysis prerequisite. Use a subprocess - double implementing the selected native commands. Show that inspection runs - first, then existing producers and consumers complete with captured products. -2. Exercise character-specific context and optional preview through the real - adapter boundary where that catches integration risk beyond unit tests. - Cover per-artifact retry/reuse without reinspecting known reusable work and - force failure preserving prior authority. -3. Confirm `session plan`, native configuration inspection, help, completion, - and unrelated stage selections do not invoke requirements inspection. Update - existing offline application fixtures that now legitimately reach preflight - so they use injected fakes instead of a host-installed executable. -4. Remove old CLI argument builders, unused duplicate context conversion, and - obsolete render-shape fixtures. Preserve useful behavioral tests rather than - adding assertions for private helper names or complete diagnostic wording. -5. If the selected Scriptorium executable/checkout is available, supplement with - a controlled requirements/prepared check using temporary native configuration - and synthetic inputs. This is optional evidence, not a default test or - availability gate. Generation against a real provider is unnecessary. - -Check: `go test ./...` and `go test -race ./...`. Diagnose failures rather than -weakening the accepted inspection policy or restoring removed CLI compatibility. - -## Stage 12: Update canonical documentation and finish verification - -**Status: Complete.** The full test and race suites, vet, build, and supported -target cross-builds passed with Go 1.27.4. - -**Purpose:** Hand off a documented, verified native integration. - -Read documentation policy and the current canonical documents below. Update them -to describe implemented behavior only: - -- `docs/integrations/scriptorium.md`: supported native interface, separated - product/diagnostic capture, exit adaptation, discovery boundary, and upstream - links. Keep volatile native feature documentation upstream. -- `docs/internal/adapters.md`, `docs/internal/overview.md`, focused trim/analyze - internals, and a concise `docs/internal/preflight.md`: component ownership, - shared context/planner use, invocation lifecycle, and findings flow. -- `docs/cli.md`: automatic run/alias preflight, explicit validation results, and - unchanged subprocess-free planning behavior. -- `docs/config.md`: Narratio's binding/variable interpretation and credential - forwarding across inspection, preview, and generation. Its public schema stays - unchanged for this feature. -- `docs/operations.md` and `docs/troubleshooting.md`: early failures, warnings, - missing-versus-optional bindings, preserved completed work, required executable - availability, and deployment migration links. -- Maintained examples only where they actually contain obsolete Scriptorium CLI - syntax or downstream definitions. Narratio invocation YAML is its own record, - not Scriptorium configuration. Link upstream for downstream migration details. - -Keep the existing workspace layout and pending Audita/workspace roadmaps intact. -The new preflight helper is an implementation boundary; it needs no new ADR or -global policy restriction. Explain actual byte-preserving result capture as -distinct from diagnostic redaction, without claiming arbitrary generated content -is scrubbed of secrets. - -Final checks with the maintained toolchain: - -```sh -go test ./... -go test -race ./... -go vet ./... -go build ./... -git diff --check -``` - -The full suite includes documentation links and maintained configuration example -validation. Run existing supported-target cross-build checks if shared subprocess -platform code changed; report cross-compilation as such. Native macOS runtime -verification and CI availability remain outside this sprint's completion gates. - -Audit the finished diff against the roadmap: native generation and preview, -byte-preserving bounded result capture, correct native exit handling, early -requirements with absent files, shared effective context, shared checking policy, -selected/prerequisite/reuse behavior, read-only explicit validation, preserved -completed authority on preflight failure, and accurate operator documentation. -Commit remaining completed work with a short plain English message and report -the resulting checks and workspace state. Do not tag, push, or release. - -## Open Questions - -None. The roadmap's inspection policies resolve the product decisions. This plan -selects native operation-budget forwarding, in-memory discovery capture, shared -stage-owned context builders, and reuse of the existing projected planner as -implementation details within that scope. diff --git a/docs/roadmap/remediation.md b/docs/roadmap/remediation.md deleted file mode 100644 index 2acffcf..0000000 --- a/docs/roadmap/remediation.md +++ /dev/null @@ -1,106 +0,0 @@ -# Scriptorium algorithmic audit - -Reviewed baseline: `f930ebf337d632afdc449cab86757291e14e5e37`. - -Scope: the twelve stages in [implementation.md](implementation.md), focusing on -algorithmic correctness and avoidable time/space costs. This is a static audit; -no real-world performance measurements were gathered. Algorithms explicitly -selected in the plan, including sequential per-target inspection, in-memory -requirements capture, deterministic argument sorting, and existing planner reuse, -are retained as scope decisions. - -## Finding 1: Avoid full-file allocation for post-capture size checks - -Status: Complete. - -Priority: P3 — bounded memory and redundant I/O optimization; no demonstrated -incorrect result or release-blocking defect. - -### Evidence and affected stages - -Stages 2–3: `internal/adapters/scriptorium/subprocess.go`, particularly -`RunArtifact` at line 118, `RenderArtifact` at lines 205–212, and -`validateNonEmptyOutput` at lines 372–380. - -Generation now streams stdout to an output file through the bounded result -writer. After success, `validateNonEmptyOutput` calls `fileops.ReadFileBounded` -and uses only the returned slice's length. That helper uses `io.ReadAll`, so the -adapter rereads and allocates the whole artifact solely for a nonempty/size check. - -Prepared preview calls the same helper, then immediately reads the file again -for `json.Valid`. The nonempty helper predates this sprint; the newly implemented -capture/preview paths retain its allocation, and preview adds another full read. -This is an optimization opportunity in the completed feature, not a claim that -the sprint introduced the original helper or a new asymptotic regression. - -### Complexity - -Let B be result size and A the number of generated artifacts. - -- The nonempty/size validation currently costs O(B) time and O(B) extra memory - per artifact, with cumulative additional reads of O(sum B_i) over A artifacts. - Existing limits bound each result at 64 MiB but still permit a substantial - transient allocation. Sequential execution does not retain all A buffers. -- For an already captured regular file, size/nonempty validation can use O(1) - extra memory and metadata work independent of B, plus existing path checks. - If read-through validation is desired, bounded streaming preserves O(B) time - while reducing its buffer space to O(1). -- Preview can combine its nonempty/limit checks with the one bounded read - already needed for its current JSON validation. That removes a redundant read - and allocation; preview's overall time and memory remain O(B). -- Generation and downstream content validation still process O(B) bytes. This - change would improve adapter validation space and unnecessary I/O, not make - the complete generation workflow constant-time or constant-space. - -### Recommended refactoring - -Separate file-property checks from content parsing. For generation, validate -the closed captured file's required properties using its metadata, preserving -existing path/type handling and the centralized size limit. Retain streaming -capture limits and propagation of write/close failures. Use a bounded streaming -check instead if preserving read-through verification is necessary. - -For preview, perform one bounded read, check nonempty content, and validate that -same buffer as JSON. Preserve stage-owned payload validation, checksums, canonical -promotion, and failure behavior. No new caching, configuration setting, or -relaxation of output validation is needed. - -Retain focused tests for empty, oversized, nonregular, and failed outputs, and -valid/invalid preview JSON. Review the implementation's buffering directly; -timing thresholds, allocator-count contracts, and benchmark gates are unnecessary. - -### Resolution and verification - -Generation validates the closed captured file with `os.Stat`, checking regular -file type, nonempty size, and the existing maximum without reading its payload. -Its post-capture validation uses O(1) extra memory. Preview performs one bounded -read and checks both nonempty content and JSON validity on that buffer. -Streaming limits, write/close error propagation, and stage-owned payload checks -and promotion remain unchanged. - -Sparse-file tests cover empty, nonempty, exact-limit, and oversized outputs; -missing/nonregular output checks and an empty-preview case complement the -existing successful, invalid, and failed subprocess cases. Verification passed: -`go test ./...`, race-enabled Scriptorium/subprocess tests, Scriptorium package -vet, and `git diff --check` using Go 1.27.4. - -## Stage-by-stage disposition - -| Stage | Algorithmic assessment | -| --- | --- | -| 1 — Result capture | Streaming writes are linear in bytes; bounded accounting and failure signaling add constant work per write. No finding. | -| 2 — Generation | Finding 1 covers the avoidable post-capture whole-file allocation. Sorted argument construction follows the selected deterministic contract. | -| 3 — Preview | Finding 1 also covers the redundant read before JSON validation. | -| 4 — Requirements adapter | Capture/decoding is linear in report bytes, with linear storage for the selected in-memory report. No finding. | -| 5 — Request context | Map conversion/copying and sorted variables preserve existing behavior. No new repeated catalog scan or quadratic construction found. | -| 6 — Planning and closure | Reuses the selected planner, manifest cloning, and existing dependency ordering. Those algorithm choices were expressly retained during planning. No additional finding. | -| 7 — Inspection targets | Builds targets with map lookups and one traversal of selected bindings; storage scales with the materialized target contexts. No finding. | -| 8 — Assessment | Single passes over inputs, variables, and issues use expected constant-time map lookups. Findings/errors append amortized linearly. No finding. | -| 9 — Automatic preflight | Uses the selected projection and checker, without a separate simulation or reinspection loop. No additional finding. | -| 10 — Explicit validation | Uses shared target construction and assessment; report assembly is linear in findings. No finding. | -| 11 — Workflow verification | Test helpers introduce no production algorithm. No additional correctness issue identified. | -| 12 — Documentation | No algorithm implemented. Documentation introduces no additional algorithmic requirement relevant to this audit. | - -No newly implemented quadratic-time algorithm or additional correctness defect -was identified within this scope. Finding 1 has been addressed by the -behavior-preserving follow-up described above. diff --git a/docs/roadmap/scriptorium.md b/docs/roadmap/scriptorium.md deleted file mode 100644 index 2bcb284..0000000 --- a/docs/roadmap/scriptorium.md +++ /dev/null @@ -1,297 +0,0 @@ -# Adopt Scriptorium v0.16 and prompt requirements discovery - -**Status: Implemented.** The [integration contract](../integrations/scriptorium.md) -describes current behavior; the baseline below records the prior implementation. - -## Purpose - -Adopt Scriptorium's native CLI for trim-bounds generation and analysis. Use its -prompt requirements discovery to identify missing Narratio input bindings before -expensive upstream work, including when the eventual input files do not exist. - -This roadmap defines the target and required changes. The -[implementation plan](implementation.md) owns the ordered implementation steps. -The Audita and session workspace roadmaps remain separate scopes. - -## Reviewed Baseline - -Narratio was reviewed at commit -`9fa1797`. The reviewed Scriptorium v0.16.0 release identifies commit -`0fa538c336fd64be51bc355fd53d3ca19f104d68`. - -The following upstream documents own Scriptorium's behavior: - -- [Release notes][release]. -- [CLI reference][cli] and [CLI migration guide][migration]. -- [Subprocess integration contract][subprocess]. -- [Configuration][configuration] and [PromptKit migration guidance][prompts]. -- [Native requirements contract][requirements]. - -Scriptorium implements the previously requested early requirements inspection. -It exposes native PromptKit findings through CommandKit, including exact input -names, requirement classifications, variable presence, selected identities, -discovery completeness, and structured issues. Further upstream changes are -unnecessary for this capability. Richer capture diagnostics for malformed -templates remain separate upstream work. - -## Reviewed Narratio Behavior - -The [Scriptorium integration](../integrations/scriptorium.md) owns the current -contract. Its adapter serves both `trim` and `analyze`, including optional -render-debug calls. - -- Generation uses the former `run --prompt`, file-valued `--input`, `--timeout`, - and `--out` interface. Preview uses the former `render` command. -- The adapter classifies exit status 2 as generated-content validation failure. -- Scriptorium writes an output file that Narratio validates before promotion. - The existing artifact limit is 64 MiB. -- Shared subprocess execution captures stdout and stderr as bounded, redacted - diagnostics. It has no separate stdout product destination. -- Configuration validation checks Narratio's artifact sources and dependencies. - It does not ask Scriptorium which prompt input names or variables are required. -- Analysis planning expands character families and computes prerequisite closure. - `session plan` currently invokes no stage-execution adapters. -- Scriptorium credentials use the same explicit forwarding and diagnostic - redaction boundary as Audita and Notarius. - -The current adapter is incompatible with the new CLI. Scriptorium is a separately -installed executable; this adoption is an integration and deployment migration, -rather than a new Go module dependency. - -## Targeted End State - -### Native generation and preview - -Use Scriptorium v0.16's native commands for both trim and analyze: - -| Existing invocation behavior | Target behavior | -| --- | --- | -| `run --prompt ID` | `run ID` | -| File bindings through `--input NAME=PATH` | Repeated `--input-file NAME=PATH` | -| `render --prompt ID` | `promptkit show prepared ID`, using its native structured output | -| `--out PATH` | Narratio captures stdout to its run-local destination | -| Former duration-valued `--timeout` | Narratio's existing supervisor deadline remains authoritative; generation may also pass `--run-timeout` for the engine budget | -| Content-validation failure at status 2 | Content-validation failure at status 4; status 2 retains native usage/configuration meaning | - -Preserve the distinction between the whole-invocation deadline and native -per-attempt provider timeouts. Existing duration settings retain their Narratio -meaning. This migration adds no per-attempt timeout setting. - -Capture generation in automatic/text format so the output file contains artifact -bytes, rather than the full native result envelope. Capture prepared preview in -the native JSON format. Keep diagnostics separate from these result streams. -Invocation records describe the actual native commands and retain credential -names only. - -Keep current stage output validation, successful promotion, failure handling, -resume, force, and dependency behavior. A partially delivered stdout file or a -file produced with a nonzero outcome does not establish stage completion. -Preserve existing treatment of older completed outputs after failed replacement. - -### Early prompt requirements inspection - -Add an adapter operation for: - -```sh -scriptorium promptkit requirements show PROMPT_ID --format json -``` - -Supply the same effective configuration, prompt, profile, applicable variables, -and session context as the eventual generation request. Preserve qualified IDs -and upstream selection semantics. Discovery, preview, and generation share -request-context construction so character-specific variables and session routing -agree. Preserve Narratio's existing `session_id=narratio-session-` -template variable, including its precedence over configured `vars.session_id`. -Do not supply a direct `--session-id`: that native option bypasses the prompt's -session template and would change routing ownership. Existing downstream -selectors remain authoritative; this work does not introduce another -configuration-resolution layer. - -Inspect named requirements before generated files exist. Discovery reads -configuration and prompt resources and makes no model call. ConfigKit's native -bootstrap and configuration acquisition still apply. Discovery does not require -future artifact payloads or prove execution credentials are ready. - -Narratio compares required prompt input names with the keys in its effective -binding map. For example, a source named -`narratio.transcript.final_trimmed_markdown` can satisfy the prompt input -`transcript` when explicitly bound under that name. Source identity and binding -name remain distinct. - -A configured binding does not guarantee that its source will be available. -Narratio omits unavailable optional sources from the eventual request. When a -prompt requires such an input and availability is unknown, report the uncertainty -as a warning without rejecting the configuration or changing the binding's -optionality. A missing required binding is a definite error; unknown future -source availability is not. Existing runtime input resolution remains -authoritative. - -Use native variable-presence findings, including explicit empty values. Associate -findings with the affected trim prompt or concrete analysis artifact. Retain -existing Narratio source validation and dependency planning as their respective -authorities. - -Inspection covers relevant trim generation and effective selected analysis -targets, including character-family expansion and required prerequisite work. -Use the existing planner to skip work it can establish will be reused and inspect -work that may execute under the projected plan. Earlier stages may produce -outputs that change later reuse decisions, so preflight does not promise exact -prediction of pending work. Actual execution remains authoritative; do not add a -second planner or simulation system. Unselected integrations remain unaffected. -The inspection policies below define entry points and handling of findings. - -### Native findings and their limits - -Consume the native report directly. Use structured fields for decisions and -upstream explanations for display. Preserve exact names, classifications, -nullable metadata, empty inventories, and false values. - -A complete report describes discovery coverage. Narratio separately determines -whether bindings satisfy the discovered requirements. Partial discovery can -return status zero and still contain useful findings. An empty partial inventory -does not establish that the prompt needs no inputs. - -Native nonzero outcomes and stderr supply invocation-failure information. Attach -Narratio context without parsing diagnostic prose for stable categories. The -native report has no Scriptorium-specific schema-version envelope or per-input -schema contract; this migration adds neither. - -Concrete `promptkit requirements validate` remains a separate upstream operation -for when files exist. Automatic concrete validation and provider smoke tests are -outside this scope. Discovery is an early configuration aid, not a guarantee of -later preparation or generation success. - -## Required Changes - -### Subprocess and adapter boundary - -Extend the existing subprocess boundary proportionately to support stdout result -capture alongside its current diagnostic-only use. Product and machine-readable -report capture must preserve result bytes. Diagnostic redaction and its 8 MiB -capture policy must not truncate or transform artifact payloads. Retain the -existing artifact-size guard, cancellation, owned-process cleanup, credential -forwarding, and contextual errors. - -Keep other adapters' existing diagnostic capture behavior unchanged. Use the -same supervised execution machinery for generation, preview, and requirements -inspection. Reuse result capture for native reports without introducing a -separate limit setting. - -Update Scriptorium argument construction, exit classification, preview handling, -invocation metadata, adapter doubles, and trim/analyze wiring. Required discovery -data and transport behavior belong behind the adapter; Narratio's binding and -selection decisions belong in the application layer. - -### Preflight integration - -Add `internal/preflight` to coordinate prompt requirements checks. Automatic -preflight and `session validate` use the same checking paths and consume the same -findings and errors. Their target selection follows the inspection policies -below; command handlers own presentation, with validation able to show fuller -warning and informational detail without changing finding severity. - -Reuse existing production machinery for effective artifact definitions, planning, -request-context construction, and adapter execution. Share or extract existing -helpers where needed rather than copying them into preflight. Keep code specific -to preflight limited to coordinating inspection and assessing intended bindings -against native findings. Avoid a second artifact graph, prompt parser, -configuration loader, or persistent discovery cache. A per-invocation inspection -result is sufficient; inspect different variable contexts independently where -needed. - -Add contextual operator findings for definite missing bindings and discovery -limitations. Preserve unsuccessful inspection as an error in both entry points; -successful partial discovery remains distinct from invocation or report-decoding -failure. Apply the inspection policies without altering unrelated stage -selection, manifest transitions, or ordinary configuration inspection. - -### Deployment and documentation - -Coordinate adapter adoption with the installed Scriptorium executable and its -native configuration/prompt definitions. Review removed directory settings, -native imports, profile identities, source-relative resources, and validation -repair budgets through the upstream migration guides. Preserve explicit -configuration-path forwarding and existing exact-name credential forwarding. - -Target the native interface directly. Version probing, legacy command fallbacks, -and automatic downstream configuration conversion are outside this scope. -Narratio does not acquire ownership of Scriptorium's backend or prompt settings. - -When implementation lands, update the integration contract and focused adapter, -preflight, trim, and analyze internal documentation. Update CLI, configuration, -operations, and troubleshooting documentation where preflight affects operator behavior. -Link upstream for native command and configuration details; document Narratio's -binding decisions, execution boundary, and failure context locally. - -Keep preview placement consistent with the existing debug workflow until the -[workspace roadmap](workspace.md) changes it. Its latest-attempt views and layout -rules remain owned by that work. The [Audita adoption](audita.md) is independently -implementable. - -## Verification and Completion - -Use focused offline tests at the subprocess, adapter, preflight, and orchestration -boundaries. Cover the consequential migration risks: - -- File bindings use native file flags; positional prompt selection and preview - commands match the selected upstream release. -- Artifact stdout is byte-preserving and separate from redacted diagnostics, - including payloads larger than the diagnostic capture limit. -- Native exit classifications, cancellation, capture failures, partial delivery, - and output validation retain correct stage-completion behavior. -- Discovery works without generated files and identifies mismatched names, - required variables, conditional inputs, and incomplete findings; uncertain - optional-source availability warns without changing binding policy. -- Discovery, preview, and generation agree on effective request context, - including expanded families and variable-based session routing. -- Inspection covers projected work and required prerequisites, including disabled - prerequisites, while skipping work the planner establishes will be reused. -- Preflight failures precede stage attempts and preserve completed outputs; - `session plan` remains subprocess-free and inspection makes no model calls. -- Automatic preflight and `session validate` agree on findings for the same - targets and context. Both stop on unsuccessful inspection or definite missing - requirements; discovery incompleteness and warnings alone do not fail. - -Default tests use subprocess doubles and temporary filesystems. They remain -independent of sibling checkouts, installed downstream tools, real credentials, -and paid providers. A controlled compatibility check against the selected -Scriptorium release can supplement those tests. - -Completion means trim generation, analysis generation, and optional preview use -the native CLI; requirements inspection implements the policies below; and -local integration and operator documentation describe the landed behavior. - -## Inspection Policies - -### Automatic inspection entry points - -Inspect applicable projected Scriptorium work before stage attempts begin, and -include requirements findings in `session validate`. -Keep ordinary `session plan` independent of subprocess inspection for this scope. -An unsuccessful inspection or definite missing requirement stops the affected -execution or validation with ordinary contextual error reporting. Warnings and -informational findings alone do not stop automatic execution. Early preflight -failure does not invalidate previously completed outputs. Unrelated stage-only -invocations remain unaffected. - -Scriptorium must consequently be available earlier for an invocation whose -projected work needs it. Validation inspects enabled trim and analysis definitions -and their required prerequisites, including disabled prerequisites. Execution -uses its selected projected work and prerequisite closure as described above. - -### Incomplete or conditional discovery - -Fail for definite missing required bindings or required variables. Display -incomplete-discovery issues and unresolved conditional requirements as warnings -while allowing execution to proceed when no definite missing requirement is -established. This uses native findings without making -static analyzability a new validity requirement for prompts. Later preparation -and generation remain authoritative for actual requests. - -[release]: https://forge.maximumdirect.net/eric/scriptorium/src/tag/v0.16.0/docs/releases/v0.16.0.md -[cli]: https://forge.maximumdirect.net/eric/scriptorium/src/tag/v0.16.0/docs/cli.md -[migration]: https://forge.maximumdirect.net/eric/scriptorium/src/tag/v0.16.0/docs/consumers/upgrading-cli.md -[subprocess]: https://forge.maximumdirect.net/eric/scriptorium/src/tag/v0.16.0/docs/integrations/subprocess.md -[configuration]: https://forge.maximumdirect.net/eric/scriptorium/src/tag/v0.16.0/docs/config.md -[prompts]: https://forge.maximumdirect.net/eric/scriptorium/src/tag/v0.16.0/docs/consumers/upgrading-promptkit.md -[requirements]: https://forge.maximumdirect.net/base-layer/commandkit/src/commit/0b53a63648c536afe50c46f948159116f776adae/docs/cli.md#promptkit-requirements