Implementation plan · Attest · September 8, 2026
Updated September 08, 2026 at 23:26 PDT · Conceptual walkthrough plus a concrete implementation work breakdown.
Let the CLI keep running. Keep every interaction in dispatch.
A driver starts a process, captures its browser URL, approves the request, and returns to the same process. The session owns its lifetime, output, cleanup, and evidence.
Attest onlymacOS + LinuxExisting cli.run stays compatibleUnfinished processes: clean up + warn
Implementation breakdown: 12 work packages with dependencies and completion checks →
Save the final output before destroying the session.
If browser approval fails, the CLI still needs cleanup and a final log. Finish that work first, collect the evidence, and only then remove the session and its storage.
One process, several bounded actions
Browser work happens while the CLI runs.
The CLI may print its confirmation while the browser action is returning. The next CLI action must still be able to find that message.
- Prepare for collectionClose resources; write final snapshots→2. Collect artifactsRead through the daemon connection→3. Destroy the sessionThe backend may now reap storage
Give the driver a way to leave and return
Start the CLI and capture its URL, use the browser, then return to the same CLI. The session keeps the process and remembers what it prints while the driver is elsewhere.
| Action | Returns when | What the driver can do next |
|---|---|---|
start | Started; optional readiness output observed | Use the handle to refer to this process later |
waitFor | The selected output matches | Use the message; keep a bookmark for the next wait |
write | Input is accepted by the writable stream | Wait for the reply, or signal that input is finished |
waitForExit | Child and its output streams have closed | Inspect the final output and exit result |
stop | Supervised termination and cleanup finish | Inspect the cleanup result |
Three outcomes. One optional final result.
Each action completes, fails, or times out. Its completion is null until the final process result is available. Driver authors do not need a separate process-state model.
Waiting successfully for a process to exit does not mean the command itself succeeded. The scenario still checks its exit result.
Someone must remain responsible.
The driver can finish a step while its CLI keeps running. The session remains responsible for that process, including stopping it if the journey ends before the driver returns.
Successful automatic cleanup warns; failed cleanup is an infrastructure failure.
Prove the connection between the CLI and the browser
A local approval page makes the relationship observable: clicking its button causes the waiting command to finish. A second journey deliberately fails before approval to prove cleanup.
01
A real approval journey. A Node child prints a URL. A real browser click causes that same child to confirm and exit.
02
The failure half. A failed browser step leaves no supervised process group behind and preserves cleanup evidence.
03
Evidence at both boundaries. The start snapshot is readable while running. The final snapshot arrives before storage disappears.
Delivery excludes the SageOx monorepo migration, PTYs, daemon-restart reconnection, native Windows live-process support, and a public streaming subscription API.
Implementation notesEach section starts with the problem, explains the approach, then introduces implementation details
1. Interacting with a CLI that has not finished
The driver needs to leave a command temporarily without losing its place. In the login example, it starts the CLI, gets a URL, uses the browser, and then checks the CLI's confirmation and exit. Each of those steps should be an ordinary dispatch action, with its own result and evidence.
Keep run for commands whose only useful stopping point is completion. For this journey, add start to return earlier, waitFor to observe a message, and waitForExit to collect the final result. Add write for commands that ask for a reply, and stop when the driver wants to end a command explicitly.
Carry a reference to the same process
Start returns a handle: a reference the driver can pass to later CLI actions. The session keeps the actual process object. For a simple login driver, store the handle in JSON session state and export the URL for the browser step. Explicit handle exports remain available when a scenario needs to select among several processes.
A handle only works in its owning session and while its entry is retained. Invalid, foreign, and expired handles produce failed actions with specific diagnostics. How the runner constructs a handle is private; Section 2 explains ownership and retention.
Answer two simple questions
Did this action accomplish its request? Use Attest's existing three outcomes. Completed means it did; failed means it could not; timeout means its deadline passed. Diagnostics explain the reason.
Is the final process result available? Use completion: ProcessResult | null. Null means finalization has not completed; it is not a promise that the OS process is alive. A result means the process has finished and output capture is complete. No additional public process-state enum is needed.
For example, a successful URL match can return completed with null completion. A successful wait for exit can return completed with exit code 1: observing the exit worked, and the scenario's assertions decide whether that code is acceptable.
// The URL was observed; the final process result is not available yet.
{ status: "completed", raw: { handle, match, completion: null } }
// The process finished; the scenario can inspect what happened.
{ status: "completed", raw: {
handle,
completion: { exitCode: 1, signal: null, stdout: "...", stderr: "..." }
} }
These examples omit ancillary fields. The final result also carries termination reason, duration, bounded output ranges, and truncation metadata. Exit code is null for signal termination. Do not invent an exit code before completion is available.
Translate those questions into consistent outcomes
| Observation | Action outcome |
|---|---|
| The requested start, match, write, exit wait, or stop succeeds | completed |
| The process exits with a nonzero code or a signal while waiting for exit | completed, with the actual terminal facts in completion |
| The selected output stream ends without the requested match | failed, with output-not-observed and any available completion |
| The action's deadline passes | timeout |
| Invalid handle/cursor/pattern, closed stdin, write failure, or unsupported platform | failed, with a specific diagnostic |
| The executable cannot start | New start: failed, with spawn diagnostics, null completion, and no usable handle. Existing run retains its current completed-with-spawn-failure convention for compatibility. |
A local output or exit wait timing out leaves the process available. Failed start with readiness matching cleans up its newly created child before returning. Do not automatically retry start or write: either may already have performed side effects. Section 2 explains when waiting ends and when the process itself ends.
Implementation: action inputs and results
Extend cliExecutor.actions with typed constructors and export their input, action, and result types through the existing package barrels. Preserve the public behavior of run. Constructors remain usable in host-side code. Bundled drivers currently use type-only framework imports and explicitly typed JSON actions; examples and the fixture must follow that existing boundary.
| Action | Inputs | Result |
|---|---|---|
| start | Command, args, cwd, env, initial stdin, keepStdinOpen, tag, timeout, maximum lifetime, optional until | Handle, initial cursors, optional readiness match, nullable completion |
| waitFor | Handle, stream, framing, pattern, optional cursor, timeout | Match text, positional/named groups, stream, match-end cursor, bounded output snapshot, nullable completion |
| write | Handle, text, optional end, timeout | Accepted byte count when known, whether stdin closed, handle, nullable completion |
| waitForExit | Handle, timeout | Handle and completion with terminal facts and bounded output |
| stop | Handle | Handle and completion with terminal facts and bounded output |
Keep action payloads JSON so dispatch can carry them through the existing machinery. Patterns use { source, flags }; callbacks, native RegExp instances, and process objects do not cross this boundary. Validate new payloads before side effects while preserving existing run payload compatibility.
Implementation: defaults that support the journey
- Command setup: use the existing command/args execution model without a shell. Add optional
env: Record<string, string>to run and start, preserving current runner merge precedence. Record override names, never an environment dump. - Replies: start may write initial stdin.
keepStdinOpendefaults to true so later replies are possible; false writes any initial input then sends EOF.write.enddefaults to false. Pipe acceptance does not imply that the child consumed the reply. - Time budgets: reuse
defaultTimeoutMsfor an action's fallback budget. AdddefaultMaxLifetimeMs, defaulting to the existing five-minute subprocess limit. Start's timeout covers startup and optional readiness; lifetime begins at spawn and is independent of later action budgets.
2. Keeping a process available between actions
Today, run starts a command and returns after it finishes. Login needs a different sequence: return when the CLI prints its URL, use the browser, then come back to the same CLI. The CLI keeps working throughout that sequence.
Driver: start and capture URL → use the browser → wait for confirmation
CLI: print URL ────────────→ poll for approval → print confirmation → exit
The framework therefore has three responsibilities: keep ownership of the process between calls, remember what it prints, and clean it up when the session is over. The details below follow from those responsibilities.
1. A returned action must not lose its process
When start returns a URL, the driver still needs a way to refer to that CLI later. The session keeps the actual process object; the driver receives a handle. A later wait, write, or stop uses that handle to find the same process.
Implementation: the existing subprocess resource maintains a private process registry. Each entry holds the child, captured output, pending waits and writes, lifetime timer, final result, and transcript revisions. Construct handles from a random runner-generation identifier and a monotonic process ordinal, and resolve them only in the owning session. Never use a host PID as the public handle.
Keep child exit, stream closure, spawn errors, and cleanup progress inside the runner. Callers see only the three action outcomes, nullable completion, and diagnostics defined in Section 1.
2. Keep listening while the driver is elsewhere
The CLI may print its confirmation while the browser action is still returning. If output collection only happens inside a wait action, the next wait could miss that confirmation. A child can also stall if its output pipe fills and nobody reads it.
The resource must therefore keep reading and remembering output even when no CLI action is active. A new wait looks through remembered output first; if it finds nothing, it waits for more.
Implementation: read stdout and stderr continuously from startup through stream closure, keeping separate bounded buffers. A wait searches stdout by default or explicitly selects stderr. Do not combine the streams or promise an ordering between them. Inspect the buffer and subscribe for new output without an asynchronous gap that could lose bytes or the end-of-stream event.
Remembering output needs limits. Retain these defaults and make any loss visible:
| What is retained | Limit | When the limit is reached |
|---|---|---|
| Raw output per stream | Existing 2 MiB cap | Discard oldest output and report the retained range; a wait cannot silently search missing history |
| Live managed processes | 8 per session | Reject a new start; never evict a live process to make room |
| Finalized process entries | Most recent 50 | Evict oldest first; later use of an expired handle fails explicitly |
The output cap reuses the existing runner limit. Eight live processes allows several coordinated commands while bounding pipes and memory; fifty finalized entries follows the existing recent-invocation retention scale. Expose the live and finalized-entry limits as validated CLI configuration. Repeated stop and waitForExit calls reuse a retained final result. Finalized entries retain no active timers, listeners, or OS resources.
3. Recognize messages rather than delivery fragments
Operating systems deliver output in chunks that need not line up with what the CLI printed. A URL can arrive in two pieces:
First delivery: Visit: https://example.test/dev
Next delivery: ice?code=ABCD\n
The first piece already resembles a URL, but navigating to it would be wrong. For ordinary CLI messages, wait for a complete line before matching it. Some prompts have no newline, so also offer text matching for those cases.
Implementation: line mode is the default. Match complete LF-delimited lines, removing a preceding CR; at end of stream, also evaluate a final unterminated line. Do not treat a truncated line as complete. Decode UTF-8 incrementally so delivery boundaries cannot corrupt a character.
Text mode matches the currently buffered decoded text without requiring a newline. Callers must include a delimiter when a variable-length capture, such as a URL, needs a definite ending. A regex end anchor alone does not prove that more output is not coming.
Represent patterns as JSON { source, flags }. Accept flags i, m, s, and u; reject stateful flags and unsupported combinations. Expressions are trusted driver-authored patterns, not untrusted user programs. For the login URL, the action describes:
until: {
stream: "stdout",
mode: "line",
pattern: {
source: "^Visit:\\s+(?<url>\\S+)$",
flags: ""
}
}
4. Give each wait a bookmark
A process may print the same prompt more than once. Searching from the beginning every time could match an old prompt. Each successful match therefore returns a bookmark, called a cursor. A later wait can search after that bookmark.
Remembered output: [prompt already matched] | [new confirmation]
↑
next wait starts here
The bookmark belongs immediately after the matched text. If the prompt and confirmation arrive together, putting it at the end of the delivery would skip the confirmation.
Implementation: use an opaque JSON cursor bound to the process generation, selected stream, and absolute decoded-output position. An omitted cursor means the beginning of stream history. Concurrent waits have independent cursors and do not consume each other's input.
If the bookmark points into discarded history, return cursor-expired with the available range. Reject zero-length successful matches so returned cursors advance. Check final buffered output before reporting that the stream ended without a match.
5. Allow a reply when the CLI asks for input
Some commands need an answer before they can print a URL. Start may supply an initial answer, and write allows later replies. The driver can also close stdin to tell the child that no more input will arrive.
Implementation: keep writes in order per child and wait for the pipe to accept input when it is full. This is backpressure handling; it does not prove the child has consumed the answer. Handle asynchronous EPIPE and stream-close errors as action failures without unhandled rejections. Follow the initial-input and EOF defaults in Section 1.
6. Ending a wait and ending a process are different decisions
A URL wait may time out while the CLI remains useful for inspection or another attempt. By contrast, when the session ends, nobody remains responsible for the child. At that point the framework must stop it even if the driver never reached its cleanup code.
| What happened | What happens to the process |
|---|---|
| A local output or exit wait times out | Keep the process available; the action returns timeout |
| Start with readiness matching fails | Clean up the newly created child before the action settles |
| The containing invocation is aborted | Cancel outstanding actions and terminate the processes those actions are operating on |
| The process reaches its maximum lifetime | Terminate it independently of individual action budgets |
| The driver calls stop, or the session ends | Terminate the process and finish capturing its output |
Implementation: use one termination path for explicit stop, readiness failure, invocation abort, lifetime expiry, resource closure, and run timeout. Remove each action's abort listener when that action settles. A successfully started child stays session-owned after its originating invocation completes. A pre-aborted action performs no spawn or write. Resource closure rejects new starts and does not depend on driver finally blocks.
A command can start child commands of its own. Termination must cover the supervised process group on macOS/Linux, addressing sageox-attest-466, rather than stopping only the first PID. Keep existing Windows run behavior unchanged.
First request termination with SIGTERM. Reuse the existing one-second grace, then escalate to SIGKILL. Bound total cleanup to five seconds so escalation and reaping fit below the daemon drain cap. Unconfirmed cleanup is an infrastructure failure; a deadline-bound action still uses the outcome rules in Section 1.
Finally, process exit and output completion are not simultaneous. Wait until captured streams close before publishing completion. Keep that distinction private, and continue cleanup escalation if a descendant holds a pipe open after the direct child has exited. Section 3 defines how final evidence is saved before session storage disappears.
Where this behavior lives
Implement these responsibilities in src/runtime/subproc.ts, behind the existing subprocess resource. The CLI executor validates inputs, delegates to that resource, and constructs typed outcomes, diagnostics, and evidence references.
Refactor run to reuse spawn, capture, termination, and finalization internally. Preserve its public result, stdin behavior, timeout behavior, diagnostics, and log format. Driver authors continue to use dispatch; registry and OS lifecycle mechanics remain internal.
3. Preserving what happened at each step
When a login journey fails, a reviewer needs to see what the CLI had printed before the browser opened, what happened in the browser, and how the CLI ultimately ended. A single log written at process exit cannot show the start step while the process is still running. A log that keeps changing can also make an earlier step appear to have seen output that arrived later.
Keep a record of what each action observed, and preserve a final record before the session's storage is destroyed. These records are evidence for the report; the raw output used to drive the next action stays available inside the session.
1. Save a snapshot when an action returns
The start action records the URL prompt it observed. The later wait records the confirmation it observed. Both belong to the same process, but each refers to its own moment in the journey.
Implementation: assign one process identity and immutable transcript revisions. Create a snapshot at each completed or failed live-process action and at autonomous process finalization. Use a distinct path for each revision in the existing subprocess artifact channel. Include identity, revision, elapsed duration, nullable completion, retained output ranges, and truncation or withholding indicators. Describe startup and cleanup failures through diagnostics, not extra public process states.
Return the exact EvidenceRef from the action so the report knows which snapshot belongs to it. Repeated terminal observations may reuse the final snapshot. Existing run logs and their historical ordinal-based attribution remain compatible.
A reference is useful only after the file is available. Publish snapshots atomically and await the write attempt before settling the action. If writing fails, report that failure without replacing the action's execution result or inventing a successful evidence reference.
The existing drain() operation remains a promise that evidence writes through a captured checkpoint have finished. It must not wait for the CLI to exit or for an ongoing output producer to become idle.
2. Save the final record before removing the session
Suppose the browser step fails and the driver never reaches its final CLI wait. Automatic cleanup still needs to stop the CLI and preserve what it printed. Today, the runner collects artifacts before destroying the session. Writing the final log only during destruction would be too late.
Finish session resources → collect their evidence → destroy session storage
Implementation: add required internal DaemonClient.prepareForCollection(). It prevents new invocations, settles the existing invocation queue with the current bounded drain rules, runs the existing reverse-order executor/resource unwind, terminates remaining children, writes final snapshots, and returns redacted cleanup diagnostics. Artifact listing, artifact reads, and the guest transport remain available.
Make preparation idempotent and share its teardown promise with ordinary disposal. The backend still owns destruction of the substrate. Call preparation for every provisioned scenario session before evidence collection, including failure and partial-bootstrap paths. Even if preparation errors, attempt evidence collection, then attempt backend teardown in finally.
Carry this operation through the fake provider, orchestrator, shared test doubles, and Shuru transport. Refresh Shuru's artifact cache after preparation. Bump the guest session protocol from revision 3 to 4 so an old guest cannot silently omit this guarantee; reject it through the existing version-mismatch path.
Successfully stopping an unfinished process produces a warning that identifies the start operation and final transcript. It does not change the authored business verdict. Failure to stop or finalize resources is an infrastructure failure.
3. Keep useful evidence without recording secrets
The browser needs the actual URL printed by the CLI, including its approval code. The persisted transcript should not expose credentials just because the driver needs them to perform the next step. This means the working output and the report copy have different responsibilities.
Implementation: keep raw matching buffers separate from redacted evidence buffers. Matching and in-daemon action results use raw output. Transcripts and diagnostic strings use the resource's existing exact-value and credential-shape redaction. Preserve value-only masking of business-result data so legitimate URLs remain usable for navigation and exports.
Output may split a secret across deliveries. Carry enough context to recognize known secret values before emitting evidence text, then apply shape redaction to complete lines. Withhold unfinished lines from intermediate persisted snapshots with an explicit marker; flush them safely at end of stream. If an unfinished line exceeds the existing stream cap, omit that evidence line with a truncation marker.
Redact before evicting evidence context so retention boundaries cannot expose fragments of recognized secrets. Record stdin byte counts rather than contents. Continue honoring the diagnostics kill switch.
4. Show the reader what is known
A start step can have succeeded while the final process result is still unavailable. The report should say that plainly, without an invented exit code or a warning that merely means “still waiting.”
Implementation: display action outcomes as completed, failed, or timeout. Show “Awaiting completion” when completion is null, and the actual exit or signal when it is available. Null completion must not produce an exit-zero badge, an unknown-exit failure badge, or a claim that the OS process is alive. Use diagnostics for startup and cleanup failures.
Attribute action and sub-action snapshots using exact evidence references. Show session-finalization snapshots as session evidence with cleanup diagnostics. Deduplicate identical references without merging different revisions. Preserve existing stored reports and legacy run logs. Existing evidence and diagnostic fields suffice; no RunSpec or report schema version bump is required.
4. Proving the whole journey works
The central claim is that the driver can leave a live CLI, interact with a browser, and return to the same CLI without losing output or control. Tests need to prove that relationship. Testing a matcher alone, or pretending that a browser click happened, cannot establish it.
Use a small local approval flow that behaves like login but has no SageOx product dependency. Then test the underlying failure cases at the lowest layer that can expose them.
1. Prove the ordinary journey
A real Node child asks for an initial answer, starts a tiny approval webpage, and prints its URL. The driver captures the URL and opens it in a real browser. Clicking Approve sends a request to the child, which prints confirmation, closes its server, and exits. The driver observes that confirmation and checks the final exit.
Implementation: keep this as three separate business operations: start/capture URL, navigate/click Approve, and observe confirmation/await successful exit. Store the handle and cursor in JSON session state; export the URL. Bind the fixture server to an ephemeral loopback port, and carry the child as an inline script in its driver bundle so the test does not depend on host or guest asset paths.
2. Prove the journey can fail safely
Add a scenario that fails after startup, leaving the child waiting for approval. The framework must stop the supervised process group and preserve its final evidence even though the final CLI operation never ran.
Also prove that the start snapshot is readable while the child is still alive. Together, these cases test both promises that exit-only command execution cannot provide.
3. Put each remaining claim at the right test layer
Use real subprocesses for pipe, exit, and cleanup behavior. Use daemon/runner integration tests for ownership between verbs and finalization ordering. Render actual writer-produced logs to check the report. Reserve backend and model-dependent tests for the behavior those layers can uniquely prove.
| Layer | Required coverage |
|---|---|
| Matcher | Split UTF-8 and URL; CRLF; EOF without newline; text prompts; match-end cursor; multiple messages per chunk; stale cursor; truncated lines |
| Real subprocess | Output before waiter registration and between actions; both streams draining; initial input; repeated writes; backpressure; EPIPE; early exit; spawn failure |
| Lifecycle | Local timeout preserves usability; readiness failure cleanup; invocation abort; lifetime expiry; repeated terminal calls; retention limits; foreign/expired handles; completion stays null between child exit and stream closure |
| Outcome contract | New start spawn failure is failed with null completion; legacy run spawn failure stays completed; unmatched EOF fails; waitForExit observing exit 1 completes with code 1; deadline yields timeout; no public process-state enum |
| Process group | A descendant outlives the direct child and holds a pipe; stop and timeout remove the group and finish |
| Evidence | Readable before action return; immutable prior revisions; redaction across chunks and retention boundaries; write failure; diagnostics disabled |
| Daemon/runner | One handle across verbs; intervening failure; finalize before pull; cleanup warning/failure; disposal idempotency |
| Report | Render actual writer bytes; correct pending/final completion attribution; startup and cleanup diagnostics; legacy logs |
| Package/transport | Action-result inference; strict JSON; packed consumer imports; revision-4 handshake; stale-guest refusal |
| Browser acceptance | Actual click completes the real child; failing scenario preserves final cleanup evidence |
Implementation: keep the tests repeatable
Reuse shared daemon/provider harnesses. Do not use the existing CLI web-preflight fixture's simulated executor as evidence of an actual click. Normal integration coverage must not require model-provider credentials: a clearly labeled injected action adapter may translate the fixed Approve instruction into a real Playwright click. Add a separate infrastructure-gated Shuru case with the built-in web executor and existing real-browser/model conventions.
Use handshakes and injected clocks/schedulers instead of sleep-based assertions. Parse wire-shaped JSON with strict Zod schemas. Demonstrate that important regression tests fail when buffering, process-group termination, snapshot flushing, or the pre-collection barrier is removed.
5. Work breakdown and delivery checks
The implementation has three parts: give the subprocess resource a usable live-process API, connect that API to dispatch and evidence collection, and prove the resulting journey through the report and package boundary. The work packages below turn those responsibilities into concrete changes.
Each package specifies affected files, implementation tasks, dependencies, and observable completion checks. W01–W12 are references within this plan; create linked Beads issues from them when implementation starts. Existing issue sageox-attest-466 supplies the process-group cleanup work in W04.
Implementation work at a glance
| Package | Deliverable | Depends on |
|---|---|---|
| W01 | Define the contracts callers and implementations share | None |
| W02 | Give the subprocess resource ownership between calls | W01 |
| W03 | Remember output and wait for a meaningful message | W02 |
| W04 | Implement replies and reliable termination | W02 |
| W05 | Write immutable, redacted process evidence | W02, W03, W04 |
| W06 | Expose all interactions through the CLI executor | W01, W03, W04, W05 |
| W07 | Finalize daemon resources while retaining artifact access | W04, W05 |
| W08 | Carry finalization through every provider and the Shuru wire | W07 |
| W09 | Prepare each scenario session before pulling evidence | W07, W08 |
| W10 | Render the action snapshots and completion model | W05, W06, W09 |
| W11 | Build and run the local approval acceptance fixture | W06, W09, W10 |
| W12 | Document adoption and complete the release checks | W01–W11 |
Dependency shape: W01 → W02 → output matching (W03) and input/termination (W04) → snapshots (W05). Dispatch (W06) and session finalization (W07–W09) then meet in reporting (W10), followed by the acceptance fixture (W11) and release checks (W12).
Integration boundary: W07–W09 introduce a required daemon operation across callers, implementations, and the guest protocol. Land them together as one coherent integration change; do not ship no-op preparation methods or a partially upgraded transport. The packages are work units, not a promise that every one is an independently releasable PR.
W01. Define the contracts callers and implementations share
Establish the action shapes and finalization contract before implementing behavior.
Depends on: None Affected files: src/executors/cli.ts, src/executors/index.ts, src/runtime/subproc.ts, src/runtime/daemon.ts, docs/adr/002-session-resources-port-fixed-daemon-behavior-def.md, docs/adr/README.md
Required changes
- Define inputs, JSON payload schemas, action/result types, and the CliAction union for start, waitFor, write, waitForExit, and stop. Define nullable completion and action-specific failure data; keep OS lifecycle states private.
- Specify configuration defaults and limits from Sections 1–2, additive env support on run/start, and private runner operations needed by the executor. Reuse the existing run result unchanged.
- Define prepareForCollection() returning { diagnostics: Diagnostic[] }, its idempotent behavior, and its requirement to preserve artifact access. Record the ADR-002 extension and protocol revision change. Introduce the required client member together with W07–W09, when every implementation is ready.
Complete when
- Strict schema cases cover valid/malformed action payloads and JSON round-tripping. Type assertions distinguish each action result and nullable completion.
- The ADR validator passes. Existing run payloads and result types remain compatible. Runtime action registration is completed in W06.
W02. Give the subprocess resource ownership between calls
A started child remains addressable after start returns, and ordinary run still works.
Depends on: W01 Affected files: src/runtime/subproc.ts, src/runtime/resources.ts, tests/runtime/subproc.test.ts, tests/runtime/resources-impl.test.ts
Required changes
- Extract shared spawn/capture/finalization machinery from run. Register children at startup, reserve ordinals once, and attach output listeners before returning a usable handle.
- Implement session-generation handles, lookup errors, live-process admission, finalized-entry retention, and resource-closing refusal. Retain completion results while releasing timers/listeners/OS resources.
- Rebuild run on the common machinery, preserving its stdin closure, result shape, exit conventions, timing, diagnostics, and legacy log format. Thread injectable time/lifecycle seams through this machinery for deterministic tests.
Complete when
- Real subprocess tests show a child continues after start, later calls resolve the same child, and final results remain available after exit.
- Foreign/expired handles and both registry limits behave as specified. Existing run and resource tests stay green.
W03. Remember output and wait for a meaningful message
A wait finds output printed before or during another action without matching a partial URL.
Depends on: W02 Affected files: src/runtime/subproc.ts, tests/runtime/subproc.test.ts
Required changes
- Add continuously filled, independently bounded stdout/stderr histories with incremental UTF-8 decoding and absolute positions.
- Implement line/text framing, supported regex flags, capture groups, match-end cursors, explicit expired-range failures, and independent concurrent waits.
- Make buffered inspection and waiter registration race-free. Resolve matching final output before EOF failure, reject empty matches, and release waiters/listeners on settlement or cancellation.
Complete when
- Handshake-driven children prove output before wait registration and output between verbs is retained; matching works across UTF-8 and delivery boundaries.
- Tests cover repeated prompts, two messages in one chunk, text prompts, CRLF, final unterminated lines, stale cursors, truncated lines, and early EOF.
W04. Implement replies and reliable termination
The driver can send input, and every cleanup path can stop the supervised process group.
Depends on: W02 Affected files: src/runtime/subproc.ts, src/runtime/resources.ts, tests/runtime/subproc.test.ts, tests/runtime/timeout-hierarchy.test.ts
Required changes
- Implement initial input and queued write/end operations with backpressure, byte-count reporting, and asynchronous EPIPE/close handling.
- Implement one process-group termination path for explicit stop, failed readiness, invocation abort, lifetime expiry, run timeout, and resource closure. Apply the existing one-second escalation grace and five-second total cleanup bound.
- Track child exit separately from stream closure; keep escalating if descendants retain pipes. Remove action abort listeners after settlement, reject pre-aborted side effects, and preserve a successfully started child across completed invocations.
- Implement macOS/Linux process-group support and explicit native-Windows rejection for new actions. Address the existing sageox-attest-466 issue with this work; preserve Windows run behavior.
Complete when
- Real children require and receive initial/later input; closed stdin and blocked writes settle predictably without unhandled errors.
- A descendant that outlives its parent and holds a pipe is terminated. Tests distinguish local wait timeout, invocation abort, lifetime expiry, repeat stop, and unconfirmed cleanup.
W05. Write immutable, redacted process evidence
Each action can reference a readable snapshot without leaking secrets or rewriting earlier history.
Depends on: W02, W03, W04 Affected files: src/runtime/subproc.ts, src/runtime/redaction.ts, src/runtime/resources.ts, tests/runtime/redaction.test.ts, tests/runtime/resources-atomic-write.test.ts
Required changes
- Add process-scoped revision paths, snapshot metadata, immutable action/finalization snapshots, and atomic publication. Return a successful EvidenceRef only after the write attempt succeeds.
- Implement redacted evidence buffering separately from raw matching: retain context for split known secrets, redact complete lines, withhold unfinished lines, and mark over-cap omissions before evicting context.
- Make drain await a captured evidence-write checkpoint; propagate write and cleanup diagnostics without corrupting action results. Preserve the diagnostics kill switch and legacy run logs.
- Expose resource cleanup summaries so session finalization can return redacted warnings/errors and reference terminal snapshots. Keep stdin contents out of snapshots.
Complete when
- Read a start snapshot before the child exits; later output cannot change its bytes. Delayed writes cannot yield premature evidence references.
- Tests exercise redaction across chunks/lines/retention boundaries, suppressed diagnostics, disk-write failure, and a continuing producer that cannot keep drain open indefinitely.
W06. Expose all interactions through the CLI executor
Drivers use dispatch for the full live-process lifecycle with correctly inferred results.
Depends on: W01, W03, W04, W05 Affected files: src/executors/cli.ts, src/executors/index.ts, src/index.ts, tests/executors/cli.test.ts, tests/executor/dispatch-typing.test.ts
Required changes
- Add typed JSON constructors, payload normalization, the execute dispatcher for the new action union, and package exports. Validate before delegating to the borrowed resource.
- Implement start with optional readiness using the same matcher as waitFor. Make readiness failure clean up the new child before settling; retain children after plain local wait timeouts.
- Map all results to completed/failed/timeout plus nullable completion. Emit exact action/sub-action evidence references and diagnostics. Add env forwarding to run and start.
- Keep spawn failure on new start as failed, preserve the existing run exception, and avoid automatic retries of side-effectful actions.
Complete when
- Executor tests pin start failure, successful matching, unmatched EOF, waitForExit observing code 1, write failure, timeout, unsupported platform, and cleanup results.
- Compile-time tests infer each constructor’s result and allow type-only driver imports with explicitly typed JSON actions. Existing dispatch/run tests pass.
W07. Finalize daemon resources while retaining artifact access
A finished session can release its resources without immediately losing its evidence transport.
Depends on: W04, W05 Affected files: src/runtime/daemon.ts, src/runtime/resources.ts, tests/runtime/invocation-semantics.test.ts, tests/runtime/daemon-evidence-flush.test.ts, tests/runtime/daemon-artifacts.test.ts
Required changes
- Implement prepareForCollection with new-invocation refusal, bounded queue settlement, existing reverse-order unwind, subprocess finalization, and collected redacted diagnostics.
- Memoize the preparation/unwind promise and share it with dispose so repeat or concurrent callers await the same work. Keep artifact listing and reads usable afterward.
- Complete action snapshot flushing on ordinary invocation returns and preserve timeout/failure diagnostics. Surface cleanup caps and unconfirmed termination as infrastructure errors.
Complete when
- Daemon tests cover a live process followed by a failing verb, final snapshots readable after preparation, rejected later invokes, and idempotent/concurrent preparation and disposal.
- Delayed writes, stuck invocations, and failing cleanup are visible diagnostics; the daemon never claims successful finalization before its bounded work completes.
W08. Carry finalization through every provider and the Shuru wire
Local and guest-backed sessions provide the same preparation guarantee.
Depends on: W07 Affected files: src/runtime/fake-provider.ts, src/runtime/orchestrator/provider.ts, src/backends/shuru/provider.ts, src/backends/shuru/protocol.ts, src/backends/shuru/wire.ts, src/backends/shuru/guest/daemon-entry.ts, tests/runtime/provider-contract.ts
Required changes
- Forward prepareForCollection through the fake provider, client wrappers, and shared test doubles; preserve secret-redaction behavior on errors.
- Add POST /prepare-for-collection to the Shuru host/guest contract with a strictly validated diagnostics response. The guest prepares resources but keeps its server and artifact routes alive.
- Have the Shuru host await preparation then refresh cached artifacts. Bump SESSION_PROTOCOL_VERSION from 3 to 4 and update handshake/stale-runtime fixtures.
- Extend the shared provider contract suite; update the shared fixture backend copies together so fixture-backend parity remains true.
Complete when
- Fake and Shuru contract coverage verifies prepare → read artifacts → dispose, repeat preparation, and refusal of later invokes.
- Malformed responses and revision-3 guests fail explicitly. Existing artifact and shutdown behavior remains covered.
W09. Prepare each scenario session before pulling evidence
The runner collects final cleanup evidence on success and failure before destroying storage.
Depends on: W07, W08 Affected files: src/runtime/orchestrator/orchestrator.ts, src/runtime/runner/runner.ts, src/runtime/runner/evidence-sink.ts, tests/runtime/runner/runner.test.ts, tests/runtime/runner/evidence-sink.test.ts, tests/runtime/orchestrator/orchestrator.test.ts
Required changes
- Add the orchestrator delegation for session preparation. Use it for each provisioned session before the runner’s artifact pull, including fail-fast, partial bootstrap, and multi-persona scenario paths.
- Return cleanup warnings/errors into existing report diagnostics and lifecycle status. Preserve the authored business verdict when automatic cleanup succeeds.
- Attempt artifact collection even after preparation failure; ensure backend deletion/reaping is attempted in finally. Publish collected evidence before scenario-finished using the existing event/report flow.
- Extend shared doubles with delayed final evidence and a backend that removes storage at teardown, so ordering regressions are observable.
Complete when
- Tests assert actual final bytes are pulled before storage removal, including a skipped finish verb and one failing member of a multi-persona scenario.
- Successful automatic cleanup warns; failed cleanup produces infrastructure failure. No preparation error can suppress best-effort evidence collection or teardown.
W10. Render the action snapshots and completion model
Reports show what each action saw and whether a final process result is available.
Depends on: W05, W06, W09 Affected files: src/dashboard/view-model.ts, tests/dashboard/view-model.test.ts, tests/dashboard/subproc-log-format.test.ts, tests/fixtures/golden-runs/
Required changes
- Extend transcript parsing/rendering for live revisions, nullable completion, actual exits/signals, and cleanup diagnostics.
- Attribute live snapshots by exact EvidenceRef to operations and sub-actions, deduplicate identical references, and leave distinct revisions distinct. Keep finalization evidence visible at session scope.
- Retain legacy run-log parsing and ordinal-based attribution. Update representative golden report evidence after binding the parser tests to real runner-written bytes.
Complete when
- Pending completion displays Awaiting completion, without exit-zero or unknown-exit failure badges. Failed startup/cleanup appears as diagnostics.
- A start snapshot and later final snapshot render under the correct steps; actual writer output and old stored reports both render successfully.
W11. Build and run the local approval acceptance fixture
A real browser action causes the same supervised child to finish, and failed browser work is cleaned up.
Depends on: W06, W09, W10 Affected files: tests/fixtures/cli-process-app/ (new), tests/runtime/harness.ts, tests/runtime/runner/runner.test.ts, tests/backends/shuru/exec-web.tier1.test.ts, tests/pack.test.ts
Required changes
- Create the inline Node approval server, initial-stdin handshake, three driver operations, business-action/verification definitions, and the failure scenario described in Section 4.
- Use typed JSON actions and type-only @sageox/attest imports in bundled drivers; existing bundling forbids runtime package-value imports. Store handle/cursor in session state and export the URL.
- Reuse shared daemon/provider harnesses. Drive a real browser click through the clearly labeled deterministic test adapter for ordinary integration coverage, without model credentials.
- Add the gated Shuru journey using the built-in web executor and existing real-browser/model conventions. Exercise the fixture against the packed package so bundle transport and published exports are covered.
Complete when
- The success journey proves URL capture → actual browser approval → CLI confirmation → final exit 0, with the child continuously owned between operations.
- The failure journey proves process-group cleanup and final evidence collection. Tests also read the start snapshot before approval, and report infrastructure prerequisites as explicit skips.
W12. Document adoption and complete the release checks
Consumers can use the feature correctly from the packed API without depending on monorepo internals.
Depends on: W01–W11 Affected files: docs/guides/getting-started.md, docs/guides/writing-runners.md, docs/guides/runner-catalog.md, src/cli/init.ts, src/executors/index.ts, tests/docs-truth.test.ts, tests/pack.test.ts
Required changes
- Update the action catalogue, conceptual driver walkthrough, result semantics, defaults/limits, cleanup policy, platform scope, and report behavior. Keep the monorepo migration as a documentation example.
- Update scaffold guidance and enforced docs assertions. Show host-side constructors and runtime type-only/JSON usage accurately; do not add a new runtime import capability.
- Run required typecheck, lint, test, build, pack, and ADR checks. Record gated-check outcomes and unresolved infrastructure prerequisites. Update linked Beads statuses when implementation is actually complete.
Complete when
- The packed consumer can import the documented public types, compile its driver bundle, and execute the fixture with no private Attest or SageOx monorepo imports.
- All required local gates pass; any gated checks are honestly reported. No publish, commit, push, or monorepo edit is part of this delivery.
Final acceptance and release checks
The delivery is complete when the packaged three-operation approval flow uses dispatch with one continuously running child; failed browser work leaves no supervised group; start evidence is readable while the child runs; final evidence is collected before storage destruction; and existing run behavior and historical reports remain compatible.
pnpm typecheck
pnpm lint
pnpm test
pnpm build
npm pack
python3 scripts/check-decision-records.py --dir docs/adr --prefix ADR \
--rule-file .claude/rules/adr/decision-records.md
Run focused package checks during development and the complete required gates before any authorized commit or push. Use strict Zod parsing for wire-shaped JSON assertions. Demonstrate that the key regression tests fail without their corresponding protections. Report gated checks as passed or explicitly skipped with the missing prerequisite.
Delivery remains Attest only. Native Windows live-process support, PTYs, restart reconnection, a public streaming subscription API, publishing, commits, pushes, and the SageOx consumer migration remain outside this plan.
Architecture and implementation anchors
SageOx ownership signal: Galex Yen owns the runtime area (6 commits; last touched July 2026). The enrichment panel includes the source and related backend architecture context.
Resource ownership: docs/adr/002-session-resources-port-fixed-daemon-behavior-def.md. Backend transport and collection: docs/adr/004-backend-adapters-are-swappable-behind-one-contract.md. Implementer entrypoints: src/runtime/subproc.ts, src/runtime/resources.ts, src/executors/cli.ts, src/runtime/daemon.ts, src/runtime/runner/runner.ts, src/dashboard/view-model.ts. Existing descendant-cleanup issue: sageox-attest-466.
Prior-art references: Pexpect stream matching, Playwright output readiness, Node child-process close semantics.
enriched by

