Skip to content

fix(cli): route residual reclaim through the Dispatch, not the handle - #15966

Closed
Tauri-EPO wants to merge 4 commits into
stablyai:mainfrom
Tauri-EPO:Tauri-EPO/step-f35870
Closed

Tauri-EPO wants to merge 4 commits into
stablyai:mainfrom
Tauri-EPO:Tauri-EPO/step-f35870

Conversation

@Tauri-EPO

@Tauri-EPO Tauri-EPO commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When starting a worker fails, Orca tells you it left a terminal behind — and then says nothing about how to clean it up. The orchestration guide mentions the command that would do it exactly once, to forbid a different use of it. So an agent following that guide is told about a leak and told, in passing, not to touch the thing that fixes it.

This makes the failed start suggest the safe reclaim command. The important part is what it refuses to suggest: nothing for a terminal that might still be a live worker, nothing for a setup terminal or a configured tab, and nothing at all when the outcome is unknown.

What Changed

A new src/cli/orchestration-residual-recovery.ts maps a residual resource to its reclaim command, and it is wired into the two surfaces #15944 names — the worker-start receipt and orchestration-mutation-recovery.ts.

A failed local start gets:

orca orchestration worker-release --dispatch <id> --json

because worker-release re-checks ownership on the host that holds the terminal, preserves inspectable output first, and retains setup terminals, configured tabs, adopted terminals and anything it cannot prove. WORKER_RELEASABLE_STATES already includes failed, so no state change was needed to make this the right command.

A federated receipt gets worker-show --dispatch plus a note naming the worker server, because workerRelease fails closed on federation and a home-side close would target the wrong host.

outcome_unknown gets no reclaim guidance at all — the host already ships worker-show / worker-abandon next-commands there — and the mutation-recovery message gains one line saying explicitly not to close a residual on that path.

Emission requires role: 'agent' with action: 'created' or 'reused_agent_terminal', the two the runtime maps to terminalOwnership: 'created'.

skill-guides/orchestration.md states at line 213 that a failed start's residue is reclaimed through its Dispatch, and restores the line-246 prohibition verbatim.

This departs from what #15944 asked for, and deliberately. That issue asked the guide to state an affirmative terminal close case for a failed start. Two review rounds killed that idea, and the second one is the reason: the receipts available at that moment prove only that the Dispatch once created the terminal and that the old Dispatch no longer owns it. Between the proof and the action, a later worker-start --terminal or a person can adopt that same terminal — and the close then destroys live work. There is no wording that fixes it, because the gap is a race, not an ambiguity. So the guide now names worker-release as the only reclaim path, since the host decides ownership at the moment of the action rather than at the moment of the receipt.

The dispatch id is admitted only if it matches ^[a-zA-Z0-9._:/@-]+$; anything else earns no command. There is no quoting and no platform branch, because process.platform describes the process that renders the string, not the PowerShell, SSH or WSL shell that would run it.

Why

orchestration-worker-specs.ts:38 promises "recovery commands when needed", and orchestration-mutation-recovery.ts emits one for the mutation (--retry-request) while printing residualResources as raw JSON with no action attached. The guide tells the orchestrator to inspect that field and stops there.

Why worker-release and not terminal close. The first revision emitted terminal close directly, and review found two ways that kills live work: the outcome_unknown text told the reader to close when abandoning rather than when retrying, so following it could destroy a worker whose prompt actually landed; and the mapper closed every terminal residual, including the running setup terminal and configured tabs a new-worktree start leaves behind. A later round then showed that even a carefully fenced exception cannot be made safe, for the adoption race described above. Ownership is already decided host-side, so routing through worker-release moves the check to the only place that can make it at the right moment, instead of duplicating a weaker version of it in the CLI.

Why an allowlist and not quoting. These commands are not only printed for a human to copy; the orchestration guide tells an agent to follow the recovery action in the receipt, and an agent runs it with terminal send --enter. A quoting helper that picks its escaping from process.platform is therefore guessing: the same string may land in PowerShell, where \" is not an escape, in a POSIX shell reached over SSH from a Windows host, or in WSL. Refusing to build a command for an id outside the safe class is simpler than being right about all of them, and a legitimately generated id always matches.

