Commit Graph
25 Commits
Author SHA1 Message Date
Brennan BensonandMerge Sim ce4a3a4186 feat(chat): add structured session rewind backend (#19235)
* feat(chat): add structured session rewind backend

* fix(chat): make interrupted session rewinds recover safely

* fix(native-chat): negotiate rewind runtime capability

* fix(native-chat): consolidate remaining adapter imports

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 12:20:24 -07:00
Brennan BensonandMerge Sim ba4e79c250 fix(runtime): apply the structured-chat setting to every RPC caller (#18700)
* fix(runtime): apply the structured-chat setting to every RPC caller

supportsStructuredAgentSessions only consulted experimentalStructuredNativeChat
when clientKind === 'mobile', so identical host settings admitted desktop and
in-process callers while refusing a phone. The server branched on client surface.

The setting is now one rule for every caller. The negotiated capability stays a
wire term asked of remote clients only, so a capability-less in-process caller is
still admitted on the setting alone.

Making the projection's structuredNativeChatEnabled argument required surfaced
eight call sites that passed `undefined` for non-mobile clients; they now read the
host setting, so tab projection follows the same single rule.

Announced behaviour change: with the flag off, session.tabs.list/listAll no longer
restore structured tabs for desktop. The desktop renderer already discards them in
that state, and startup record/lease reconciliation is unaffected.

* fix(runtime): keep structured session cleanup available

* test(runtime): enable structured chat in desktop projection fixture

* test(agent-session): settle merged fixtures against the all-clients structured policy

The merge with main left three fixtures written for the old mobile-only rule:
a duplicate getClientSettings key, a create fixture with no host settings at
all, and a projection call whose 'old client' is now the mobile fallback-title
case.

* fix(native-chat): let an admitted caller close a chat after the setting is off

Turning `experimentalStructuredNativeChat` off revoked admission for every
`agentSession.*` method, including `close`. A chat opened while the setting was
on stays mounted, so its owner was left with a live provider child and an X
button that answered `structured_agent_session_unsupported`.

Split the surface by what a method does to work in flight rather than by how it
sounds, and write that rule where the gate lives so the next method lands on the
right side: starting, extending, retaining or reading needs admission; stopping
or retiring work the caller already owns does not. Moves `close` and `cancel`
onto the cleanup gate alongside `unsubscribe` and `release`.

The tightening is unchanged - the cleanup gate still demands the negotiated wire
capability and never creates a host, so an incapable client still cannot see the
surface and no method that starts work is reachable with the setting off.

Extracts the dispatcher harness and the method-to-gate table into fixtures so
the new admission suite can share them without a max-lines disable.

* Drop a duplicate lastActivityAt key carried in from main

The main commit this branch merged (fb322046e8) had two lastActivityAt
properties in the same object literal at both journal stubs, which fails
TS1117 and oxlint. Upstream has since kept only the later value; match it.

Not introduced here, but merged in, so it has to be fixed here.

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-06 23:32:00 -07:00
Brennan BensonandMerge Sim f1d8545024 feat(chat): support structured /clear and /compact commands (#19164)
* feat(chat): support structured clear and compact commands

* fix(chat): authorize mobile commands and bound clear-chain projection

* fix(chat): localize conversation command send errors

* fix(chat): retain clear pane identity with reopened history

* test: account for combined structured session RPC additions

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-06 21:17:00 -07:00
Brennan BensonandMerge Sim bf4e270504 fix(native-chat): list the slash commands and skills a structured Claude session actually loaded (#19127)
* fix(native-chat): list the slash commands and skills a structured Claude session actually loaded

The chat composer's `/` menu was built from a curated five-command catalog plus a
host disk scan of skill roots. Neither is what the running session can do: the
session reports its own `/` surface, which carries this repo's `.claude/commands`,
the skills that only reach it through plugin roots, and a hide-list of commands
that mean nothing outside a terminal UI. On one local session the menu offered 6
commands and 17 skills where the session reported 62 commands and 33 skills.

Read that surface per session and let it drive the picker:

- A per-session catalog seeded from the frame that proves the session and kept
  current by every later report, exposed over a new `agentSession.commands` read.
- The report is the authority on WHICH skills exist; the disk scan stays the
  source of scope and description for the names both know about, so a skill the
  session never loaded is no longer offered and one it loaded from a root the
  scan cannot see now is.
- A host that predates the read answers `method_not_found` and the composer keeps
  its curated catalog, so mixed versions and the PTY lane are unchanged.

* test: register agentSession.commands on the three surface ratchets

The structured method count, the mobile allowlist, and the cross-version call
table each enumerate the agentSession surface on purpose, so an additive method
has to be declared in all three rather than counted around.

* fix: preserve session catalog authority and publish live updates

* fix(native-chat): publish authoritative command catalogs on session updates

* fix: seed Claude slash catalog before the first prompt

* test: verify unclassified catalogs survive session publication

* test: complete structured rename journal fixtures

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-06 20:33:14 -07:00
Jinwoo Hong 06a607a1d7 feat(orchestration): make multi-agent workflows durable (#16904)
<!-- 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 70b4811267 (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.
2026-09-06 14:34:03 -04:00
6494f2a4f0 fix(native-chat): resume a structured chat from Agent Session History (#18933)
* fix(native-chat): resume a structured chat from Agent Session History

Clicking Resume on a chat-UI row could only reveal an already-open tab. If the
chat had been closed, or this process had never published it, the click re-read
an inventory that did not contain it and toasted "Retry in a moment" — advice
that could never come true, because nothing republishes an unpublished tab. The
legacy `claude --resume` fallback is deliberately refused for structured-owned
rows, so the row had no way back at all.

`close` already keeps the record and the journal on disk so a session can be
attached again, and the hold path already resurrects one in full. What was
missing was the tab: `restoreReadableSessions` is latched to run once, at
startup, so nothing could ask for a single session later.

Adds `agentSession.reveal`. The host looks up its own record, restores the
session readable, and republishes the tab through the same call
`agentSession.create` uses. Deliberately narrow:

- It takes no hold. A provider child exists because a surface asked, and the
  chat pane asks when it binds.
- A journal it cannot read is not a refusal. A chat whose journal predates the
  SQLite store restores to nothing here, but attach still recovers it, so the
  tab is published and the pane's hold finishes the job.
- Workspace and provider come from the record, never the client, so a session
  id alone cannot aim the publication at another workspace.

Claude and Codex both, by construction: eligibility is `adapterSupportsRecord`,
which the router answers from the record's own provider.

Gated on a new advertised capability rather than probing for method_not_found,
matching agent-session.structured.hold.v1 — absence is visible during
negotiation instead of by calling.

* fix(native-chat): negotiate reveal against the host that owns the workspace

The capability gate read the LOCAL runtime's advertised capabilities while the
call went to the host that owns the workspace, which for a paired workspace is
a different build. On desktop the renderer and its local host are always the
same build, so the gate passed unconditionally and proved nothing about the
host being called: an older paired host still received the unknown method and
its method_not_found was reported to the user as 'this chat is no longer on
this host'. The cache it read also starts empty and resets to empty when
status.get fails, so 'not fetched yet' and 'unsupported' were the same value.

Gate on the environment that will answer, the way agentSession.close already
does, and skip the round trip entirely for a local host. Reveal now reports
four outcomes instead of a boolean, so a host that is merely too old is not
reported as a chat that is gone, and a host we could not reach keeps the
retryable message.

Also syncs the localization catalog: the 'gone' key shipped without an en.json
entry, which reddens static analysis and verify while typecheck stays green.

* fix(native-chat): tell a refused reveal apart from a missing chat

The host raises two refusals here and they mean opposite things to a user: it
holds no such record, or it holds one no adapter of its own can open. The
client collapsed both into 'this chat is no longer on this host', which is a
eulogy for a chat still sitting on disk. Read the refusal code, and fold the
host-side case in with the too-old host under one honest message, since the
remedy for both is the same.

Adds the coverage the readiness pass found missing: the host's reveal answer
itself (workspace and provider from the record, both refusals, an unreadable
journal, a live session), and the activation branches for a host that cannot
open the chat and for one that never answered.

* fix(native-chat): read a host version block as the host's age, not a lost link

The capability probe reaches assertRuntimeStatusCompatible, which throws a
runtime_compat_block error. Treating that as unreachable told a user with an
out-of-date host to retry, which is the one thing that cannot help. Branch on
isRuntimeCompatBlockError the way remote-agent-session-launch already does for
the same probe.

Also adds the refusal-code case a previous commit claimed and did not deliver:
nothing drove a structured_agent_session_unsupported reply through the reveal
client, which is the branch that commit existed to add. Corrects a doc comment
that reveal made wrong: attach is no longer the only call that builds the host.

* fix(native-chat): let a dragged history row reach the same reveal as a click

Dropping an Agent Session History row onto a pane activated the tab by id and,
on a miss, raised the very toast this PR exists to remove — so the same row
answered a click and a drop differently, and the drop kept the advice that can
never come true. The structured branch never used the drop pane, so routing it
through the shared activation loses nothing and gains the reveal.

The helper only ever read one field, so its parameter narrows to that field and
the drag payload satisfies it directly. A source ratchet holds both entry points
to the reveal-capable path, since a mounted drag harness does not exist for this
layer and what regresses is a call site, not a rendering.

* fix(native-chat): stop an advisory refresh ending the click, and one click per row

Manual QA found the reveal never ran: the inventory refresh that precedes it
is an optimization, but its failure returned early with 'not available yet,
retry in a moment' — reinstating the dead end this PR removes, one step
earlier. A failed refresh now falls through to the reveal, which is the repair
and does not need the refresh to have worked.

The click can chain a refresh, a capability probe, a reveal and a second
refresh, each with its own timeout, while nothing on the row says it is
working. A per-session in-flight guard keeps an impatient second click from
running the whole sequence again and landing its own toast.

Also drops an unreachable owner scope: the snapshot apply discards any
worktree whose execution host is not local before it reads one, so naming a
remote scope there described a synchronisation that cannot happen.

* fix(native-chat): bound the capability probe and stop naming the wrong machine

The in-flight guard releases when the activation settles, so an await that
never settles holds the row for the life of the process. The capability probe
was the one call in the chain not raced against a deadline: on a cache hit it
awaits a promise an earlier probe created, which may carry no deadline of its
own. Race it like the two calls around it.

A version block can name either side — evaluateRuntimeCompat reports
client-too-old as well as host-too-old — so a message that blamed the host
pointed half of those at the wrong machine. Name the remedy instead of the
machine, which is true for every case that reaches it.

* chore: remove a scratch repro file committed by mistake

It was swept into the previous commit by a broad `git add` while a diagnostic
ran in this worktree. It asserts the current renderer-sync defect as expected
behaviour, so it would fail the moment that defect is fixed.

* fix(native-chat): stop a reveal's own inventory refresh discarding its republished tab

Manual QA: the host answered reveal with ok:true and republished the tab, and
the chat still did not reopen — only a renderer reload brought it back.

The renderer publishes under one epoch string for its whole lifetime, and a
frame recorded under a different lineage retires that epoch permanently with
nothing to un-retire it. The Resume click asks for an inventory first, and a
worktree the host holds no entry for answers with the none/v0 sentinel; the
structured path recorded it, retiring the renderer's own epoch, so the tab the
reveal published a moment later was dropped. A reload minted a new epoch,
which is why reloading appeared to fix it.

A frame that carries no publication is not a later publication to fence
against. Treat the sentinel and a removal frame as a cursor reset, the way the
mainstream session-tabs path already clears its tracking — its comment names
this exact hazard: recording that sentinel would retire the host epoch and
reject the next live frame.

Pre-existing, and it swallows an ordinary new-tab launch on an empty worktree
too; the reveal is what turned a silent invisibility into a visible failure.

* fix(native-chat): let a retraction prune its rows without retiring the epoch

Correcting the previous commit. Skipping a retraction frame outright stopped it
pruning the mirrored rows, so a worktree the host no longer publishes would
have kept a chat on screen with nothing behind it. Apply the frame as before
and clear its cursors instead of recording them, which is what the mainstream
session-tabs path does.

The unpublished sentinel keeps its cursor now too: it is skipped rather than
cleared, so a stale frame arriving late is still fenced. Adds the case the
earlier version would have broken.

* fix(native-chat): keep the retraction's fences, and fence the reveal's refresh

Correcting the retraction handling again. Clearing its cursors was more than the
bug needed and cost a guard: the host mints a fresh epoch when it rebuilds a
pruned entry, so a republication is never gated by the retained cursor, while
dropping it left an inventory response issued before the close free to land
afterwards and strand a chat row for a worktree the host no longer publishes.
Skip only the recording. The mainstream path keeps its epoch history for the
same reason, as a tombstone fence.

The test that justified the stronger clearing asserted a host behaviour that
does not exist — a rebuilt entry republishing under the renderer's epoch with a
restarted counter. It now uses what publishStructuredAgentSessionTab actually
mints for a pruned entry, and a new case covers the frame that would strand.

Also fences the reveal's inventory refresh on the sync generation, which every
other caller that applies an inventory already does: structured chat can be
switched off mid-flight, and the answer would otherwise re-seed a row into a
renderer that just discarded them.

* fix(native-chat): drop the retraction's epoch history, keep its version cursor

Third and final shape for this branch, and the only one of the three that holds.

Keeping both maps re-poisons the epoch one cycle later: the consumer here is
also the publisher, so the history's current is the renderer's own lifetime
epoch, and recording the reveal's fresh epoch retires it. The next chat the
renderer publishes is then dropped — this bug again, one close later. Deleting
both loses the guard that stops a frame issued before the close landing after
it and stranding a row nothing republishes.

So: clear the history, keep the cursor. The mainstream path keeps its history
as a tombstone because there the epochs belong to a remote publisher; that
reasoning does not carry to a path that publishes under its own.

Each of the three variants now fails a different test.

* fix(native-chat): a retraction forgets what is current, not the tombstones

The delete lost a fence the cursor cannot replace: the version cursor only
compares within a lineage, so a delayed frame from an already-superseded epoch
had nothing left to stop it putting a chat row back for a worktree the host no
longer publishes. Keeping the record intact had the opposite fault — the
renderer's own epoch is the history's current, so the next frame under any
other epoch retired it.

Clearing only current does neither: noteRetiredValue retires nothing when there
is nothing current, and the tombstones stay. Each of the four shapes now fails
a different test.

* fix(native-chat): narrow the retraction frame through its own type

Typecheck caught what the tests could not: `removed` is not on
RuntimeMobileSessionTabsResult. The repo already names the shape —
RuntimeMobileSessionTabsRemovedResult — so this reads it through a guard rather
than the inline cast the mainstream path uses.

---------

Co-authored-by: Orca Worker <orca-worker@localhost>
Co-authored-by: Merge Sim <sim@local>
2026-09-06 00:50:20 -07:00
Neil 6d691a4c04 test: bound release checkout lock fixtures and gate delayed imports (#18981) 2026-09-05 18:43:36 -07:00
Brennan BensonandMerge Sim 2513e21390 fix(native-chat): publish structured session status from the host so the sidebar never goes stale (#18776)
* fix(native-chat): publish structured session status from the host

The sidebar learned whether a structured chat was mid-turn by replaying
the session journal in the renderer, through a reader whose lifetime was
tied to the chat pane. Hiding the pane stopped the reader before the
turn's settlement arrived, so the row stayed on "working" until the chat
was reopened. The same coupling meant a tab never opened this session
showed no status at all, and a reloaded renderer lost every settled row.

The host owns the journal, so it now projects each session's status once
per journal publication and fans the changes out on one stream per client
(`agentSession.subscribeStatus`). The projection survives eviction of an
idle session's provider child and is republished when readable sessions
are restored. The renderer bridge subscribes to that feed per runtime
target and never opens a transcript reader; the observation hook is gone.

Additive wire surface behind the existing structured capability; old
hosts reject the method and the renderer retries, showing no status.

* fix(native-chat): negotiate the status feed and stop losing a change on subscribe

The status stream is additive to a surface that already shipped, so a host
advertising agent-session.structured.v1 can still answer subscribeStatus with
method_not_found. Every renderer error path reconnected, so a remote host one
release behind got a relay round-trip every 5s and no sidebar status at all.
Give the method its own capability and probe it before subscribing; a failed
probe still retries, an absent capability does not.

Re-projecting on subscribe also wrote straight into the shared cache, so a
second client could pin the first to a stale summary. Route those diffs
through publish() before the arriving subscriber is registered.

* fix(native-chat): bound the status prompt, merge snapshots, and prove the unread path

One status frame carries every retained session and a send admits 256 KB per
prompt, so ~16 large-prompt sessions could push the snapshot past the 4 MB
outbound guard and into the retry loop. Bound latestPrompt to the same
200-char single-line preview every other agent-status row already carries.

A snapshot also replaced the cached map wholesale, so the empty first frame
from a restarting host retracted every row before restore republished them.
Merge instead; the tab map, not this feed, decides which sessions are listed.

Tests: the hidden-pane claim now sits at the host, where a journal with no
transcript subscriber is driven from running to idle; the RPC test reads a
real projection instead of its own stub.

* fix(native-chat): merge the duplicated status-event type import

* test(native-chat): pin the restart status publication, and log the unsupported host

Startup restore indexes a readable session and publishes its status, which is
what puts a never-reopened tab back in the sidebar. Only an Electron screenshot
covered that wiring; a sitting status subscriber now pins it directly.

The terminal "host too old" branch was silent, so a mixed-version report showed
an empty sidebar with nothing in the log to explain it.

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-05 15:35:03 -07:00
Brennan BensonandMerge Sim cb7f7dd11a fix(native-chat): tell old mobile builds why a structured chat is missing (#18756)
* fix(native-chat): tell old mobile builds why a structured chat is missing

A structured native chat started on desktop was simply absent on a paired phone
running any shipped App Store build. The host strips every `agent-session` tab
from a client that does not advertise `agent-session.structured.v1`, and no
released mobile build advertises it — so the chat had no representation at all
and no way to explain itself.

Keep the row and retitle it instead of deleting it. The shipped client does not
filter unknown tab types and renders whatever title the host sends, so an old
build now shows the chat's slot with a title naming the fix. Nothing is removed,
so the tab order, groups and layout it belonged to are left intact.

The prompt is keyed on the capability for that specific agent, not on the
combined policy boolean: a capable phone whose desktop simply has the experiment
off would otherwise be told to take an update that cannot help it. Claude rows
are prompted too — mobile cannot render them yet and a later build can, so the
message is true for that client as well.

Restore is no longer gated on the caller's capability. It stayed gated on the
host setting, which is what decides whether there is anything to reach at all,
but gating on capability left an old client with nothing to project after a
desktop restart: neither the chat nor the prompt.

Tab titles are capped at 128px on one line in every shipped build, so the string
is sized for ~15 characters rather than a sentence.

Prompted rows are visible rows, so the host now permits all five session-tab
mutations on them, close included. That is intended: a mobile close runs the same
teardown as the desktop's own Close button.

* fix(native-chat): keep fallback tabs safe and truthful

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-04 20:08:39 -07:00
a65332a8bd feat(claude): move structured native chat onto the Claude Agent SDK and enable it on macOS and Linux (#18560)
* Join structured attach teardown through journal bind

* fix: restore structured chat parity

* feat: add Claude structured session adapter

* fix: harden Claude structured adapter

* fix: close Claude adapter edge cases

* fix: start Claude init deadline after launch

* feat: wire Claude structured sessions

* fix: harden Claude structured runtime

* fix: fence Claude structured compatibility

* fix: preserve Claude free-text prompt answers

* fix: decode addressed Claude prompt text

* feat: enable Claude structured chat on mobile

* fix(mobile): keep structured chat provider-aware

* fix(mobile): negotiate Claude structured tabs

* fix: keep scoped RPC tests native-free

* fix: secure mobile structured image delivery

* fix: close structured session data-loss gaps

* fix: prove real Claude structured startup

* fix: consume pre-spawn proof before retry

* feat(native-chat): add desktop structured sessions

* fix(native-chat): satisfy structured session cleanup gates

* fix(native-chat): keep structured renders pure

* fix(native-chat): open composer pickers upward

* fix(native-chat): use existing view for structured sessions

* fix: harden structured desktop status projection

* fix: close structured desktop lifecycle gaps

* fix: fence structured AI Vault resumes

* fix: fence structured AI Vault resumes

* fix: preserve structured tabs during activation

* feat: toggle structured sessions between chat and TUI

* fix: harden structured session handoffs

* fix: bind structured TUI before rollout proof

* fix: complete structured chat round trips

* fix: align structured TUI return readiness

* fix(native-chat): make reverse handoff transactional

* Add Claude structured TUI handoff seams

* fix(native-chat): clear sticky handoff recovery

* fix(native-chat): complete mobile reverse after TUI exit

* fix(native-chat): keep TUI transcripts readable

* fix(native-chat): recover TUI transcript gaps

* fix(native-chat): recover claimed TUI owners

* fix(native-chat): retain cold TUI proof authority

* fix(native-chat): preserve Claude handoff authority

* fix(native-chat): recover TUI transcripts read-only

* fix(native-chat): harden Claude handoff recovery

* fix(native-chat): serialize structured handoff recovery

* fix(native-chat): close handoff admission races

* fix(native-chat): validate pinned launch environment

* fix(native-chat): revalidate restored and retried owners

* fix(native-chat): gate restart recovery publications

* fix(i18n): catalog Claude session controls

* fix(native-chat): wait for structured TUI process proof

* fix(native-chat): queue stale idle TUI handoffs

* fix(native-chat): route structured Codex options directly

* fix(native-chat): persist structured session options

* fix(native-chat): hydrate resumed structured options

* fix(native-chat): preserve options across structured handoffs

* fix(native-chat): replay pending option mutations

* fix(native-chat): rotate settled handoff operations

* fix(native-chat): rotate refused send operations

* test(native-chat): derive refusal retry state from host

* test(native-chat): give the host-oracle matrix test an explicit timeout

* fix(native-chat): keep Claude option controls idle

* fix mobile structured first-send hydration race

* fix(native-chat): preserve handoff launch authority

* fix(native-chat): harden shared handoff recovery

* fix(native-chat): serialize structured handoff recovery

* fix(native-chat): close handoff admission races

* fix(native-chat): validate pinned launch environment

* fix(native-chat): revalidate restored and retried owners

* fix(native-chat): gate restart recovery publications

* fix(i18n): catalog structured session recovery control

* fix(native-chat): wait for structured TUI process proof

* fix(native-chat): queue stale idle TUI handoffs

* fix(native-chat): keep structured recovery provider-neutral

* fix(native-chat): drop local terminal topology from structured sync

* fix structured outbox and tab restore races

* fix(native-chat): preserve Claude question groups

* fix structured provider visibility and request handling

* fix structured session TUI handoff recovery

* fix reverse structured session handoff

* fix(native-chat): recover Claude outbox and resume state

* chore(mobile): preserve the working-tree lockfile state before the main merge

Carries the pre-existing uncommitted mobile/pnpm-lock.yaml modification into history so the
main merge cannot overwrite it. Verified benign pnpm drift (babel 7.29.7->7.29.8 transitives
plus deprecation metadata); drops no patchedDependencies (the mobile lockfile declares none).

* test(native-chat): drop orphaned Claude handoff-auth test left by the main merge

'pins Claude handoff auth through the terminal provider boundary' is absent from main and its
production counterpart preserveClaudeAuthEnv no longer exists outside this test - orphaned residue
of the terminal/native handoff work this PR excludes by scope.

Removed rather than repaired: the failure was a renamed field (providerHome -> providerRoot), and
renaming it would have carried out-of-scope handoff code into the merge. Body preserved as evidence
and logged in CLAUDE-STRUCTURED-DISPOSITION-TABLE.md.

* Fix mobile structured turn state

* fix Claude structured session blockers

* fix claude structured lane blockers

* fix Claude acquisition exit proof

* fix(claude): route stream-json launch through process wrapper

* fix(claude): gate structured chat support

* Fix Claude structured launch gating

* fix(claude): split session acquisition and prune mobile scope

* test(claude): align structured session fixtures

* fix(agent-session): preserve handoff launch arguments

* fix(claude): open journals through the factory after origin/main split

The journal opener moved to journal-store-factory on main; retarget the
Claude structured tests that still imported the old path.

* fix(claude): resolve Claude structured launch args, auth, and win32 proof

The origin/main merge re-expressed the lane's Claude wiring onto main's split
orca-runtime facade and dropped three wires past green typecheck and lint.

- resolveLaunchArgs discarded its provider parameter, so structured Claude
  sessions were launched with Codex app-server flags; Claude exits on
  --dangerously-bypass-approvals-and-sandbox, and a Codex arg-parse throw
  could block Claude session creation outright.
- resolveClaudeLaunchEnv was no longer supplied, so the launch resolver fell
  back to the whole process env as configuredEnv and
  buildClaudeChildProcessEnv re-applied every auth var it had just stripped.
  The resolver now merges the Claude overlay onto a strip-applied copy of the
  inherited env, which also keeps PATH intact for withCliRuntimeOnPath.
- The windowsProcessStartTimeAvailable producer was gone while the contract
  field and both consumers survived, so the renderer gate fail-closed and
  structured native chat was unreachable on every win32 host.

Separately, structured Claude pinned CLAUDE_CONFIG_DIR unconditionally. An
explicit pin makes the CLI abandon the macOS Keychain even when it names the
CLI's own default, so a default claude.ai account could not authenticate where
the legacy Claude terminal could. Pin only a home the CLI would not resolve on
its own, matching ClaudeRuntimePathResolver, and compare against the env the
child would otherwise inherit so a diverging overlay cannot outrank the
record's account home.

Also await the now-async revealNativeSession in its regression test, and set
the native status before revealing so a rejecting reveal cannot leave a
session released but never marked native.

Claude-Session: https://claude.ai/code/session_013UqKCRB6k5e8UaYhXUHeWY

* fix(claude): scrub case-insensitive Windows auth env

* fix(native-chat): settle handoff outcome-write failures instead of leaking them

A store write failure while recording a handoff outcome escaped the flow
runner's catch handler, so the client never received the failure and the
flow surfaced as an unhandled rejection (seen as an intermittent
agent_session_store_corrupt error in the proven-dead-retry suite, whose
teardown raced the flow's trailing outcome write). Record the failed
outcome best-effort, and drain the coordinator before that test's
teardown removes the store root.

Claude-Session: https://claude.ai/code/session_011aXkcHyeiRJuezupQdjZaM

* fix(native-chat): make the structured close-failure toast provider-neutral

The structuredSessionCloseFailed toast fires for any structured session,
but its copy said 'Codex chat', so a Claude structured session that fails
to close showed the wrong provider name. The launch-failure toast is only
reachable behind the agent === 'codex' gate, so its copy stays as is.

Claude-Session: https://claude.ai/code/session_013ugSpCx4AWkySaJb69BQax

* fix(native-chat): wire structured handoff proof recovery

* fix(native-chat): wire structured handoff proof recovery

* fix(native-chat): correct the structured chat opt-in copy

The one `experimentalStructuredNativeChat` toggle gates both providers —
`useStructuredAgentSessionCreate` runs `canUseStructuredNativeChat` for
`'claude'` as well as `'codex'` — but its description named only Codex.

Its scope line also said Windows keeps using terminal chat, while the gate
refuses win32 only until the host proves it can read a process start time.
`structured-native-chat-availability.test.ts` already pins that Windows is
allowed once the proof is cached, so the two contradicted each other.

Claude-Session: https://claude.ai/code/session_01RJFsidQWmKYFmeoUuVu4Tp

* test(claude): pin @anthropic-ai/claude-agent-sdk 0.3.251 contracts against a scripted CLI

PR 1 of the SDK migration: dependency + test-only harness, no product wiring.

- Pin @anthropic-ai/claude-agent-sdk to exactly 0.3.251 — not the newest
  release — because 0.3.251 (published 2026-08-28) clears the repo's 3-day
  minimumReleaseAge supply-chain gate with no exclusion, while the newest
  release was minutes old and would have required excluding a brand-new
  publish from the exact control built to catch brand-new malicious
  publishes. Every contract this design depends on was verified identical
  on 0.3.251: the full option surface, no pid on SpawnedProcess (custom
  spawner stays mandatory), env defaulting to process.env when omitted, and
  --replay-user-messages appearing only via extraArgs.
- Exclude all eight bundled CLI platform binaries via
  ignoredOptionalDependencies. The setting lives in pnpm-workspace.yaml
  because pnpm 12 no longer reads the package.json "pnpm" field (it warns
  and ignores it; verified by install ablation). Excluding the binaries is
  what makes Orca's pathToClaudeCodeExecutable override mandatory rather
  than merely preferred. Note: pnpm 12.0.0 honors the ignore list when
  reconciling an existing lockfile but not on fresh resolution of a new
  dependency, so the lockfile's SDK entry was pinned surgically; both
  'pnpm install' and 'pnpm install --frozen-lockfile' verify clean and
  stable against the committed lockfile.
- Contract-pin suite drives the real SDK against a scripted fake CLI and pins:
  unknown type/field/content-block pass-through (and keep_alive interception),
  spawner env fidelity plus the omitted-env process.env inheritance sharp edge,
  extraArgs producing --replay-user-messages, argument parity for every
  CLAUDE_STRUCTURED_BASE_ARGS entry plus --session-id/--resume/
  --resume-session-at, canUseTool wire request_id stability and abort on
  control_cancel_request, one spawn per query, pathToClaudeCodeExecutable
  honored by the default spawner, the exact SDK version, and the eight platform
  binaries staying uninstalled.

Claude-Session: https://claude.ai/code/session_01FGCRfYUnb4hbvfTAHGtJKQ

* feat(claude): drive the structured transport through the agent SDK

Replaces the hand-rolled `claude -p --input-format stream-json` transport with
@anthropic-ai/claude-agent-sdk 0.3.251, keeping the existing connection
interface for this commit so the acquisition path changes minimally. The
control-plane rewrite is a separate change.

Orca still supplies the process. `spawnClaudeCodeProcess` routes through
`spawnProcess`, retains the child and its pid — the triple the durable lease
adjudicates on — drains stderr so exit errors keep their tail, and hands `.cmd`
shims to Orca's Windows argument encoder rather than the SDK's plain spawn.
`close()` keeps Orca's own bounded tree-kill and exit deadline, so it still
resolves true only after an observed exit.

Launch resolution emits an SDK options object instead of argv; durable
`launchArgs` translate to a typed option where one exists and to `extraArgs`
otherwise, refusing a token neither can carry rather than dropping it. The
child env is always passed explicitly — omitting it would let the SDK inherit
`process.env` and reintroduce the ambient `ANTHROPIC_*` leak. The stdout line
parser is deleted; the SDK owns framing, and unknown frames still reach the
translator verbatim.

Claude-Session: https://claude.ai/code/session_01JMhFjh9HEnkcJ5YTfCdgD3

* fix(claude): settle the frame the SDK pulled but never wrote

The SDK's input pump is `for await (frame of prompt) { await transport.write(frame) }`.
When that write rejects — the child dies between Orca's liveness guard and the
write — the for-await ends abruptly and calls the generator's `return()`, so the
code after `yield` never runs. The frame was already shift()ed out of `queued`,
so the later `fail()` from the exit path could not reach it and `send()` never
settled: `dispatchClaudeTurn` awaits that send before it can return `unknown`,
wedging the caller and the durable outbox. The pre-SDK transport rejected on the
stdin write callback instead.

Retain the in-flight entry and settle it from the generator's cleanup, and let
fail() reach it too for the pump that never resumes at all.

Claude-Session: https://claude.ai/code/session_01AobxxokqQ3qcxS7sy7ckum

* fix(claude): keep the agent SDK behind the structured-Claude boundary

The ordinary OrcaRuntimeService graph statically reaches the Claude adapter and
so the transport module, whose first line imported @anthropic-ai/claude-agent-sdk.
The SDK is evaluated whenever the regular runtime loads, before any structured
Claude session is chosen: it sets process.env.NoDefaultCurrentDirectoryInExePath,
changing Windows executable resolution for later subprocesses, and a missing or
incompatible install would break normal runtime startup — for a user who never
leaves the terminal/TUI path.

Defer the SDK to the connection, memoized so it loads once per process, and add
the import-graph ratchet: a walk from the Electron main entry that fails on any
static import of the package, plus a clean-fork check that loading the runtime
leaves the Windows search variable untouched and a child-process pin that the
side effect is still real.

Claude-Session: https://claude.ai/code/session_01AobxxokqQ3qcxS7sy7ckum

* fix(claude): answer list_models so the picker stops serving the seed

sendControlRequest had no list_models case, so every request hit the default
reject; readClaudeStructuredSessionOptions swallows that with .catch(() => null)
and falls back to the static catalog. Every structured session therefore served a
hardcoded model list with no per-model effort levels, no resolvedModel and no
default detection, and nothing surfaced the failure. The pre-SDK transport got the
live catalog from the CLI.

Route it through the SDK's supportedModels(), wrapped in the { models } envelope
the existing parser reads.

Claude-Session: https://claude.ai/code/session_01AobxxokqQ3qcxS7sy7ckum

* fix(claude): reap the child's descendants before killing it

The forced step of the exit ladder went through the Codex helper, which spawns
`pkill -KILL -P <pid>` and SIGKILLs the parent in the same tick: the parent
usually dies first, the descendants reparent to pid 1, and `-P` matches nothing.
An MCP or launcher descendant of a stubborn Claude child was left running. The
test named for that requirement declined to assert it and killed the survivor by
hand instead, so it could not fail for the thing it was named after.

Route the Claude reap through Orca's existing sweep, which snapshots descendants
while their parent link still exists and signals them before the root goes, and
on Windows uses the identity-gated `taskkill /T /F`. The test now asserts the
descendant is dead; the manual kill stays only as a failure-safe. close() still
returns true only on an observed exit.

Claude-Session: https://claude.ai/code/session_01AobxxokqQ3qcxS7sy7ckum

* fix(native-chat): merge the duplicated handoff type import

CI's static-analysis lint (`oxlint --config
config/oxlint-code-quality-native-plugins.json src config tests mobile
--deny-warnings`) exits 1 on the two separate `import type` statements from the
same module.

Claude-Session: https://claude.ai/code/session_01AobxxokqQ3qcxS7sy7ckum

* fix(claude): answer a permission callback whose signal already aborted

settleFrom registered the abort listener and then delivered the request. A
callback that arrives already aborted never fires that event, so the promise
stayed pending behind a durable prompt with no cancel path. Check the signal
first, emit the cancel, and resolve the SDK's null sentinel without registering.

Claude-Session: https://claude.ai/code/session_01AobxxokqQ3qcxS7sy7ckum

* test(claude): wait for the child to record the frame, not just for its report

The scripted CLI writes its report at startup, so `until(readReport)` returned a
report with no user messages whenever the child had not yet read the line. The
assertion then failed under parallel load. Poll for the frame instead of for the
file.

Claude-Session: https://claude.ai/code/session_01AobxxokqQ3qcxS7sy7ckum

* fix(claude): coalesce partial deltas onto one assistant item and stop painting result frames

Under --include-partial-messages every stream_event frame carries its own
uuid, and the final assistant frame for a block carries yet another; only
message.id ties them. The translator keyed each delta by its frame uuid, so a
reply painted as one bubble per delta chunk followed by a complete duplicate
under the final frame's uuid. The block's first stream frame now mints the
claude:(sessionId, uuid) identity, deltas coalesce onto it through the shared
60ms seam, and the final frame reconciles onto that same item.

Known SDK bookkeeping no longer reaches the provider-fallback row: result
subtypes are catalogued and settled by the turn lifecycle, an empty thinking
block (redacted thinking) is a modeled kind, a string-content user replay is a
text block, and an empty user frame paints nothing. An unmodeled result
subtype or content kind still lands on the bounded fallback row.

Claude-Session: https://claude.ai/code/session_01GaP5HpYQbvy2hYehVhwfEW

* fix(claude): prove descendant exit at the close boundary instead of on an unref'd timer

close() reported proven=true as soon as the direct child exited while the
descendant sweep's SIGKILL sat on an unref'd 2 s timer, so a SIGTERM-resistant
MCP server outlived the lease release. The reaper now composes the same shared
primitives the Codex structured provider uses: snapshot, verified bounded
descendant termination on POSIX, taskkill /T /F on Windows. The proof is false
whenever descendants outlive the deadline, a retried close re-verifies the
retained snapshot rather than trusting the dead root, and the raw pipe child no
longer goes through the PTY job sweep it never owned a job for.

Measured on macOS: a killed child of a SIGSTOPped parent stays a matching zombie
row in ps, so the root is killed while verification runs rather than stopped
first as the Codex non-group path does.

Claude-Session: https://claude.ai/code/session_0161QFm3KVRNJKfdzWVGVNWk

* feat(claude): replace the hand-rolled control plane with the SDK's native surface

PR 3 of the Claude structured SDK migration removes the wire-frame scaffolding
PR 2 kept, so Orca drives the SDK's typed control surface directly.

Inbound permissions move from a rebuilt control_request dispatch to the SDK's
canUseTool / onUserDialog callbacks. The prompt registry now carries the
callback's own resolver: a decodable can_use_tool becomes a durable prompt whose
answer settles the callback; a malformed one is denied without registering; the
SDK's abort signal (fired on control_cancel_request, which the SDK matches and
dedups itself) forgets the prompt and settles it null, and a late answer after
abort finds no prompt and is refused. Closing settles every in-flight callback so
no promise dangles. The claude-agent-sdk-control-bridge that rebuilt the wire
frame is deleted.

Outbound control maps to Query methods: interrupt() for cancel, setModel /
setPermissionMode / applyFlagSettings for options, supportedModels for the model
list, initializationResult() for init proof, each under Orca's own request
deadline and error classification. Cancel is interrupt-receipt aware: a CLI
advertising interrupt_cancel_queued_v1 gets cancel_queued in one round trip,
otherwise the receipt's still_queued uuids are swept with cancel_async_message so
a cancelled turn cannot spawn a later unexpected turn; older CLIs resolve no
receipt. Init keeps the 10s deadline and the unauthenticated-startup guidance.

Every behavior is failing-first and ablation-proven; the toggle-off import
boundary and the accepted loss of unknown-control visibility rows are unchanged.

Claude-Session: https://claude.ai/code/session_01Pqjduxt5G4rr9aYvtp7rNm

* fix(claude): arm the descendant snapshot before stdin closes and make the tree verdict unproven by default

A healthy Claude root leaves within the graceful window, and the close ladder
only snapshotted descendants when the root was still alive after that window.
So the common close never looked at the tree: `treeExited` stayed null,
`!== false` passed it, and close() reported a proven exit with an MCP child
still running. A root that died before the walk made the snapshot vacuous too.

The proof is now unproven by default. The reaper holds one verdict in Orca's
vocabulary (exited / live / unverifiable), assigned in exactly one place from
the bounded verification, and close() returns true only on `exited`. The
snapshot is armed before stdin closes, while the root can still be walked, and
is verified after the root exits; a root that left before any snapshot could
be armed stays unverifiable rather than vouching for descendants it never
showed us. The shared verifier gains the three-way verdict behind its boolean
face, and the connection reports the root and tree verdicts separately along
with the child's exit status.

One verification per close attempt: the retried close re-verifies, so the
intra-attempt re-reap is gone from the teardown budget.

Claude-Session: https://claude.ai/code/session_01BSmXgkWSsNHft8jFkdBFG9

* fix(claude): verify the Windows tree after taskkill instead of trusting that it ran

`terminateWindowsProcessTree` resolves from taskkill's callback whatever the
error says, so a timeout, an access denial, a recycled root and a surviving
descendant all looked identical to the reaper — which then returned a proven
exit unconditionally. close() reported true and the lease was released with an
MCP descendant potentially still live.

The Windows branch now snapshots the root's descendants while it is alive and,
after taskkill, polls a fresh process table to a bounded deadline: a row still
matching by pid AND creation time is `live`, an unreadable table is
`unverifiable`, and only a table with no match is `exited`. Creation time is
the PID-reuse guard the POSIX path gets from ps lstart, so a descendant that
denied a creation-time query is omitted rather than signalled on a bare pid.
A root already observed exited is never taskkilled: `/T /F` on a recycled pid
would take an unrelated tree down with it.

The captured tree is tagged by platform so neither verifier can be handed the
other's rows.

Claude-Session: https://claude.ai/code/session_01BSmXgkWSsNHft8jFkdBFG9

* fix(claude): release a reservation on a first-hand root exit instead of latching it into manual recovery

Making close() strict about the descendant tree exposed a second defect at the
same boundary. A create-time acquisition has no ownerProcess until publication,
so an unproven cleanup mapped to handoffStage `manual-recovery`, and
adjudication then refuses every later attach with agent_session_ownership_unknown.
A user who was merely signed out, or whose --resume the CLI rejected, wedged the
session id permanently.

Each question now answers from its own evidence. close() is unchanged and stays
strict about the tree. Separately, the lease is keyed on the root's pid and
start time, so when Orca's own child handle observed that root exit and no
descendant snapshot was ever admissible, the reservation is released and the
CLI's exit code and stderr reach the user. A descendant observed still alive,
or a root Orca never saw leave, stays unproven and keeps the reservation.

The settlement records only what was observed: the released lease says the
provider process exited and its descendants were not verifiable, rather than
reusing the wording that claims cleanup proved no child remains.

Claude-Session: https://claude.ai/code/session_01BSmXgkWSsNHft8jFkdBFG9

* fix(claude): surface an API error a result frame reports instead of settling the turn on it

The SDK models an API failure as a SUCCESS-subtype result whose `result` string
is the user-facing error text, with no assistant frame behind it. The translator
suppressed every catalogued result subtype as turn bookkeeping, so that turn
tombstoned its lifecycle and showed the user a completed, empty reply with no
sign anything had failed.

Suppression is now by meaning. A result reporting a failure routes to the
bounded provider-error surface, leading with the provider's own sentence and
keeping the raw frame behind the row's disclosure; ordinary successful results
stay off the timeline as before. A turn the user aborted also stays suppressed:
its interrupt frame already says so, and its execution diagnostic would only be
noise on every stop.

Claude-Session: https://claude.ai/code/session_01BSmXgkWSsNHft8jFkdBFG9

* fix(claude): drop the stream state of turns that never received their final frame

Every streamed delta recorded its block's identity, latest text and checkpoint
length. Only the final assistant frame removed them, so an interrupted turn left
its whole accumulated reply reachable until the session was disposed, and a long
session with repeated interruptions grew those maps without bound. The partial
text was already journaled by the flush that precedes settlement, so the live
copy was pure retention.

That state now lives in its own module, named for what it does — grow a streamed
block's journal row between its deltas and its final frame — and turn settlement
drops every block still awaiting a final. The translator reports how many remain,
which is the invariant: a settled turn leaves none.

Also makes a timed-out process-table read retryable while the root is still
alive. A loaded host can miss the table's one-second deadline, and latching that
as "no descendants" both lost the descendant sweep and, on a busy machine, made
the close ladder report unproven for a tree it never actually looked at. Only
the root's death still makes a missing snapshot final.

Claude-Session: https://claude.ai/code/session_01BSmXgkWSsNHft8jFkdBFG9

* perf(claude): capture the Windows descendant tree from one process-table read

The capture walked the descendant tree and then read the table again for the
creation times the walk's projection drops. Each read is bounded in seconds and
both run inside the close ladder's budget, so the second one cost the worst-case
teardown three seconds for data the first read already held.

The walk is now exported from the module that owns it and runs over rows the
caller has already read, which is also what lets the snapshot keep the
PID-reuse guard the projection cannot carry.

Claude-Session: https://claude.ai/code/session_01BSmXgkWSsNHft8jFkdBFG9

* fix(pty): spend the descendant verification window instead of surrendering on one slow table read

The verification abandoned the whole check the first time a process-table read
missed its own one-second deadline, with seconds of its window still unspent.
On a loaded host that reported a tree unverifiable without ever having looked at
it, which the Claude close ladder then turned into an unproven close and a
retried teardown. It also made the descendant-exit tests flake under a parallel
suite run, for the same reason and with the same honest-but-premature verdict.

A read that missed its deadline is now simply not an answer: the loop waits and
reads again until its own deadline, and only a window that ends without a
readable table reports unverifiable. This can only turn a premature verdict into
one backed by evidence; it never manufactures a proof.

Claude-Session: https://claude.ai/code/session_01BSmXgkWSsNHft8jFkdBFG9

* fix(claude): never let a later failed look collapse an observed live descendant into unverifiable

The reaper's single assignment site latched only 'exited', so a second reap
whose table reads all missed their deadline overwrote an earlier completed
verification's 'live' with 'unverifiable'. The acquisition release gate
discriminates on exactly that pair, so a root exit after such a decay released
the lease over a descendant that had been observed alive. The latch is now
monotone in trust order: exited is final, and live is only ever raised to exited.

Claude-Session: https://claude.ai/code/session_01HfdhsvSJucLw4cTZxzg2CP

* fix(claude): never prove a Windows tree gone while a descendant denied identification

The Windows snapshot dropped rows that denied the creation-time query, and an
emptied snapshot was judged exited without any table read: a descendant Orca was
refused information about was treated as one that had left. The snapshot now
counts the unidentified rows it saw, and verification caps its verdict at
unverifiable while any exist. Nothing is ever signalled on a bare pid, as before.

Claude-Session: https://claude.ai/code/session_01HfdhsvSJucLw4cTZxzg2CP

* fix(claude): classify cleanup after a first-hand exit as a root exit instead of a proven tree

When the CLI died between a successful acquire and the host's commit or proof
of the lease, handleExit had already removed the session, so releaseAcquisition
found nothing and reported true. The attach flow then settled exit-proven with
deathEvidence claiming cleanup proved no provider child remains, though the
tree was never verified. The adapter now keeps the exit that removed a
published session until the session is acquired again; acquisition cleanup runs
that connection's close ladder and classifies its verdict exactly as a
start-time failure would be, so the record reads root-exit-observed. The wire
helper keeps that typed classification and its provider diagnostic instead of
wrapping it as unproven, and the router gives up its owner even when the
release throws.

Claude-Session: https://claude.ai/code/session_01HfdhsvSJucLw4cTZxzg2CP

* fix(claude): integrate SDK teardown and picker lifecycle fixes

* fix(claude): preserve resume leaf and settle processless spawns

* fix(claude): reacquire from persisted resume leaf

* fix(native-chat): restore Claude grouped question handling

* fix(claude): persist only resumable transcript leaves

* fix(claude): recover structured session exits safely

* fix(claude): close remaining structured session P1s

* fix(claude): harden transcript branch proof

* Remove superseded root fix reports

* fix(windows): restore indexed descendant row walk

* fix(router): forward force-close lifecycle

* fix(claude): fence stale turn cancellations

* fix(claude): fence cancellation after unknown dispatch

* fix(claude): fence replay and option recovery races

* fix(claude): block replay fallback after waiter eviction

* fix(claude): fence evicted slash results

* fix(claude): fence ambiguous results and restore options safely

* fix(claude): scrub SDK child env and localize pending launch

* fix(claude): pin transcript roots and exit recovery proofs

* fix(claude): retain unproven SDK exits

* fix(claude): settle retained exit before reacquire

* fix(claude): resume from settled retained cursor

* chore: remove tracked review artifact

* fix: harden Claude SDK transport session cleanup

* fix: close Claude sessions safely

* fix(claude): close races with fresh child snapshots

* fix(claude): fail closed on recycled child identities

* fix(claude): gate root cleanup on process identity

* fix(claude): fence same-second root identity reuse

* fix(claude): restore the root SIGKILL fallback the identity gate took away

The direct root kill goes through the handle Node owns, not through a pid:
libuv drops that handle in the same turn it reaps, so the signal either
reaches the process Orca spawned or reaches nothing at all. Gating it on a
process-table probe therefore bought no safety and cost the tree its only
fallback whenever the probe declined -- a first capture landing in the fork's
own second, a recycled descendant pid voiding the snapshot, or a process table
that could not be read on either platform.

Identity verification stays where a bare pid is genuinely addressed: Windows
`taskkill /T /F`, and the descendant sweep's own revalidation before it signals.

Also stops a declined root probe from collapsing an observed `live` or `exited`
descendant verdict into `unverifiable`, and stops a successful taskkill from
reporting `unverifiable` because a later probe found the root correctly dead.

* docs(claude): rewrap the root-kill ordering comment

* Match the Claude structured launch to the terminal path's managed-account auth rules

The SDK path stripped ambient Anthropic auth unconditionally, let an explicit
agentDefaultEnv override beat a pinned managed account, and had no account-switch
guard. Reuse the terminal preflight's own predicate and messages so both transports
strip, refuse, and report identically, and cover the CLI transcript location that
mobile native chat depends on.

* Reach the Claude structured chat lane from the desktop UI

The main process has had a complete, correctly gated Claude Agent SDK lane for
a while, but no renderer ever asked for it: the launch route accepted only
`codex`, and the create path was typed `agent: 'codex'` end to end.

Widen both to the structured provider union that already exists
(`AgentSessionHandleProvider`), and generalize the codex-named create path
instead of adding a Claude twin beside it. The pending-launch registry is now
keyed by agent as well as workspace — a shared key handed a second caller the
first agent's intent, so a Claude and a Codex launch in one worktree collided.

Windows, per agent. Codex's client-side win32 refusal is deliberate and settled
elsewhere, so it stays exactly as it was. Claude's answer is no longer guessed
from the client's platform: a structured session fences its provider child on
that child's process start time, and only the executing host knows whether it
can read one. `agentSession.createSupport` already answers precisely that, per
agent, and had no renderer caller — so the Claude create path asks it before
creating and turns a "no", or a probe it cannot get answered, into the
definitive refusal the launch fallback already handles. Fail closed either way.

That refusal mapping also closes a real gap: the host reports an unsupported
location by throwing `structured_agent_session_unsupported`, which reaches the
client as a transport rejection rather than a refusal envelope, so
`StructuredAgentSessionCreateRefusalError` never fired. The launch would retry
the create, strand itself in `visibilityUnknown`, run no legacy fallback, and
show an error toast.

Close a fail-open hole while Claude and win32 become reachable: `create` with a
client-supplied location, and `ensure`, both skip the worktree-resolving support
check. They now ask the executing host the same question directly, so a host
that cannot fence a provider child no longer creates one on a client's say-so.

Also deletes `structured-agent-session-provider-routing.ts`, a duplicate of
`structured-agent-session-provider-support.ts` with no importers.

WSL, SSH and paired hosts, floating workspaces, draft prompt delivery, explicit
TUI customization and initial session options all keep refusing; folder
workspaces keep working.

* P1-1: make the structured Claude auth policy required and testable

The optional dep plus a {stripAuthEnv:false} fallback meant a dropped wiring
under-stripped silently. Required at all three hops, asserted at install time for
the @ts-nocheck caller, and the settings-to-policy mapping is now a named tested
function.

* P2-3: mobile's default Claude transcript root must follow CLAUDE_CONFIG_DIR

session-file-resolver's default ignored the variable the pinned account home
follows, so a CLAUDE_CONFIG_DIR launch wrote one tree and mobile read another. The
Task-4 test now resolves with no root override (mobile's own call) and checks the
answer against the root the CLI itself reports, instead of mirroring the code under
test's own expression.

* P2-1/P2-2/P3: close the teardown window, join the live-auth gate, align the refusal

P2-1: a switch beginning inside the acquire teardown left a dead chat and no
replacement. Past that point the launch waits the swap out and refuses only if it
never settles; the entry guard still refuses outright, because nothing is torn down
there yet.
P2-2: structured children now hold the same OAuth-refresh gate a Claude PTY does,
so a managed refresh cannot rotate the token out from under a live turn.
P3: the refusal now matches the strip it guards (case-folded on win32, presence not
truthiness), and the dead structured-to-TUI builder states its auth policy instead
of silently signing a system-auth user out.

* Make the live-auth gate tests independent of sibling connection teardown order

* Do not offer structured Claude under a WSL-only managed account

Structured Claude launches against the ambient Claude config, which the account
service keeps in sync with the selected HOST account. A WSL-bound managed
account lives inside the distro and is never synced there, so on Windows a
structured session would authenticate as whatever the ambient identity happens
to be while the UI names the WSL account — the user is told one identity and
given another.

That was unreachable only because nothing offered structured Claude on win32.
Enabling it makes it reachable, so gate it here rather than patching the auth
layer: refuse the structured path when the active managed Claude account is
WSL-bound, and let the terminal-backed path — which resolves the account per
runtime — handle that account shape.

The answer rides the agentSession.createSupport seam the renderer already
consumes, so no new capability and no renderer knowledge of account internals.
A create the host declines becomes the definitive refusal the launch fallback
already turns into a legacy native chat tab, with no error toast.

Unknown answers refuse. An install with no managed accounts claims no identity
and is fine, but an active selection that cannot be resolved — or account state
that cannot be read at all — is not evidence that the ambient identity is right.

Claude only. Codex resolves its account through a different path and its
createSupport answer is untouched, as is every Codex routing decision.

* Read the structured Claude account gate through the auth policy's accessor

The gate resolved the active account from the account-service snapshot's
runtime map; the auth policy resolves it with
getSelectedClaudeAccountIdForTarget(settings, { runtime: 'host' }). Those are
two sources and two resolution rules, and they disagree on a legacy settings
blob that carries the selection only in the flat activeClaudeManagedAccountId:
the accessor falls through to it, a direct read of the runtime map does not. The
gate would then refuse a launch the policy would have run under host-1 — and in
the mirror case a session could be admitted under a policy computed from a
different account than the gate approved.

Read the same settings through the same accessor so agreement is structural
rather than coincidental, and drop the controller accessor that existed only to
reach the snapshot.

No behaviour change for any state both already agreed on; Codex is untouched.

* Round-3 review fixes: N-1 empty-value regression, N-2 gate leak window, N-4 lost history

N-1: my presence-based conflict predicate refused a terminal launch that works
today. 'ANTHROPIC_API_KEY=' is how a user blanks a variable and the settings
pipeline preserves that empty value; an empty override cannot beat the pinned
account and the strip removes the name anyway. Back to truthiness for the value,
keeping the win32 case folding.
N-2: enter the live-auth gate only after the exit/close handlers that release it,
so no throw in between can leave an entry nothing reconciles.
N-4: the Claude transcript resolver searches config-dir-then-default and de-dupes,
matching the Codex sibling in the same file, so adopting CLAUDE_CONFIG_DIR no
longer hides history written before it.

* Run the managed-account gate on every Claude acquisition, not just create

createSupport gates the create path, but a session's account state can change
while it lives. A reacquire after an unexpected child exit re-resolves the
launch and re-derives auth, with nothing re-checking the gate — so a session
created while supported could come back up in the refused shape. With the strip
predicate keyed on there being an active non-WSL account, the WSL-only user's
normalized steady state (accounts exist, none active) does not strip, and that
reacquire reaches the child with ambient auth while the UI names the account.

Gate at resolveLaunch, the one choke point every acquisition passes through,
refusing with the pre-spawn error the caller already handles. Same predicate as
create-time, now sharing one settings reader so the two cannot drift.

Claude only; Codex resolves its account on a different path and is untouched.

The runtime class that wires this does not typecheck its own `this` calls — a
missing hookup compiles clean — so the wiring is pinned behaviourally rather
than trusted to the compiler.

* Move the structured Claude gate out of the @ts-nocheck runtime files

Both call sites of the managed-account gate sat in files whose first line is
`// @ts-nocheck`, so neither was typechecked: three arguments to a one-argument
function plus an undeclared identifier compiled clean. New auth-identity
decision logic had no compiler behind it.

Move the verdict into a checked module that takes the two facts the runtime
owns — the adapter's answer and a settings getter — and decides. The runtime
class now only forwards. Move the gate reader's construction into the checked
installer too, so the nocheck file passes a plain settings closure and never
names a gate symbol.

Every reference to the gate predicate and its reader now lives in a checked
file, so the ablation that used to pass silently is a compile error at both the
create-support and reacquire sites.

Removing the file-level @ts-nocheck is a separate, larger job and is not
attempted here.

* Derive the gate test's auth policy from the settings under test

A hardcoded stripAuthEnv asserts a gate/policy pairing production cannot
produce, and false additionally lets launch.env inherit the runner's real
process.env. Derive via claudeStructuredAuthPolicyForSettings instead: the
gate settings type is the same Pick the policy takes, and both resolve the
account through getSelectedClaudeAccountIdForTarget.

* Pin the absent-vs-empty distinction in the managed-account gate

An empty claudeManagedAccounts array is a real answer: the user has no managed
accounts, nothing claims an identity, and the ambient path is legitimate. A
readable settings object with no such field is settings we failed to parse —
the same unknown as unreadable — so it refuses.

The two are one character apart in the code and the difference is invisible
without the reasoning, so record it at the branch and pin both sides. The test
fails under the obvious "consistency fix" of treating a missing field as empty.

* fix(claude): keep command queue bookkeeping out of the transcript

Claude Code 2.1.258 emits a `command_lifecycle` frame for every uuid-stamped
command it starts, completes or cancels. The frame carries a command uuid and a
state and no content, and the CLI keeps it out of its own transcript -- but it
is absent from the SDK's SDKMessage union and so from Orca's frame catalogue,
where an uncatalogued kind defaults to a substantive row. Every structured turn
therefore painted raw JSON rows into the user-visible transcript.

Catalogue it and disposition it as status chrome. The unknown-kind default stays
`timeline-substantive`: a kind we have never seen is likelier to carry content
than to be chrome, and a visible row we can catalogue later beats content we
silently dropped. A lifecycle state that reads as a failure still surfaces,
because the payload error check in `classifyProviderFrame` outranks the
catalogue.

* fix(claude): let a re-walked descendant become eligible for the forced sweep

A descendant first observed by a capture inside its own birth second could never
be SIGKILLed: `ps lstart` is second-resolution, so that capture cannot rule out
a pid recycled later in the same second, and the merge pinned each retained row
to the boundary of the walk that first saw it. SIGTERM-resistant children forked
in that window were signalled and then never escalated -- they survived close,
quit and restart, reparented to init, and had to be killed by hand.

Advancing that boundary on any later capture would be unsound: a later capture
matching pid, pgid and start-second is exactly what an impostor would also show.
But a capture is not a match -- it is a fresh ppid walk from a root Node pins
through its own handle, so a row it re-derives is proved ours at that instant
without appealing to its start time. Chain the fence from there instead, and
take that walk at the close boundary while the root certainly still lives: the
root may leave inside the grace window, and the post-timeout refresh never runs.

A row absent from the later walk still keeps its earlier boundary, and a row no
walk has ever re-derived in a later second is still never escalated.

* Treat an absent managed-account list as empty, not as unreadable

An empty claudeManagedAccounts array and a missing one are the same answer:
this user has no managed Claude accounts, so nothing claims an identity and
ambient auth is the truth. Refusing on absence strands any profile that simply
never wrote the key, and it disagrees with the auth policy, whose own predicate
takes `(accounts ?? [])` for exactly this reason.

Only settings that cannot be READ stay unknown, and those still refuse — as do
a WSL-bound active account and a selection naming an account the list does not
explain.

The earlier reasoning treated a missing field as settings we failed to parse.
That conflated "not present" with "not readable"; only the second is unknown.

* Support structured Claude when accounts are registered but none is selected

Registered-but-deselected Claude accounts were refused, which is behaviourally
identical to having no accounts at all: the auth policy does not strip, ambient
auth is the truth, and the UI names no host identity. A user who deselected
their accounts silently got legacy chat with nothing explaining why.

Nothing selected for the host runtime is two states the settings cannot tell
apart after the fact, because pruneInvalidClaudeRuntimeSelection empties the
host slot and persists null in the second one:

  honest deselection      -> ambient auth, UI names nothing   -> SUPPORTED
  the WSL-only steady state -> ambient auth, UI names the WSL account -> REFUSED

The presence of any WSL-bound account in the list decides. Simplifying this to
"none active -> supported" re-opens the auth-identity misrepresentation, so the
tests fail loudly on exactly that: five of them, across the unit rule and the
createSupport path.

* Stop treating an unanswerable create-support probe as a refusal

A worktree is not resolvable for a beat after createWorktree resolves, so a
probe fired immediately after creation fails the RPC with selector_not_found
instead of answering. The catch collapsed that into `supported = false`, so the
composer refused and quietly built a terminal session — the gate never said no,
it was never asked successfully. Elapsed time was the only input that decided
whether a Claude launch went structured.

"Could not answer" and "answered no" are different states and only the second
is a verdict. Retry while the host cannot yet resolve the selector, with a
bounded backoff that covers the measured window with margin, and keep refusing
on the first ask for everything else. Fail-closed is unchanged: a probe that
still cannot be answered when the budget is spent refuses.

The retry is narrowed with the shared error-code matcher, which classifies a
token that transports re-wrap into a longer message without matching prose that
merely mentions it.

Codex never probes, so this race has never been able to refuse a Codex launch —
the race itself is identical for it. Recorded at the early return, because
whoever gives Codex a probe inherits the bug.

* fix(claude): fence the forced sweep on re-derivation, not on lstart's second

A descendant forked in the same wall-clock second as every walk that sees it was
signalled with SIGTERM and then never escalated, so a SIGTERM-resistant child
survived tab close, app quit and a full relaunch. Two children of one parent
96ms apart across a second boundary took opposite paths. The leak predates this
branch: it reproduces with the change reverted.

`ps lstart` has one-second resolution, so a walk landing inside a row's birth
second can never rule out a pid recycled later in that same second. But a walk
is not a match: a ppid walk only reaches what the root actually parents, and the
root is pinned by Node's own handle, so a row the walk re-derived is ours
whatever second it was born in -- a stranger would have to have been forked into
our tree, and then it is not a stranger. Fence the escalation on that.

Rows a merge retained from an earlier walk are not re-derived and still answer
to the start-time fence, which remains correct for them.

Scoped to callers that revalidate identity before signalling, which is the
Claude close path. Codex teardown reaches this same verifier and is unchanged;
the argument holds there too, but widening it is its own deliberate change.

Also reverts two changes from the previous attempt at this leak. Advancing the
capture boundary on a later walk is inert once the sweep fences on re-derivation
-- both key on the same set of rows, so the new term short-circuits for exactly
the rows whose boundary it advanced. The extra ladder refresh was a duplicate
full process-table read: close() already awaits tree.refresh() immediately
before proveClaudeChildExit, on the only path that reaches it.

Known property: the kill lands roughly a grace window after the walk that proved
membership, so a pid recycled inside that gap could in principle be signalled.
It is bounded -- matchingSnapshotRows already requires the live row to carry the
same start-second and pgid, so an impostor must be born in the remainder of that
one second, land on that exact pid, and sit in the same process group, and it
has already received the unfenced SIGTERM from the same loop.

* Run the Claude structured integration suite as a runtime client

The suite exercises agentSession.* for Claude, not the mobile surface: nothing
in it asserts anything mobile-specific and its sibling integration suites use
'runtime'. Mobile now additionally requires the experimental structured-chat
setting, which structured-agent-session.test.ts pins in both states, so the
stale 'mobile' fixture was claiming coverage it never had.

* fix(claude): report effort from get_settings, which is the only frame that has it

The composer's Effort pill rendered blank in every structured session. This is
not a missing source: the publication reads `effortLevel` off the `system/init`
frame, and that frame has never carried an effort of any kind, while the correct
value is already fetched at acquisition and thrown away on the auth diagnostic.
Verified two ways -- a live get_settings probe against Claude Code 2.1.258, and
the shipped binary's own init frame construction, which lists `model` and no
effort. So `reportedOptions.effort` was always empty, the options reader dropped
the key, and the pill had no value. Model survived only because
`currentModelId()` has a fallback chain.

The get_settings call acquisition already makes reports the session's current
effort as `effective.effortLevel`; pass that into the publication instead.
Selecting an effort already worked, so this is the arrival value only.

The legacy PTY path is unaffected and must not be "fixed" to match: it reads its
effort by parsing the startup banner (`CLAUDE_MODEL_EFFORT` in
src/renderer/src/components/native-chat/claude-terminal-session-options.ts),
which is why it shows a value where the structured path does not.

Also removes the fixture that hid this: the fake init frame invented
`effortLevel: 'high'`, a field the CLI does not send, which is why every gate
stayed green over a value that is always empty in production. The fixture's
get_settings now returns the real {applied, effective, sources} shape instead of
a bare `{env: {}}`, so the two adapter tests that asserted an effort keep
asserting it through the path production actually uses.

The reader returns null rather than defaulting: an effort nothing measured would
repeat the fixture's mistake, and a blank pill is the honest degradation if the
provider ever renames the key.

* fix(claude): only record an effort the child confirms it adopted

apply_flag_settings answers `success` for an effort it then ignores. Measured
against Claude Code 2.1.258: applying `bogus-effort-xyz` returns
subtype "success" with no error while `applied.effort` stays at its previous
value, and a valid `low` moves it. The option write treated the absence of a
throw as adoption and recorded the requested value unconditionally, so Orca
would show and persist an effort the child was not using, with nothing anywhere
reporting a problem.

Read the effort back after applying it, through the same reader the arrival
value uses, and reject when the child reports a different one. A readback that
could not be taken is not evidence of a refusal -- the apply itself succeeded --
so it still records; only a readback that disagrees rejects.

Not reachable from today's picker, which offers catalog values only, but the
CLI's effort catalog is server-delivered and has changed before, so a retired id
would otherwise become a pill confidently displaying a setting that never took.

* test(claude): assert the effort contract against the real binary

The blank pill survived every gate because the only tests that touched it were
fixture-backed, and the fixture invented the field. A test that pins the shape
we read cannot catch the provider renaming the key, which is the failure mode
that produced this defect.

Asserts both halves against a live authenticated CLI: that no frame it publishes
carries an effort at all, and that the session's current effort arrives through
get_settings. Which frame proves the session varies by host -- this machine
proves it with a SessionStart hook rather than a system/init frame -- so the
negative half asserts over every published frame rather than picking one.

Skips with the rest of the file when no authenticated CLI is present.

* fix(claude): stop the synthesised content-part kinds leaking into the transcript

Sending an image put a bare `claude · message:user:content:image` row between
the user's bubble and the answer. Two causes, and only the second is a family.

An image part counted as modelled only when `source.type === 'url'`, but
claudeDispatchMessageContent sends a local attachment as a base64 source and the
CLI replays that shape back, so every attached image was classified unmodelled.
Accept the base64 and file sources Orca itself sends.

The family is the real defect. `message:<role>:content:<type>` kinds are
synthesised at runtime from whatever `part.type` arrives, so unlike the
top-level frame catalogue they can never be enumerated ahead of time -- the
`?? 'timeline-substantive'` default then prints the synthesised name at a user
who cannot act on it. That default is right for top-level frames, where
"substantive" means show the frame; here it meant show our own vocabulary, which
drops the content AND leaks the opcode.

So an unrenderable part now renders a sentence saying exactly that, with the
kind and payload still on the row's disclosure. A part that carries its own
readable sentence keeps it -- the placeholder is a fallback, not an override.

An unknown future part type is therefore visible, never silently dropped and
never printed as a kind: the same principle as the effort readback, which
records only what the provider confirms.

* Declare agentSession.requestHandoff on the cross-version wire surface

The manifest is a ratchet for cross-version reachability, so the method is
declared with real HandoffParams rather than counted. requestHandoff is
capability-gated through requireStructuredHost and has no client caller, so
declaring it is the whole of the change.

Also model two host capabilities the harness omitted: the stub host's
supportsCreate, and the fake adapter's, without which adapterSupportsCreate
falls through to a supportsLocation the fake also lacks. Every ensure was
refused for the harness's silence rather than for its location.

* Gate structured Claude session tabs on the client capability that names them

The Claude structured lane deleted the projection's `agent !== 'codex'`
filter and added CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY in the
same commit, but never wired the constant to anything. Paired clients then
received agent-session tabs for Claude, which no shipped client renders --
mobile's resolveMobileNativeChat returns null for every agent but codex, so
the row listed and selected into a pane with neither chat nor terminal.

Restore the filter behind the declared capability instead of the bare agent
name. No client advertises it yet, so this matches main's behaviour today
and becomes a negotiation a future client can opt into.

* Confirm the structured Claude model against the model the CLI reports

set_model answers success for any string, including a model it cannot
resolve — the failure only surfaces when the turn runs — and get_settings
reports the settings-file model, not the session's. The init frame that
opens each turn is the only channel carrying the adopted model, so keep
the session's reported model current from it instead of reading it once
at acquisition.

Also stop rejecting an effort the readback cannot represent: max is
session-scoped and excluded from the persisted effortLevel, so a readback
reporting the level underneath it is an absence of evidence, not a refusal.

* Clear the session-option hedge when the provider confirms the value

The pill claimed every option was unconfirmed for the life of the session:
the renderer recorded each write as dispatched and nothing ever moved it,
so a model the CLI had already reported back still read as unconfirmed.

Carry the provider's own confirmation to the surface. Main reports which
option ids the provider named rather than merely accepted, and the client
re-reads options as a turn changes, because the frame that opens a turn is
where the adopted model arrives. A value the provider has not reported
stays hedged, including an effort whose readback could not be taken.

The confirmed list is optional on the wire: a host that predates it sends
nothing and the client keeps hedging, which is the behaviour it had.

* Keep the model report current across an acquisition fence bump

* Show the picked session-option value and let the provider report correct it

The pill showed a "not confirmed" second tooltip line for any value we had sent
but not yet seen reported back. Nothing acts on it, and for the PTY lane it was
permanent — that transport has no report channel. The pill now shows the picked
value immediately and the provider's per-turn report corrects it when the two
disagree; a newer local write still outranks a report that precedes it.

`dispatched` stays as a provenance member rather than collapsing into `applied`:
it is produced independently by the PTY lane, and it is where the `confirmed`
wire field lands, which would otherwise be unobservable.

Effort keeps its readback and its rejection path. That matters more now, not
less: with the hedge gone the rejection is the only user-visible failure signal
on this surface, so a spurious one would be the loudest bug here. Skipping the
readback for an effort the settings response structurally cannot echo is what
prevents it — the response carries the persisted level, so reading it back for a
session-scoped value would report the level underneath and fail a valid write.

* Hedge a session-option value only when the terminal transport sent it

Both lanes emit `dispatched`, so it could never say which one produced a value.
The descriptor now carries the transport that built it, set once in the shared
snapshot builder from a parameter that is required rather than defaulted — the
builder is the only place a descriptor is constructed, so a new producer has to
name its lane or fail to compile.

The structured lane confirms every value from the provider's own per-turn report,
which makes the hedge transient noise there. The terminal lane can only learn an
outcome by parsing the screen back, and only for Claude: every other agent's
`dispatched` value stays unconfirmed for the life of the session, so the line is
the only signal that we sent something we never saw land.

* Refuse an effort the session's model advertises no control for

* Refuse tab mutations on a Claude row the client never negotiated

The branch added a case asserting a client advertising only
agent-session.structured.v1 may mutate a claude row. That is the same
ungated behaviour the projection gate removes, encoded a second time —
mutation authorization reads the projection, so hiding the row refuses
the write. Assert that contract instead, and add the positive case for a
client that does negotiate Claude rows.

* Resolve the Claude session's current model in one place so the effort guard and the pill agree

* Record an effort the child did not adopt instead of refusing the write

apply_flag_settings answers success for an effort it then ignores, so the
readback exists to detect that. Refusing on it made the detection a veto,
and a veto is only correct if the readback can never be wrong about which
model is current -- which it was, twice. The pre-flight guard already
refuses a level the model advertises no control for, so the veto guarded a
door that is now locked upstream.

Keep the detection, drop the refusal: a disagreement records the child's
own answer and omits the option from confirmed, so main stops vouching for
a value the provider rejected without blocking the user's write.

* Stop a slow whole-machine ps from being read as an absent process

`ps -axo ...command=` pays a per-pid argv read: measured 1.15s for 1,948
processes (0.03s without `command=`), and CPU contention stretched the same
capture to 6.0s. Two budgets sized for a cheap look then misreport a readable
machine.

The reader's 3s ceiling killed 6 of 20 consecutive captures at load 27, so
every consumer answered "unverifiable" about a table it could read. Raise it
to 15s, and stamp the capture instant at ps START so `capturedAgeMs` is the
upper bound its contract promises -- a 6s capture used to report itself as
freshly taken, understating staleness against a 5s kill gate. The TTL keys on
completion so a slow capture still coalesces instead of forking ps per caller.

`readStructuredTuiProcessIdentity` then spent its whole 5s wait inside one
capture and concluded "no exact child" after a single look taken before the
child existed (observed landing at ~3.5s). Absence needs a look that did not
race the spawn, so require two captures before the deadline can end the loop.

Both surfaced by the real-binary Claude TUI resume test, which failed ~1 in 5
under load; 14/14 now, 8 of those runs containing a capture the old 3s budget
would have killed.

* Let the desktop renderer negotiate Claude structured tabs

The paired-client gate hides agent-session rows an agent the client cannot
render. The desktop renderer's own IPC dispatches as clientKind 'runtime'
advertising only agent-session.structured.v1, so the gate hid Claude rows
from the surface this feature ships on. It renders them; it should say so.

* Stop a slow process table from silently blinding every freshness gate

Stamping `capturedAgeMs` at ps START made the number honest, and honest broke
both consumers that read it. `ps -axo ...command=` measured 2.5-9.0s on an idle
2,002-process laptop and 4.0-18.6s at load 46, so the age it now reports lands
past every budget: `planRelayPtySweep` refuses the stop as "too old", and the
renderer's `admitRemoteForegroundEvidence` refuses the record outright. That
second one is the expensive half and was outside the diff -- a refusal bumps
`consecutiveInspectionErrors`, the poll scheduler backs off to its 10s floor,
and agent-completion detection stops for the pane. The subsystem went blind on
exactly the loaded hosts the honest stamp was meant to serve.

The evidence-publishing read now gives up at 1,200ms instead of waiting out
`PS_TIMEOUT_MS`. It is one budget for one question: these consumers ask whether
an observation describes NOW, and past this it does not -- a late answer is
refused by the age gate anyway, having first blocked a polled path for the whole
capture, so a prompt `unverifiable` is both the truthful verdict and the cheap
one. Both relay call sites already produce it from a rejection, and an admitted
`unverifiable` costs a poll where a refusal costs the cadence. Identity proof
keeps the full 15s through `getFreshProcessTableSnapshot`, because it asks
whether a process EXISTS and must never read slow as absent. The budget bounds
the wait, never the capture: the reader coalesces, so an abandoned wait leaves
its capture running to fill the cache rather than forking a second whole-machine
`ps` on the host that can least afford one.

1,200ms is bracketed rather than picked. The floor is the capture's own cost --
`command=` measured 1.15s for 1,948 processes on an idle host, and a budget
under that answers `unverifiable` about a machine nobody is straining. The
ceiling is the consumer's: 2,000ms, less the 500ms a TTL-shared capture may
already have aged, leaves 1,500ms, and transit takes the rest.

That ceiling only fits once the capture stops being charged twice. `ps` runs
inside the RPC round trip, so its duration is already in `receiveDelay`, and
`capturedAgeMs` is that same duration on the host's clock; summing them halved
the budget this gate grants a host from ~2.0s of `ps` to ~1.0s, which is why a
1.2s capture arriving at 1.3s read as 2.5s old and was refused. Admission now
takes the larger of the two. The sweep's gate keeps its sum, which is correct
there: `evidenceAgeSinceListingMs` is stamped after the listing ARRIVES, so it
measures planning time and overlaps nothing.

A stated limit rather than an assumed one: 15s is not proven sufficient for
identity proof. The same capture reached 18.6s at load 46, so that path can
still time out and answer "no exact child" about a host it simply could not read
in time. Narrowing it needs a cheaper question than a whole-machine argv read,
not a larger number.

The one test guarding this field could not fail. `beginPtyHandlerTest` installs
fake timers, so `Date.now()` is frozen, the real reader reports exactly +0, and
`0 <= 500` held identically for a hardcoded zero, for completion-stamping and
for start-stamping -- while the real reader on that host returns thousands of
ms. It now drives a measured age in and asserts the handler publishes it rather
than restamping; that the reader MEASURES it correctly stays pinned separately,
against a controllable clock. Both consumers get boundary coverage either side,
and each new gate was ablated red before it went green.

* Keep the compatibility fields off the capture the budget just abandoned

inspectProcess falls back to processHasChildren and listProcesses to
getForegroundProcessName, and both read the same TTL-shared capture with
no budget of their own. On a slow host they joined the in-flight capture
the budgeted evidence read had just given up on, so the call still blocked
for the full 6-18s and the budget bought nothing -- once for inspectProcess
and once per managed PTY for listProcesses.

Use the degraded answers those helpers already give for an unreadable
table, reached promptly. pty.hasChildProcesses keeps its unbudgeted fresh
probe: it is a one-shot destructive gate that can afford to wait.

---------

Co-authored-by: Merge Sim <merge-sim@local>
Co-authored-by: Merge Sim <sim@local>
2026-09-04 15:55:20 -07:00
Brennan BensonandMerge Sim 98e77ef1a7 feat(mobile): structured native Codex chat (#18074)
* feat(mobile): finalize structured native Codex chat

* fix(mobile): close structured chat lifecycle gaps

* wip(mobile): fence stale structured inventory and bound operation-id retention

Fence local structured-session inventory and subscription responses with a
sync generation so a toggle-off clear, reconnect restore, or retry cannot
apply a mirror from a superseded instance. Bound mobile ambiguous
operation-ID retention at 128 with unmount cleanup.

Staged on the reconcile branch only: the sync module is now 312 lines and
needs a real split before this can reach the PR head.

* fix(ci): split the structured session-tabs sync and give static analysis mobile types

The local structured session-tabs sync module outgrew the 300-line cap once it
took on generation fencing, so split it along its real seams instead of raising
the cap: the generation/cursor fence, snapshot projection, snapshot apply,
inventory refresh, and the subscription loop. The original path stays as a
barrel so no importer moves.

Repoint the host-session-mirror settle census at the apply module, which owns
two receipts now — the snapshot it mirrors in, and the toggle-off teardown that
retracts what it published. The teardown receipt is named rather than anonymous
so the pin says which direction it settles.

The changed-code quality gate lints mobile files and resolves their types from
mobile/node_modules, but mobile is a separate pnpm project that the root install
never populates, so every mobile type degraded to an `error` type and the gate
reported phantom findings. Install mobile dependencies in static analysis when
the diff touches mobile, gated on a new classifier output.

* fix(mobile): let a slow capability handshake still reach connected

The mobile capability update is an advisory whose result is discarded, yet an
unanswered one was fatal while an explicit rejection was tolerated. A 5s timeout
on the direct client force-closed the socket, and on the relay path it failed
`confirmResume` before `connected` was ever published, so a consistently slow
link redialled forever. Both paths now share one helper that settles every
ambiguous outcome (timeout, mid-flight drop) like a rejection and rejects only
when the frame never reached the wire — the one case nothing else recovers from,
since the socket's own desync force-close is gated on already being connected.
The generation guard still keeps a replaced session from connecting.

Retained structured-session operation ids were capped at 128 with oldest-first
eviction, but every retained id belongs to a send whose outcome is unknown, so
eviction turned a user's retry into a second message on the host. Bound the map
by expiry against the id's own embedded timestamp instead, mirroring the host's
operation ledger, so no id is released while the host would still honour it.

Also give the mobile CI install the root install's lockfile drift guard (mobile's
lockfile carries patchedDependencies a silent rewrite would drop), gate
mobile_dependencies on should_run, and key the pnpm store cache on both lockfiles.

* refactor(mobile): extract the relay pending-request registry

The merge composed two independently-sized changes — this branch's capability
handshake settle and main's dial-stage tracking — pushing the relay session file
to 304 lines against a 300 cap. Neither side broke it alone.

Move the in-flight request registry (id generation, tracking, settlement, and
reject-all with its delivery-ambiguity marking) into RelayPendingRequests,
matching the existing collaborator pattern alongside RelayDialStageTracker and
RpcSessionLivenessWatchdog. No behavior change.

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-03 15:19:26 -07:00
NeilandBrennan Benson fbe94ceff6 fix: close readiness gaps found by merged-change audit (#17159)
* fix(ssh): fence stale kills and retired pane replay

* fix(ssh): support cancellable interactive authentication

* fix(ssh): await remote catalog before snapshot adoption

* fix(pty): contain Windows ConPTY input failures

* fix(power): avoid redundant macOS display blocking

* perf(editor): narrow markdown override subscriptions

* fix(quick-open): close directory handles after reads

* refactor(linux): remove unused proc socket scanner

* fix(usage): apply flat Sonnet 4.6 pricing

* ci: prime Node next native test cache

* docs(skills): resolve snapshot cleanup data path

* fix(ssh): recover install locks after host reboot

* test(ssh): recognize boot-aware install locks

* test(ssh): prove previous-boot lock recovery live

* test(wire): pin pre-metadata release coverage

* fix(terminal): preserve remote tab ownership through recovery races

* test(runtime): fence replaced terminal handles in agent guard

* fix(ssh): preserve remote snapshot authority across polls

* fix(pty): contain late ConPTY output EPIPE

* test(pty): register Windows exit watcher before kill

* fix: close SSH and tab readiness race gaps

* fix(tabs): retain headless order and placeholder titles

* fix(build): avoid parallel electron-vite config race

* test(windows): avoid MSYS temp path rewriting

* test(windows): avoid killing exited PTY

* fix(pty): avoid late ConPTY input teardown race

* fix(terminal): sync reconnect error ownership after commit

* fix(runtime): use canonical worktree identity comparison

* test(ssh): assert complete cold-hydration baseline

* test(windows): invoke quoted retention fixture via PowerShell

* test(windows): read ConPTY grid through mode con

* fix(terminal): publish PTY replacements atomically

* fix(terminal): infer stale identity on reattach

* fix(terminal): fence stale pane PTY callbacks

* fix(terminal): fence stale pane binds after rebind

* fix(terminal): reject stale pane transport callbacks

* fix(terminal): fence mirrored reattach spawn callbacks

* fix(terminal): replace stale pane PTYs on remount

* fix(ci): size the Windows launcher-compile test budget from measurement

`native-smoke (windows-latest)` fails ~4.5% of runs on
`preserves a multiline argument through the compiled remote launcher`
with "Test timed out in 15000ms" — on unrelated PRs, for reasons that
have nothing to do with them. Across 176 sampled attempts it is the only
red that job produced, and it hit seven different PRs in two days:
#16900, #16904, #16915, #16955 (twice), #16979, #17014, #17085.

The test is six process creations: powershell.exe forks csc.exe, then
the freshly compiled orca.exe forks node.exe, twice. Hosted Windows
runners periodically slow process creation down, and this test amplifies
that far harder than anything else in the job. Comparing the 80 attempts
where it ran under 3s against the 12 where it ran over 12s, its own
median goes 2198ms -> 15917ms (7.2x) while the same file's
powershell-only test moves 556 -> 686ms (1.2x), the cmd.exe and Git Bash
process tests in the neighbouring file move 1.4x, and the other 35 files
put together move 1.5x.

Measured across those 176 attempts: 1881ms to 35438ms, p50 4264ms,
correlation +0.881 with the job's total Vitest duration. 8 of 176 (4.5%)
exceeded the 15s cap; 2 of 176 (1.1%) also exceeded the shared 30s
testTimeout, so deleting the override and inheriting the config is not
enough on its own. 60s clears all 176 with 1.7x headroom on the worst.

This is slow, not hung. Every body here is synchronous spawnSync, so
Vitest cannot interrupt one — the timer fires only after the body
returns and the reported duration is real elapsed time. That is why a
failure reads `× ... 22464ms` under `Test timed out in 15000ms`. The
work finished; the stopwatch was short. Seven reruns at one identical
head measured 2053 / 4680 / 5551 / 8732 / 13506 / 14868 / 21937ms — the
last of those would have been red on code that had not changed.

The 15s came from #8897, which raised this test off Vitest's built-in 5s
default because the job then ran bare `pnpm vitest run`. #8909 landed
3h27m later and pointed the job at config/vitest.config.ts, which is the
real fix for that. The constant stayed behind and has been the binding
budget ever since.

* fix(terminal): fence stale remount reattach ownership

* fix(terminal): reconcile mounted pane identity after replacement

* fix(terminal): fence stale reattach fallback ownership

* fix(terminal): fence deferred SSH reattach ownership

* fix(terminal): fence stale split pane ownership callbacks

* fix(terminal): keep stale spawns from consuming startup

---------

Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
2026-08-31 08:17:40 -07:00
Neil 09429768c5 test(cross-version-wire): compare published fields per frame (#17301) 2026-08-30 00:26:17 -07:00
Jinwoo Hong 252dbd60ea fix(terminal): restore lossy initial remote snapshots (#17113)
* fix(terminal): restore lossy initial remote snapshots

* test(terminal): strengthen lossy snapshot causal oracle
2026-08-30 03:11:55 -04:00
Brennan BensonandBrennan Benson 11d8673112 test(cross-version-wire): derive skew expectations from the baseline under test (#17178)
* test(cross-version-wire): derive skew expectations from the baseline under test

The cross-version wire job pairs current code against whichever release tag is
newest, so a hand-written "the old side does not have X" assertion expires by
itself: v1.4.192 was the first tag containing the SnapshotStart `terminalOwner`
field, and cutting it turned the new-client/old-server pairing red on unrelated
pull requests with no code change anywhere.

Read what each build publishes from that build. Each host is now paired against
a client of its own version to produce a reference, and the skewed pairings are
compared against that reference, so the expectation is whatever the release
actually shipped. The same class of assertion in the agent-session suite —
"the old build advertises no structured capability and registers no structured
method" — becomes "each build's advertisement agrees with what it registers",
and the "client too old to know this capability" is derived by removing the
capability from the baseline's own list.

The guard is unchanged in strength: a field the old host still publishes may not
be dropped, skew may not change what a host puts on the wire, and a new pairing
asserts the oracle still stalls when a peer cannot decode an opcode the other
side sends.

* test(cross-version-wire): exercise release structured methods

* test(cross-version-wire): load the registered method manifest

* test(cross-version-wire): assert execution, not registration, on both host gates

The release-shaped checkout gate accepted any reply that was not
method_not_found, so a registered-but-throwing handler passed it. The
capability gate asserted a shared host spy had been called at all, so the
second method mapped to that spy could stop reaching the host unnoticed.

* test(cross-version): make the release-shaped skew cover the whole agent-session manifest

The release-shaped checkout is the only place the "registered means usable"
claim is executable today — the baseline release registers none of these
methods — and it was exercising one of sixteen. A handler registered and
returning an execution error passed the suite.

- Declare each method's result in the manifest, so "answered" is the contract
  rather than "did not say method_not_found".
- Give each build a seam to install a host into its own module slot; a release
  checkout has its own copy, so the working tree's host was never this
  dispatcher's, and every host-backed method answered
  structured_agent_session_unsupported — the capability gate's own words.
- Run one execution contract over both skews instead of two divergent loops.
- Pair the AI Vault never-called spy with a positive control; renaming the
  runtime method it watches left it green.

---------

Co-authored-by: Brennan Benson <brennanbenson@Brennans-MacBook-Pro.local>
2026-08-29 13:42:50 -07:00
Brennan Benson fd9125ea8c feat(native-chat): Codex structured native chat restructure (#16729)
* feat(native-chat): port structured Codex sessions from restructure-recovery

Rebuilds the desktop structured native-chat implementation from
brennanb2025/native-chat-restructure-recovery (tip 4e31c08db3) on top of
current main as a single commit, scoped to the local Codex path.

Ported:
- Structured agent-session core: durable record store + single-writer lease,
  canonical journal, agent-session wire host/attach/eviction/subscribers,
  `agentSession.*` RPC surface (registered via ALL_RPC_METHODS; host-side
  mobile allowlist included for wire compat), pty write gate, transcript
  additions, and the Codex app-server adapter/launch resolution.
- Renderer: NativeChatStructuredSession view/composer stack, structured
  launch path with the single-flight guard, local structured session tabs
  sync, activation gate + structured inventory (read-only
  `agentSession.handoffStatus` probe), agent-session tabs in the tab strip,
  AI-vault structured session activation, and the settings pane with the
  parent Experimental Chat UI toggle plus the nested "Use updated structured
  native chat" toggle. New sessions require both flags, agent codex, no
  prompt, and a local non-WSL, non-Windows-host execution host
  (structured-native-chat-availability).
- Fixes 72c013cea6 (verified Codex launch recovery), 8ddbaf5e3d (defer
  native terminal view switching affordances), and 4e31c08db3 (release the
  launch gate after a visibility retry) with their regression tests,
  including the third-launch-after-retry guard case.
- Cross-version agent-session wire test + CI lane, packaging entries
  (proper-lockfile, agent-tooling asar excludes), and the wire-compat doc
  section.

Deliberately not ported: mobile/ changes, the Claude structured runtime
(only the claude-transcript-branch-proof and claude-structured-owner-identity
leaf modules remain, backing the kept TUI-recovery arms), the terminal↔chat
adoption/handoff flow (`agentSession.adoptTerminal`/`requestHandoff`, the
handoff request engine, TUI adoption machinery, orca-runtime adoption
methods), renderer switching affordances and their dead leftovers, the
hook/subagent-status refactor cluster, and unrelated branch changes. The
crash-during-acquisition recovery path (restart handoff adjudication,
restore/reverse re-acquire, lease schema handoff keys) is kept because every
plain direct launch depends on it; a trimmed handoff coordinator exposes
only status/restore/close.

Branch edits that targeted files main has since split (ipc/pty.ts,
worktrees.ts, rpc/methods/terminal.ts, useIpcEvents, pty-connection,
store/slices/terminals.ts, runtime-types, web preload) were re-applied to
the split modules, preserving main's newer logic (Windows CIM fallback,
browser tab close rework, cold-restore resume flow, dispatcher threading).

Known seam: the mobile clipboard image-provenance CONSUMER gate ships
(agentSession.send refuses unproven mobile image refs with
agent_session_image_untrusted) but the producer hunk in
rpc/methods/clipboard.ts stays with the unported mobile cluster, so mobile
image sends into structured chat fail closed until that side ports.

* fix(native-chat): trust only authenticated local image uploads

* fix(build): preserve Windows process-tree patch application

* test(windows): include process creation time in addon fixture

* fix(build): run windows-process-tree node-gyp from the physical package dir

gyp expands the node-addon-api dependency by probing node, whose cwd
resolves to the package's physical directory in the store, so the emitted
target is a store-relative ../../../../node-addon-api@... hop. gyp then
resolves that hop against the rebuild cwd; from the node_modules
symlink/junction it escapes the store and configure fails with
"node_addon_api.gyp not found" (run 32999886072).

Rebuild from realpath(package dir) so both bases agree, matching how the
package manager itself runs native install scripts. The regression test
replays gyp's expansion+resolution against the planned cwd and fails
without the fix.

* fix(native-chat): keep chat tabs visible through terminal closes and empty-worktree launches

Two proven blockers in the native Codex tab contract:

closeTerminalTab pre-empted the canonical unified close. With one terminal
left it deactivated the worktree on a terminal/editor/browser-only check,
blanking a workspace that still held a renderable agent-session tab; with
two or more it pre-picked a successor from terminal entities only,
re-stamping the group active before closeUnifiedTab's MRU/neighbor repair
could land on the chat tab. Successor choice now defers to the unified
contract whenever the terminal has a unified row, and deactivation is
gated on the unified renderable count (matching leaveWorktreeIfEmpty),
with the legacy pre-pick kept only for terminals without a unified row.

A structured session created on an empty worktree was published into the
host's headless group while preserveLocalLayout froze the local layout,
leaving the tab in store but permanently off screen. A preserveLocalLayout
owner now always takes client-owned placement — repairing a rendered
leaf whose group record is missing, or materializing a rendered group on a
truly empty worktree — and applies the client-derived layout repair while
still rejecting host-authored layout.

Regression tests drive the real store through closeTerminalTab (git
worktree and folder workspace) and the real snapshot applier for the
empty-worktree adoption states; all fail without the fixes.

* fix(native-chat): close stale turns and retry rejected sends

* fix(native-chat): retire hosted rows on structured tab activation

* fix(native-chat): preserve rpc defaults across main merge

* chore: format remote wire compatibility guide

* test(native-chat): cover retry after unconfirmed send

* fix(native-chat): reload outbox on session switch

* docs(settings): disclose structured chat platform limits

* fix(native-chat): await Codex launch-home preparation

* fix(codex): align child-process allowlist with async trust bridge

* test(identity): update inventory for tab surface refactor

* fix(windows): preserve process-tree CRLF patch sources

* fix(native-chat): anchor an unmatched chat echo where it was sent (#16117)

* fix(native-chat): anchor an unmatched chat echo where it was sent

The reported symptom was old user messages replaying below every new turn, so the
conversation read as scrambled. The cause was not that the echo failed to match a
transcript row. Claude consumes a mid-turn send through a `queued_command`
attachment and writes no `type:"user"` record for it, so some echoes can never
match, and no amount of matching will change that. The cause was WHERE an
unmatched echo rendered: buildMobileNativeChatTransientData appended every pending
item after the entire transcript, so it re-read below each turn that landed
afterwards.

Render each echo directly after the transcript row it was sent against, using the
baseline the send already captures. An unmatched echo is then at worst a duplicate
in the right position rather than a scrambled one, and it stays visible. Echoes
sharing an anchor keep send order; a send with no baseline, or one whose anchor
folding dropped, still falls back to the tail.

Deliberately NOT fixed by deleting the echo. Inferring from send ordering that an
echo can never match, then removing it, loses the user's own text for a message
the agent did receive, and it cannot fire in the common case anyway - measured
drain groups are 1,017 of size 1 against 55 larger. It also escalates an existing
gap: the count pass has no baseline-tail guard, unlike the glue pass, while
`messages` is a 40-row window that head-trims, resets on reconnect and grows at
the front on loadEarlier, so a false landing there would license deleting a
DIFFERENT outstanding message.

That count-pass gap is real and left for a separate change; anchoring makes its
worst case a duplicate in place rather than a scrambled conversation.

* fix(native-chat): preserve folded echo anchors

* fix(native-chat): preserve forward-folded echo anchors

* fix(native-chat): keep leading folded echoes in place

* fix(workspace-cleanup): show git status for every row (#16690)

* fix(native-chat): refuse structured chat on every Windows execution path

canUseStructuredNativeChat only refused win32 when a project runtime
resolved, so folder-workspace keys (and other keys with no project
runtime) failed open into structured chat on Windows. Fail closed on
win32 unconditionally after the host check, matching the settings copy:
local macOS/Linux only; Windows/WSL/SSH stay on terminal chat.

* fix(native-chat): restore runtime refusals behind the win32 gate

506d375de3 replaced the project-runtime checks with a bare platform test,
so a WSL or repair-required runtime resolution would no longer refuse
structured chat off-win32. Keep the unconditional win32 refusal and
re-run the runtime resolution after it, so the gate does not depend on
the resolver's own platform guard. Tests inject WSL and repair-required
resolutions on darwin/linux and fail against the regressed gate.

* fix structured session journal durability

* fix structured tab active pointer after restart

* fix(native-chat): await optional lease renewal callbacks

* refactor(skills): extract install error messages

* fix(agent-session): harden recovery ownership

* fix(native-chat): retain panes across tab activation

* fix(native-chat): address round-one review findings

* test(native-chat): align integration coverage after main merge

* fix(native-chat): harden round-two reliability

* fix(native-chat): harden round-three reliability

* fix(native-chat): close round-four recovery gaps

* fix(native-chat): separate bounded journal key forms

* fix(native-chat): reset outbox error in render on session switch

The switch effect adjusted error state after the sessionId prop changed,
tripping react-doctor's no-adjust-state-on-prop-change on the changed-code
gate and flashing the old session's banner for a frame. Reset it with the
render-time previous-value guard instead.

* fix(native-chat): invalidate stale outbox settlements

* test(native-chat): restore settled-error session-switch regression

a6e2379bd1 replaced this test with the in-flight settlement race test,
leaving the render-time error reset unpinned: deleting the reset block
still passed the whole native-chat suite. Keep both scenarios pinned;
they are distinct (settled error clears on switch vs stale settlement
invalidated in the commit-to-passive window).

* test(wire): make release checkouts race safe

* test(wire): pin cross-process checkout single-flight and importer specifier contract

* test(wire): harden release checkout lifecycle

* fix(build): drop CR-byte residue from windows-process-tree patch

The two trailing CR bytes on the patch's deletion lines are a proven
no-op: pnpm hashes patches CRLF-normalized (both forms hash to the
lockfile's 946ffb2b) and materializes this package without applying the
patch in either form, so the load-bearing build edits come solely from
applyWindowsProcessTreeBuildFixes() (#16947), which handles both source
EOL forms. Restore byte-identity with main and repin the contract test
to the post-#16947 reality: LF-only patch bytes plus lockfile hash sync.

* fix(native-chat): skip empty startup recovery
2026-08-28 16:45:58 -07:00
Jinwoo Hong d60a3c900b Reset stale terminal modes after dead TUI replay (#16379) 2026-08-26 19:49:26 -07:00
Jinjing 4d2dc0fae5 test: pin cross-version browser placement test to explicit baseline (#16554)
* test: use explicit baseline for cross-version browser placement test

Pin to v1.4.184 to ensure consistent testing against the release
predating client placement. This avoids coupling the legacy-baseline
bump to unrelated schema refactors in newer versions.

* fix(windows): treat inaccessible processes as alive in tests

When checking process state on Windows, EPERM (permission denied) indicates
an inaccessible but live process. Only ESRCH (process not found) proves
exit. Correct isAlive() to distinguish these cases.

Also add windowsHide:true to child process spawns and use explicit SIGKILL
when force-killing the host process.
2026-08-26 00:02:12 -07:00
Jinwoo HongandJinwoo-H a9781a4118 STA-4150: client-hosted remote browser (consolidated) (#15448)
Co-authored-by: Jinwoo-H <jinwoo@stably.ai>
2026-08-25 15:36:51 -07:00
Neil eb22e497bb Revert "fix(ssh): reapply the reattach-identity work and stop the fallback fence stranding moved panes" (#14395) 2026-08-13 18:11:33 -07:00
Neil 6a0c8fa541 fix(ssh): reapply the reattach-identity work and stop the fallback fence stranding moved panes (#14384)
* Reapply #13326 and #13928 (un-revert #14361)

Restores the SSH reattach-identity and daemon-occupancy fixes. Reverting them
reintroduced their P0s, filed as STA-4224, STA-4225, STA-4227, STA-4230,
STA-4232, STA-4233 and STA-4234 against #14361.

The tab loss that motivated the revert is fixed in the commits that follow, so
this reapplication is not a straight redo.

* fix(relay): stop the fallback attach fence refusing a pane that moved tabs

The primary fence was moved to the shell's own incarnation precisely because
paneKey/tabId froze the pane's LOCATION at spawn and refused panes that had
merely moved. The fallback that older clients fall into kept the old rule, so
the correction never reached it — the same 'the rule exists, but this path does
not ask it' leak this work has hit repeatedly.

A refusal here is not recoverable: an identity mismatch never grounds a respawn,
so the pane keeps a live shell it can no longer reach and renders blank.

Narrowed to paneKey, which is the identity; the tab is a location. Restoring the
tabId comparison reddens the new test.
2026-08-13 16:45:24 -07:00
Neil 11cd2b4310 revert(ssh): back out #13326 and #13928 — reconnect loses every tab (#14361)
* Revert "fix(daemon): stop killing live coding agents when the daemon can't report its sessions (#13928)"

This reverts commit 2e8cf589de.

Reverted together with #13326: the 1.4.182-daily.202608131439 build carrying
both loses every tab on an SSH disconnect/reconnect cycle. Reverting first so
main stays releasable and the P0 fixes in the wild remain cherry-pickable,
rather than fixing forward on a shipped regression.

* Revert "fix(ssh): stop SSH reconnect from multiplying terminals and resuming agents twice (STA-3077)" (#13326)

This reverts commit 3ab8b6a117.

Reported on 1.4.182-daily.202608131439: connect to an SSH worktree, disconnect
the host from the hosts popup, reconnect — every tab is gone. That is worse than
the behaviour this PR set out to fix, where most tabs were retained.

Reverting rather than fixing forward, so main stays releasable and the P0 fixes
already out in the wild stay cherry-pickable. STA-3077 stays open.
2026-08-13 14:54:29 -07:00
NeilandOrca 3ab8b6a117 fix(ssh): stop SSH reconnect from multiplying terminals and resuming agents twice (STA-3077) (#13326)
* fix(ssh): stop reconnect from grafting panes and stacking remote leases

Reconnecting an SSH-backed workspace added terminal panes the user never
opened, and the remote host accumulated shells nobody was using — one
report went from 2 to 19 to 20 relay PTYs across three reconnects
(STA-3077).

Two root causes, both in the store.

Reattach could create UI. `persistPtyBinding` has four creating branches
— mint a tab, mint a root leaf, split the root and graft a leaf, mint a
layout. All four are load-bearing for `pty:spawn`, which can beat the
renderer's debounced layout writer, but none of them is appropriate on
reattach, where the pane either already exists or is gone for good. Add
`mayCreate`, defaulting true so the spawn path is untouched; every
creating branch already sets `terminalMembershipChanged`, so refusing is
a check rather than a new code path.

Lease identity had no pane key. `upsertSshRemotePtyLease` matched on
`(targetId, ptyId)` alone, so a pane that re-leased under a new relay id
left its predecessor live with nothing to retire it, and the next
reattach fanned out over both. One pane now keeps at most one live
lease. Superseded leases are marked `expired` rather than terminated:
losing a lease is not proof the shell died, so the remote process is
deliberately left running.

Tests assert observable behavior rather than mechanism, so they stay
valid under any implementation that fixes this.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): record the terminal session behavior contract

Properties stated as observable behavior rather than mechanism, so an
oracle written against them survives a change of implementation.

Records the weaker, correct form of the timer rule — a timer may never
be the sole cause of a destructive action — because recovery budgets and
scratch-file age gates are correct code that an absolute ban would
condemn. Also notes which mechanisms are deliberately not required, so
each has to earn its place rather than arrive with an architecture.

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): heal duplicate pane leases that predate pane-keyed supersession

Pane-keyed supersession stops new duplicates, but it does nothing for
installs that already carry the ones STA-3077 accumulated — the report
behind this reached 20 live leases across a handful of panes, and every
reconnect fanned out over all of them.

Retire the stale duplicates once per reattach pass, keeping the newest
lease for each pane under a total order so two hosts resolve a tie the
same way. As with supersession, retired leases are marked `expired`
rather than terminated: their remote shells are deliberately left
running, because a lease we chose not to revive is not evidence the
shell died.

The relay-session store stubs gain the new method. Note the gap this
leaves open: those shells keep running and are no longer reachable from
the app, so the "accumulates unused shells" half of the report needs a
visible recovery surface rather than a silent kill.

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): stop respawning a shell that is still running

A pane that failed to reattach spawned a fresh shell. Because the
restored session id came along, the replacement resumed the same agent
session, and two processes appended to one transcript — reported
repeatedly, up to five concurrent resumes of a single session.

Two defects fed it.

The relay reported a source that merely needed re-establishing as
`SSH_SESSION_EXPIRED`. The shell was still running; only its output
source was gone. Give that outcome its own error so it stops reading as
"the session no longer exists".

The reattach failure handler then treated every error as proof of death.
It checked for expiry and, in the else branch, took the identical
action — so the check bought nothing and a transport fault, a timed-out
call, or a wedged relay all respawned. Respawn now requires proof: an
explicit host expiry or a not-found PTY. Anything else, including an
error we have never seen before, is unresolved, leaves the shell
running, and keeps the binding for a later reattach.

Two existing tests asserted the old behavior. One threw a bare error as
scaffolding to reach the spawn-adoption door; it now throws proof, which
is what it meant. The other pinned the expiry mapping itself, and now
asserts the outcome fails closed *without* being reported as expiry.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): record what makes a retention bound safe

Shortening a grace period is the wrong lever. Measuring process time and
gating reclamation on an independent observation are what make one safe,
and they are what deployed systems actually do.

Also records that lifecycle belongs in the attach reply rather than a
delivered event — that is what removes the need for a durable per-consumer
cursor to guarantee an exit is never lost.

Co-authored-by: Orca <help@stably.ai>

* test(terminal): assert the empty-failure case without an empty Error

A thrown empty value exercises the same property — a failure carrying no
usable message is not proof the session is gone — and does not trip the
empty-error-message lint.

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): let the durable pane binding outrank recency when retiring leases

Choosing the newest lease for a pane is wrong whenever a newer lease
exists that no pane is bound to: it retires the lease the pane is
actually attached to, detaching a live terminal instead of healing it.

Two changes. Arbitration now prefers the lease matching the pane's
durable binding, across both the SSH-target and local partitions,
falling back to recency only when no binding names either candidate.

And supersession at upsert time now defers rather than expiring a bound
predecessor. When a lease arrives for a pane that is still bound to a
different PTY, the binding has not caught up yet, so both stay live and
reattach arbitrates once the binding is available.

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): roll back a lease retirement whose durable write fails

`flush()` logs and swallows write errors, so a failed write left these
leases retired in memory while disk still called them attached — and the
pane bindings scrubbed alongside them stayed scrubbed. Use `flushOrThrow`
and restore both the lease states and the affected session partitions
when it throws, reporting nothing retired.

Co-authored-by: Orca <help@stably.ai>

* test(ssh): prove pane and remote PTY cardinality across reconnects

Counts the shells the relay actually hosts, on the container, rather
than inferring them from app state — that is the census the report was
based on. Asserts the PIDs are unchanged, not merely the count, so a
kill-and-respawn cannot pass.

Every pane streams before the transport is severed: an idle pane sends
no recovery checkpoint, so only a live source comes back needing
re-establishment, which is the outcome that used to read as expiry.

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): actually pass mayCreate:false from the reattach binding write

The `mayCreate` guard was correct and had no production caller, so the
reattach path still went through the creating branches and grafted panes
back. `restoreReattachedPtyRuntime` is that call site — RC3 in the
original diagnosis — and it now refuses to create.

Binding moves ahead of runtime registration, because registering first
would surface a pane the user never opened before the refusal landed. A
refusal leaves the remote shell running and reattachable; a *thrown*
write stays unknown and still registers, so a failed disk write cannot
detach a live pane.

Adds an oracle over the call site itself. The store-level tests all
passed while the fix was inert, because they called the store directly —
only pinning the wiring catches that.

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): apply the respawn-requires-proof rule to both reattach paths

connectPanePty has two near-verbatim reattach blocks — one keyed on the
deferred SSH session, one on the restored session — and only the second
was fixed. The first still checked for expiry and then respawned
unconditionally anyway, so a transport fault there resumed the same agent
session a second time.

Also keep the wire token out of the pane. The main-process bridge only
special-cases expiry, so a source-restore failure crossed IPC as raw
`SSH_SOURCE_RESTORE_REQUIRED: <id>` text and surfaced to the user. It
correctly does not respawn; it just should not read like that.

Co-authored-by: Orca <help@stably.ai>

* test(ssh): state plainly that the reconnect spec is a forward guard

It was run against an unfixed tree and passed, so it does not prove the
STA-3077 fixes and should not be read as if it does. A clean severed
transport does not reproduce the field conditions — accumulated duplicate
leases, or a source returning needing re-establishment.

It keeps its place as a forward guard: it counts the shells the relay
actually hosts and pins their PIDs, so a later change that grafts a pane
or respawns a shell fails here.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): record that a guard must be pinned at its call site

A refusal that exists and is never passed is indistinguishable from no
refusal, and store-level tests cannot tell the difference — they call the
store directly. Learned from `mayCreate`, which was correct and had no
production caller for several commits.

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): park one PTY's exhausted delivery recovery instead of dropping the channel

A per-PTY recovery budget running out disposed the whole relay channel,
so one PTY that could not re-prove its delivery aborted every in-flight
filesystem and git request on that host and stalled every sibling pane.
A retry count is not proof of anything, and it certainly is not proof
about the other sessions sharing the channel.

Exhaustion now parks that PTY's delivery. The remote shell keeps
running, its lease stands, and the next relay open reattaches it with a
fresh delivery generation — the parked state is cleared on teardown and
the generation changes on reconnect, so a reconnect recovers it.

The consecutive-attempt ceiling goes away entirely; the per-generation
one is what bounds the retry cost, and the second ceiling only existed
to reach the channel drop sooner.

Tradeoff worth stating: the failing pane used to self-heal within
seconds because the forced reconnect wiped all rejection state, and it
now stays frozen until the next relay open. That is a worse outcome for
that one pane and a much better one for every other session on the host,
and reconnecting is user-reachable.

Co-authored-by: Orca <help@stably.ai>

* fix(pty): let liveness say unknown instead of forcing it to say dead

`IPtyProvider.hasPty` returned a boolean, so a provider whose inventory
was empty for reasons that have nothing to do with the session — socket
down, cache never hydrated, provider generation just constructed — had no
way to say so and answered "absent". Its own siblings already knew
better: `probePtyLiveness` and the runtime's `PtyController.hasPty` were
both already `boolean | null`, with consumers branching on null
correctly. The lie was injected at exactly one interface.

Now three-valued, and each provider answers unknown where it cannot
prove absence: the daemon adapter off-socket, the SSH provider before a
completed listing, the router when any adapter cannot answer, and the
degraded provider rather than fabricating a verdict. `terminal_gone`
requires unanimous proven absence.

Also fixes a real cold-start bug this surfaced: `pty:hasPty` never
awaited the daemon-swap startup promise, though the sibling
`probePtyLiveness` bridge already did, so before the swap the local
provider answered an authoritative false for every daemon-owned id.

Net +27 production lines. The plan behind this predicted -92 on the
strength of deleting the renderer's dead-session reconcile path; that
code is live (`pty-connection.ts` imports it), so nothing was deleted.
Expressing a third value where there were two costs lines, and a
deletion that is not real is not worth manufacturing.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): track the terminal-session correctness handoff package

The package was untracked under a gitignored `docs/**`, with the
un-ignore rules living only in an uncommitted .gitignore edit — a single
`git clean -xdf` would have destroyed the authoritative plan.

The 814-path construction snapshot is now pushed as
`nwparker/react185-authority-snapshot` too; it had no remote ref.

Co-authored-by: Orca <help@stably.ai>

* test(ssh): make the reconnect settle window actually wait

The settle poll reused a matcher the assertion 15 lines above had already
satisfied, and Playwright's poll engine probes immediately and returns as
soon as the matcher passes — so it observed the same state twice and
elapsed 0ms. A shell grafted a second or two after reattach reported
ready slipped through into the next cycle.

Reviewer was right on #13111. Test-only; no production change.

Co-authored-by: Orca <help@stably.ai>

* test(ssh): census both durable session partitions on reconnect

Adds a second reconnect scenario and a helper that reads pane records
from the local partition as well as the ssh host partition. That split
matters: the reattach binding call passes no hostId, so a grafted pane
lands in the LOCAL partition and an oracle reading only the host
partition passes whether or not the guard is present.

Both tests remain forward guards. The second one was reported as
discriminating and did not reproduce: with `mayCreate: false` removed
from the call site and the app rebuilt, both still passed. Its induction
races `pty:kill` against a severed transport, so when the kill lands the
lease is cleaned up and there is nothing left to graft. The handoff
README is corrected to say so rather than claim a journey.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): record the user decision relaxing G6

G6 becomes minimise-and-justify rather than strictly net-negative. The
deletion budget the plan assumed does not exist: an entrypoint-rooted
import graph found 51 of 53 candidate files reachable and instantiated
on live paths, leaving 263 deletable LOC against roughly +1,021 to
offset. Correctness may still not be traded for line count.

Co-authored-by: Orca <help@stably.ai>

* test(terminal): add discriminating oracles for restart, daemon, skew and namespaces

Six parallel streams, each required to fail with its guard removed rather
than merely pass.

Local restart proves the OS process itself survives, by reading
`ps -o lstart=` for the shell's own pid. That matters: with the quit path
made destructive, the tab, leaf and pty ids all came back byte-identical
while the shell underneath was a new process — every existing restart
spec would have stayed green. Two separate guards were removed to redden
it, and the second reddens only the stale-operation case.

Daemon restart discriminates by reverting three-valued `hasPty`; version
skew now covers publication semantics and confirms the new
`SSH_SOURCE_RESTORE_REQUIRED` token mutates nothing on an old client;
two-host isolation censuses both containers.

Deletes `src/relay/pty-source-replay-index.ts` — 201 production lines
with no importer outside its own test, verified against an
entrypoint-rooted import graph rather than a name grep.

Five namespace tests are skipped, not passing: they reproduce a defect
still live on main where folder-workspace ids compare equal with the
instance suffix stripped. PR #12474 fixes it; they are its oracle.

Co-authored-by: Orca <help@stably.ai>

* test(ssh): induce the reattach graft deterministically instead of racing a kill

The previous induction closed a pane while the transport was severed and
relied on `pty:kill` FAILING so the lease outlived the pane record. It
does not fail: with the provider already torn down, `pty:kill` takes its
tombstone branch and marks the lease terminated, and `reattachKnownPtys`
filters terminated leases out of the fan-out — so the reconnect never
visited the PTY the test was about. It passed on both trees.

Seed the precondition instead. Spawn a real remote PTY on a leaf that
never becomes a pane, then roll the host partition back to its pre-spawn
snapshot, leaving a live lease and a live remote shell that no durable
pane owns. No failure races a success.

Adds a vacuity guard that is independent of the tree under test: the
lease's own `lastAttachedAt` must advance, proving the fan-out actually
visited this lease before the pane census is trusted.

Verified on this machine under an isolated TMPDIR, since the e2e
harness keys its seeded-repo pointer on a machine-global tmpdir path:
guard present passes, guard removed fails with the phantom leaf grafted
into the local partition, guard restored passes.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): propose one authoritative binding identity

Every defect this program has touched is the same defect: identity
compared with the wrong key, or not compared at all. Lease keyed without
the pane, reattach using a creating write, folder-workspace ids compared
with the instance suffix stripped, local mutating IPC carrying only an
id, a live shell classified as expired, liveness unable to say unknown.

Proposal: one branded binding type built from fields that already exist
and are already persisted, constructible only from an authoritative
source, carried by mutating operations, compared by one shared function.
Makes a wrong-key comparison a type error rather than the next incident.

Under adversarial review, including against the open issue corpus.
Not accepted.

Co-authored-by: Orca <help@stably.ai>

* fix(pty): refuse mutating operations aimed at a superseded PTY

`pty:write`, `pty:writeAccepted` and `pty:resize` accepted any id. The
renderer queues input, so a keystroke buffered before a reattach landed
on whatever PTY had since taken the pane — and a resize reshaped the
successor's shell.

Main already tracks `ptyPaneKey` and `paneKeyPtyId` in lock-step, so
their disagreement is proof the caller's id was superseded. No wire
change, no renderer change, nothing added to the input payload.

An id with no recorded pane stays permitted: unowned and orphaned PTYs
are unknown, not stale, and unknown never authorizes refusing an explicit
operation. That is also what keeps orphan cleanup working — those ids
have no pane by construction.

The tests pin the CALL SITES, not the predicate. A capability that exists
and is never called is indistinguishable from no capability, which is
exactly how `mayCreate` sat inert here for several commits with every
test green.

Co-authored-by: Orca <help@stably.ai>

* fix(pty): fence signals at a superseded PTY, and pin why kill is exempt

A signal means "interrupt my pane", so delivering one to a PTY the pane
has already replaced is a misdirected interrupt. Fence it with the same
lock-step proof used for write and resize.

`pty:kill` stays deliberately unfenced and a test now pins that: a
superseded PTY is orphaned, and reclaiming it is exactly what the
orphan-cleanup callers ask for. Refusing there would break the operation
that reclaims leaked shells — the opposite of the intent.

The fence sits at the IPC boundary, above `tryGetProviderForPty`, so it
covers local, daemon and SSH rather than the local path alone.

Co-authored-by: Orca <help@stably.ai>

* test(terminal): poll the pane binding read so a slower host cannot flake it

`readPaneBinding` took a single unpolled read of a DOM dataset attribute
immediately after a renderer reload, while its sibling helper polls the
same data for 15s. On a native Linux host both tests failed every run
with 'No bound terminal pane is mounted' while the app was demonstrably
healthy — the screenshot showed the terminal restored with a live prompt
and the boot PID echoed.

The assertion is unchanged; it is only awaited. Nothing is weakened.

Found by running this spec on native Linux rather than assuming macOS
behaviour generalises.

Co-authored-by: Orca <help@stably.ai>

* test(terminal): make the restart identity spec run on Windows too

Both probes were POSIX-only and unconditional: `echo ...=\$\$` for the
shell's own pid, and `ps -o lstart=` for its start time. Running the spec
on a real Windows host proved it dies before reaching either guard, so
Journey 1's Windows half was unprovable rather than merely unproven.

PowerShell exposes the same two facts as `$PID` and `Get-Process`
StartTime. The start time still matters on both platforms for the same
reason: a PID alone cannot separate a survivor from a reused number.

Still green on macOS. The Windows path is written from the host probe and
has not itself been executed end to end — that is the next thing to run
there, not a claim being made here.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): record the fence's real gap and what peer designs taught

Marks the client-constructed binding proposal as rejected with the three
false claims that sank it, and records what shipped instead.

States the shipped fence's actual limitation rather than leaving it
implied: it compares a binding, not an incarnation, so a respawn under a
reused ptyId passes. The obvious remedy is wrong here — the agent-create
id is deterministic by design so a replayed create stays idempotent, and
randomising it would trade this narrow gap for a duplicate-spawn bug.

Also records the ranked lessons from four comparable agent IDEs, chiefly
that a typed end-reason at end time is what stops a user quit from
looking like a resume candidate.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): promote Journey 1 to proven on all three platforms

The oracle now runs natively on macOS, Linux and Windows, and its
discrimination was watched on each: a mutation reddens it, a restore
greens it. On Linux and Windows both mutations were run, and the second
reddens only the stale-operation test — so the journey's two clauses are
proved independently rather than jointly.

Windows is the new evidence. The PowerShell branches added blind at
ebffb85a848 executed correctly on their first run: `$PID` expanded to
real integers, which also proves the pane shell there is PowerShell-family
rather than Git Bash, and `Get-Process StartTime` returned kernel start
times 5.4s apart — so a recycled pid could not have passed as a survivor.

First journey promoted in this program. The other twelve are unchanged,
and the residual limit on "every stale exact operation" is recorded
rather than glossed.

Co-authored-by: Orca <help@stably.ai>

* test(terminal): add discriminating oracles for the daemon, skew and multi-host journeys

Daemon: replaces a spec that modelled only a client restart and never
crossed the daemon boundary, whose successor generation owned nothing so
"the live successor is neither killed nor replaced" was vacuous. The PTY
leader is now a real login shell reporting `$$` back through the
production write path, resolved to a kernel start time. Two mutations
each redden exactly one of the three clauses, on macOS and Linux:
reverting three-valued `hasPty` reddens only the unknown-not-dead
clause; widening the sole-provider fallback reddens only the stale
generation clause.

Skew: reverting the restore-required publication to expiry reddens 4 of
5 new tests while the legacy control stays green — the regression this
branch fixed is now caught if reintroduced.

Multi-host: restoring `mux.dispose('connection_lost')` reddens sibling
isolation on one host. It does NOT redden across hosts, and that is
recorded rather than glossed: a mux belongs to one relay session per
target, so its dispose cannot cross a host boundary. Journey 4's
cross-host clause rests on isolation-by-construction, not on a mutation.

No production code changes.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): record journey evidence that falls short of promotion

Four journeys now have discriminating oracles but none meets its full
stated scope, and each shortfall is named rather than rounded up.

Journey 2 is one WSL run from promotion. Journey 12's tests are
in-process, so they do not close the live-skew gap the original ledger
named. Journey 4's cross-host clause cannot be proven by mutation at all
— a mux is per target, so its dispose cannot cross hosts, and the
cross-host test stayed green under the mutation that reddens siblings.
Journey 13 measured one dimension of ten, on lifted predicates rather
than through real IPC.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): promote Journey 2 to proven on macOS, Linux and physical WSL

The oracle runs on every environment the journey names, and is
clause-selective on all three: reverting three-valued `hasPty` reddens
only the unknown-not-dead clause, and widening the sole-provider fallback
reddens only the stale-generation clause.

Selectivity in WSL was established rather than assumed. The spec runs
serially, so a red first test reports the others as "did not run" — they
were re-run alone under the same mutation and stayed green.

Also records that an Orca WSL-mode terminal now starts on that host at
all, which it could not before: the distro had no provisioned default
Unix user, so every interactive launch blocked on first-run setup.

One diagnosis from the WSL run is corrected here rather than repeated:
the unrelated `local-pty-shell-ready` failure was attributed to bash
5.3.9, but macOS runs the same bash version and passes 67/67. The trigger
is environmental to that distro, and the underlying defect is that the
spec pins an absolute count of OSC markers it does not own.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): correct the WSL provider-suite diagnosis

The WSL run blamed bash 5.3.9 for the unrelated
`local-pty-shell-ready` failure. macOS runs the same bash version and
passes 67/67, so the version is not the cause — the trigger is
environmental to that distro, and the underlying defect is that the spec
asserts an absolute count of OSC markers it does not own.

Co-authored-by: Orca <help@stably.ai>

* test(runtime): unskip the workspace-namespace oracles now their fix has merged

These five reproduced a defect that was live on main: folder-workspace
ids were compared with the instance suffix stripped, so two workspaces
sharing a directory read as the same namespace. They were committed
skipped, pointing at the PR that fixes it.

That PR is merged, and they pass. Verified they still bite: restoring the
suffix-stripping comparison reddens exactly these five and leaves the
other four green.

An oracle written before its fix, held skipped, and confirmed against the
fix after the merge — rather than deleted and rewritten from the answer.

Co-authored-by: Orca <help@stably.ai>

* test(ssh): add MaxSessions, lazy-discovery and paired-skew oracles

Three journeys attempted; none promoted, and the reasons are recorded in
the ledger rather than rounded up.

MaxSessions=1 against real OpenSSH, with the cap read back from `sshd -T`
rather than assumed, and remote pids read on the container two
independent ways that must agree, each carrying its kernel start time.
Two disjoint mutations discriminate — one reddens only the reconnect
clause, the other only the two restart clauses. But the disconnect clause
is a forward guard: four separate guard removals left it green, so
nothing shipped is load-bearing for it.

Lazy discovery samples sshd's own accept log and live session census
across a 22s window with the in-use host as a positive control. No
mutation reddens its third clause alone — the real cross-host lease
scoping is load-bearing, but removing it breaks the sibling host during
setup, so the failure carries no clause information.

The paired-runtime skew spec pairs two real processes at different
versions and refuses to run rather than degrade into a same-version
pairing that would look green and prove nothing.

No production code changes.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): record why the duplicate-resume fix was not built

I recommended adding a typed end-reason so a user quit stops looking like
a resume candidate, then went to implement it and stopped.

`SleepingAgentSessionRecord` already carries three fields that each exist
to stop something resuming that should not have — `origin`,
`restoreOnTabOpenOnly`, and `automaticResumeBlockedBy` — each traceable
to its own incident, consulted at 22 non-test sites. A fourth predicate,
however well typed, is the fifth containment cycle.

The designs without this bug do not have a better flag; they resume only
on an explicit action, into a new terminal id, and make two agents in one
terminal unrepresentable in the schema. The first of those is a product
decision about whether automatic resume stays a feature, so it is the
user's call rather than mine.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): reconcile G6 with the recorded decision and assess its clauses

G6's body still demanded strictly-negative production LOC after the user
relaxed it to minimise-and-justify, so the gate had two conflicting pass
conditions and no single truth value. Its body now points at that
decision.

Assessed the remaining clauses against the branch rather than assuming.
Two fail structurally: more than one identity comparison and mutation
admission path still exist, and `terminal-input-quarantine.ts` is still
reachable from two production files.

Records why the quarantine is not subsumed by the superseded-PTY fence,
which I had assumed and checked. The fence refuses writes aimed at a
stale ptyId; the quarantine guards the user's next keystrokes landing on
the successor under its current, correct id — a case the fence never
sees. Removing it needs the recovery path to surface a different shell as
unresolved, not a deletion.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): the input quarantine is load-bearing, not superseded

G6 lists "no superseded quarantine remains reachable" and this module was
assumed to be one. Disabling its single call site reproduces the hazard
it exists for — `cho hi; rm -rf x` reaching the shell — so deleting it
without a replacement re-opens command execution.

The replacement was costed by building it rather than estimated: +26
production LOC to thread the incarnation, ~+33 complete, and the
cross-remount state it needs outlives the destroyed pane so it becomes a
module about the size of the one deleted. Floor is roughly +140 to delete
88, and it would add a second identity comparison to a gate already
failing for having more than one.

The decisive part is that the route is not uniformly available: remote
runtime results carry no incarnation, old hosts cannot be made to publish
one, and mixed versions are the normal state. A paired client reads
unknown, which this program's own rule says is not proof — so either
every remote reattach surfaces unresolved, or a fallback is needed and
the only correct fallback is this module.

Whether to amend the clause or accept something weaker on remote hosts is
a user decision, so the clause verdict is left as failing rather than
quietly reclassified.

Co-authored-by: Orca <help@stably.ai>

* refactor(runtime): collapse duplicate identity comparisons

G6 requires one identity comparison; five implementations existed across
two concepts.

Worktree-namespace identity had two: `runtimeWorktreeIdsEqual` and
`runtimeWorktreeIdentityKey` independently re-derived repoId plus
normalized path. Equality now derives from the key, so the comparison and
the sleep / mutation-queue keying cannot drift into two different rules —
which is exactly how the suffix-stripping bug reached production once.

Pane identity had three byte-identical leaf-UUID comparisons, in
orchestration `db.ts`, `lifecycle-reconciliation.ts`, and
`orchestration-legacy-process-identity.ts`. One copy moved to
`stable-pane-id.ts`, which already owns `PaneKey`, `parsePaneKey` and
`makePaneKey` and which all three already imported. No new module, no
branded type, no parallel comparison.

Net -14 production lines. The namespace oracle still bites: restoring the
filesystem parser inside the identity key reddens exactly its five cases.

The raw counts are not the actionable set, and the classification is
worth recording: of 409 non-test `worktreeId` comparisons, 71 are typeof
guards and 81 are sentinel tag checks. Most of the remainder are renderer
predicates over store rows where both operands are the same main-minted
id, so normalizing there would widen equality rather than correct it.

Co-authored-by: Orca <help@stably.ai>

* refactor(terminal): finish a half-done fixture move and audit the rest

`xterm-bypass-event-fixture.ts` and `__fixtures__/xterm-bypass-event.ts`
were byte-identical apart from an import path. The `__fixtures__` copy had
zero importers and the live copy compiled as production — someone started
the move and left both. Dead copy deleted, live one moved, its three test
importers updated.

Audited the wider G6 clause by importer rather than filename: 32 test-only
files, roughly 3,300 LOC, currently compile as production; 4 of the 36
candidates have real production importers and are correctly placed. The
list is recorded in the goalposts.

Those 32 are almost all older than this program and outside the terminal
surface, so sweeping them belongs in its own change rather than inside a
terminal PR. The clause stays failing, with the remaining files named.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): the fixture clause already holds where it matters

Checked what the build emits rather than reasoning from file paths. None
of the 32 test-only fixtures appears in `out/` — Rollup drops them because
no production entrypoint reaches them. On "compiles into the shipped
product", this clause holds today.

On the other reading it cannot be closed by moving files at all: both
production tsconfigs use bare `include` globs with no `exclude`, so a
`__tests__/` directory matches exactly like any other path, as does every
`*.test.ts` in the repo. Relocating 32 fixtures would remove nothing from
typecheck scope.

A sweep was started and stopped once this was verified, rather than
landing 32 moves across areas this program does not own for no gain. If
the intent is that typecheck scope should exclude test code, that is a
repo-wide tsconfig change with a different owner.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): add plain-language design and test overviews

Two reviewable documents with diagrams, written so someone with no prior
context can follow what breaks, why, and what changed.

The design overview explains the five things stacked behind one terminal
rectangle, the 2 -> 19 -> 20 report, the three root causes, and the rule
underneath all of them: unknown is not dead.

The test overview explains why a green test proves nothing on its own,
the four-step mutation proof we adopted, and — the part worth reviewing
hardest — an honest account of what could not be proven and why, including
the properties that are true by construction and therefore have no guard
to remove.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): add a self-contained visual report of the design and its evidence

Pre-renders every diagram to inline SVG in both themes so the report opens
offline and stays sharp when zoomed. States the gate/journey score and the
retractions alongside the fixes, so the unproven half is as visible as the
proven half.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): record the finalized two-plane architecture decision

Adopts the data-plane proposal and adds the control-plane track it does not
cover: re-key ownership by pane, split orphan inventory out, then delete the
compensating code. Records that the host-authority alternative was refuted and
that the shipped keystroke fence is inert on the reattach path.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): add the design brief the review counsel works from

Separates verified code facts from unverified leads so reviewers attack the
design rather than a reconstruction of it, and records which simpler
alternatives were already refuted and why.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): report the design counsel's outcome and the live respawn bug it found

Three review rounds across two models replaced the two-record split with one
leaf-keyed record, deleted attach-time pane identity, and made orphans a
connect-time projection. Records that a shipped gesture still turns a healthy
remote shell into a duplicate agent resume, and that the renderer classifier in
that chain treats an error-message shape as proof of death.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): correct the report — the respawn proof gate guards a minority path

