Skip to content

fix(orchestration): stamp and lift the settled worker resume fence (STA-4577) - #17651

Closed
nwparker wants to merge 2 commits into
mainfrom
nwparker/sta-4577-settled-worker-resume-fence
Closed

nwparker wants to merge 2 commits into
mainfrom
nwparker/sta-4577-settled-worker-resume-fence

Conversation

@nwparker

@nwparker nwparker commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​942 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​931
Prod 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​326 $\color{#cf222e}{\Huge{\mathbf{−}}}$​69 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​257

Fixes STA-4577. Supersedes #17430, which GitHub would not let me reopen after the branch was rebased (its original head commit is no longer reachable). Same branch, same work, plus the de-risking below. One of 6 real defects split out of the test-detected-bugs sweep.

ELI5

When a supervised orchestration worker finishes, we're supposed to put a "do not auto-resume" sticker on its pane. We were forgetting the sticker — so the auto-resume logic would cheerfully restart a worker that had already reported done.

This stamps the fence at settlement time, and — equally important — lifts it once the dispatch is released, retained, or gone.

Why the lift matters as much as the stamp

startFreshSpawn refuses any fenced pane. A fence that outlives its dispatch leaves a terminal that can never spawn again. Release, user retain, user takeover, and dispatch pruning all drop the row from the recovery plan — that is the signal to retire the fence.

Fence-lift completeness

Every stamp path and every lift path, enumerated:

Stamps the fence Lift path that covers it
Settlement (orchestration.send / orchestration.check lifecycle reconciliation) the same sweep, next time the plan no longer claims the pane
Persisted record in the workspace session liftRetiredLegacyWorkerResumeFences
Renderer-only push (fenced IPC) with no persisted record behind it liftRendererLegacyWorkerResumeFences (new)
Retires the dispatch Sweep runs?
orchestration.workerRelease yes (new)
orchestration.workerRetain yes (new)
orchestration.workerTerminalUserInput (real takeover) yes (new), gated on changed > 0
Settlement / dispatch pruning yes (already)
App start yes (already)

Two gaps were found and closed in this revision:

  1. Release / retain / takeover ran no sweep. Each drops the worker's row from the recovery plan, but nothing re-read the plan, so the fence stayed stamped until the next app start. All three now run sweepSettledWorkerResumeFences in the same call. sweepingRetiredWorkerResumeFences wraps by method name so every early return in those handlers is covered; orchestration.workerList is a pure read and is deliberately excluded. The takeover path is gated on changed > 0 because every terminal pane reports there on a 30s throttle, and only a real takeover retires the resource.

  2. A renderer-only fence had no lift path at all. The fenced resolution is pushed live, so it can exist with no persisted record behind it (session sync lag, persistence unavailable). The runtime now remembers what it fenced in rendererFencedWorkerPaneWorktreeIds and lifts before the persistence bail-out, so an unreadable workspace session can no longer strand a fence this runtime pushed.

Bound on the worst case: even before these fixes, every fence was swept at the next app start, so the failure mode was "dead pane until restart", not literally never. main today stamps the persisted fence for live dispatches with no lift at all; this PR adds the first one.

Paired remote: agentStatus:legacyWorkerTerminalRecovery is Electron IPC only and never crosses the remote wire, so a paired client cannot observe a fence it can't lift.

Residual (accepted, minor): the lift matches on pane key alone while the stamp also carries worktreeId. Pane keys are tabId:leafId UUID pairs, so a cross-worktree collision is not reachable in practice.

Failing closed

  • An unreadable recovery plan stamps nothing and lifts nothing, and retries next pass. An unreadable plan is not evidence that any pane stopped needing its fence.
  • release_state = 'unknown' keeps the fence — the SQL matches release_state NOT IN ('released','retained'). An unverifiable release refuses a fresh spawn over a possibly-live process.
  • settled: (alreadySettled ?? true) && settled demotes a reused pane when any dispatch holding it is still live.
  • The sweep swallows its own errors: a fence sweep must never fail the RPC that triggered it.

The red changed e2e specs check: a real defect, in main, not in the fence

completed-worker-retirement-resume.spec.ts was failing with Active terminal PaneManager did not finish mounting. That is exactly what a wrongly-stamped fence would look like, so it was worth being precise about. It was not the fence.

Evidence:

  • Run A — this branch: fails at spec line 492, empty tab strip.
  • Run B — origin/main product + origin/main spec: fails earlier, at line 275 (state: 'working', received 'done'). The spec was already red on main; the branch's working→done edit legitimately fixes that first failure.
  • Run C — origin/main product + this branch's spec file only: fails at the identical line 492 with the identical message. Main's product code causes it.
  • Run D — instrumented: at failure, activeWorktreeId is the target, everActivated: true, activeTabId: null, tabCounts: { coordinator: 1, target: 0 } (row present, empty array), and sleepingAgentSessionsByPaneKey: {}. No fence in sight.

Root cause: an orchestration-retired worker tab leaves tabsByWorktree[worktreeId] = [] — the closed-last-tab tombstone. On activation, renderableTabCount === 0 makes shouldGateAgentActivation true, so seeding is deferred into gateWorktreeAgentActivation(...).then(...). That gated branch called ensureWorktreeHasInitialTerminal without reseedEmptiedWorkspace, unlike the ungated branch directly below it and unlike the folder-workspace twin. The tombstone therefore suppressed re-seeding permanently, and no pane could ever mount.

Fixed in product code (worktree-activation.ts) by giving the gated branch the same re-seed authority the ungated one already had. The test was not weakened.

Non-vacuity: forcing reseedEmptiedWorkspace: false in the new unit test makes it fail - 1 / + 0.

Wire compatibility

fenced / unfenced are new values on the existing LegacyWorkerTerminalRecoveryEvent.resolution field, plus a new optional worktreeId (so the renderer can reject a pane-key alias). No new stream opcode, so no capability negotiation is required; old clients ignore resolutions they don't know.

Proof

Revert the product files to 2daea491b96:

Test Result
orchestration-settlement-resume-fence.test.ts 2 failed / 1 passed
agent-status-settled-worker-resume-fence.test.ts 3 failed / 1 passed
orca-runtime.test.ts 6 failed / 1211 passed

New in this revision:

Test Covers
orchestration-worker-resume-fence-lift.test.ts release, retain, and real takeover each lift the fence; an unowned pane sweeps nothing. Runs against a store-less runtime, so the fence exercised is the renderer-only one that previously had no lift path.
worktree-activation-emptied-workspace-reseed.test.ts (+2) the gated activation path re-seeds an emptied workspace, and still honours providesInitialSurface

Verification at HEAD:

  • pnpm tc — clean.
  • pnpm test src/main/runtime/ src/renderer/src/hooks/ src/renderer/src/store/slices/agent-status-settled-worker-resume-fence.test.ts — 666 files, 6865 passed | 5 skipped. One unrelated failure, terminal-output-frame-chunks-equivalence.test.ts, an 800-trial fuzz that exceeded its 30s wall-clock budget on a loaded machine (load avg 71); it is byte-identical to origin/main, shares no code with this diff, and passes in 51s with a raised timeout.
  • completed-worker-retirement-resume.spec.ts — 6/6 green across three runs (1×, then 2× repeat-each). Both cases run; the worker-release case that CI skipped now executes and passes.
  • oxlint — exit 0, 0 errors. pnpm run check:code-quality:changed — 0 new findings across 27 changed files.

Known P2, accepted and documented

The fence is persisted to the workspace session. If a user runs this build, settles a worker whose terminal resource is still owned-and-unreleased, then downgrades, the older build has no code path to lift the fence.

What the downgraded user sees: that one pane stays blank and will not spawn a shell. Workaround: close the tab and open a new terminal tab — the fence is keyed per pane key (tabId:leafId), so a new pane is unaffected. Rolling forward again self-heals on the first sweep.

Reduction attempt, evaluated and rejected. The obvious fix is to persist settled fences under a new enum value (e.g. 'settled-orchestration-worker') rather than reusing 'legacy-orchestration-worker'. An older build's salvagingRecord would fail to parse that record and drop only it, so the downgraded build would see no fence at all — the P2 disappears. It works, but it touches ~6 strict === 'legacy-orchestration-worker' comparison sites plus the IPC payload and the stamp/lift transition logic, which is more surface than a CI fix and a de-risk pass should carry. Recorded here so the next change in this area can pick it up.

Otherwise accepted because: it is not a regression of this build (rolling forward self-heals via the lift); the previous build already leaks fences it stamps itself, so this enlarges the population of a pre-existing old-build defect rather than introducing one; and reachability is narrow. Removing it would mean not persisting the fence at all — which is precisely the bug.

Note on src/shared/worktree/id.ts

This PR adds worktreeIdsEqual (a small helper over the already-existing worktreeIdComparisonKey) because the recovery listener needs it. The STA-5701 PR adds the identical function. The additions are byte-identical, so the two merge cleanly in either order — verified by merging all split branches and diffing against the original combined tree (empty).

Performance Measurement

Deterministic settled-worker fixture: the old path allowed 1 fresh-resume attempt after settlement; the fence makes that 0 while the dispatch is settled, then retires the fence when the dispatch is released, retained, or taken over. No extra polling or subprocess work is added. The new sweeps are one recovery-plan read on release/retain/takeover — user-initiated, low-frequency events, and the takeover path is gated on an actual ownership change so ordinary panes never pay for it.

User-Facing Trade-offs

None in the current build. Settled workers no longer restart spuriously; an emptied workspace now re-seeds a terminal on the gated activation path instead of opening blank; and the documented downgrade caveat now carries an explicit user workaround.

…irement path

Two follow-ups to the STA-4577 fence, plus the root cause of the red e2e spec.

E2E root cause (product, pre-existing on main): an orchestration-retired worker
tab leaves `tabsByWorktree[worktreeId] = []` — the closed-last-tab tombstone.
Activating that workspace routes through the agent-activation gate, and the gated
branch of `activateAndRevealWorktree` seeded without `reseedEmptiedWorkspace`,
unlike the ungated branch and the folder-workspace twin. The tombstone therefore
suppressed seeding forever and no PaneManager ever mounted.

Fence-lift gaps closed:
- release / retain / user takeover each drop the worker's row from the recovery
  plan but ran no sweep, so the fence outlived its dispatch until the next app
  start. A shared sweep module now runs on all three.
- a renderer-only fence (session sync lag, persistence unavailable) had no lift
  path at all. The runtime now remembers what it fenced and lifts before the
  persistence bail-out.
@pullfrog

pullfrog Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

the model provider had a temporary upstream failure.

The provider refused or dropped the request mid-run — nothing in your repo or your credentials is at fault. Re-trigger Pullfrog; if it keeps happening, check the provider's status page.

provider error: {"code":504,"message":"Upstream idle timeout exceeded","metadata":{"error_type":"timeout"}}

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@greptile-apps

greptile-apps Bot commented Aug 31, 2026

Copy link
Copy Markdown

Greptile Summary

This PR adds automatic-resume fences for settled orchestration workers, retires those fences when terminal ownership ends, and repairs gated activation of emptied workspaces.

  • Extends legacy terminal recovery planning to include settled workers with owned, unreleased terminal resources.
  • Propagates fenced and unfenced resolutions through main-process IPC, preload, and renderer state.
  • Sweeps fences after release, retain, takeover, and lifecycle-message settlement.
  • Re-seeds an initial terminal when gated worktree activation encounters an emptied workspace.
  • Adds unit, integration, and end-to-end coverage for settlement, persistence, renderer recovery, and workspace activation.

Confidence Score: 4/5

The PR should not merge until worker-stop settlement paths stamp the same automatic-resume fence as other settled-worker transitions.

Stopping a worker leaves its terminal owned and makes the dispatch eligible for the new fence, but the stop handlers never run the sweep, leaving a window in which the stopped provider session can be resumed.

Files Needing Attention: src/main/runtime/rpc/methods/orchestration-worker-release.ts and worker-stop reconciliation paths

Important Files Changed

Filename Overview
src/main/runtime/orca-runtime.ts Implements renderer and persisted fence stamping/lifting, including fail-closed handling when the recovery plan is unreadable.
src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts Extends recovery rows to settled dispatches that still own unreleased terminal resources.
src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.ts Distinguishes settled blocked panes from live adoption candidates and handles panes shared by multiple dispatch rows.
src/main/runtime/rpc/methods/orchestration-worker-release.ts Adds retirement sweeps for release, retain, and takeover, but omits worker-stop paths that also create settled fence candidates.
src/main/runtime/rpc/methods/orchestration.ts Sweeps after lifecycle-message reconciliation completes or fails a worker dispatch.
src/renderer/src/hooks/ipc-events/agent-status-listeners.ts Applies fence events only to sleeping records whose worktree identity matches.
src/renderer/src/store/slices/agent-status.ts Persists the resume block across record derivation only while provider-session identity remains unchanged.
src/renderer/src/lib/worktree-activation.ts Gives gated activation the same emptied-workspace reseeding authority as the ungated path.

Sequence Diagram

sequenceDiagram
  participant W as Worker lifecycle
  participant DB as Orchestration DB
  participant R as Orca runtime
  participant UI as Renderer
  W->>DB: Settle worker dispatch
  DB-->>R: Recovery plan includes owned settled pane
  R->>UI: fenced(paneKey, worktreeId)
  UI->>UI: Block automatic provider resume
  W->>DB: Release, retain, or user takeover
  DB-->>R: Recovery plan drops pane
  R->>UI: unfenced(paneKey, worktreeId)
  UI->>UI: Permit fresh terminal spawn
Loading

Reviews (1): Last reviewed commit: "fix(orchestration): lift the settled wor..." | Re-trigger Greptile

Comment on lines +33 to +36
const FENCE_SWEEPING_METHOD_NAMES = new Set([
'orchestration.workerRelease',
'orchestration.workerRetain'
])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Worker stops skip fence stamping

When an owned, unreleased worker terminal is settled as stopped, the stop paths do not run the new fence sweep, leaving the settled provider session eligible for automatic resume until an unrelated later sweep or restart.

Knowledge Base Used:

@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4cf8e11a-7203-46f9-ad24-95aa360ee6ad

📥 Commits

Reviewing files that changed from the base of the PR and between 0293ebe and 864b42e.

📒 Files selected for processing (27)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts
  • src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts
  • src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.ts
  • src/main/runtime/orchestration/orchestration-settled-worker-resume-fence-db.test.ts
  • src/main/runtime/rpc/methods/orchestration-settlement-resume-fence.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release.ts
  • src/main/runtime/rpc/methods/orchestration-worker-resume-fence-lift.test.ts
  • src/main/runtime/rpc/methods/orchestration.ts
  • src/main/runtime/rpc/methods/settled-worker-resume-fence-sweep.ts
  • src/main/window/runtime-window-lifecycle.ts
  • src/preload/api/agent-status-api.ts
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/pty-connection-cold-restore-resume-command.test.ts
  • src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts
  • src/renderer/src/hooks/ipc-events/agent-status-listeners.ts
  • src/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.ts
  • src/renderer/src/hooks/legacy-worker-terminal-recovery-event.ts
  • src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts
  • src/renderer/src/lib/worktree-activation-emptied-workspace-reseed.test.ts
  • src/renderer/src/lib/worktree-activation.ts
  • src/renderer/src/store/slices/agent-status-settled-worker-resume-fence.test.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/shared/agent-status-types.ts
  • src/shared/worktree/id.ts
  • tests/e2e/completed-worker-retirement-resume.spec.ts
Files not reviewed due to moderation or processing errors (1)
  • src/main/runtime/orca-runtime.test.ts

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


📝 Walkthrough

Walkthrough

The change keeps owned settled worker terminals in recovery planning and marks their panes as settled. Runtime reconciliation fences settled panes and lifts fences when recovery rows retire. Lifecycle and worker ownership RPCs trigger guarded fence sweeps. Shared IPC types now include worktree identity and fenced states. Renderer handlers apply matching automatic-resume blocks and preserve them across sleeping-session record derivation. Gated worktree activation now respects caller-provided initial surfaces.

Merge Risk: 🟡 Moderate · up to 864b4

The PR prevents settled workers from auto-resuming and adds cleanup when ownership is released, but an asynchronous release can finish after cleanup has run, leaving a released pane blocked from spawning until a later reconciliation or app restart. Merge should wait for that completion path to trigger cleanup or for the risk to be explicitly accepted.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 32 functions across 25 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: stamping and lifting settled worker resume fences.
Description check ✅ Passed The description is detailed and covers the change, motivation, linked issue, testing, compatibility, performance, trade-offs, and known limitations. It does not include the template's explicit Visual …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description is detailed and covers the change, motivation, linked issue, testing, compatibility, performance, trade-offs, and known limitations. It does not include the template's explicit Visual Proof, Review, Agent skill upstream boundary, or Checklist sections, but the substantive required information is mostly present.

Full details: Docstring Coverage

Explanation

Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 32 functions across 25 files. (2 skipped: 2 too large.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

@nwparker
nwparker requested a review from Jinwoo-H September 1, 2026 08:01
Jinwoo-H added a commit that referenced this pull request Sep 4, 2026
…worker pane

Between worker_done and release the pane still holds a resumable provider
session, but listLegacyWorkerTerminalRecoveryRows selected live worker states
only, so nothing fenced it: reopening the workspace after a restart re-ran
`codex resume <session>` on a finished worker.

Settled workers whose terminal resource is still owned and neither released nor
retained now join the recovery rows, the plan marks those panes settled so they
never compete for adoption, and any fence the plan no longer claims is lifted —
on release, retain, user takeover and dispatch prune. An unreadable plan fails
closed and lifts nothing.

Ported from PR #17651, adapted to this branch's worker_terminal_resources
ownership model.
Jinwoo-H added a commit that referenced this pull request Sep 6, 2026
<!-- orca-pr-loc -->
<!-- Programmatic LoC summary. Do not edit by hand; rewritten on every commit. -->

| | Files | Added | Deleted | Net |
| :--- | ---: | ---: | ---: | ---: |
| Test | 225 | $\color{#1a7f37}{\Huge{\mathbf{+}}}$​21666 | $\color{#cf222e}{\Huge{\mathbf{−}}}$​2820 | $\color{#1a7f37}{\Huge{\mathbf{+}}}$​18846 |
| Prod | 348 | $\color{#1a7f37}{\Huge{\mathbf{+}}}$​17107 | $\color{#cf222e}{\Huge{\mathbf{−}}}$​4706 | $\color{#1a7f37}{\Huge{\mathbf{+}}}$​12401 |

<!-- /orca-pr-loc -->

## ELI5

Orca now treats orchestration like a durable control plane instead of inferring success from terminal keystrokes. Agents can tell whether a prompt was accepted or a turn started, replay an ambiguous request without sending twice, and recover coordinator mail after a crash. Completed workers can be inspected, released, or retained, and their panes no longer auto-resume as if the work were still running.

## What changed

- **Run receipts** from `run-create/use/current/show/list` are the row without routing plumbing (`home_database`, `coordinator_pane_key`) and without the duplicate `binding` object.
- **`terminal send` receipts are honest and idempotent.** `input_accepted` and `turn_started` are the only stages; `--wait-submit` observes without resending; `--retry-request <uuid>` replays the exact request against the same process incarnation. A transport timeout keeps the retry ID; only a different runtime answering strips it. Value-less or non-UUID `--retry-request` is rejected on the CLI and the SSH shim.
- **Mailbox delivery is committed before wakeup.** Pointer writes are staged in the DB before any PTY byte, replayed once after restart, and never emit a naked Enter. The watermark that parks concurrent deliveries is released with the DB reservation. Restart rescans pointer-pending and `dispatch:` mailboxes.
- **Lifecycle is a guarded transition graph** (`lifecycle-transition.ts`) with a table-driven test over every caller edge. Task reopen/overturn stays in the public contract. A PTY exit during `worker-stop` is the stop succeeding, not a failure.
- **Worker lifecycle CLI:** `worker-start` (`--spec` creates Task + attempt in one call), `worker-show`, `worker-read` (provider transcript first, bounded terminal fallback with a typed reason, local/WSL/SSH), `worker-stop`, `worker-abandon`, `worker-release`, `worker-retain`, `worker-list` (rowid-fenced pagination, fleet liveness, `attention`, literal `nextAction`).
- **Release is an explicit ownership table** (`decideWorkerTerminalRelease`): only an `owned` resource can be settled, the archive is mandatory where reachable, and an owner whose process is proven exited can always get out of `retained` via `archive_status: unavailable`. User-taken-over, external, and transferred panes stay retained.
- **Settled-worker resume fence** (folds in #17651): a settled dispatch whose pane is still open is fenced at settlement, on stop/abandon/exit, and at startup; lifted on release, retain, takeover, and pane reuse.
- **Liveness is `live` / `unverifiable` / `exited` only**, from execution-host evidence. Fleet projection reads the evidence clock, not the relay delivery clock. A host-certified exit outranks the worker's settled state. `unverifiable` never authorizes stop, abandon, retry, or release, in code or in the guide.
- **Federation:** structured reads negotiate by `method_not_found` so every shipped host keeps transcript-first output; exited remote workers are closed before being reported closed; epoch fencing holds across peer restart, downgrade, and pairing rotation; no per-second forced capability probe.
- **Schema v35:** repairs databases stamped v34 by the pre-fix branch (mailbox_handle default, index predicates), drops the write-only `lifecycle_transition_receipts` ledger and five never-read v31 identity columns.
- **Schema v36:** `dispatch:<id>` mailboxes get a real consumer generation on `dispatch_contexts` and `remote_dispatch_attachments`, bumped and fenced in the same transaction on every re-attach (manual inject, worker-start, federated attach). A stale worker whose Dispatch moved to another process now gets `consumer_fenced` instead of silently acking the new worker's Delivery. Run mailboxes already worked this way.
- **Schema v37:** `dispatch_contexts` records its creator (`creator_handle`, `creator_pane_key`), so a coordinator's context-only self-dispatch is bookkeeping rather than a nesting parent; before this, one self-dispatch made every later `worker-start` from that coordinator fail the depth cap. Pre-v37 rows keep counting (fails closed).
- **Dispatch-mailbox ownership is checked, not inferred.** A `check` from a process whose pane no longer holds the Dispatch, or whose last Attempt was abandoned/failed and moved to another terminal, gets `consumer_fenced` instead of an empty inbox that reads as "no mail yet". `--peek`/`--all` stay readable. A paneless caller still gets `stable_pane_required` with the rebind recovery.
- **Liveness certification is stricter:** a `process_exited` stage whose termination reason is `unknown` (a stop that was issued but never observed) projects `unverifiable`, not `exited`. Federated `worker-show` carries the execution host's verdict and host kind instead of a local guess. A live, ready worker with nothing pending has `nextAction: none` rather than pointing at the `worker-show` that produced it.
- **Wire:** `workerShow` keeps `dispatch.task_id` next to `taskId` for shipped CLIs. `ask --json` uses the standard `{ok, result}` envelope like every sibling verb.
- **Migration start-version detection** treats the two v32 recovery columns as versioned. Before this, every shipped database stamped below 32 resolved to the v6 floor and replayed the whole chain (the v23 backfill synthesized 68 phantom retained workers on a real v30 profile). Verified on a copy of a real 62 MB v30 profile: starts at 30, no row delta, integrity ok, 11 ms.
- **Skill guide** rewritten as a ≤200-line kernel plus seven references, to the outcome-first standard (Result / Done / Safe failure first, conditions not case lists, one done bar, references loaded at the point of use). The canonical loop uses `worker-start --spec`, names `worker-list` for completion accounting, documents `--retry-request` / `request-show` / `--wait-submit`, and requires positive evidence before any stall action. The other seven guides get the same treatment in #18724, split out so this PR stays orchestration-only.
- **`rpc/methods/orchestration-*`** (126 flat files) regrouped into `orchestration/{worker,federation,messaging,runs,gates}/`.

## Why

User reports showed the same boundary failures: false `agent_prompt_stalled` causing duplicate sends (#15180), coordinators unable to trust screen scrapes, cold-parked terminals receiving a pointer without the submit, settled workers accumulating as live tabs and auto-resuming after restart, and no way to tell a stalled worker from a working one.

## Linked issues

Fixes #15180. Fixes #17935 (orchestration skill description is 866 characters; a guard now caps every bundled skill at 1,024). Supersedes #17651 (fence folded in). Advances #16660, #16522, #14907, #13047.

## Review record

This PR was reviewed adversarially after revival: eight independent lenses (lifecycle, mailbox, send, worker, federation, transcript, complexity, live ergonomics), each required to prove findings with a failing test. That produced 16 proven blockers, all fixed with red-then-green regression tests, followed by two re-review rounds and a third fix wave that caught 3 regressions introduced by the fixes and 7 fixes that missed their target; all closed. A final pass (five lenses incl. a live built-runtime smoke, then a re-review of the fix wave) found and fixed seven more, chiefly the stale-worker mailbox steal, the self-dispatch depth wedge, and the unproven-exit certification. Three independent Codex (gpt-6-astra) passes followed: the first found nothing new, the second found and fixed 3 defects (task-status reachability, WSL-local host classification, peer-capability epoch), the third found and fixed 6 (production PTY controller never installed settled writes, ambiguous in-flight pointer failures allowed duplicate replay, SSH/relay deadlines cut off a valid `--wait-submit`, stop-vs-exit race during inspection, and two release-recovery paths for vanished or exited terminals). The full record (findings, proof tests, triage, declines with reasons) is archived outside the repo.

**Rework after the live smoke.** A first live cross-host run on the shipped adhoc build (this Mac, a paired Windows host on the same build, a paired Mac on 1.4.195, and an SSH host) found a P1: a running local worker read `unverifiable`/`missing_status` because the fleet snapshot rows lacked the terminal handle the matcher keyed on. A 59-row failure table over every bug fixed during review showed the same two classes recurring: a fact dropped in transit through optional fields, and two authorities for one fact. Two blind designs (Opus, Codex) converged on the same mechanisms, and the scoped tranches landed here with red-then-green seam tests from the real producer to the real consumer, faults injected only at the transport or hook-ingest boundary:

- **Settlement (data-loss class):** one three-valued `WriteSettlement` (`accepted | refused{reason} | unverifiable{reason, bytesHandedToTransport}`) from the SSH multiplexer through daemon client, providers, controller, to pointer staging. No boolean, no rejection-as-third-state. The two silent degrades that fabricated a handoff are deleted; a provider that cannot settle refuses before any effect. Pointer text and Enter share the contract; a partial flush is `unverifiable`, never `refused`.
- **Evidence identity (false-liveness class):** fleet agent-status evidence is a tagged union (`binding: worker | pane | unresolved{reason}`, `clock: observed | delivery`) minted once at ingest, so a hook row captured on one process incarnation can never bind to a later dispatch on the same pane. The matcher's `!worker.paneKey ||` defaults are gone. One host-scope parser replaces two.
- **Small pre-merge items:** `capability_unsupported` from an old peer is no longer relabelled `host_unavailable`; a producer census test asserts every agent-status consumer path projects a pane-only hook row as `live`.

Two ergonomics defects the second live run surfaced on a real database are fixed here too: a pre-v3 dispatch already marked `completed` projected as `outcome_unknown` / `requiresAction: true` forever (three copies of the outcome ladder disagreed on legacy rows; now one resolver, legacy `completed` reads `succeeded` with nothing to act on, legacy `failed` stays actionable on the failure), and an unscoped `worker-list` enumerated the entire database (now defaults to the Run bound to the calling terminal, `--run` overrides, and the receipt's additive `scope` field says which).

A third live round on the shipped adhoc build of `b082443e1f` (same four hosts) plus an unscripted run in the user's own prompt style (a plain Claude Code shell, `/orchestration`, three workers, zero errors, bound-Run default confirmed) found two more branch defects, fixed with red-then-green tests: a worker freshly started on a paired server projected `unverifiable`/`host_indeterminate` with `requiresAction` for ~3 minutes, including after its own `worker_done`, because the host's federation observation returned `missing_liveness_verdict` for any PTY the liveness register had not yet swept (the host now reads a connected pane it owns locally as `live`; disconnected or SSH-scoped panes stay `unverifiable`); and six pre-v3 completed rows still carried an `input` category because settling through the task-status path or `failDispatch` never closed the Dispatch's pending question threads (both paths close them now, and schema v38 closes threads already pending on settled rows). The guide's `worker-start` examples now show `--model sonnet`, since an omitted model inherits the launcher's default.

A Codex adversarial pass on the tranche diff found one real design hole (identity minted at read time instead of ingest, now closed) and two daemon settlement paths that threw instead of settling (fixed). Two `@ts-nocheck` runtime mixins on these paths were extracted into checked modules; the repo-wide `@ts-nocheck` count is unchanged at 171.

Deletions during review: ~1,900 lines (write-only ledger, unread columns, dead v1 archive path, test harnesses shipped in prod, duplicated liveness and state-machine copies, self-capability checks that were compile-time true).

## Testing

- `pnpm typecheck:tsc:node|cli|web` clean
- `pnpm run check:code-quality:changed` 0 findings; `check:react-doctor:changed` 0
- `pnpm verify:bundled-skill-guides`, `verify:skill-bundle-manifest`
- full `pnpm test` on the integrated head: 72,332 pass / 292 skipped; the only failures were three non-PR files (two zsh live-shell suites hit a node-pty spawn-helper ENOENT while a concurrent native rebuild ran, 44/44 in isolation; `release-checkout.unit.test.ts` is a known 30 s load timeout that passes in isolation on `origin/main` too).
- CI on 70b4811 (rerun, pre-Codex): the only reds are five SSH e2e specs plus `terminal-send-agent-prompt-submit:198`, each shown failing identically on main (main's E2E workflow is red on its last 40 runs). The terminal-send spec is root-caused and fixed separately in #18707. The Windows hook-service flake (#17721) and the federation load flake did not recur.
- Skills: `pnpm exec vitest run` over the skill gate files plus `src/cli`, `config/scripts`, `src/main/skills` pass; live smoke on the built CLI of `skills get orchestration` and `--full` (7 references).
- live headless runtime (`orca-dev serve`, isolated profile): canonical loop, stop, release, archive read, retry rejection, stale-handle check, SIGKILL-and-replay all verified with receipts
- Live cross-host smoke on the shipped adhoc build of `0d465e7931` (this Mac and a paired Windows host on the build, a paired Mac left on 1.4.195, an SSH host): local, paired-new, paired-old and SSH loops all settle; running workers read `live` on every host and `exited` after release; the old peer reads `capability_unsupported` and refuses release honestly. Injected 10 s relay stall with a send in flight: delivered exactly once after recovery, zero duplicates. Every liveness field across 104 receipts is only `live` / `unverifiable` / `exited`.
- Final live cross-host smoke on the shipped adhoc build of `b082443e1f` (same hosts): every loop settles; 942 of 948 legacy completed rows read settled with `requiresAction: false` before the question-thread fix and all of them after; `worker-list` scope reads `bound` / `flag` / `all` correctly; 122 JSON receipts carry only `live` / `unverifiable` / `exited`. Unscripted prompt-style run: clean.
- Confirmation smoke on the shipped adhoc build of `2da076d4e9` (this Mac and the paired Windows host, both updated): a freshly started Windows worker reads `live` on the first fleet poll and on all 20 that follow, with no `host_indeterminate` at any point, and `exited` after release; all 948 legacy completed rows read `requiresAction: false` with `nextAction: none` after schema v38; every verdict across 60 receipts is `live` / `unverifiable` / `exited`.
- Not physically exercised: WSL hosts, the renderer notification bell (headless has no renderer), same-session fence via a real pane close (renderer-only state), restart mid-delivery on a real app (covered by e2e only).

## Notes

- Remote-wire additions are optional fields or `method_not_found`-negotiated methods; one new Electron-only IPC channel (`agentStatus:legacyWorkerTerminalResumeFence`) never crosses the wire.
- SSH contact loss remains `unverifiable`; the execution host stays authoritative.
- Intentional wire projection change: an SSH host scope with an empty `targetId` now projects host id `ssh` instead of an empty string (remote-wire-compatibility rule 3, old clients decode the same field). A fleet pane key without a terminal handle is now `unidentifiable` rather than matched by pane key alone.
- Found live but pre-existing on main, filed separately: a relay daemon-start collision during transport loss rewrites the endpoint credential and wedges the surviving relay (host needs a manual kill); `terminal create` on a reconnecting SSH host reports an opaque `No PTY provider for connection`; `terminal list` reports `orphaned:false` and `terminal close` reports `ptyKilled:true` for a pane whose relay is gone (orchestration's own projection reads `unverifiable` correctly at the same moment).
- Downgrade after this PR is not a supported path: main opens a v37 database and early-returns (its inserts still work against the v36/v37 defaulted columns), but its one-outstanding-Delivery-per-Run index is a no-op against the branch's mailbox-scoped index of the same name.
- Known follow-ups (not blockers): `worker-list` materializes every dispatch row per call; a positive "agent absent" signal distinct from PTY liveness is a product decision left open (a headless fake agent never reaches `live`, so its `nextAction` stays `inspect`); a context-only self-dispatch still lists as `role: worker` in `worker-list`; `dispatch` task-not-found / task-not-ready / inject-rejected still surface as `runtime_error`; task and inbox receipts still expose raw row columns. Deferred skill product decisions live on #18724.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
<!-- orca-pr-loc -->
<!-- Programmatic LoC summary. Do not edit by hand; rewritten on every commit. -->

| | Files | Added | Deleted | Net |
| :--- | ---: | ---: | ---: | ---: |
| Test | 225 | $\color{#1a7f37}{\Huge{\mathbf{+}}}$​21666 | $\color{#cf222e}{\Huge{\mathbf{−}}}$​2820 | $\color{#1a7f37}{\Huge{\mathbf{+}}}$​18846 |
| Prod | 348 | $\color{#1a7f37}{\Huge{\mathbf{+}}}$​17107 | $\color{#cf222e}{\Huge{\mathbf{−}}}$​4706 | $\color{#1a7f37}{\Huge{\mathbf{+}}}$​12401 |

<!-- /orca-pr-loc -->

## ELI5

Orca now treats orchestration like a durable control plane instead of inferring success from terminal keystrokes. Agents can tell whether a prompt was accepted or a turn started, replay an ambiguous request without sending twice, and recover coordinator mail after a crash. Completed workers can be inspected, released, or retained, and their panes no longer auto-resume as if the work were still running.

## What changed

- **Run receipts** from `run-create/use/current/show/list` are the row without routing plumbing (`home_database`, `coordinator_pane_key`) and without the duplicate `binding` object.
- **`terminal send` receipts are honest and idempotent.** `input_accepted` and `turn_started` are the only stages; `--wait-submit` observes without resending; `--retry-request <uuid>` replays the exact request against the same process incarnation. A transport timeout keeps the retry ID; only a different runtime answering strips it. Value-less or non-UUID `--retry-request` is rejected on the CLI and the SSH shim.
- **Mailbox delivery is committed before wakeup.** Pointer writes are staged in the DB before any PTY byte, replayed once after restart, and never emit a naked Enter. The watermark that parks concurrent deliveries is released with the DB reservation. Restart rescans pointer-pending and `dispatch:` mailboxes.
- **Lifecycle is a guarded transition graph** (`lifecycle-transition.ts`) with a table-driven test over every caller edge. Task reopen/overturn stays in the public contract. A PTY exit during `worker-stop` is the stop succeeding, not a failure.
- **Worker lifecycle CLI:** `worker-start` (`--spec` creates Task + attempt in one call), `worker-show`, `worker-read` (provider transcript first, bounded terminal fallback with a typed reason, local/WSL/SSH), `worker-stop`, `worker-abandon`, `worker-release`, `worker-retain`, `worker-list` (rowid-fenced pagination, fleet liveness, `attention`, literal `nextAction`).
- **Release is an explicit ownership table** (`decideWorkerTerminalRelease`): only an `owned` resource can be settled, the archive is mandatory where reachable, and an owner whose process is proven exited can always get out of `retained` via `archive_status: unavailable`. User-taken-over, external, and transferred panes stay retained.
- **Settled-worker resume fence** (folds in stablyai#17651): a settled dispatch whose pane is still open is fenced at settlement, on stop/abandon/exit, and at startup; lifted on release, retain, takeover, and pane reuse.
- **Liveness is `live` / `unverifiable` / `exited` only**, from execution-host evidence. Fleet projection reads the evidence clock, not the relay delivery clock. A host-certified exit outranks the worker's settled state. `unverifiable` never authorizes stop, abandon, retry, or release, in code or in the guide.
- **Federation:** structured reads negotiate by `method_not_found` so every shipped host keeps transcript-first output; exited remote workers are closed before being reported closed; epoch fencing holds across peer restart, downgrade, and pairing rotation; no per-second forced capability probe.
- **Schema v35:** repairs databases stamped v34 by the pre-fix branch (mailbox_handle default, index predicates), drops the write-only `lifecycle_transition_receipts` ledger and five never-read v31 identity columns.
- **Schema v36:** `dispatch:<id>` mailboxes get a real consumer generation on `dispatch_contexts` and `remote_dispatch_attachments`, bumped and fenced in the same transaction on every re-attach (manual inject, worker-start, federated attach). A stale worker whose Dispatch moved to another process now gets `consumer_fenced` instead of silently acking the new worker's Delivery. Run mailboxes already worked this way.
- **Schema v37:** `dispatch_contexts` records its creator (`creator_handle`, `creator_pane_key`), so a coordinator's context-only self-dispatch is bookkeeping rather than a nesting parent; before this, one self-dispatch made every later `worker-start` from that coordinator fail the depth cap. Pre-v37 rows keep counting (fails closed).
- **Dispatch-mailbox ownership is checked, not inferred.** A `check` from a process whose pane no longer holds the Dispatch, or whose last Attempt was abandoned/failed and moved to another terminal, gets `consumer_fenced` instead of an empty inbox that reads as "no mail yet". `--peek`/`--all` stay readable. A paneless caller still gets `stable_pane_required` with the rebind recovery.
- **Liveness certification is stricter:** a `process_exited` stage whose termination reason is `unknown` (a stop that was issued but never observed) projects `unverifiable`, not `exited`. Federated `worker-show` carries the execution host's verdict and host kind instead of a local guess. A live, ready worker with nothing pending has `nextAction: none` rather than pointing at the `worker-show` that produced it.
- **Wire:** `workerShow` keeps `dispatch.task_id` next to `taskId` for shipped CLIs. `ask --json` uses the standard `{ok, result}` envelope like every sibling verb.
- **Migration start-version detection** treats the two v32 recovery columns as versioned. Before this, every shipped database stamped below 32 resolved to the v6 floor and replayed the whole chain (the v23 backfill synthesized 68 phantom retained workers on a real v30 profile). Verified on a copy of a real 62 MB v30 profile: starts at 30, no row delta, integrity ok, 11 ms.
- **Skill guide** rewritten as a ≤200-line kernel plus seven references, to the outcome-first standard (Result / Done / Safe failure first, conditions not case lists, one done bar, references loaded at the point of use). The canonical loop uses `worker-start --spec`, names `worker-list` for completion accounting, documents `--retry-request` / `request-show` / `--wait-submit`, and requires positive evidence before any stall action. The other seven guides get the same treatment in stablyai#18724, split out so this PR stays orchestration-only.
- **`rpc/methods/orchestration-*`** (126 flat files) regrouped into `orchestration/{worker,federation,messaging,runs,gates}/`.

## Why

User reports showed the same boundary failures: false `agent_prompt_stalled` causing duplicate sends (stablyai#15180), coordinators unable to trust screen scrapes, cold-parked terminals receiving a pointer without the submit, settled workers accumulating as live tabs and auto-resuming after restart, and no way to tell a stalled worker from a working one.

## Linked issues

Fixes stablyai#15180. Fixes stablyai#17935 (orchestration skill description is 866 characters; a guard now caps every bundled skill at 1,024). Supersedes stablyai#17651 (fence folded in). Advances stablyai#16660, stablyai#16522, stablyai#14907, stablyai#13047.

## Review record

This PR was reviewed adversarially after revival: eight independent lenses (lifecycle, mailbox, send, worker, federation, transcript, complexity, live ergonomics), each required to prove findings with a failing test. That produced 16 proven blockers, all fixed with red-then-green regression tests, followed by two re-review rounds and a third fix wave that caught 3 regressions introduced by the fixes and 7 fixes that missed their target; all closed. A final pass (five lenses incl. a live built-runtime smoke, then a re-review of the fix wave) found and fixed seven more, chiefly the stale-worker mailbox steal, the self-dispatch depth wedge, and the unproven-exit certification. Three independent Codex (gpt-6-astra) passes followed: the first found nothing new, the second found and fixed 3 defects (task-status reachability, WSL-local host classification, peer-capability epoch), the third found and fixed 6 (production PTY controller never installed settled writes, ambiguous in-flight pointer failures allowed duplicate replay, SSH/relay deadlines cut off a valid `--wait-submit`, stop-vs-exit race during inspection, and two release-recovery paths for vanished or exited terminals). The full record (findings, proof tests, triage, declines with reasons) is archived outside the repo.

**Rework after the live smoke.** A first live cross-host run on the shipped adhoc build (this Mac, a paired Windows host on the same build, a paired Mac on 1.4.195, and an SSH host) found a P1: a running local worker read `unverifiable`/`missing_status` because the fleet snapshot rows lacked the terminal handle the matcher keyed on. A 59-row failure table over every bug fixed during review showed the same two classes recurring: a fact dropped in transit through optional fields, and two authorities for one fact. Two blind designs (Opus, Codex) converged on the same mechanisms, and the scoped tranches landed here with red-then-green seam tests from the real producer to the real consumer, faults injected only at the transport or hook-ingest boundary:

- **Settlement (data-loss class):** one three-valued `WriteSettlement` (`accepted | refused{reason} | unverifiable{reason, bytesHandedToTransport}`) from the SSH multiplexer through daemon client, providers, controller, to pointer staging. No boolean, no rejection-as-third-state. The two silent degrades that fabricated a handoff are deleted; a provider that cannot settle refuses before any effect. Pointer text and Enter share the contract; a partial flush is `unverifiable`, never `refused`.
- **Evidence identity (false-liveness class):** fleet agent-status evidence is a tagged union (`binding: worker | pane | unresolved{reason}`, `clock: observed | delivery`) minted once at ingest, so a hook row captured on one process incarnation can never bind to a later dispatch on the same pane. The matcher's `!worker.paneKey ||` defaults are gone. One host-scope parser replaces two.
- **Small pre-merge items:** `capability_unsupported` from an old peer is no longer relabelled `host_unavailable`; a producer census test asserts every agent-status consumer path projects a pane-only hook row as `live`.

Two ergonomics defects the second live run surfaced on a real database are fixed here too: a pre-v3 dispatch already marked `completed` projected as `outcome_unknown` / `requiresAction: true` forever (three copies of the outcome ladder disagreed on legacy rows; now one resolver, legacy `completed` reads `succeeded` with nothing to act on, legacy `failed` stays actionable on the failure), and an unscoped `worker-list` enumerated the entire database (now defaults to the Run bound to the calling terminal, `--run` overrides, and the receipt's additive `scope` field says which).

A third live round on the shipped adhoc build of `b082443e1f` (same four hosts) plus an unscripted run in the user's own prompt style (a plain Claude Code shell, `/orchestration`, three workers, zero errors, bound-Run default confirmed) found two more branch defects, fixed with red-then-green tests: a worker freshly started on a paired server projected `unverifiable`/`host_indeterminate` with `requiresAction` for ~3 minutes, including after its own `worker_done`, because the host's federation observation returned `missing_liveness_verdict` for any PTY the liveness register had not yet swept (the host now reads a connected pane it owns locally as `live`; disconnected or SSH-scoped panes stay `unverifiable`); and six pre-v3 completed rows still carried an `input` category because settling through the task-status path or `failDispatch` never closed the Dispatch's pending question threads (both paths close them now, and schema v38 closes threads already pending on settled rows). The guide's `worker-start` examples now show `--model sonnet`, since an omitted model inherits the launcher's default.

A Codex adversarial pass on the tranche diff found one real design hole (identity minted at read time instead of ingest, now closed) and two daemon settlement paths that threw instead of settling (fixed). Two `@ts-nocheck` runtime mixins on these paths were extracted into checked modules; the repo-wide `@ts-nocheck` count is unchanged at 171.

Deletions during review: ~1,900 lines (write-only ledger, unread columns, dead v1 archive path, test harnesses shipped in prod, duplicated liveness and state-machine copies, self-capability checks that were compile-time true).

## Testing

- `pnpm typecheck:tsc:node|cli|web` clean
- `pnpm run check:code-quality:changed` 0 findings; `check:react-doctor:changed` 0
- `pnpm verify:bundled-skill-guides`, `verify:skill-bundle-manifest`
- full `pnpm test` on the integrated head: 72,332 pass / 292 skipped; the only failures were three non-PR files (two zsh live-shell suites hit a node-pty spawn-helper ENOENT while a concurrent native rebuild ran, 44/44 in isolation; `release-checkout.unit.test.ts` is a known 30 s load timeout that passes in isolation on `origin/main` too).
- CI on 70b4811 (rerun, pre-Codex): the only reds are five SSH e2e specs plus `terminal-send-agent-prompt-submit:198`, each shown failing identically on main (main's E2E workflow is red on its last 40 runs). The terminal-send spec is root-caused and fixed separately in stablyai#18707. The Windows hook-service flake (stablyai#17721) and the federation load flake did not recur.
- Skills: `pnpm exec vitest run` over the skill gate files plus `src/cli`, `config/scripts`, `src/main/skills` pass; live smoke on the built CLI of `skills get orchestration` and `--full` (7 references).
- live headless runtime (`orca-dev serve`, isolated profile): canonical loop, stop, release, archive read, retry rejection, stale-handle check, SIGKILL-and-replay all verified with receipts
- Live cross-host smoke on the shipped adhoc build of `0d465e7931` (this Mac and a paired Windows host on the build, a paired Mac left on 1.4.195, an SSH host): local, paired-new, paired-old and SSH loops all settle; running workers read `live` on every host and `exited` after release; the old peer reads `capability_unsupported` and refuses release honestly. Injected 10 s relay stall with a send in flight: delivered exactly once after recovery, zero duplicates. Every liveness field across 104 receipts is only `live` / `unverifiable` / `exited`.
- Final live cross-host smoke on the shipped adhoc build of `b082443e1f` (same hosts): every loop settles; 942 of 948 legacy completed rows read settled with `requiresAction: false` before the question-thread fix and all of them after; `worker-list` scope reads `bound` / `flag` / `all` correctly; 122 JSON receipts carry only `live` / `unverifiable` / `exited`. Unscripted prompt-style run: clean.
- Confirmation smoke on the shipped adhoc build of `2da076d4e9` (this Mac and the paired Windows host, both updated): a freshly started Windows worker reads `live` on the first fleet poll and on all 20 that follow, with no `host_indeterminate` at any point, and `exited` after release; all 948 legacy completed rows read `requiresAction: false` with `nextAction: none` after schema v38; every verdict across 60 receipts is `live` / `unverifiable` / `exited`.
- Not physically exercised: WSL hosts, the renderer notification bell (headless has no renderer), same-session fence via a real pane close (renderer-only state), restart mid-delivery on a real app (covered by e2e only).

## Notes

- Remote-wire additions are optional fields or `method_not_found`-negotiated methods; one new Electron-only IPC channel (`agentStatus:legacyWorkerTerminalResumeFence`) never crosses the wire.
- SSH contact loss remains `unverifiable`; the execution host stays authoritative.
- Intentional wire projection change: an SSH host scope with an empty `targetId` now projects host id `ssh` instead of an empty string (remote-wire-compatibility rule 3, old clients decode the same field). A fleet pane key without a terminal handle is now `unidentifiable` rather than matched by pane key alone.
- Found live but pre-existing on main, filed separately: a relay daemon-start collision during transport loss rewrites the endpoint credential and wedges the surviving relay (host needs a manual kill); `terminal create` on a reconnecting SSH host reports an opaque `No PTY provider for connection`; `terminal list` reports `orphaned:false` and `terminal close` reports `ptyKilled:true` for a pane whose relay is gone (orchestration's own projection reads `unverifiable` correctly at the same moment).
- Downgrade after this PR is not a supported path: main opens a v37 database and early-returns (its inserts still work against the v36/v37 defaulted columns), but its one-outstanding-Delivery-per-Run index is a no-op against the branch's mailbox-scoped index of the same name.
- Known follow-ups (not blockers): `worker-list` materializes every dispatch row per call; a positive "agent absent" signal distinct from PTY liveness is a product decision left open (a headless fake agent never reaches `live`, so its `nextAction` stays `inspect`); a context-only self-dispatch still lists as `role: worker` in `worker-list`; `dispatch` task-not-found / task-not-ready / inject-rejected still surface as `runtime_error`; task and inbox receipts still expose raw row columns. Deferred skill product decisions live on stablyai#18724.
@nwparker

Copy link
Copy Markdown
Contributor Author

Closing as superseded by merged PR #16904: #16904

The merged replacement explicitly folds in this settled-worker resume-fence work (including settlement, release, retain and takeover handling). The branch has no commits after that merge.

Verified during the repository-wide issue/PR audit. The original branch is preserved.

@nwparker nwparker closed this Nov 16, 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.

1 participant