Linked Issue

Fixes #15944

Relates to #15920, a dispatch failing at dispatch_input and leaving exactly this residue.

Visual Proof

N/A — CLI receipt text and skill-guide prose. The output delta is the added command lines quoted above.

Testing

Verified on Windows 11 against a rebased branch at upstream/main:

pnpm typecheck        exit 0
pnpm build            exit 0   (including build:native)
vitest src/cli        88 files / 889 tests passed, 33 in the three targeted files
pnpm lint             clean through oxlint, both code-quality audits, reliability
                      gates, max-lines ratchet and verify:bundled-skill-guides;
                      fails only at verify:skill-bundle-manifest, the pre-existing
                      clean-tree failure whose inputs (skills/, resources/skills/)
                      git status confirms untouched

Coverage: outcome-unknown, setup and configured-tab residuals producing nothing, federated, SSH, mixed-version, and host-supplied commands left untouched. On the id allowlist — single quote, double quote, backtick, $(), pipe, ampersand, percent, space, empty, LF and CRLF, C1 (U+0085, U+009B), Unicode separators (U+2028, U+2029), NBSP, DEL and an astral character, each asserted on both the local and federated branches; a renderer-versus-shell matrix pinning process.platform to win32, linux and darwin and asserting identical rejection and identical accepted output on all three; and positive cases keeping legacy and remote shapes such as legacy-dispatch.7, run:home/ctx_9 and worker@windows working.

  • I manually tested these changes locally
  • Automated tests added/updated

Platforms: Windows 11.

AI Disclosure

Written with Claude Opus 5 at high effort under my direction, and taken through three review rounds — two by an independent Codex (gpt-5.6-sol) pass and one by CodeRabbit on this PR. Round 1 found unsafe guidance on the outcome_unknown path and a mapper that would close setup terminals. Round 2 found the shell-family guess in the quoting helper and the adoption race in the two-receipt exception. Every shape in this PR that differs from the original issue came out of those rounds; the reviews are the reason the affirmative terminal close case is gone.

Review

Cross-platform: no path handling.
SSH / remote / federation: a federated residual handle belongs to the worker server, so remote cleanup is routed by Dispatch and the receipt is left untouched when the host already shipped nextCommands / recoveryCommands — which is also the mixed-version guard.
Wire compatibility: recoveryCommands is derived client-side from residualResources, so there is no host or wire change and an old host is unaffected.
Agent compatibility: the guide change is the agent-facing surface; the settled-Dispatch prohibition is restored verbatim rather than weakened.
Performance: pure string derivation on a failure path.
UI: none.
Security: no privilege boundary is involved — a dispatch id is generated by Orca, and the allowlist is a robustness and cross-shell-correctness measure rather than a mitigation. The command suggested is one the caller could already run, and only for a resource this Dispatch provably created.

Agent skill upstream boundary

  • Not applicable — no upstream skill-installer source is copied or translated. The skill-guide edit is Orca's own orchestration guide.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • N/A with reason for visual proof
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • pnpm lint, pnpm typecheck and pnpm build pass locally

Author

  • X / Twitter: @EnricoPin

… leaves