A final review traced every auto-respawn route. The primary one converts the
reattach failure into a boolean before any classifier sees it, so the shipped
proof gate never runs there. Records that two of the six shipped changes are
narrower than claimed, and why their tests could not have caught it.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): explain the landed design on its own terms

One leaf-keyed ownership record, orphans computed at connect, and replacement
shells only on positive proof — with the shipping order and the one product
trade the design asks the owner to accept.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): rewrite the design explainer in plain English

The first version assumed the reader knew the codebase. Reframed around two
bugs, two fixes and one decision, with the jargon replaced by pane / program /
note / helper and a five-word glossary for what could not be avoided.

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): stop reading an identity mismatch as a dead shell

The relay reports a pane-identity mismatch by saying the pty was not found,
but it found it — comparing identity is how it noticed. Publishing that as
expiry made the renderer clear the binding and cold-restore with agent resume,
so a live shell gained a second agent on one transcript. Reachable today by
detaching a pane into a new tab, which changes the tab the relay froze at spawn.

Mismatch now carries its own token and the classifier refuses it as proof.
Genuine absence still expires, so a shell that really went away is not stranded.

The three failure tokens move to src/shared: main published them and the
renderer decided respawn on them, from two copies that had drifted apart.

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): stop sending pane identity on reattach

The relay froze pane identity at spawn, so moving a pane to another tab made it
refuse a live shell — and refuse by saying 'not found'. The comparison is
presence-guarded, so not sending the fields disarms it on every relay version
including ones already installed on hosts: no wire change, no redeploy.

