Repository navigation
feat(orchestration): coordinator-driven release of settled worker terminals (STA-905) - #12355
Conversation
…minals (STA-905) After processing each accepted worker_done, coordinators now either reuse the exact worker terminal (ownership transfers to the new Dispatch) or run worker-release, which freezes an inspectable output archive (provider transcript pin or bounded redacted terminal tail) before closing only the exact coordinator-owned agent terminal. worker-retain records a durable user-requested exception; worker-list reports terminal accounting separately from Task status. Schema v23 adds worker_terminal_resources ownership/release records with a conservative backfill (owned only for unique exact creation evidence). External, transferred, user-taken-over, and unproven identities are always retained; releases are idempotent mutations with durable retry receipts, and a startup/reconnect reconciler finishes only previously requested releases. Real user keystrokes durably relinquish orchestration ownership on the terminal-owning runtime. Federated dispatch release fails closed with a typed retained receipt.
📝 WalkthroughWalkthroughAdded coordinator-controlled worker terminal release, retention, and reuse behavior. Added durable ownership and archive storage with schema version 23 migration and recovery reconciliation. Added RPC and CLI commands for release, retention, listing, archived reads, and user takeover reporting. Worker output remains readable through transcript pins or bounded redacted terminal archives after release. Updated orchestration guidance and tests to enforce settled-worker cleanup rules. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (4)
src/main/runtime/orchestration/db.ts (3)
5625-5635: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winPrefer exact JSON membership over
LIKEfor prior owners.
LIKEtreats_as a single-character wildcard. Dispatch ids contain_(for examplectx_...), so the pattern can match a non-identical id. Usejson_eachfor exact membership.♻️ Proposed change
getWorkerTerminalResourceFormerlyOwnedBy( dispatchId: string ): WorkerTerminalResourceRow | undefined { return this.db .prepare( `SELECT * FROM worker_terminal_resources - WHERE prior_owner_dispatch_ids LIKE ? + WHERE EXISTS ( + SELECT 1 FROM json_each(prior_owner_dispatch_ids) p WHERE p.value = ? + ) ORDER BY updated_at DESC LIMIT 1` ) - .get(`%"${dispatchId}"%`) as WorkerTerminalResourceRow | undefined + .get(dispatchId) as WorkerTerminalResourceRow | undefined }
5691-5712: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReuse
WORKER_RELEASABLE_STATESfor the releasable-state gate.
worker-terminal-ownership.tsexportsWORKER_RELEASABLE_STATESwith the same['succeeded', 'failed']set. Import it here so the release rule stays in one place.
5909-5943: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winReplace the per-row resource lookup with a single join.
listWorkerTerminalResourcesruns onegetWorkerTerminalResourceByOwnerquery for every worker dispatch row. For a Run with many dispatches this becomes an N+1 read on a command path. ALEFT JOIN worker_terminal_resources ON owner_dispatch_id = w.dispatch_idreturns the same data in one statement. Select the resource columns with a distinct alias prefix so the row mapper can rebuild theWorkerTerminalResourceRowshape.src/main/runtime/orchestration/worker-terminal-release-reconciliation.ts (1)
45-48: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winLog the swallowed failure cause.
The
catchblock discards the error. A repeated archive or endpoint failure then shows only as a risingpendingcount, with no cause to diagnose. Log the resource id and the error, without transcript content.♻️ Proposed change
- } catch { + } catch (error) { // Archive or endpoint failure: durable intent stays requested; a later discovery retries. + console.warn( + '[orchestration] worker terminal release retry failed', + { resourceId: resource.id, dispatchId: resource.owner_dispatch_id }, + error + ) result.pending += 1 }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 2f35620b-5b8e-4b90-a34c-86e05a8cd528
📒 Files selected for processing (29)
config/scripts/orchestration-skill-guidance.test.mjsskill-guides/orchestration.mdsrc/cli/bundled-skill-guides.tssrc/cli/handler-group-manifest.tssrc/cli/handlers/orchestration.tssrc/cli/help.tssrc/cli/index.test.tssrc/cli/specs/orchestration-worker-specs.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/orchestration-db-retention-pagination.test.tssrc/main/runtime/orchestration/worker-output-archive.tssrc/main/runtime/orchestration/worker-terminal-ownership.tssrc/main/runtime/orchestration/worker-terminal-release-reconciliation.tssrc/main/runtime/rpc/methods/orchestration-worker-archive-read.tssrc/main/runtime/rpc/methods/orchestration-worker-control.tssrc/main/runtime/rpc/methods/orchestration-worker-legacy-federated-read.tssrc/main/runtime/rpc/methods/orchestration-worker-methods.tssrc/main/runtime/rpc/methods/orchestration-worker-output.tssrc/main/runtime/rpc/methods/orchestration-worker-release-completion.tssrc/main/runtime/rpc/methods/orchestration-worker-release.test.tssrc/main/runtime/rpc/methods/orchestration-worker-release.tssrc/main/runtime/rpc/methods/orchestration-worker-topology.tssrc/main/runtime/rpc/methods/orchestration-workers.tssrc/main/runtime/rpc/methods/orchestration.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/lib/worker-terminal-takeover-report.tssrc/shared/orchestration-rpc-contract.tssrc/shared/orchestration-worker-output.ts
| { | ||
| path: ['orchestration', 'worker-retain'], | ||
| summary: 'Keep one supervised worker terminal live for debugging', | ||
| usage: | ||
| 'orca orchestration worker-retain --dispatch <dispatch_id> [--retry-request <id>] [--json]', | ||
| allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'], | ||
| notes: [ | ||
| 'Records a durable user-requested exception, so later release calls leave the terminal running.', | ||
| 'Performs no process or filesystem action.' | ||
| ] |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Add a retention-clear operation before documenting later release.
worker-retain makes later worker-release calls return retained, so a user cannot release the terminal after debugging. This leaves retained worker terminals live indefinitely.
src/cli/specs/orchestration-worker-specs.ts#L84-L93: add a command or flag that clears durable retention.src/cli/handlers/orchestration.ts#L984-L992: route the retention-clear operation to a runtime mutation.skill-guides/orchestration.md#L235-L235: document the actual command to release a retained terminal after debugging.src/cli/bundled-skill-guides.ts#L33-L33: keep the bundled guide aligned withskill-guides/orchestration.md.config/scripts/orchestration-skill-guidance.test.mjs#L238-L273: add coverage for retain, clear retention, and successful release.
📍 Affects 5 files
src/cli/specs/orchestration-worker-specs.ts#L84-L93(this comment)src/cli/handlers/orchestration.ts#L984-L992skill-guides/orchestration.md#L235-L235src/cli/bundled-skill-guides.ts#L33-L33config/scripts/orchestration-skill-guidance.test.mjs#L238-L273
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/runtime/rpc/methods/orchestration-worker-release.test.ts (1)
451-453: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: assert the suffix with
endsWith.
suffixis a local constant, so the ast-grep ReDoS hint is a false positive. A plain string check removes the linter noise and reads more directly.♻️ Proposed simplification
expect(read.terminal.tail).toHaveLength(1) - expect(read.terminal.tail[0]).toMatch(new RegExp(`${suffix}$`)) + expect(read.terminal.tail[0].endsWith(suffix)).toBe(true) expect(read.terminal.truncated).toBe(true)Source: Linters/SAST tools
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c47bc29a-26b0-41f5-b1cb-e4090a2fada8
📒 Files selected for processing (17)
config/scripts/orchestration-skill-guidance.test.mjsskill-guides/orchestration.mdsrc/cli/bundled-skill-guides.tssrc/cli/handlers/orchestration.tssrc/cli/specs/orchestration-worker-specs.tssrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/worker-output-archive.tssrc/main/runtime/orchestration/worker-terminal-ownership.tssrc/main/runtime/orchestration/worker-terminal-release-reconciliation.tssrc/main/runtime/orchestration/worker-transcript-read.test.tssrc/main/runtime/orchestration/worker-transcript-read.tssrc/main/runtime/rpc/methods/orchestration-worker-archive-read.tssrc/main/runtime/rpc/methods/orchestration-worker-release-completion.tssrc/main/runtime/rpc/methods/orchestration-worker-release.test.tssrc/main/runtime/rpc/methods/orchestration-worker-release.tssrc/renderer/src/lib/worker-terminal-takeover-report.test.tssrc/renderer/src/lib/worker-terminal-takeover-report.ts
🚧 Files skipped from review as they are similar to previous changes (10)
- src/cli/specs/orchestration-worker-specs.ts
- config/scripts/orchestration-skill-guidance.test.mjs
- skill-guides/orchestration.md
- src/main/runtime/rpc/methods/orchestration-worker-release.ts
- src/cli/bundled-skill-guides.ts
- src/main/runtime/orchestration/worker-output-archive.ts
- src/main/runtime/orchestration/worker-terminal-ownership.ts
- src/main/runtime/rpc/methods/orchestration-worker-archive-read.ts
- src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
- src/main/runtime/orchestration/db.ts
| if (endOffset !== undefined && (await stat(filePath)).size < endOffset) { | ||
| return { ok: false, reason: 'source_changed', warnings: [] } | ||
| } | ||
| const page = await readNativeChatTranscriptTailFile(filePath, limit, decode, false, endOffset) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Revalidate the pinned boundary after the transcript read.
Both checks run before the file is opened and scanned. If the transcript truncates after this check, an archived read can return a successful partial result instead of source_changed. Revalidate that the source still reaches endOffset after the bounded read before returning success.
src/main/runtime/orchestration/worker-transcript-read.ts#L103-L106: revalidate the boundary afterreadNativeChatTranscriptTailFilecompletes.src/main/runtime/orchestration/worker-transcript-read.ts#L124-L128: revalidate the boundary after the forward scan completes and map a shrink tosource_changed.
📍 Affects 1 file
src/main/runtime/orchestration/worker-transcript-read.ts#L103-L106(this comment)src/main/runtime/orchestration/worker-transcript-read.ts#L124-L128
|
Electron QA passed on commit
|
|
Provider orchestration validation passed with no confusion observed.
Both providers independently:
Audit run: |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts (1)
26-92: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the shared release test fixture.
This
setup()body duplicatessetup()insrc/main/runtime/rpc/methods/orchestration-worker-release.test.tslines 28-98 almost line for line. The two copies already differ: the release test also mapsterm_remintedingetTerminalPaneKey,getTerminalProcessIncarnation, andgetOrchestrationDispatchAuthority. The copies will keep drifting as the runtime surface changes.Move the fixture into a dedicated module, for example
orchestration-worker-release-fixture.ts, and import it from both test files. Use a concrete domain name, nothelpers,utils, orcommon.As per coding guidelines: "Do not use vague names such as
helpers,utils,common,misc, orshared-stufffor files, folders, or modules; use concrete domain names instead."Source: Coding guidelines
src/main/runtime/orchestration/worker-output-archive.ts (1)
56-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRecord why the provider transcript capture was skipped.
readWorkerTranscript(...).catch(() => null)discards the thrown error, and the!snapshot.okcase discardssnapshot.reason. When a provider session exists but the transcript cannot be read, the archive falls back to the terminal tail with no record of the cause. The fallback warning at Line 103 is emitted only when the terminal tail is also empty, so a non-empty tail archive gives the reader no reason at all.Carry the reason into the terminal-tail warnings so
worker-readcan explain the fallback.♻️ Proposed change to preserve the fallback reason
const session = args.runtime.getExactWorkerProviderSession(args.terminalHandle, args.attachedAtMs) + const transcriptWarnings: string[] = [] if (session) { const snapshot = await readWorkerTranscript({ agent: session.agent, sessionId: session.providerSession.id, transcriptPath: session.providerSession.transcriptPath, limit: MAX_WORKER_TRANSCRIPT_MESSAGE_LIMIT - }).catch(() => null) + }).catch((error) => { + transcriptWarnings.push( + `Provider transcript capture failed: ${error instanceof Error ? error.message : String(error)}.` + ) + return null + }) if (snapshot?.ok && snapshot.messages.length > 0) {Then include
transcriptWarningsin theterminal_tailwarningsarray, and pushsnapshot.reasonwhensnapshotis present but notok.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 62ab6663-3b96-47c2-883a-4e5abd449709
📒 Files selected for processing (9)
config/reliability-gates.jsoncsrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/worker-output-archive.tssrc/main/runtime/rpc/methods/orchestration-worker-archive-read.tssrc/main/runtime/rpc/methods/orchestration-worker-release-completion.tssrc/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.tssrc/main/runtime/rpc/methods/orchestration-worker-release.test.tssrc/main/runtime/rpc/orchestration-mutation-executor.tssrc/main/runtime/rpc/orchestration-mutation-ledger.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
- src/main/runtime/orchestration/db.ts
| const content = JSON.parse(archive.content) as | ||
| | WorkerTranscriptPinArchive | ||
| | WorkerTranscriptSnapshotArchive | ||
| return isTranscriptSnapshot(content) | ||
| ? readFrozenTranscript(args, archive, content) | ||
| : readLegacyPinnedTranscript(args, content) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Guard the archive JSON parse.
JSON.parse(archive.content) is unguarded. If a stored archive row is truncated or corrupt, this throws a raw SyntaxError instead of a typed OrchestrationError. The caller then receives a generic failure with no recovery guidance, on the exact path a user takes to inspect a released worker.
🐛 Proposed fix to return a typed error
- const content = JSON.parse(archive.content) as
- | WorkerTranscriptPinArchive
- | WorkerTranscriptSnapshotArchive
+ let content: WorkerTranscriptPinArchive | WorkerTranscriptSnapshotArchive
+ try {
+ content = JSON.parse(archive.content)
+ } catch {
+ throw new OrchestrationError(
+ 'archive_unavailable',
+ `The preserved output archive for Dispatch ${args.dispatchId} is unreadable.`
+ )
+ }
return isTranscriptSnapshot(content)
? readFrozenTranscript(args, archive, content)
: readLegacyPinnedTranscript(args, content)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const content = JSON.parse(archive.content) as | |
| | WorkerTranscriptPinArchive | |
| | WorkerTranscriptSnapshotArchive | |
| return isTranscriptSnapshot(content) | |
| ? readFrozenTranscript(args, archive, content) | |
| : readLegacyPinnedTranscript(args, content) | |
| let content: WorkerTranscriptPinArchive | WorkerTranscriptSnapshotArchive | |
| try { | |
| content = JSON.parse(archive.content) | |
| } catch { | |
| throw new OrchestrationError( | |
| 'archive_unavailable', | |
| `The preserved output archive for Dispatch ${args.dispatchId} is unreadable.` | |
| ) | |
| } | |
| return isTranscriptSnapshot(content) | |
| ? readFrozenTranscript(args, archive, content) | |
| : readLegacyPinnedTranscript(args, content) |
| const pendingClose = deferred<Awaited<ReturnType<OrcaRuntimeService['closeTerminal']>>>() | ||
| vi.mocked(runtime.closeTerminal).mockReturnValue(pendingClose.promise) | ||
|
|
||
| const first = reconcileRequestedWorkerTerminalReleases(runtime) | ||
| await vi.waitFor(() => expect(runtime.closeTerminal).toHaveBeenCalledTimes(1)) | ||
| const second = reconcileRequestedWorkerTerminalReleases(runtime) | ||
| expect(second).toBe(first) | ||
| pendingClose.resolve({ handle: 'term_worker', tabId: 'tab-worker', ptyKilled: true }) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Resolve the declared return type of OrcaRuntimeService.closeTerminal.
set -euo pipefail
rg -nP -C 6 '\bcloseTerminal\s*\(' --type=ts src/main/runtime/orca-runtime.ts
rg -nP -C 8 'RuntimeTerminalClose' --type=ts src/shared src/mainRepository: stablyai/orca
Length of output: 13335
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the test file around both mocked call sites and definitions of helper/types used.
sed -n '1,230p' src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts
# Check whether runtime.closeTerminal in this file is the Claude Agent Teams method or notifier.closeTerminal.
rag -n "closeTerminal|RuntimeTerminalClose|closed|ptyKilled|tabId|handle" src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.tsRepository: stablyai/orca
Length of output: 9586
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
# Read-only check: compare the two mocked resolution shapes in the test to RuntimeTerminalClose.
from pathlib import Path
text = Path("src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts").read_text()
shapes = {
"setup-closeTerminal": ("{ handle: 'term_worker', closed: true }", "closed")
}
for line in text.splitlines():
line = line.strip()
if "RuntimeTerminalClose" in line:
print("found RuntimeTerminalClose literal:", line)
shapes["literal"] = line
if '.mockResolvedValue({ ' in line:
parts = [a.strip() for a in line.splitlines()]
print("mockResolvedValue start:", line)
PY
rg -n "RuntimeTerminalClose|closeTerminal\\(" src/shared/runtime-types.ts src/main/runtime/orca-runtime.ts src/main/runtime/claude-agent-teams-types.ts || trueRepository: stablyai/orca
Length of output: 1610
Fix the closeTerminal mock shape in setup().
OrcaRuntimeService.closeTerminal returns Promise<RuntimeTerminalClose>, and RuntimeTerminalClose is { handle, tabId, closeMode?, ptyKilled }, so the later fixture at line 184 is correct. The setup mock at line 81 should use the same { handle: 'term_worker', tabId: ..., ptyKilled: true } shape instead of { handle, closed: true }; the as never cast hides this type mismatch.
…minals (STA-905) (stablyai#12355) Co-authored-by: OrcaWin <[email protected]>

Summary
Coordinator-created orchestration worker terminals no longer accumulate after
worker_done(STA-905). After processing each accepted report, the coordinator either reuses the exact worker terminal for a follow-up Dispatch (cleanup ownership transfers to the new Dispatch) or runs the neworca orchestration worker-release --dispatch <id>, which freezes an inspectable output archive first — the exact hook-reported provider transcript when available, otherwise a bounded, redacted terminal tail — and then closes only the exact coordinator-owned agent terminal.worker-retainrecords a durable user-requested debugging exception, andworker-listreports terminal accounting (active/reclaimable/retained/release_pending/release_unknown/released) separately from Task status.Durable state is a new schema-v23
worker_terminal_resourcesrecord (ownership + release state machines keyed to pane key and process incarnation) with a conservative backfill: legacy rows become releasable only with unique, exact, same-operation creation evidence. External--terminalreuse, transferred ownership, user-taken-over terminals (real keystrokes now durably relinquish orchestration ownership on the terminal-owning runtime), and unprovable identities are always retained. Release is an idempotent mutation with durable retry receipts; a startup/reconnect reconciler finishes only previously requested releases and defers while terminal inventory is incomplete. Federated (connected-server) dispatches fail closed with a typedretained/federation_unsupportedreceipt. Worker outcome fields never change after release, and setup terminals, configured sibling tabs, and coordinator terminals are never touched.Screenshots
No UI change (main-process, CLI, and skill-guide behavior). New user-facing CLI copy, verified live:
Testing
pnpm lintpnpm typecheckpnpm testpnpm build23 new RPC tests (
orchestration-worker-release.test.ts) cover: succeeded/failed release with exact single close, duplicate-release idempotency, active-worker rejection without recorded intent, external/user-takeover/identity-changed retention, missing-terminalrelease_unknownplus retry-to-completion, capture-failure retaining the live PTY, exited-PTY explicit-empty archives, archivedworker-readwith source-pinned cursors and dcap redaction, exact-reuse ownership transfer with old-Dispatch fencing, reconciler recovery and defer-on-incomplete-inventory, backfill uniqueness, and a 50-worker resource regression (live terminals do not grow with settled passes; controls survive). Migration and guidance tests updated; CLI help/spec gates extended.Full suite: 44,318 passed. 7 failures in 4 files are pre-existing on this base — each fails identically with this diff stashed (local node 26 vs the repo's node 24 pin).
Live QA on an isolated
orca serveruntime with a real claude worker: coordinator receivedworker_done,worker-releasereturnedreleasedwith a real provider-transcript archive, exactly one claude process exited, the worktree's setup/coordinator/externally-reused terminals all survived,worker-readserved the archived transcript after the PTY was gone, duplicate release returnedalready_released, andworker-listseparated Task outcome from terminal state.AI Review Report
The implementation plan was fact-checked against the codebase by four parallel exploration agents before any code was written; every claimed behavior (worker_done settlement ordering,
reused_agent_terminallabeling, mutation-receipt contract, close-path routing) was verified with file:line evidence, and the review's findings were folded into the implementation:workerRelease/workerRetainare registered inORCHESTRATION_MUTATION_METHODSso replayed Deliveries dedupe; exited PTYs with zeroed tails produce explicitemptyarchives instead of silent success; user takeover is recorded durably on the runtime from the renderer's real-keystroke signal only (xterm auto-replies, programmatic prompt delivery, resize, and output are excluded); andrelease_unknownnever falls back to a broad terminal close.Cross-platform was explicitly checked for macOS, Linux, and Windows: no keyboard shortcuts or shortcut labels are involved; no filesystem paths are constructed by hand (transcript paths come from provider metadata; archives live in the orchestration SQLite DB, whose existing POSIX-vs-Windows-DACL hardening is unchanged); terminal close routes through the existing host-authoritative
runtime.closeTerminalpath, which covers native, WSL, and SSH-provider PTYs; SSH-disconnect close errors map torelease_pending/release_unknownrather than a local guess; and folder workspaces need no Git metadata at any release step. Git-provider surfaces are untouched.Security Audit
Reviewed input handling, IPC, and data exposure. The release/retain RPCs validate Dispatch state and exact process identity (pane key + incarnation) before any effect and only ever close the recorded handle — no path or command construction from user input. Archived terminal output passes the existing dispatch-capability redaction before persistence; the archive is stored in the permission-hardened orchestration DB, and provider transcript paths are never exposed through CLI receipts or
worker-list(cursors are Dispatch-scoped and source-pinned, so a cursor cannot cross into another session). The newworkerTerminalUserInputRPC is fail-safe by construction: any caller can only narrow automation (mark a resource user-owned), never trigger a close. Release mutations use the existing durable request ledger (payload-hash mismatch rejection, replay receipts). Known limitation stated in the guide/tests: redaction covers dispatch capability tokens only — the archive is not a general secret filter, matching the pre-existing live terminal-read behavior.Notes
retained/federation_unsupported, fail-closed); mobile/remote-viewing keystrokes do not count as takeover (they arrive viaterminal.send, indistinguishable from programmatic sends);stopped/abandonedworkers reject release (worker-stopalready closed, or identity is uncertain) — abandoned-worker residual cleanup stays with STA-2911.