A failed or unknown `worker-start` names what it left behind in
`residualResources`, but the only recovery command the receipt emitted was
`--retry-request` for the mutation itself. A residual `kind: "terminal"` has
one exact reclaim command — `orca terminal close --terminal <id> --json` — so
emit it per residual resource, in the receipt (`recoveryCommands`, only for a
nonzero start so a ready worker's live terminal is never offered up) and in the
unknown-outcome error message (conditional on the retry settling first).

The guide half: state the affirmative case for a failed start, and scope the
`terminal close` prohibition to a settled Dispatch's release, which is what it
was always about.

Fixes stablyai#15944
Review found the previous receipt guidance could destroy live work.

- outcome_unknown no longer gets any reclaim guidance: the mutation may have
  landed, so the residual handle can be a live worker. The unknown path keeps
  the host's own retry/worker-show/worker-abandon guidance, and the mutation
  error now says explicitly not to close a residual there.
- ownership is no longer inferred per handle. A command is emitted only for a
  residual the receipt proves this start created and this Dispatch owns —
  role agent with action created or reused_agent_terminal — so setup
  terminals, configured tabs and adopted terminals get nothing, and an
  unrecognized effect shape from another host version gets nothing.
- the command itself is now Dispatch-routed: worker-release on this server, so
  the host re-checks ownership and archives output before closing anything, and
  worker-show for a connected-server worker whose handle a home-side terminal
  close would target on the wrong host.
- a receipt that already carries host commands is left untouched.

The settled-Dispatch terminal-close prohibition in the guide is restored
verbatim; the affirmative case is stated separately and only for a terminal
worker-release reports as no_owned_resource.

Fixes stablyai#15944
@coderabbitai

coderabbitai Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Worker-start receipts now support recovery guidance for failed starts with residual agent terminals. The recovery logic validates receipt state, Dispatch identity, resource ownership, identifiers, and existing commands before generating release or server inspection commands. The CLI displays recovery fields and preserves host-provided commands. Mutation recovery messages prohibit closing residual resources before retry. Specifications and orchestration guidance document these rules.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 7 files. (1 skipped: 1 unsupported.) Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description covers the required sections, linked issues, testing, platform scope, risks, and checklist status.
Linked Issues check ✅ Passed The description links issue #15944 with Fixes and identifies related issue #15920.
Out of Scope Changes check ✅ Passed The implementation, tests, guide updates, and CLI changes are focused on safe recovery for failed worker starts.
Title check ✅ Passed The title clearly summarizes the main change: routing residual reclaim through Dispatch instead of direct handle cleanup.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 09a1a970-3da7-4254-ac7b-b8903bc3fb12

📥 Commits

Reviewing files that changed from the base of the PR and between 80b2a02 and 24305af.

📒 Files selected for processing (9)
  • skill-guides/orchestration.md
  • src/cli/bundled-skill-guides.ts
  • src/cli/handlers/orchestration-gate-cli.test.ts
  • src/cli/handlers/orchestration-worker-cli.test.ts
  • src/cli/handlers/orchestration.ts
  • src/cli/orchestration-mutation-recovery.ts
  • src/cli/orchestration-residual-recovery.test.ts
  • src/cli/orchestration-residual-recovery.ts
  • src/cli/specs/orchestration-worker-specs.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment thread skill-guides/orchestration.md Resolved
Review round on stablyai#15966.

- The recovery commands are printed for a human to copy into a shell, and the
  dispatch id reached them raw. Legacy and remote ids are not guaranteed to be
  ctx_-shaped, so 'ctx_1; printf INJECTED' parsed as two commands. The argument
  now goes through quoteCliCommandArgument, and an id carrying a control
  character or line break earns no command at all, since no quoting makes a
  line break safe to paste on one line.
- The guide no longer treats a lone no_owned_resource release receipt as proof
  that terminal close is safe: a Dispatch from `dispatch --inject` reports the
  same retained reason for a terminal it never owned. The exception now needs
  the originating failed worker-start receipt to name that exact terminal in
  its residualResources, and every other retained reason stays excluded.
- The spec note and the guide now state that a receipt already carrying
  host-supplied commands gets no recoveryNote/recoveryCommands.

Fixes stablyai#15944
…ption

Review round 3 on stablyai#15966.

- quoteCliCommandArgument picks a shell family from process.platform, which is
  the platform of the process rendering the receipt, not of the shell that will
  run the pasted command: a printable id holding a double quote, quoted by the
  win32 branch, is two statements in PowerShell. The id now has to match the
  shell-neutral class ^[a-zA-Z0-9._:/@-]+$ or it earns no command at all. No
  quoting, no platform branch. The class also subsumes the codepoint check it
  replaces, so C0, DEL, C1 and the Unicode separators stay rejected.
- The terminal-close exception is gone. It proved only that the Dispatch once
  created the terminal and that the old Dispatch no longer owns it; between
  those two receipts a later worker-start --terminal or a human can adopt that
  same terminal, and the close then kills live work. worker-release stays the
  reclaim path because the host decides ownership at the moment of the action.

Fixes stablyai#15944

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8dfc7363-1595-4e2d-92aa-48955574012c

📥 Commits

Reviewing files that changed from the base of the PR and between 24305af and ba2f440.

📒 Files selected for processing (5)
  • skill-guides/orchestration.md
  • src/cli/bundled-skill-guides.ts
  • src/cli/orchestration-residual-recovery.test.ts
  • src/cli/orchestration-residual-recovery.ts
  • src/cli/specs/orchestration-worker-specs.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Comment on lines +27 to +29
// Why: these commands are printed for a human to paste into an unknown shell — PowerShell, a POSIX
// shell over SSH, WSL — which the rendering process cannot identify, so no quoting is provably
// inert. An id outside this class earns no command instead.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Keep rationale comments to one line.

The changed comments provide useful rationale, but each spans multiple lines. Compress each to one concise sentence.

  • src/cli/orchestration-residual-recovery.ts#L27-L29: reduce the shell-neutral identifier rationale to one line.
  • src/cli/orchestration-residual-recovery.test.ts#L105-L106: reduce the unsafe-ID test rationale to one line.
  • src/cli/orchestration-residual-recovery.test.ts#L138-L139: reduce the platform-independence rationale to one line.
📍 Affects 2 files
  • src/cli/orchestration-residual-recovery.ts#L27-L29 (this comment)
  • src/cli/orchestration-residual-recovery.test.ts#L105-L106
  • src/cli/orchestration-residual-recovery.test.ts#L138-L139

Source: Coding guidelines

Comment on lines +38 to +39
'The call exits 0 only for ready. Failed or outcome_unknown exits 1 and JSON includes stage/failedStage, setup, effects, residualResources, and recovery commands when needed.',
'A failed start that left its own agent terminal adds recoveryNote and recoveryCommands routed through the Dispatch, never a direct terminal close, and adds neither when the receipt already carries host-supplied commands; outcome_unknown gets retry guidance instead because the start may have succeeded.'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Document Dispatch-ID-based command suppression.

workerStartRecovery omits recovery commands when dispatchId is unsafe to render, even when it finds an owned agent terminal. The current text promises commands for that receipt shape and says no command proves no reclaimable ownership.

  • src/cli/specs/orchestration-worker-specs.ts#L38-L39: state that generated recovery fields also require a safely renderable Dispatch ID.
  • skill-guides/orchestration.md#L215-L215: state that omitted commands can result from an unsafe Dispatch ID, not only absent ownership evidence.
📍 Affects 2 files
  • src/cli/specs/orchestration-worker-specs.ts#L38-L39 (this comment)
  • skill-guides/orchestration.md#L215-L215

@Tauri-EPO

Copy link
Copy Markdown
Contributor Author

Closing: #16904 (merged 2026-09-06, 06a607a1d7) covers what this PR proposed, through a different mechanism.

  • The failed worker-start receipt now names the Dispatch-scoped reclaim path itself: src/main/runtime/rpc/methods/orchestration/worker/worker-start-receipt.ts:57 returns recovery: "This start created a terminal that never ran the Task. Close it with: orca orchestration worker-release --dispatch <id>" once the residual terminal is adopted by the Dispatch.
  • The guide now says the same: skill-guides/orchestration/references/recovery-and-cleanup.md:140-156 names worker-release as the reclaim path and tells agents never to substitute terminal close.

What is not there is the recovery line in the human-readable worker-start output (src/cli/handlers/orchestration/worker-output.ts prints nextCommands only). That is small enough to be a fresh PR after the release carrying #16904, if it still matters then. #15944 stays open until I can retest on a released build.

@Tauri-EPO Tauri-EPO closed this Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Other]: Include Dispatch-aware reclaim guidance in failed worker-start receipts

1 participant