Nothing is lost. It existed to catch a relay restart recycling pty-N for a new
shell, and in exactly that case pane and tab both still match, so it accepted
the wrong shell anyway. The incarnation the attach returns is what distinguishes
those, and it already crosses the wire.

Removes the whole client-side apparatus: the expected-identity type, its
per-lease derivation, its map, and the parameter threaded through four layers.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): add tracked goalposts for the new design

Each goalpost is a behaviour with an oracle and the mutation that must redden
it, so 'proven' cannot be claimed from a green test. Records the anti-inert rule
as a first-class goalpost, since three guards in this program passed their tests
while sitting off the route production takes.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): record that the recovery grant is dead code, deleting a design step

The lease stores a relay-native pty id and the caller passes the app form, with
a raw equality comparison between them, so the 30s grant cannot fire for a real
SSH pane. The death rule that existed to referee it is deleted rather than
built, and the dead path itself becomes a removal.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): keep the full design detail in the repo

It only existed in an ephemeral job directory, so the plain-English explainer
had no durable source for its specifics — record shape, death rule, reattach
algorithm, migration order and the 25 oracles.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): add a resume prompt for a clean session

Points at the goalposts as the contract, names the three goalposts whose oracles
are already written and red, and carries the process rules that were learned the
expensive way — prove guards reachable, verify mutations land, commit per step,
and never let a subagent write production files in a shared worktree.

