# 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.