Co-authored-by: Orca <help@stably.ai>

* test(ssh): add the failing oracles for goalposts S3, S4 and S5

Intentionally RED: 14 clauses that fail against current behaviour and go green
under the changes named in new-design-goalposts.md. The branch is held unmerged,
so red here means unimplemented, not broken.

Each was verified to fail for the right reason and to flip green under the
identified fix, which was then reverted. Each pins the producer as well as the
consumer, so no clause can pass vacuously if its route is ever severed — the
failure mode that let three earlier guards ship inert.

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): stop fabricating an exit when a reattach fails

A failed attach never proves the shell exited. The relay answers not-found for
a pane-identity mismatch and for any id it merely cannot hand back, so treating
it as death sent the pane a synthetic `pty:exit { code: -1 }`, cleared provider
state, deleted ownership and expired the lease — four claims about a process we
know nothing about, on a shell that is usually still running.

Collapse every failure into the non-destructive branch that already existed a
few lines above (`restoreRequired = 'reattachAttemptsExhausted'` + wakeRecovery).
A branch collapse, not a new mechanism: goalpost S3.

Two tests pinned the deleted premise and are INVERTED rather than patched, so
the new intent stays covered:
- ssh-relay-orphan-abandon-paths: "retires the lease without a kill when the
  relay proves the PTY is gone" -> "leaves the shell running when the relay only
  reports the PTY as not found". Its comment claimed attach verifies liveness
  before answering not-found; it does not.
- ssh-relay-session: "invalidates and broadcasts remote PTYs that cannot
  reattach" -> "leaves an unreattachable remote PTY alone while its sibling
  reattaches".

Also repairs two clauses left red by c51be8072b (step A), which dropped the
expected-identity parameter and the expectedIdentityByPtyId map.

Mutation proof: restoring the destructive block reddens 6 of the 8 oracle
clauses in ssh-relay-reattach-exit-proof.test.ts; the 2 producer pins stay
green. Verified the mutation landed before believing the result.

Net production: -21 lines.

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): give an SSH pane binding one home

An SSH pane's durable binding lived in two persisted partitions. Main's spawn
wrote `ssh:<target>`; the relay's reattach write passed no hostId and landed in
`local`; the renderer has always published SSH pane membership to `local` on
purpose. So `durablyBoundPtyIdForPane` hedged ssh-first-then-local, read a
partition no live writer maintained, saw the arriving lease disagree with a
stale pty id, and bailed — supersession silently no-opped and both leases stayed
live. That is the STA-3077 2 -> 19 -> 20 mechanism.

`local` wins: it is the only publisher of pane membership and where
`mayCreate:false` is evaluated. Every reader and writer now names it.
- resolvePersistedStablePaneOwner / retirePersistedStablePaneOwner drop their
  connectionId parameter and read the default partition.
- the CAS write and both spawn upserts drop the hostId argument (each was an
  if/else that collapses to one call).
- durablyBoundPtyIdForPane stops hedging.
- a one-time load fold moves any legacy `ssh:<target>` ptyIdsByLeafId into
  `local`, preferring `local` on conflict, sequenced after the leaf remap so
  every folded binding keys on a UUID.

Side effect worth naming: the renderer never hydrated the `ssh:*` partition
(listKnownRuntimeHostIds filters to `runtime:*`), so the Issue #217 force-quit
binding protection had never worked for SSH panes. It does now.

Mutation proof, run as a 2x2 because the two edits can mask each other:
- fold disabled, reader local-only -> 1 clause reddens (the fold is live)
- fold disabled, hedge restored    -> 3 more redden (the reader is live)
- fold enabled,  hedge restored    -> ALL GREEN

That last row is why this commit adds an eighth clause: with the fold shipping,
the fold erases the divergent copy at boot, so the reader guard would have
shipped unproven — the exact failure mode G5 exists to catch. The new clause
rewrites `ssh:<target>` mid-session (orphan adoption still writes there) and
reddens when the hedge is restored, pinning the reader on its own.

Five clauses in ipc/pty.test.ts pinned the two-partition shape and are INVERTED
to the single home, each keeping an explicit arity check so a re-added partition
argument fails loudly rather than silently.

Net production: +9 lines (the fold is new state repair; the call sites shrank).

Co-authored-by: Orca <help@stably.ai>

* fix(ssh): bind a pane through one producer so the fence is live on reattach

The superseded-PTY fence refuses a keystroke queued for a shell whose pane has
since bound a different one. It reads `ptyPaneKey` disagreeing with
`paneKeyPtyId` — and only spawn ever wrote those maps. Reattach bound the pane
through `runtime.registerPty` instead, so the maps never learned the successor,
`isSupersededPtyId` returned false by construction, and the fence was inert on
the one path it was built for. Goalpost S5; a defect in already-shipped work.

Collapse to one `bindPaneShell` producer that writes the durable record and the
fence maps together. All three binding paths call it: the relay reattach and
both spawn handlers. Error policy stays at the call sites because it genuinely
differs — a caller that just created a shell must clean it up on a failed
durable write, a caller that merely reattached must not detach anything.

The paneKey is composed from the tab that holds the leaf *now*, resolved from
the live layout, not from the tabId frozen in the lease. Only the leaf half of
a pane key is remint-stable; `detachTerminalPaneToTab` moves a live pane and its
PTY into a new tab, so a stored tabId names the tab the pane left.

Mutation proof, both sub-guards isolated:
- drop the `rememberPaneKeyForPty` call    -> 3 clauses redden
- prefer `args.tabId` over the live layout -> 1 clause reddens
The second clause is new in this commit. Every pre-existing clause in the fence
oracle used one tabId on both sides, so a producer that simply forwarded
`lease.tabId` would have gone green and shipped the tab bug unnoticed.

Two source-text clauses are STRENGTHENED, not relaxed. They previously required
the relay to hold a `persistPtyBinding` call of its own and merely forbade an
ssh-partition argument on it. The relay now has none, so they assert ZERO direct
binding writes there plus a `bindPaneShell` call — a second bind producer is
exactly the defect this removes.

Also repairs a latent false green: the "persistence fails" case in
ssh-relay-session-reconnect-incarnation was passing because a missing mock made
the call throw a TypeError that happened to emit the console.error it asserted.
The failure is now injected at the producer, so it is a real oracle for "a
thrown durable write must not detach the PTY".

Net production: +60 lines. This is the one step in the program that grows;
the shrink arrives with S8's deletion. Reported rather than smoothed over.

Co-authored-by: Orca <help@stably.ai>

* feat(terminal): show an unreachable pane as disconnected with two actions

Ships with S3. Collapsing the fabricated exit removed a lie, but it left the
pane frozen: `restoreRequired` never crosses to the renderer, so a relay-driven
reattach failure had no user-visible signal at all, and the renderer's own
reattach arms showed a raw error toast with no way to act.

An unproven failure now renders the pane as disconnected with exactly two
explicit actions — "Try again" (remount against the same shell via
requestTerminalPaneRecovery) and "Start a new terminal" (retire the binding,
then spawn fresh). Nothing infers death and nothing auto-spawns; the user
decides, because at that point no one knows whether the shell is alive.

The two actions are the same two things the code already did, moved behind a
click: the retry is the existing pane-recovery request, and "start a new
terminal" is the existing clearExitedPanePtyLayoutBinding + clearTabPtyId +
startFreshColdRestoreAgentResume sequence that used to run automatically on a
"proven gone" error. No new IPC channel: the silent-respawn decision was always
renderer-local.

Copy constraint, enforced by an oracle rather than a review note: the banner may
never assert the shell exited. STYLEGUIDE.md:236 already forbids result verbs
without result data, and a failed attach is not result data. A test asserts the
rendered text matches no death verb and shows no wire token.

`TerminalRemoteRuntimeReconnectBanner` is renamed `TerminalPaneDisconnectedBanner`
— it now serves any transport, and per AGENTS.md the name must say what it holds.
Existing i18n key strings are kept verbatim so no shipped translation breaks;
the SSH copy is additive (4 new en.json keys).

`describeReattachFailure` is deleted with its last caller. Its two cases were
not dropped: "keeps the wire token out of the pane" is re-asserted against the
new copy, which is a stronger place for it.

Renderer production (excluding the pure rename): +28 lines.

* refactor(terminal): delete the SSH pane recovery grant, which could not fire

For a disconnected pane, `recoverTerminalPane` consulted a recently-expired SSH
lease and, on a match, spawned a replacement shell. It could never match: leases
store a relay-native pty id (`pty-7`, normalized on every write) while the
runtime registers the app-form id (`ssh:<conn>@@pty-7`), and the comparison was
a raw `===`. The branch was also unreachable for a local pane, which has no SSH
lease. Goalposts S6 and S8.

A characterisation oracle lands FIRST and proves it, rather than assuming it:
ssh-pane-recovery-grant-reachability.test.ts mints BOTH id forms from the
production helpers — never as two hand-typed literals — so it tracks the real
namespace split instead of restating it, and seeds a lease that qualifies on
every other predicate (state, worktree, tab, leaf, grace window). Anti-vacuity
assertions pin that control actually reaches the gate rather than bailing early.

Mutation proof, run before the deletion: normalizing the comparison at the
`lease.ptyId === ptyId` site makes the grant fire and reddens the oracle. That
is the exact "fix" someone would reach for, so the oracle is pinned to
unreachability rather than to the throw.

Deleted: the grant tail, the `terminalPaneRecoveryByIdentity` dedup map (whose
only consumer was the grant), and the dead `ptyId` parameter.
NOT deleted, and worth naming because over-deleting here would break users:
`getRecentExpiredSshLease` itself, `hasRecentExpiredSshLeasePane` and
`SSH_PANE_RECOVERY_GRACE_MS` all stay. Their other two callers pass `ptyId`
undefined, which short-circuits the broken comparison — those are live today and
feed headless-mobile terminal-tab visibility.

Also NOT done: deleting only the gate while keeping the spawn. That would have
granted a respawn to every disconnected pane — a behaviour change in the
dangerous direction. The refusal is what stays.

Four tests pinned the grant. All were seeded through a helper that stores the
lease id as the same literal it registers as the runtime pty, with a null
connectionId — a shape production cannot mint. Three are INVERTED, keeping their
scenarios; the fourth is now tautological and carries a comment saying so rather
than being left silently hollow. The oracle's own counterfactual control is
inverted by this deletion too, which is recorded in the file: its flip from
grant to refusal is what "inert" means here.

Honest limit, stated in the oracle rather than smoothed over: unreachable BY
CONSTRUCTION for SSH panes; for a local pane, unreachable only up to a random
UUID collision.

Net production: -32 lines.

* docs(terminal): record S3, S4, S5 and S8 proven, and G1 missed

All seven step goalposts are now proven. G1 (net-negative production) is NOT met
at +83 and is reported as a miss with a per-step breakdown rather than reframed.

Also records the near-miss G5 caught: S4's reader guard showed no mutation
response because the load fold had already erased the divergent state at boot.
It was correct and would have shipped unproven. An added clause pins it.

* fix(terminal): a reattach not-found is not proof the shell is gone

Closes the last live route to the reported duplicate agent resume (RC2), found
by the E2E harness rather than by reading: when a relay is stalled and replaced,
the fresh relay has no memory of `pty-1` while the old shells keep running under
its predecessor. It answers not-found, and the renderer read that as proof.

A not-found means the relay WE ASKED cannot hand that id back. That proves an
exit only if the relay process that minted the pty is the one answering. The
design says exactly this (D3 row 2), and gates the grant on `relayInstanceId`
equality — a field step E-2 never built. `SSH_SESSION_EXPIRED` is not
independent evidence either: its ONLY producer is that same not-found mapping in
reattachSshPtySession, and the token's own doc comment claimed "the host proved
the session is gone", which it never did.

So `isProvenSshSessionGoneError` returns false. Both reattach arms now always
take the non-proof path and surface the pane as disconnected, which is what the
owner approved in D1 — and what makes that affordance load-bearing rather than
near-unreachable, since it was previously only reached by errors that were
already rare.

The respawn tails are deliberately NOT deleted. The design preserves the grant
as a conditional for E-2, so the decision point stays and a clause pins that
nothing reaches it meanwhile. This is the one place in the program where an
unreachable branch is kept on purpose, and it is labelled as such.

Tests: three clauses asserted a not-found proves death and are INVERTED, with
the reasoning recorded. The #12101 cold-restore case reached the spawn door by
throwing a not-found; that door is now opened by the user's "Start a new
terminal", so the test drives that instead and keeps all four of its original
assertions verbatim — strictly better coverage, since it now pins that the
automatic respawn stopped AND that the door still works.

Mutation proof: restoring the old predicate makes the new no-respawn clause fail
with "expected connect to be called 1 times, but got 2", confirming it reddens
on the real production route rather than passing vacuously.

* test(ssh): add E2E oracles for pane cardinality and duplicate resume

Both reported failures now have end-to-end coverage against a real Docker
OpenSSH relay, gated on ORCA_E2E_SSH_DOCKER like the rest of the suite.

- ssh-reconnect-pane-cardinality-across-partitions: three real reconnect cycles;
  after each, pane ids unchanged, exactly one live lease per leaf, exactly one
  remote shell per pane key, and exactly one pty id bound per leaf ACROSS BOTH
  durable partitions. Two partitions agreeing is tolerated; two naming different
  shells is the S4 divergence and fails. PASSES.
- ssh-reattach-does-not-resume-agent-twice: the host itself records one line per
  shell launch via a .bashrc hook keyed by ORCA_PANE_KEY, so a duplicate resume
  is counted at the source rather than inferred. Fault is SIGSTOP on the
  detached relay. PASSES.
- ssh-disconnected-pane-affordance: written whole but held as test.fixme. The
  banner needs the target CONNECTED while a single pane's attach fails, and both
  host-side faults drove the target out of connected instead. Held rather than
  deleted so it runs the day a seam exists; the reason is measured, not assumed.

New helpers: docker-ssh-relay-stall (SIGSTOP/SIGCONT, reads the stop back off
/proc so a fault that did not land cannot make an oracle vacuous), and
remote-pane-launch-transcript.

Note for whoever picks these up: a stalled relay leaves two detached relay groups
on the host, and readDockerSshRelayProcessSnapshot throws on more than one, so
call it before the fault.

Writing these is what surfaced RC2 surviving S3 — fixed in 7cd7fef927.

* fix(ssh): fold the pane incarnation with the binding it fences

Found by adversarial review. `persistPtyBinding` writes the binding and its
incarnation into the SAME partition, and the incarnation is what its CAS
compares. Step P's load fold moved only `ptyIdsByLeafId`, so after upgrade a
pane whose incarnation had been written to `ssh:<target>` kept the guard in the
partition nothing reads: `resolvePersistedStablePaneOwner` read `undefined` from
`local`, the CAS then compared undefined against undefined, and the incarnation
half of the fence passed for any value until the next write healed it.

Not data loss and not a wrong-shell bind — the ptyId half still held — but a
guard silently weakened by a migration is the exact shape this program keeps
finding, so it is closed rather than noted.

Mutation proof: disabling the incarnation half of the fold reddens the new
clause; the other eight stay green.

One clause in persistence.test.ts asserted the incarnation survives a reload in
the SSH partition. Its subject is that the reconciled value is preserved, not
which partition holds it, so the assertion follows the binding to its one home
and additionally pins that the ssh partition no longer keeps a copy.

* docs(terminal): record the two defects found after the goalposts were met

RC2 survived S3 and was found by writing the E2E test, not by reading. The load
fold left the incarnation half of the pane fence behind and was found by
adversarial review. Both were invisible to unit oracles that had already gone
green, which is the useful part of the record.

* fix(terminal): close four defects found by adversarial review

Four reviewers over the diff, every finding put to an independent skeptic. Nine
of twelve agents died on prompt length, so most findings arrived UNREFUTED
rather than refuted — I checked those myself instead of counting them clean.
Four were real.

1. "Start a new terminal" resumed the agent instead of starting a new one.
   The action passed the cold-restore startup, which carries the agent's
   providerSession. That was correct for the automatic respawn it replaced,
   because that only ran on PROOF the shell was gone. Behind this button the
   shell is probably still alive, so it put a second agent process on one
   transcript — the exact defect this pane exists to prevent, reintroduced by
   the fix for it. Now starts a genuinely fresh shell, which is also what the
   button says.

2. The banner was never retracted. The app-SSH transport publishes no recovery
   states, so nothing cleared the card: it sat over a live shell with armed
   buttons. Both actions now clear it before acting.

3. The load fold destroyed bindings it could not move. When a tab existed only
   in the ssh partition there was no local layout to fold into, and the code
   cleared the source anyway — deleting the only record of that binding. It now
   leaves such a tab alone: with no second home there is nothing to disagree
   with and nothing to fold.

4. The relay registered the pty under the lease's frozen tabId while
   bindPaneShell bound and fenced it under the live one, splitting a moved pane
   across two tabs and ensuring a mobile surface for the tab it left.
   bindPaneShell now returns the resolved tabId so both use one coordinate.

Also repairs a reliability-gate manifest entry the banner rename broke. That
would have been caught by the pre-commit lint gate, which I had been skipping
with --no-verify; the full-repo sweep caught it instead.

Mutation proofs, each verified to land before being believed:
- restoring the resume reddens on `registerAgentLaunchConfig` and, with that
  clause disabled, on the spawned command being
  "codex '--dangerously-bypass-approvals-and-sandbox' 'resume' 'codex-session-1'"
- disabling the fold's move reddens the ssh-only-tab clause
- registering under lease.tabId reddens the moved-tab clause

The first clause was VACUOUS on its first attempt and is recorded as such: the
fixture had no resumable agent, and it asserted a field name the spawn path does
not use. It now pins the fixture itself, so it fails loudly rather than going
quiet again if `codex` stops being resumable.

* fix(terminal): drop the remote-host assumption from the disconnected copy

The banner said the shell 'may still be running on the host'. The reattach arm
that publishes it is not SSH-only — a local or folder-workspace pane reaches it
too, and there is no host to speak of there. The claim that matters is that the
shell may still be running, which holds either way.

* fix(terminal): close round-2 review findings, including one regression

Round 2 ran narrow per-area scopes so agents stopped dying on context: 7 of 7
reported, versus 3 of 12 in round 1. Two findings survived refutation and both
were real.

1. REGRESSION I INTRODUCED. `bindPaneShell` resolved the tab from the live
   layout for EVERY caller. That is right on reattach, where the lease's tabId
   is the frozen side — but backwards on spawn, where the caller's tabId is
   fresh truth and the persisted layout is the stale side inside the renderer's
   publish debounce. Breaking a pane out into a new tab and spawning into it in
   that window resolved back to the tab the pane had just left, writing the
   durable binding and the fence under one tab while the lease and the runtime
   registration used the other — the split-coordinate defect step F exists to
   remove, reintroduced on the spawn path.
   Live-layout resolution is now opt-in via `tabIdMayBeStale`, set only by the
   reattach bind. A clause pins that no spawn-side call sets it.

2. The fold moved every incarnation even for a binding it had deliberately left
   in place, splitting a pane's binding from the incarnation that fences it —
   the same defect 994733d8b1 closed, in the other direction. Incarnations now
   move only with the binding they belong to. The reload clause that had been
   inverted for the fold is restored to its original assertion, because an
   ssh-only pane now correctly keeps both halves together.

Also closes a live route to the reported duplicate resume that my earlier fix
missed. `isProvenSshSessionGoneError` covered the rejected-promise arms, but a
reattach can also report expiry through the transport's error callback and then
resolve falsy; those two branches still cleared ownership and cold-restore
resumed the agent. A skeptic refuted this as pre-existing rather than caused by
this branch, and that is correct on causation — but it is a live second route to
the exact defect this work exists to remove, so leaving it would make the claim
that duplicate resume is fixed false. Both branches now surface the disconnected
pane.

Five tests pinned that callback respawn. Two are INVERTED to the disconnected
outcome; two keep their real subject (stale-callback fencing, delayed parked
snapshot) and now reach a replacement shell through the banner's "Start a new
terminal", which is the new production route; one — the cold-restore resume
after expiry — is inverted to assert no resume command and no agent launch
config, with a fixture pin so "no resume" cannot pass vacuously.

* fix(terminal): close round-3 review findings on tab resolution and the fold

Round 3, narrow scopes again: 9 of 9 agents reported. Two findings confirmed.

1. A thrown durable write lost the resolved live tab. `bindPaneShell` resolved
   the tab internally, so when `persistPtyBinding` threw, the relay's `bind`
   stayed null and it registered the pane in the runtime graph under the frozen
   lease tab — splitting the graph from the durable record it had just moved.
   Resolution is now an explicit `resolvePaneShellTabId` the relay calls BEFORE
   the write, so a throw cannot lose the answer. This also deletes the
   `tabIdMayBeStale` flag added a commit ago: the reattach resolves its own tab
   and passes a live one, and spawn callers simply pass theirs. The distinction
   is now carried by which caller resolves, not by a flag they must remember.

2. The fold could pair a binding with an incarnation that was never written
   alongside it. Where both partitions named a leaf, local won the binding but
   the incarnation was copied across independently — so local's pty could end up
   fenced by the superseded partition's incarnation. `persistPtyBinding`'s CAS
   compares both, so that pane's next legitimate update would be refused. An
   incarnation now moves only when the pty it belongs to is the one that ends up
   bound.

   My first attempt at this over-corrected and skipped the case where both
   partitions name the SAME pty — where the incarnation does belong with it. The
   existing clause caught that immediately, which is the fixture doing its job.

Also hardens `findTerminalTabIdForLeaf`: it now requires the tab to still exist
in `tabsByWorktree`. A layout entry outlives the tab it described, and binding a
live shell to a deleted tab registers a pane under a ghost and can resurface it.
The fence oracle's fixture gained the live tab it was missing, so that clause
cannot pass by resolving nothing.

New clause covers the divergent-pty case the reviewer named — the two partitions
naming DIFFERENT ptys for one leaf, which is the divergence being migrated and
was previously untested.

* fix(terminal): check tab liveness without depending on a worktreeId match

A reviewer asked, correctly, whether lease.worktreeId always matches the
tabsByWorktree key exactly — including for a folder workspace, whose worktreeId
carries a `::workspace:<uuid>` suffix and is matched by full-string equality.

Rather than assert that invariant, this removes the dependency on it. Tab
liveness is now checked across every worktree instead of under one key. A leaf
id is a UUID, so there is nothing to disambiguate by worktree, and the resolver
no longer has an answer that depends on two strings agreeing — which is exactly
the class of full-string comparison that produced issue #12474 in this area.

Had they diverged, resolution would have silently returned undefined and fallen
back to the stale lease tab, quietly restoring the moved-pane bug for folder
workspaces only. Failing open like that is worse than the check itself.

* style(terminal): keep the membership authority under the max-lines limit

My previous comment pushed the file to 301 lines. AGENTS.md forbids a max-lines
disable or a per-file bump, so the comment is trimmed to the repo's concise
standard and the liveness check folded into the existing condition.

* fix(ssh): resolve every incarnation in the pass that clears its binding

Round 4 confirmed one defect, in my own round-3 fix. The filter that stopped an
incarnation following a LOSING binding also stopped it being deleted — while the
binding itself was still cleared. So a conflicted leaf left the superseded
incarnation behind with nothing to fence: durable fence state in a partition
holding no binding, which is the one-home invariant this step exists to
establish, broken by the code establishing it.

The reviewer also named the test gap exactly: the clause I added asserted only
that the value was not copied into local, never that it was gone from the
partition it lost in. Both are asserted now.

Incarnations are resolved in the same loop that clears the bindings, so no
binding can be cleared without its fence being resolved. Three outcomes, by
which pty ends up bound:
- this binding moves (local had none)   -> its incarnation moves and OVERWRITES
  any local value, because a local incarnation with no local binding is a
  leftover rather than a fence. That case previously synthesized a pair.
- both name the same pty                 -> keep whichever fence local holds.
- local wins with a different pty        -> drop this incarnation with the
  binding it belonged to.

The second and third outcomes were flagged by the same reviewer as real but
attributable to my earlier commit rather than that one. They are the same defect
class, so they are fixed here rather than filed.

Two new clauses: the superseded incarnation is deleted, not merely uncopied; and
a moving binding overwrites an orphaned local incarnation.

* fix(ssh): never pair a moving binding with a fence that was not written for it

Round 5 ran a mechanical ten-case matrix over the fold twice, independently. Both
passes landed on the same primary defect, and it is one my previous fix created.

Case 7: the ssh partition holds a binding with NO incarnation, and local holds a
stale incarnation with no binding. The binding moves into local and inherits that
leftover, producing (arriving pty, unrelated incarnation) — a pair no writer ever
produced. persistPtyBinding's CAS compares both halves, so the pane's next
legitimate update is refused. The previous fix only replaced local's leftover
when the ssh side had an incarnation to replace it WITH; absent one, the leftover
survived. A moving binding now takes the ssh fence whatever it is, including
absent, in which case local's is deleted.

Also fixes the bookkeeping both passes flagged: the function defaulted
`workspaceSession` at the top, so a profile with no local session could be
mutated on a path that then returns false — a mutation with no save scheduled.
It now returns early instead: with no local session there is nothing to fold
into, which is also the honest reading.

Two findings are deliberately NOT fixed, recorded rather than silently dropped:
- An ssh incarnation whose binding was already missing BEFORE the fold survives,
  because iteration is binding-driven. It is a pre-existing orphan isolated in a
  partition no reader consults for pane bindings, and reinterpreting it is not
  this migration's business. The comment claiming an incarnation never outlives
  its binding overclaimed and is corrected to say what the code does.
- Two ssh partitions carrying the SAME tab and leaf resolve by object-key order.
  A tab belongs to one worktree on one host, so this is not a shape production
  writes; making it deterministic would mean inventing a precedence rule for a
  state that should not exist.

New clause covers case 7 directly. The matrix cases both reviewers named as
uncovered are now covered except the two above.

* refactor(ssh): delete the pane-binding fold; its premise was false

The migration moved legacy `ssh:<target>` pane bindings into `local` and cleared
them, on the theory that the ssh partition was a stale spill of the desktop
plane's state. Investigation of both hypotheses the team raised disproved that:

- NOT cross-version compat. The introducing commit says it is for CONCURRENT
  multi-host. Nothing about the partition crosses the wire (zero references under
  src/main/runtime/rpc/), and the payload that does cross the SSH boundary —
  RemoteWorkspaceSnapshot — is projected from `local`. The only downgrade-compat
  comment protects `local`, the other direction.
- NOT multi-client. PersistedState is one file on one machine; phones and CLI are
  RPC clients into that same process. Orca's real per-client state is
  `mobileClientTabSelectionsByDeviceId`, 13 lines above in the same struct, and
  it carries selections only — never a ptyId.

What it actually is: the headless/CLI/mobile plane's OWN home, written and read
deliberately across several tickets (STA-3463, STA-3465), with tests that assert
that partition by name. So the fold was not tidying a spill — it was erasing
another plane's live state. Measured symptom: a split SSH tab would disappear
from mobile while its shell kept running.

The desktop plane's fix never needed it. Supersession multiplied panes because
`durablyBoundPtyIdForPane` hedged into the other plane's copy; reading `local`
alone is the fix, and it stands without any migration.

Deleting rather than redesigning, because the redesign had no target: five review
rounds each found a defect in that function, three of them inside the previous
round's fix, and every one was a cell of a merge matrix that only existed to
serve a premise that was false.

The `boundPtyIdsAcrossPartitions` clause is INVERTED, not dropped. It required
the two partitions to AGREE after load — which encoded the false premise, and is
what made a migration look necessary. It now asserts the narrower, stronger
property: what the desktop plane resolves follows `local` alone, whatever the
other plane holds.

Also proven, and the reason unification was NOT attempted: worktreeId is
`<repoId>::<path>` where repoId is a randomUUID minted client-side at repo add
(orca-runtime.ts:18722), so two servers cannot collide on one. Host scoping was
not protecting against that here — but the two planes' opposite choices are each
deliberate and each test-pinned, so choosing a winner is an architecture call,
not a cleanup.

Net production: -75 lines.

* fix(ssh): arbitrate on the pane, not the tab its lease was written in

Correctness review round 1 on #13326: 5 raised, 2 confirmed, both real.

1. Arbitration looked the durable binding up under the lease's FROZEN tabId.
   `detachTerminalPaneToTab` moves a live pane and its PTY, and nothing re-keys a
   lease, so after a break-out the binding lives under the new tab and the lookup
   found nothing. The bound shell then lost to recency and supersession expired
   the pane's OWN lease; the follow-on scrub could not clean up either, because
   it matches lease.tabId against the layout's tabId. Reconnect skipped the
   expired-but-bound PTY and reattached the stale winner onto the pane.

   The leaf is the stable half of pane identity, so the lookup now prefers the
   named tab and falls back to wherever the leaf actually is.

2. Arbitration read the desktop plane only while the scrub reached into
   `ssh:<target>`, so a headless-plane pane was invisible to the ranking and
   then lost its live binding to it.

   Fixed at the reader, not the scrub: local FIRST, headless plane only as a
   fallback. That is NOT the STA-3077 hedge — that bug was preferring
   `ssh:<target>`, letting a copy no live writer maintains outvote the real
   binding. A fallback consulted only when local is silent gives a headless-owned
   pane a vote without ever outranking a live desktop binding.

   Proven by mutation: swapping the two back to ssh-first reddens 4 clauses,
   including the ten-reconnect cardinality one.

Also closes two fulfilled-result routes to the duplicate agent resume that the
earlier RC2 fix missed — `handleReattachResult` respawned on a result flagged
`sessionExpired` and on a result carrying no pty id. A skeptic refuted both as
pre-existing rather than PR-caused, which is correct on causation, but they are
live routes to the defect this PR claims to fix.

Scoped to SSH panes only. The first attempt diverted every pane and broke three
daemon tests — correctly: a local provider is authoritative about its own ptys,
so "cannot reattach" there is not the ambiguous evidence it is for a relay that
may have been replaced. New clause covers both routes; disabling the diversion
reddens it.

43,253 pass; the 7 failures are pre-existing on clean main in this environment.

* fix(ssh): supersede on the leaf, so a moved pane retires its own predecessor

Correctness round 2. This is the reported cardinality growth in its surviving
form, and it is the sharpest finding of the review so far.

Supersession matched sibling leases on `(worktreeId, tabId, leafId)` and bucketed
duplicates under the same key. A lease freezes its tabId when written, and
`detachTerminalPaneToTab` moves a live pane — so after a break-out the pane's
next lease carries the NEW tab and its predecessor carries the old one. The two
never match, the predecessor is never superseded, and the live count grows on
every reconnect. Exactly the reported 2 -> 19 -> 20, for any pane that has been
moved between tabs.

Round 1 fixed the same frozen-tabId mistake at the binding LOOKUP. It did not fix
it here, at the sibling match and the bucket key, which is why the bug survived a
round. Both are now keyed on the leaf — the stable half of pane identity, per
stable-pane-id.ts: the tab half changes on break-out.

Two clauses cover it: a predecessor whose lease names the tab the pane left is
superseded, and the live count stays flat across ten reconnects that each land in
a new tab. Restoring `tabId` to either the match or the key reddens both.

E2E re-run against a real Docker relay after the change: 2 passed. Full suite
43,255 pass; the 7 failures are pre-existing on clean main in this environment.

* fix(ssh): a supersession decided from one plane only mutates that plane

Correctness round 2 confirmed finding. Arbitration ranks leases using the desktop
plane's binding, then handed its losers to a scrub that walked BOTH planes — so
the headless/CLI/mobile plane's binding was deleted for a lease it never got to
vote on. Its owner then has no durable record to reattach that shell by, and can
fall back to recency or orphan a shell that is still running.

`clearSshRemotePtyBindingsForLeases` now takes `arbitratedFrom`. A decision
reached by reading one plane may only mutate that plane. An explicit expiry or
termination is plane-agnostic — the pty is gone for everyone — so those callers
pass nothing and still scrub both, which is what the existing
`markSshRemotePtyLease` oracle pins.

I initially assessed this as not-a-defect, reasoning that local winning IS the
STA-3077 fix. That was about RANKING and did not justify DELETING the other
plane's record; the round-2 verdict was right and I was wrong.

It did also catch a comment of mine that had gone stale — a clause claimed the
other plane was "deliberately left alone" while the code cleared it. The comment
now says what the code does and why.

Mutation: letting arbitration scrub both planes again reddens the new clause.
43,256 pass; the 7 failures are pre-existing on clean main in this environment.

* fix(terminal): put the unreachable-pane guards in one place

Correctness round 3. The leaf-keying from round 2 came back clean, twice and
independently. But the renderer produced findings for a third consecutive round,
and they were all one shape: `publishUnreachablePane` is called from seven sites,
each needing the same guards, and a different one was missing at each.

So this stops patching sites and moves the guards into the publisher:

- `disposed` — a late rejection republished a card for a numeric pane id that had
  already been reused, giving a fresh pane a phantom card whose actions closed
  over a dead session.
- `connectionId` — the deferred catch is not SSH-only. A local/daemon pane could
  be shown an SSH ambiguity card it can never clear, and would loop: retry
  remounts, reattach rejects, card returns. Its provider is authoritative about
  its own ptys, which is exactly why the two branches in handleReattachResult
  already had this guard — and why the catch needed it too.

Two more real defects in the banner's own actions:

- "Start a new terminal" passed `null` to suppress the saved agent startup, but
  connect FALLS BACK to the startup its transport was constructed with whenever a
  per-call field is absent (pty-transport.ts). So the "fresh" shell could resume
  the same provider session — the duplicate transcript this pane exists to
  prevent, for the third time in this button. `suppressSavedStartup` makes the
  suppression explicit; `??` means passing null could never have worked.
- It also cleared both durable bindings BEFORE the spawn, and discarded the
  promise. A spawn that resolves null left the pane blank, unbound, and with no
  way back to a shell that may still be running. Bindings are now cleared only
  once a replacement actually starts, and the card returns if it does not.
- "Try again" voided its boolean; a declined remount left no card and no shell,
  strictly worse than the toast it replaced. It now republishes.

The strengthened clause is the point: the old one asserted the ABSENCE of
per-call startup fields on a mocked transport, which passes whether or not the
production fallback fires. It now asserts the explicit suppression, and reddens
when the flag is dropped.

Four fixtures were under-specified — they drive SSH reattach scenarios but never
seeded an SSH repo, so `connectionId` was null and they had been passing without
the pane being SSH at all. Seeded, not weakened.

43,256 pass; the 7 failures are pre-existing on clean main in this environment.

* fix(terminal): suppress the whole saved startup set, not field by field

Round 4 self-check on my own round-3 fix. `suppressSavedStartup` guarded four of
the six values `connect` falls back to — `launchAgent` and
`startupCommandDelivery` still inherited from the transport's constructor. Adding
the guard per field is precisely how those two were missed, and the guarded
expressions had become unreadable.

The saved values are now one object that `suppressSavedStartup` drops wholesale.
A field added later is covered by construction rather than by remembering.

Found by asking the question the review lens was given rather than waiting for
its answer: does the suppression cover EVERY channel, or only the ones I noticed?
It did not.

* fix(terminal): stop stranding a local pane whose restore fails

The unreachable-pane card is SSH-only: a local, daemon or runtime-host pane has
no connection to be unreachable ON. Consolidating that guard into the publisher
made it silent, and four callers paired the now-conditional publish with an
unconditional `return` — so on the deferred-reattach path, which unlike the
direct-SSH one is not nested under `connectionId`, a local pane got no card, no
error and no replacement. Frozen, with a stale binding.

The diversion now reports whether it took ownership of the failure, so a caller
can only stop when something actually handled it. A pane that cannot show the
card falls through to the replace-in-place it had before, which is correct: its
provider is authoritative about its own ptys.

The two direct-SSH sites are inside `if (connectionId)`, so they are unchanged
in behaviour; the return value simply makes the pairing impossible to get wrong
at the next call site.

* docs(terminal): put two comments back on the thing they describe

The lease-healing docblock had drifted onto durablyBoundPtyIdForPane, which
neither retires leases nor returns a count, leaving the real healing entry point
undocumented and its neighbour carrying two contradictory descriptions.

The suppression comment claimed to cover "every startup value this transport was
constructed with"; env/envToDelete are constructor values and deliberately stay
outside the set. Nothing behavioural changes here — but a comment that overstates
a boundary is how the next maintainer picks the wrong one.

* docs(terminal): do not claim a remote runtime is authoritative about its ptys

A remote runtime reaches its pty over a connection that can fail, so a failed
reattach proves no more there than it does over SSH. It keeps replacing in place
only because the card is SSH-scoped, not because its provider is authoritative.
Say that, so the limitation is deliberate rather than implied.

* perf(ssh): stop fsyncing the whole store from the main thread on reconnect

supersedeDuplicatePaneLeases runs at the top of every reattach pass, and when it
retires anything it flushed synchronously. flushOrThrow fsyncs a multi-MB file
from the Electron main thread — this file already documents (see flushAsync) that
on a stalled network profile mount that syscall is uninterruptible, so the app
stops repainting and no deadline can bound it, because the deadline's own timer
is stuck behind the same block.

The population that hits this is exactly the one the heal exists for: an upgraded
install carrying accumulated duplicates. It now awaits the async durable twin its
neighbours on this path already use. Still "OrThrow", because a retirement that
is not durable must not be believed — the rollback is unchanged.

* fix(ssh): make a parked PTY delivery expire instead of going dark for good

Exhausting the per-generation recovery budget parks one PTY's delivery rather
than dropping the shared relay channel — right, because the channel is shared and
a retry count proves nothing. But the only escape it named was "the next relay
open", and a channel that stays healthy never gives it one. That leaves a pane
with no output and no way back, which is the exact state this change exists to
prevent; before this branch, exhaustion dropped the channel and the reconnect
ladder recovered the pane (loudly, at every sibling's expense).

The park is now a cooldown rather than a verdict: the next rejected frame after
it starts a fresh budget. Recovery is rate-limited, never abandoned, and the
containment that made parking right in the first place is untouched.

Elapsed time, not a timer, so there is nothing to cancel on teardown and no late
fire after dispose.

* fix(ssh): let a due park past the retired-delivery filter, and prove it

The cooldown added in 124e00e8a8 was reactive: it needed a later rejected frame
to reach recovery. But retirement is ours, not the host's — a stalled source keeps
publishing the very token we retired, and acceptPtyData drops those frames before
classification. So the wake-up could never fire in the case that actually happens,
and the pane stayed dark exactly as before.

A parked PTY past its cooldown is now let through that filter. It costs nothing:
the frame is re-classified as rejected and re-retired, so no output reaches the
terminal — it only regains the ability to ask for recovery.

The test shipped with that commit could not have caught this: it woke recovery
with a fabricated NEW delivery token. Retirement holds one key per relay PTY, so
that frame overwrote the key and un-retired the original — the assertion passed
with the wake-up path fully broken. It now reuses the original token throughout,
and reverting the guard above reddens it.

* refactor(terminal): one i18n namespace per component, and two notes worth keeping

The disconnected banner was renamed but kept reading five keys under the old
component's namespace while its new strings sat under the new one — a component
translating from two namespaces at once. Keys moved across all five locales;
values and behaviour unchanged.

Two comments earn their place. durablyBoundPtyIdForPane deliberately does NOT
require the tab to still exist, unlike findTerminalTabIdForLeaf which must —
adding the "missing" check there would make arbitration retire shells more
eagerly, which is the opposite of what this change is for. And the respawn after
the proof check in the direct-SSH catch is unreachable today by construction;
saying so stops it reading as forgotten code.

* fix(ssh): unknown PTY liveness is not proof of death

hasPty is three-state and says so: null means the provider has not listed the
host yet — ignorance, not death. The retry gate tested it with `!`, which reads
null and false alike, so it ended recovery on ignorance.

That state is not exotic: a reconnect builds a fresh provider with an empty set,
which is exactly the moment rejected frames arrive. The attempt was deleted and
no retry scheduled, and because the delivery token was already retired, no later
frame could revive it — the pane stayed dark. It also short-circuited the park
cooldown, since parkedAt was never set on an entry that no longer existed.

Only an explicit false stops us now. The proven-exit clause still pins that.

* fix(terminal): do not unbind a live shell the new-terminal spawn adopted

While the card is up the pane keeps its durable binding on purpose, so a failed
replacement can put the card back. But main resolves a stable pane's owner from
that same binding: if the shell answers again between the failed reattach and the
click, the spawn adopts it and returns its id. Nothing was replaced, and clearing
the binding then unbound a shell that is live and attached to this very pane —
leaving it running with no durable record of what it owns.

Detected by identity: an id equal to the one we were replacing means adoption,
not replacement. Suppressing adoption outright would need a new spawn option
plumbed renderer -> transport -> IPC; the user-visible oddity that remains is
getting the old shell back rather than a new one, which is benign next to
orphaning it.

* feat(ssh): record the host-attested shell identity on the lease

A lease names a shell by ptyId, and ptyId alone cannot identify one: a replaced
relay restarts its ids at pty-1, so the same id can name somebody else's shell.
This adds the missing primitive — the incarnation the HOST attested — so a later
change can tell "my shell" from "a different shell wearing its id". No behaviour
changes yet; nothing reads the field.

Only host-attested values are stored. The provider synthesizes a stand-in when a
host reports none; that stand-in is first-write-wins and is dropped when provider
state resets, so the same live shell can present a different one after a
reconnect. Recording that would later read as a different shell and strand a live
pane, so it is refused, and the synthesizer now shares the prefix constant with
the predicate that rejects it.

Leases are rebuilt field by field on load, so the normalizer had to learn the
field too — adding it to the type alone drops it on every boot, which is how a
fence ships silently permitting everything. The oracle reddens on exactly that.

* fix(ssh): fence a recycled relay PTY id on the shell's own identity

A reset relay restarts its ids at pty-1, so an id alone can name somebody else's
shell: a pane still bound to pty-1 could attach to a shell another pane was
already driving, and the two would share keystrokes and output.

The guard that used to catch this compared the paneKey and tabId frozen at spawn.
It was removed for good reason — a pane moved to another tab was refused its own
live shell, and refused as "not found", which read as death and resumed the agent
a second time. So it traded a cross-attach for a double resume.

The incarnation is the shell's OWN identity, so it discriminates a recycled id
without caring where the pane lives: both failures close at once. The relay
refuses a mismatch and is deliberately not worded "not found" — that phrasing is
what the client maps to an expired session, and expiry authorizes a respawn onto
a shell this branch just proved is alive.

Only a host-attested expectation is sent. The locally synthesized stand-in is not
stable across reconnects and would refuse a pane its own shell. An older relay
ignores the field and an older client sends none, so both stay permissive.

The tab-keyed comparator is deleted rather than left dormant, and its suite is
inverted onto the new identity: a recycled id is still refused, and a pane that
moved tabs now attaches instead of being told its shell is gone.

* fix(ssh): only an exit the relay watched may authorize a replacement

A bare not-found became SSH_SESSION_EXPIRED, and expiry authorizes a respawn.
But "the relay I asked cannot hand that id back" proves an exit only if that
relay is the one that minted it — a replaced relay answers exactly this for
shells still running under its predecessor. So after a relay restart, live
orphaned shells were read as dead: ownership cleared, lease expired, and the
agent resumed a second time onto a transcript its first process was still
writing to.

The relay now keeps what it actually observed. On a real exit, and on the
liveness probe that finds a pid gone, it remembers {code, incarnation} in a
bounded map and answers a later attach with SSH_PTY_EXITED instead of throwing
that knowledge away. That is first-hand, same-process evidence, and it is the
only answer that now maps to expiry.

A remembered exit for a DIFFERENT incarnation is not an answer about the caller's
shell, so a recycled id cannot report a stranger's death as its own. A crash
loses the map, which correctly reads as no knowledge rather than as death.

The carrier is the message text: the relay's error transport keeps only a message
and a numeric code, so a structured payload would not survive. It is deliberately
worded to avoid "not found", which older clients map to expiry.

Cost, stated plainly: against a relay too old to remember exits, a genuinely dead
shell is now unproven, so the pane offers the disconnected card instead of
replacing itself. That is the affordance's purpose, and it is the safe direction.

* fix(ssh): a remembered exit answers only the shell that asked for it

Review found three ways the new proof could be believed too easily.

A caller that names no shell was still handed a remembered exit. That is the same
double resume in a new costume: relay A is killed leaving pty-1 alive and
orphaned, relay B mints its own pty-1 and THAT one exits, and a pane carrying no
recorded identity would be told its shell is gone — then replace a process still
running. The expectation must now be present AND match. Panes with nothing to
compare get the disconnected card, which is the direction that cannot lose work.

The proof is also gated on the client declaring it understands it. What the host
answers reaches clients that predate the reply, and one of those reads an
unrecognised attach error as neither death nor recovery — a stranded pane. Older
clients keep the wording they already act on; nothing is lost, because they could
not have used the proof anyway.

And the match is anchored on the whole grammar rather than the token, with the id
and incarnation percent-encoded. A substring test would let any text that merely
quotes the token stand in for the relay's own observation.

Two callers that key on "already gone" now also accept a proven exit, so the
liveness-probe reap does not burn a retry before reaching the same conclusion.

The oracle for the first of these was itself vacuous: `toThrow` with a negated
asymmetric matcher passes whenever anything throws at all. It now reads the
thrown message, and reverting the guard reddens it.

* fix(ssh): the liveness reap proves nothing to a caller who named another shell

The remembered-exit route was fixed to require a present, matching expectation.
The liveness probe is the other route to the same claim, and it still answered
anyone: it fires when a pty EXISTS but its pid is gone, and under a given id a
replacement relay may hold a shell that is not the caller's at all. Its death is
then no evidence about a pane whose own shell may be running orphaned under the
relay this one replaced — and the reply authorizes replacing it.

Both routes now demand the same thing. The reap still happens either way, because
a dead shell should be cleared whoever asked; only the answer depends on whose it
was, and a caller who named a different shell is told exactly that.

Found by asking whether the guard ordering was right, after the first fix closed
only the half that had been reported.

* fix(ssh): the client checks whose exit the proof is about

Enforcement lived only on the host. But the host is the party whose answer is in
question, and mixed versions are the normal state — a host that applies the rule
loosely, or not at all, could hand back an exit for a shell the pane never owned
and the client would replace a process that is still running.

The incarnation travels in the proof precisely so the asking side can check it.
A proof that cannot be tied to the shell this pane asked about is not proof, and
falls through to the disconnected pane. A pane that knows no incarnation cannot
verify anything, so it does not get to act on one either.

Both halves now apply the same rule independently, which is what makes it hold
across versions rather than only when both ends agree.

* fix(ssh): fence the reconnect path too, not just the pane-driven restore

There are two client attach routes and only one was fenced. The pane-driven
restore goes through reattachSshPtySession, which was sending the shell identity;
the relay session's own reattach — the one that reconnects EVERY known pty when a
relay comes back — goes through attachForReconnect, which sent nothing.

That is the wrong one to leave open. A relay coming back is exactly when ids have
been reissued from pty-1, so the main reconnect was the likeliest place to attach
somebody else's shell, and it was attaching by id alone.

It now sends the identity the lease recorded, which is what the lease field added
earlier was for; the two halves finally meet. Pane identity is still not sent —
only the shell's own — so a pane that moved tabs is unaffected. It also declares
exit-proof support, so a proven exit can reach the path that reattaches after a
host restart.

Callers with nothing extra to say keep the older call shape, so this does not
churn every reconnect assertion in the suite over trailing undefineds.

* fix(ssh): actually write the shell identity the reconnect fence reads

The lease field was declared, preserved on load, and read on reconnect — and
never written. Both spawn writers omitted it, so every lease carried only
"pty-N", the reconnect always took the no-expectation path, and the fence added
for it could not fire. The main reconnect went on attaching by id alone, which
is the replaced-relay case the fence exists for.

Worse than inert: a successful unfenced attach durably binds the pane to
whatever answered, so the wrong identity would be recorded and carried forward.

The host attests the identity at spawn and it was already in scope one line
above both writers.

The oracle for this had to pin the WRITE. Every other clause — the type, the
loader, the reader, the reconnect forwarding — was green throughout, because
each was correct in isolation; only nothing joined them. The test that covers
the spawn now seeds a host incarnation and requires it on the persisted lease,
and removing either writer reddens it.

* refactor(ssh): one home for the exit-proof rule, and comments the house style allows

AGENTS.md asks for brief non-obvious comments, one line where possible. Several
of mine ran to five and eight lines of narrative on the relay's attach path,
which is the one place a reviewer most needs to scan the branching quickly. They
now say the same thing shorter.

Both gone-paths in attach() had independently spelled out the rule that proof
must name the caller's own shell. That duplication is what let the earlier fix
close one and miss the other, so the condition is now a single predicate both
ask — a change to the rule cannot reach one path and skip the other.

The renderer kept its own copy of SSH_SESSION_EXPIRED while this branch created
a shared home for exactly that token, whose whole reason for existing is that the
two copies once disagreed about an identity mismatch and the renderer respawned a
live shell. It imports the shared one now.

Not changed, after checking: the per-generation recovery budget still does not
reset on a successful reattach. Resetting it looks obviously right and is wrong —
a flapping PTY alternates failure and success, and a covering test drives exactly
that for forty rounds. The park cooldown already bounds the harm.

* fix(ssh): keep the pane fence for clients that cannot name a shell

Deleting the relay's pane-identity comparison disarmed the recycled-id guard for
every client that has not upgraded. The relay is shared and host-side: one person
updating a host would leave their colleagues attaching by id alone, with nothing
checking it in either direction.

It is back as a FALLBACK, used only when the caller sends no incarnation. A
client that can name the shell is still fenced on that and still attaches after
moving tabs; a client that cannot gets the older, coarser check it was already
living with rather than none at all.

The two clauses inverted when it was deleted are restored, because they send pane
identity with no incarnation — the old-client shape, which should be refused. The
moved-pane property they used to contradict is pinned separately by the clause
that sends an incarnation, and reverting the override reddens it.

* fix(ssh): a bare not-found must not retire a pane's owner

Retiring a stable pane's owner authorizes a replacement that carries the pane's
agent resume payload. Until this branch, an SSH reattach failure reached that
decision as SSH_SESSION_EXPIRED, which the gone-check did not match, so it never
fired for SSH. Retiring the not-found mapping changed that: the raw
`PTY "<id>" not found` now matches, so a replaced relay answering for a shell its
predecessor is still running would retire the owner, fabricate an exit, and
respawn with the resume payload — the double resume, reintroduced by the commit
meant to prevent it.

For an SSH pane the two proving answers are the relay's own observed exit and the
expiry the reattach mints only after verifying that proof names this shell. A
bare not-found is neither, and now propagates instead: the pane keeps its owner
and surfaces as disconnected.

Local and daemon ptys are unchanged — their provider owns its ptys, so absence
really is proof. The shutdown paths that also use the gone-check are untouched:
there, "not found" is the outcome being asked for.

The covering test drove the dangerous shape directly — bare not-found, retire,
respawn with `codex resume …`. It now drives the proof, and the bare not-found
case is pinned beside it.

* fix(ssh): retire a lease the relay proved dead

Reattach failure left every record untouched, including the one answer that
settles it. A shell the relay watched exit kept a live lease, so every later
reconnect fanned out an attach for it — two attempts and a ten-second deadline
each — and the set only grew, in a file written to disk.

A proven exit now retires the record. `terminated`, not `expired`: expiry is the
state the recovery grant reads, and retiring a record must not also authorise a
replacement.

Everything else is unchanged and still leaves the pane detached and recoverable,
which is the point — a not-found is also what a replaced relay answers for shells
its predecessor is still running.

* fix(ipc): one import of the incarnation module, not two

CI's code-quality plugins deny a second import of a module already imported in
the same file; the pre-commit hook runs a different oxlint config and did not
see it. Both failing checks were this: `verify` is a gate that only reported
static analysis, with typecheck, tests and both package jobs already green.

* fix(ssh): harden PTY reattach reliability

* fix(persistence): fence duplicate lease rollback

* test(pty): pin incarnation write fence

* fix(ui): center narrow terminal recovery actions

* fix(ssh): make the unreachable-pane state reachable, and its actions work

The decisive cases for this affordance have sat at `fixme` because the state was
not inducible: the card needs the SSH target CONNECTED while exactly one pane's
attach fails without proving the shell gone, and every host-side fault takes the
whole connection down instead. So the behaviour was only ever argued from
reading, which is how several oracles here ended up green for the wrong reason.

It is inducible now, using the fence this branch added for another purpose: the
relay refuses an attach whose expected incarnation names a different shell, which
is per-pty and leaves the connection healthy. Rewriting a pane's recorded
identity while the app is closed reproduces it deterministically.

Running it immediately found two defects that reading had not:

The error toast painted over the card. It renders at z-50 in the same bottom
strip and was suppressed only for the connection overlay, not for the pane's own
card — so in the one state this affordance exists for, BOTH its actions were
unclickable.

"Start a new terminal" then did nothing at all: no shell, no host change, card
straight back. It routes through the path that resolves the pane's owner and
attaches it, and the owner is the very shell we cannot reach — so the attach
fails and nothing is created. The action now refuses adoption, which is what
makes it a creation. Nothing is killed; the old shell stays alive and unbound.

Honest status: the gate is NOT green. The card now clears and the action runs,
but shell creation is not yet observed reliably across runs. Committing so the
oracle and both fixes are not lost; the remaining failure is the next work.

* fix(ssh): a session id is the instruction to attach, so a refused adoption drops it

Skipping stable-pane owner resolution in main was not enough: the action still
sent the pane's recorded sessionId, and the provider reattaches on that before
any owner logic runs. So "Start a new terminal" kept attaching the very shell it
could not reach, and created nothing.

The id is now dropped at the last gate before the IPC, where it cannot be
reintroduced by a caller that forgets.

Also records what running the gate has established so far, including the one
defect still open: with both fixes in, the click still produces no spawn at all
(visible=true launches=1 shells=1), while the main log over the same window shows
only the pane's own restore retries. The evidence points at the action closure
belonging to a superseded connection, not at the spawn path — so the next step is
to instrument the handler rather than add a third spawn-path guard.

* docs(ssh): locate the remaining defect — main re-derives the session id

Instrumented the handler, the transport and main in one correlated run. The
closure hypothesis was wrong: the handler runs, the connection is live, and the
renderer half is correct — it sends no session id and asks for adoption to be
refused. Main re-derives the id anyway, attaches the unreachable shell, and the
spawn rejects, so the action resolves null and the card returns.

That narrows it from "a renderer race" to one gate in main:
createFreshShellForUnreachablePane covers only the early owner resolution, while
a second site downstream still passes sessionId: owner.ptyId to the provider.

Recorded with the evidence and the shortlist of call sites, plus the instruction
to gate where the owner is CONSUMED rather than adding a third condition at a
third producer — this is the same rule leaking at a third site, which is the
signature this branch keeps producing.

* fix(ssh): refuse adoption where the owner is consumed, not where it is derived

The unreachable pane's "start a new terminal" still attached the shell it could
not reach. The renderer was already correct — instrumenting handler, transport
and main together showed it sending no session id and asking for adoption to be
refused, while main re-derived the id anyway.

The rule had been applied at the two places an owner is PRODUCED and missed at
the one place it is CONSUMED: spawnForStablePane turns an owner into `sessionId`
for the provider, which is what makes an attach an attach. Gating there closes it
for every producer at once.

The decisive E2E now passes: with the target connected and one pane unreachable,
the action creates exactly one shell, leaves the unproven old shell running and
unbound, and clears the card. Reverting the single condition reddens it.

This rule leaked at three sites in a row and each fix was necessary while none
was sufficient. The one that held was placed where the value is used.

* refactor(terminal): the same-id guard now protects a new shell, not an adoption

Refusing adoption removed the case this guard was written for. What remains is
the opposite: a reset relay can reissue the old id to a genuinely NEW shell, and
main has already bound the pane to it — so clearing by that id would unbind the
shell just created. Same code, and it is still needed; the comment said the wrong
reason, which is how the next reader deletes it.

This also closes the planned "tell the user we recovered your terminal" work as
obsolete: there is no silent recovery left to announce, because the action now
always creates.

---------

Co-authored-by: Orca <help@stably.ai>
2026-08-13 01:36:01 -07:00
Neil 54e01e6df8 test(wire): select stable desktop release baselines (#14156) 2026-08-13 00:59:56 -07:00
Jinwoo Hong 06780260c0 test(remote-runtime): run an old client and an old server against current code (#12682)
Mixed versions are the normal state of the remote-server feature: users update clients and servers independently. Until now nothing tested that. Every cross-version claim was made by code reading plus unit tests with hand-written old/new shapes — enough to catch design problems, not enough to catch a real skew regression.

This runs the REAL protocol implementations from two builds against each other in one process: the actual host methods and RPC dispatcher on one side, the actual renderer multiplexer on the other, with a transport that reproduces the production asymmetry — each side decodes with its OWN codec and drops frames whose opcode it does not know. A frame survives only if the RECEIVING build understands it, which is what makes this level sufficient without launching two apps. The old side is a genuine checkout extracted from the release tag; the extracted client was confirmed to lack a symbol that exists only on main.

Journey: subscribe, first snapshot, input reaching the process, live output, hide/reveal snapshot, transport drop, resubscribe, input landing again — across old->new, new->old, and a current/current control. Every step ends on an observed-state barrier; no sleeps. The oracle asserts the recorded step list, the exact 16-frame named sequence, negotiated capabilities, the exact input the host wrote to the PTY, rendered content, and zero decoder-rejected frames. A host method the stub lacks is recorded by name and asserted empty, so a harness gap cannot masquerade as a wire break.

Detection is proven per violation shape, and it attributes each to the correct side: an unnegotiated opcode goes red only where a decoder would reject it, a removed published field goes red only where an old client consumes it, and a legal additive field stays green in all three pairings so the harness will not cry wolf on safe changes.

It also documents the three compatibility rules in docs/reference/remote-wire-compatibility.md, linked from AGENTS.md, since they previously existed only as folklore — notably that "decoders reject unknown opcodes" is true for the desktop decoder but NOT for mobile, which silently drops them.

Deliberately scoped: terminal stream only. The session-tab sync channel is not covered, nor agent-session publications, file/Git RPCs, mobile E2EE framing, or the relay transport. Two version points, so a regression introduced and reverted between them is invisible.

CI selection was verified rather than assumed — `vitest list` confirms 0 matches under the shard's exclude and 4 under the dedicated job — because a lane silently running zero tests is precisely how a host-side defect escaped CI earlier in this series. Closes STA-3469.
2026-08-05 01:31:29 -07:00