Skip to content

feat(orchestration): orchestrate native-born structured chat sessions - #18827

Merged
brennanb2025 merged 37 commits into
mainfrom
brennanb2025/orchestration-structured-delivery
Sep 7, 2026
Merged

brennanb2025 merged 37 commits into
mainfrom
brennanb2025/orchestration-structured-delivery

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 58 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​6622 $\color{#cf222e}{\Huge{\mathbf{−}}}$​384 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​6238
Prod 116 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4815 $\color{#cf222e}{\Huge{\mathbf{−}}}$​616 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4199

What

Orchestration can now start, dispatch to, mail, read, stop and release a native-born structured native chat session (Claude or Codex) as a worker.

There is no flag. The worker mode follows the user's own setting for new agent tabs: with structured native chat on by default, a local Claude/Codex worker starts as a structured chat session. Where a dispatch cannot be structured, it starts as a normal terminal worker anyway and says why — fallback, never refusal, and never silent.

Before this, a structured session was not merely refused by orchestration — it was invisible. Orchestration resolves every worker through a terminal handle and a pane key backed by a live PTY; a session created directly as structured is published as {type:'agent-session', id:'agent-session:<sessionId>', sessionId, agent} with no ptyId, leafId, paneKey or term_ handle, so nothing in the dispatch, mail, or lifecycle paths could name it.

How

A second authority source, not a parameter channel. orchestration.send and verifyDispatchCapability are untouched. They keep deriving sender identity host-side and keep ignoring anything the CLI claims. Instead, a registry (structured-worker-identity.ts) maps a session id to the same three facts the PTY path supplies — a bearer handle, a pane key, and a host scope — and the four runtime getters consult it before giving up on ptysById:

  • getOrchestrationDispatchAuthority
  • getTerminalPaneKey
  • getTerminalProcessIncarnation
  • getLiveTerminalPaneKey

PTY handles short-circuit on the structworker_ prefix, so the existing terminal path is untouched.

Delivery is a sibling lane to the PTY pointer path, not a fork of it: same outstanding-run, waiter, reserved-type and batch-limit rules. The nudge travels as a session turn instead of as bytes, because a structured session has no PTY to type into. Orchestration's database stays the source of truth — the send is best-effort, exactly as the byte write is today, and mail is consumed only on a proven-accepted dispatch.

Readiness is attach returning ok. There is no boot-then-idle gap to wait through, so the structured branch skips tui-idle entirely.

Security properties

These are the crux of the change and each is pinned by test:

  • The pane key's leaf is random and persisted, never derived. orchestration.check is identity-gated, not capability-gated: it falls back to a caller-supplied terminalPaneKey, and dispatch lookup matches assignee_pane_key directly. A derivable leaf would let anyone who learns a session id — tab ids embed it in plain text — read and consume that worker's mailbox with no token. PTY pane keys are safe only because their leaf is a random UUID; these match that.
  • The handle is a random bearer token and deliberately not term_-prefixed, because issueHandle revalidates the renderer graph epoch and a main-minted term_ leaf would evaporate on window reload.
  • ORCA_PANE_KEY is not injected into the structured child. Only ORCA_TERMINAL_HANDLE and ORCA_CLI_COMMAND. Claude structured sessions run hooks, and a pane key there would flow into hook-attestation and agent-row pipelines that all assume a pane key names a PTY leaf.
  • Hook attestation stays closed for structured handles — the structured authority leaves launchTokenHash and ptyId empty, and the test covers a fabricated empty-ptyId receipt.
  • Process continuity comes from record lineage, never the runtime fence. The fence is an owner-generation counter that the host bumps during its own transparent crash recovery; fencing identity on it would make a recovered-but-identical worker fail capability verification forever and wedge release as identity_unproven.
  • A resume-capable hold is taken at start and released on settlement. Without it the release clock evicts the provider child 15s after the last holder leaves, so a user opening and closing the worker's chat tab would kill an idle worker mid-dispatch.

Delivery correctness

  • Mail is consumed only on dispatchState === 'accepted'. Both rejected and unknown retain — a dead provider child settles unknown, never rejected, so treating it as delivered would be silent mail loss.
  • Delivery waits for the session to be between turns. Mid-turn is refused for both providers rather than delegated to them: one answers a mid-turn turn-start with turn already running, the other accepts the frame but cannot acknowledge inside the dispatch ack window. Waiting is the one contract that holds for both, and it preserves orchestration's existing idle-edge-only policy.
  • A turn settles by tombstone, not by a completed row, and the history tail page can lie if a running lifecycle item is paged out behind a burst of tool calls — so a full page carrying no lifecycle item reads as busy.
  • Pending approvals and questions are treated as busy, since they have no running turn but only a human can clear them.
  • Operation ids are durable per pointer batch and re-minted on batch growth and 24h expiry.

Also in this change

  • The "Orchestration paused" notice is removed. It gated only on dispatchStatus and never checked for a structured session, so it also rendered over bridge chat — a live TUI where orchestration works normally.
  • The implicit-sender fallback now refuses when a worktree has more than one candidate leaf, instead of silently picking an arbitrary first one. That closes the same misattribution for PTY workers with stripped env, which exists today.
  • Archive kinds are now one named type with a compile-time assertion that the capture set cannot drift ahead of the storable set. The previous hand-widened copies were how a kind could reach a durable row the read side could not answer — which blocks worker-release and leaks the dispatch's resources.

What this changes for you

Starting a worker

Before — orca orchestration worker-start could only ever create a TUI terminal worker. If you had structured native chat set as your default for new agent tabs, your orchestration workers ignored that and came up as terminal agents anyway.

After — the worker mode follows your own setting. With structured native chat on by default, a local Claude/Codex worker starts as a structured chat session. There is no flag. Where a dispatch cannot be structured — a remote --on, a reused --terminal, a worktree-creating placement, --model/--effort, a non-Claude/Codex agent, WSL, Codex on Windows — it still starts, as a terminal worker, and the receipt names which mode ran and why. Nothing is refused for being unstructurable, and nothing falls back silently.

Orchestrating a structured chat session at all

Before — a session created directly as structured chat was invisible to orchestration, not merely refused. It could not be started as a worker, could not be named as a dispatch target, and could not receive mail. Orchestration resolves every worker through a terminal handle and pane key backed by a live PTY, and a structured session has neither.

After — structured sessions are first-class orchestration workers: worker-start, dispatch, mail, worker_done, worker-show, worker-read, worker-stop, worker-abandon, worker-release all work.

Mail to a worker whose pane is in structured chat

Before — if a worker's pane was adopted into Structured Chat, orchestration mail to it silently queued. The chat pane showed an "Orchestration paused" banner — which was also shown over ordinary bridge chat, where orchestration worked perfectly well.

After — mail is delivered into the session as a turn. The banner is gone, because it is no longer true anywhere.

A worker reporting back

Before — a structured worker running the worker_done line it was taught would fail capability verification, and the message was converted to a rejection. The dispatch never settled, the coordinator's check --wait blocked to its timeout, and the worker could retry in a loop.

After — a structured worker's identity resolves host-side like any other, so send, check, ask, reply and worker_done all behave identically to a terminal worker's.

Reading, stopping and releasing a structured worker

Before — worker-read threw worker_identity_changed for a worker whose identity had not changed. worker-stop returned three separate "could not confirm" receipts and never actually stopped the provider child. worker-release failed with archive_failed, so the dispatch's resources were never freed.

After — read serves the session journal, stop routes to the real session close and only settles on a proven exit, and release archives the journal instead of failing.

⚠️ Behaviour change for EXISTING terminal workers — needs a release note

This is the one change here that is not scoped to structured sessions. It alters shipped orca CLI behaviour for ordinary PTY terminal workers.

What changed. When an orchestration command has to work out which terminal the caller is — an implicit --from, i.e. no --from flag and no ORCA_TERMINAL_HANDLE in the environment — it used to fall back through three guesses in order:

  1. the active mobile-session tab (where the user last looked),
  2. the tab's activeLeafId (the last-focused pane),
  3. any leaf in the target worktree, first in iteration order.

All three answer "which terminal am I?" with someone else's pane. For an identity claim, all three are now skipped, and the command refuses with no_active_terminal — surfaced by the CLI as no_active_sender_terminal with guidance — whenever more than one terminal in that worktree could have been meant. The same refusal applies on the graph-not-ready path, which had the identical arbitrary pick.

Who notices. Anyone running orca orchestration send / ask / a lifecycle verb without --from and without ORCA_TERMINAL_HANDLE set, in a worktree containing more than one terminal. That used to succeed silently against an arbitrary terminal; it now fails with an actionable error telling you to pass --from. A worktree with a single terminal is unaffected, and any caller that passes --from or has the env var — which is every agent Orca launches — is unaffected.

Why it is worth the break. The arbitrary pick was a real misattribution, not a cosmetic one: a bare send --type worker_done could settle a sibling's context-only dispatch — a tier with no capability token to reject on — and every message sent that way was attributed to the sibling terminal.

Scope. Only the implicit-sender resolution opts in (resolveImplicitOrchestrationSender). orca terminal … and every other getTerminalHandle caller pass no option and are byte-for-byte unchanged. orchestration check resolves through the --terminal scope, which still guesses and is untouched by this PR.

What an agent sees

Before — n/a (structured workers did not exist).

After — nothing mode-specific. The dispatch preamble is byte-identical either way, a structured worker can dispatch sub-workers exactly like a terminal one, and the orchestration skill guide needs no "if structured…" caveat anywhere. The worker mode is a runtime detail, not part of the orchestration contract.

CLI parity — what works, and what does not

An audit after the first review round found that structured workers were second-class across the CLI in ways the earlier description overclaimed. Nine of eleven gaps are fixed here; two are deferred with reasons. A later round then found a silent-misdelivery defect in one of this PR's own new verbs, fixed below. This section is the honest picture.

Fixed in this PR

  • orca worktree rm no longer destroys a live structured session. It previously ran three PTY-derived sweeps and nothing else, so a worktree containing only structured sessions looked empty: removal proceeded, the provider child kept running with its cwd deleted, the dispatch stayed dispatched, and worker-show reported the worker healthy and live. Uncommitted work was lost. A new sweep now refuses without --force, and closes properly with it. This is a new failure on a destructive verb — see the behaviour-change note below.
  • A structured worker can now use its own identity. Twelve coordinator verbs (run-create, task-create, worker-start, the gate verbs, dispatch, …) resolved the caller by validating ORCA_TERMINAL_HANDLE through terminal.show, which has no structured branch, so every one failed with no_active_sender_terminal — including the sub-dispatch commands the preamble itself teaches. A new read-only terminal.resolveIdentity answers for both lanes.
  • dispatch --to … --inject no longer reports no_agent_detected for a session that has an agent.
  • Group addressing (@all, @idle, @claude, @codex, @worktree:) no longer silently omits structured workers. @idle reads liveness from the full journal timeline, because a bounded page reads a busy worker as idle.
  • run: mail now nudges a structured coordinator. Both delivery lanes previously declined it, each believing the other owned that mailbox.
  • worker-release no longer closes a session a user has taken over. The takeover signal was PTY-only, so the user_owned guard was intact but never armed — and the spec explicitly promises the opposite.
  • A plain structured chat session's bare orchestration check no longer consumes a sibling's mailbox. Such sessions have no orchestration identity, so check resolved to a neighbouring pane and destructively consumed its batch. They now carry a marker and the command refuses instead of guessing.
  • orca terminal verbs refuse with an accurate reason pointing at the structured equivalent, instead of claiming the handle went stale.
  • orca orchestration worker-read --source transcript no longer silently misdelivers. Its cursor fingerprinted only the oldest item on the page, so it could not detect the page being revised underneath a poller. A coordinator watching a worker could skip lines it never saw, or re-read lines it already had, with no signal either way — the failure was silent in both directions. The cursor now anchors on the oldest item plus every item below the caller's position, by id and revision. Ablated both ways: reverting to the old anchor reddens exactly the two silent shapes (in-place revision, mid-array insert) and nothing else; widening the anchor to the whole page reddens unread-tail growth. The frozen archive keeps a constant identity, since nothing there can be revised under a caller.

Not fixed — deferred, with reasons

  • terminal list and worktree ps do not show structured workers, so a worktree with a busy structured worker reads as idle to an agent — while the desktop sidebar already shows it running. An investigation split this into two changes rather than one, and both ship separately from this PR. worktree ps should get them: it is main-process only and needs no wire change — RuntimeWorktreeAgentRow is already a non-PTY shape (paneKey, state, agentType, with no ptyId, connected or writable), both inputs already exist, and the status mapping is already written in the renderer and simply never crosses into main. terminal list should not. Every safe consumer of a terminal summary checks ptyId, but the breaking ones key off connected or mere row presence, which no added field can qualify: mobile mounts a terminal WebView per row that can never receive a frame; a connected && !inSessionTabs check goes permanently true and pins shipped mobile clients to a fast refresh cadence with no exit; and in main, a worktree holding one PTY plus one structured session starts refusing caller identity claims from the row count alone. The plugin projection has no field that can carry writable: false at all. The follow-up instead publishes an honest partial-listing count — "N agent sessions not listed" — which needs no handle and no pane key.
  • terminal read on a structured worker does not support cursor paging, and no windowed read should be added later. It returns the recent tail; a cursor read refuses. An earlier revision of this section gave the wrong reason — it claimed the journal had stable item identity and only terminal.read's numeric cursor stood in the way, and the refusal text acted on that by pointing callers at another verb. Both are corrected here. The journal is a reduced, mutable timeline: a tool item gains its result text at its original sequence after later items already exist, the delta coalescer revises items repeatedly, settlement can rewrite an item smaller, a pending approval renders as nothing and then as something, and sequence resets on epoch rollover. No bare position index survives that, numeric or opaque. The decisive point is the failure direction: a broken cursor fails unsafe, as a silent hole in a poller's output (precisely the defect fixed above), while diffing a bounded tail fails safe, as a harmless re-read. The refusal now states the approach that works — the tail is bounded and newest-last, so poll it and diff — and deliberately names no alternative verb, because there is none. Read this together with the worker-read cursor fix above: they are one decision, not two. What makes that cursor sound is not merely that it is opaque, but that it is opaque enough to carry a fingerprint of the already-delivered prefix — so a revision under the caller is detected and answered with source_changed rather than silently skipped. terminal.read's cursor is a bare number with nowhere to put that fingerprint, and its result shape has no source_changed to answer with, so the same revision would pass undetected. Both surfaces refuse loudly rather than misdeliver; only one of them can page at all.
  • No "orchestration paused" notice for a mid-handoff adopted pane. The notice was removed because it was false for native-born workers and stale for settled adopted panes. It is still warranted in one narrow state — an adopted pane that is mid-handoff — but the condition needs write-gate state that lives in main and never reaches the renderer, and restoring it re-stamps two SHA-pinned hook-order ratchets. Deferred rather than stamp a baseline around an undecided data source.

⚠️ Behaviour change: orca worktree rm can now refuse

Removing a worktree that contains a live structured chat session now fails unless --force is passed. This is deliberate and mirrors the existing unstopped-PTY gate, but it is a new refusal on a command people run frequently, and it is the change most likely to surprise. --force closes the sessions properly rather than orphaning their provider children.

Merged with the durable multi-agent workflow work (#16904)

That PR landed in this same subsystem, so a good part of this branch is now a decision about which of two independent solutions survives. It never generalized past the PTY assumption anywhere, so nothing here became redundant: it hardens the first authority source, this branch adds a second under the same contracts.

  • Schema. Both sides independently wrote a current < 31 migration from a shared base of 30, with different bodies, and main went on to 38 — so 31 named two different schemas, and a database written by this branch failed the skew checker and replayed from v6. That is the checker working correctly, and the replay is row-safe (every DROP in the chain is a copy-forward rebuild gated on shape; no DELETE, no TRUNCATE). Nothing shipped stamped 31 with this content — the commit is in no tag and no release branch — so the migration renumbers to 39. It no longer creates structured_pointer_operations, because createTables runs unconditionally on every open ahead of migration; only the widened archive CHECK needs a migration, since IF NOT EXISTS cannot widen a constraint.
  • A crash this merge fixes. Main's new summarizeWorkerOutputArchive JSON-parses every non-transcript_pin kind as a terminal tail, so this branch's structured_journal reached content.lines.every(...) and threw, at three live call sites. A structured session's journal now reports as transcript — it is the session's transcript, and a third source would leak the structured/terminal split into a CLI surface this PR keeps uniform.
  • Batch selection is genuinely shared again. Both sides changed the same region; main dropped the JS post-filter, and it is provably dead — the unfiltered waiter returns early, so every surviving waiter contributes a concrete type list that SQL excludes byte-exactly, and the trailing slice sits behind an identical SQL LIMIT. Main's simplification is adopted, its lane now calls the shared selector, and the helper's docblock no longer claims to catch a mid-selection waiter, which cannot happen. Nothing covered any of this, so it now has tests against a real database.
  • Delivery gate. This branch gated only run: mailboxes on the premise that a delivery row exists only for a run: address. Main made that false and generalized correctly, keying the lookup on the exact handle being nudged. Adopted — and worth more here than in the PTY lane, since a structured nudge costs a whole provider turn.
  • PTY pointer refusal. Main shipped the same fix independently and narrower, so this branch's hunk is dropped.

One regression this merge restores, which is main's rather than this branch's: the shared ancestor passed canDispatchSubWorkers on the local worker's dispatch preamble; main's extraction of startLocalWorker does not, and buildDispatchPreamble treats its absence as false. So a locally started worker on main is no longer taught the sub-dispatch verbs, and with the default nested depth of 1 that applied to every first-generation worker. Main still passes the same argument at three other call sites, so this reads as a line lost while moving ~300 lines. Restored here for both lanes. Worth fixing on main independently of this PR.

Notes for reviewers

  • Two wire-touching changes, making different compatibility bargains. terminal.resolveIdentity is new, and a client hitting an older host gets method_not_found and falls back to terminal.show — safe, because a host without the probe has no structured workers to miss. orchestration.workerTerminalUserInput widened from a required paneKey to paneKey | sessionId; an older host rejects the new shape at validation and the report, being best-effort, degrades silently to today's behaviour. Worth reviewing as a pair.
  • ORCA_STRUCTURED_SESSION=1 is a new child-env contract. It carries nothing else — no handle, no pane key, no session id, no token — and deliberately does not add the CLI PATH prepend, so it can only ever cause a refusal, never enable a command that previously could not run. The session id is omitted on purpose: a session id is one tab-id hop from the pane key, and the pane key is a credential.
  • getLiveLeafForHandle throws a different error for structured handles, which changes classifyTerminalProcessInspectionFailure from terminal_gone to unclassified for those handles. That is an improvement — terminal_gone was itself a false claim, since the session is alive — but it is a classification change at a widely-called choke point.
  • @idle performs a full journal reduction per structured worker per group send. Required for correctness; negligible at current worker counts, but relevant if fan-out grows.
  • Two files were split rather than waived to stay under max-lines. Note orchestration.test.ts was sitting at exactly 800 lines before this branch touched it — one line from breaking for anyone.

Why a structured worker gets a handle and a pane key

A structured session has no PTY, so it is fair to ask why it is given a terminal-shaped handle and a pane key at all.

Because those are not a claim that a terminal exists — they are orchestration's identity primitive. Dispatch rows, mail routing, capability verification and the worker-lifecycle verbs are all keyed on a handle plus a pane key. Every worker needs one. Giving a structured session those two facts is not dressing it up as a terminal; it is giving it the same identity every other worker already has.

The alternative — teaching orchestration a second kind of target — would push the distinction all the way out to the agents. A worker would have to know which kind it is before choosing a verb, a coordinator would have to branch on it, and the orchestration skill guide would need an "if structured… otherwise…" caveat on most of its commands. That guide is loaded into every orchestrating agent's context, so the cost is paid on every session, in exchange for a distinction that is irrelevant to the work the agent is doing. It is also a reliable source of bugs: agents branching on a runtime detail they cannot verify will get it wrong.

So the uniformity is deliberate, and it is scoped to the contract layer: what an agent is taught, what it runs, and what it reads back. The orchestration skill guide required no changes for this PR, which is the practical evidence that the abstraction holds.

Where the abstraction deliberately stops. The moment something asks a process question rather than an identity question, a structured session answers honestly or refuses — it never fabricates:

  • terminal.show does not resolve a structured handle. It returns a ptyId, a leaf id and a pane runtime id, and synthesising those would hand every caller of a public terminal verb something that looks writable and is not.
  • worker-show returns terminal: null for a structured worker rather than inventing a terminal summary.
  • Liveness uses live / unverifiable / exited. Squashing that into connected: boolean would report a running worker as exited on loss of contact — the inversion docs/reference/ssh-execution-boundary.md forbids.
  • The structured authority leaves ptyId and launchTokenHash empty, which is what keeps hook attestation closed for a session that has no PTY, no launch secret and no hook to attest with.

The one fact worker-start genuinely needs from a coordinator — its worktree id — is resolved from the dispatch authority rather than by routing through showTerminal, precisely so that no fake terminal has to be produced to get it.

A consequence worth stating: because the pane key is part of orchestration's identity, and orchestration.check is identity-gated rather than capability-gated, the pane key is effectively a credential. That is why a structured worker's pane-key leaf is randomly minted and persisted rather than derived from anything guessable, and why there is a test that fails if it is ever "simplified" back to a derivable value.

Agents cannot tell which mode they are in

The worker mode is an implementation detail of the runtime, not part of the orchestration contract. Neither a worker nor a coordinator is taught, or asked to read, anything that differs by mode.

  • The dispatch preamble is byte-identical in both modes, pinned by a test that starts the same task twice and compares after normalising ids.
  • canDispatchSubWorkers is depth-only. A structured worker dispatches sub-workers exactly like a PTY one — proven with showTerminal mocked to reject and asserted never called.
  • worker-read presents uniformly; a coordinator never branches on mode.
  • The orchestration skill guide needs no "if structured…" caveat anywhere.

Three residual asymmetries are documented rather than hidden, none referenced by any instruction an agent reads: mode exists in the worker-start receipt JSON (the CLI prints the reason for humans; nothing tells an agent to read the field); worker-show returns terminal: null for a structured worker; and terminal.show does not resolve a structured worker handle, because connected/writable derive from a single boolean that cannot express the three-valued liveness verdict and ptyId has no honest value.

Tab visibility (resolved by #18906)

A structured worker's tab was initially invisible in the renderer: the session was addressable and its transcript readable, but the tab never reached the tab bar.

That was a pre-existing renderer defect which this change was simply the first to make reachable — the normal user launch path self-heals, and orchestration has no renderer-side launcher to do so. A publication epoch is inherited rather than minted per generation, so once a live publisher's epoch had been retired by a transient interloper, every later frame reusing it was dropped permanently.

Fixed separately in #18906, now merged and included here.

Out of scope

  • A structured session as a Run's own top-level coordinator was not a validation target. A structured worker can dispatch sub-workers — canDispatchSubWorkers is depth-only and mode-independent.
  • SSH / WSL. Structured sessions require a local execution host and no WSL distro, so remote plumbing is deliberately absent.
  • Nothing is refused for being unstructurable. A remote --on, a reused --terminal, a worktree-creating placement, --model/--effort, a non-Claude/Codex agent, WSL and Codex-on-Windows each fall back to a terminal worker with a named reason in the receipt.

Testing

pnpm tc clean, oxlint clean, oxfmt clean.

Merged with main, which landed a native-chat routing fix in that span. Both conflicts were the same shape: main fixed code this branch had already extracted elsewhere, so keeping either conflict side alone would have silently reverted it. Main's own routing test was red on the merge before the ports and green after, which is what proves they are load-bearing rather than cosmetic. Full suite after the merge: 1920 files / 20111 tests passed, 0 failed, pnpm tc clean, tree clean.

Unit and integration coverage for the identity registry, the four getters, the delivery lane, operation-id lifetime, the hold, stop/abandon/release settlement, the archive round-trip, and the v31 migration's old-row survival. The security invariants above each have a dedicated pin, and the ptyId-emptiness pin was ablated to confirm it actually reddens.

Validated in isolated Electron instances against real Claude and Codex sessions, with instance ownership proven each time and the structured-chat settings seeded before first paint.

Verified in the running app for both providers: a structured worker starts, its dispatch preamble is visible in the chat, worker_done settles the dispatch, worker-read returns the session journal, worker-stop / worker-release settle, and the "Orchestration paused" banner is absent.

Precisely what the mail evidence covers. The structured nudge — a user turn reading "You have N orchestration messages…" — was observed directly for Codex. For Claude, the worker under test was parked on orchestration check --wait, so the mail reached it through the long-poll waiter rather than the structured pointer lane; an open waiter deliberately suppresses pointer delivery, so that run did not exercise this PR's delivery path for Claude. That case is being re-run against a Claude worker with no waiter open, including a mid-turn send retained and delivered once on settle. Screenshots are on the PR.

Structured sessions require a local execution host and no WSL, so this cannot be a mobile, Windows/WSL or SSH change; those lanes were skipped by design rather than overlooked.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ Minor suggestions only — the orchestration change itself is thorough and well-pinned by tests; two defer-able cleanups/observations below.

Reviewed changes

  • Structured worker identity registry (structured-worker-identity.ts + structured-worker-authority.ts) — a second authority source mapping a session id to a bearer handle, a random persisted pane key, and a host scope, consulted by the four runtime getters before they give up on ptysById.
  • Structured delivery lane (structured-mailbox-pointer-delivery.ts, structured-session-pointer-delivery.ts, structured-pointer-operation-id.ts) — sibling to the PTY pointer path with the same eligibility rules, but the nudge travels as a session turn and mail is consumed only on an accepted dispatch.
  • Worker lifecycle (orchestration-structured-worker-*.ts, orchestration-local-worker-start.ts) — start with a resume-capable hold, preamble-as-turn, stop/abandon/release settlement, journal archive round-trip, and the observation vocabulary live / unverifiable / exited.
  • Schema v30→v31 — structured_pointer_operations table, worker_terminal_archives rebuilt to admit structured_journal, migration file renamed to migrate-v13-latest.ts.
  • Renderer cleanup — the "Orchestration paused" notice and its orchestrationDispatchStatus prop are removed, since the notice gated only on dispatchStatus and rendered over live bridge chat.

ℹ️ Orphaned renderer subscription left behind

Removing NativeChatOrchestrationPausedNotice and the orchestrationDispatchStatus prop also removed the last consumer of chatPaneDispatchStatus, but the selector and its plumbing were left in place. The value is still subscribed (use-terminal-pane-chat-state.ts:59), threaded through use-terminal-pane-projection.ts into TerminalPaneProjectionController, and read by nothing. It's a redundant reactive subscription to agentStatusByPaneKey[...].orchestration.dispatchStatus that should be deleted with the notice.

Technical details
# Remove orphaned chatPaneDispatchStatus

## Affected sites
- `src/renderer/src/components/terminal-pane/use-terminal-pane-chat-state.ts:59` — the `useAppStore` selector that computes the value.
- `src/renderer/src/components/terminal-pane/use-terminal-pane-chat-state.ts:283` — returns it in the projection.
- `src/renderer/src/components/terminal-pane/use-terminal-pane-projection.ts:28` and `:217` — destructures and re-exposes it on `TerminalPaneProjectionController`.

## Required outcome
- Delete the selector and its plumbing so the dead subscription and the `TerminalPaneProjectionController` field no longer exist.

ℹ️ Restart leaves a surviving structured worker without its hold and redrive

The release path documents (and deliberately defers) that a restarted runtime is not rebound to a structured worker's hold or redrive subscription. A worker that survives a restart therefore keeps no resume-capable hold — its provider child is evictable by the 15s release clock, which is the exact idle-parked-worker kill the hold exists to prevent — and parked mail waits for the next arrival rather than a turn-settle edge. No mail is lost (the DB stays the source of truth and unknown retains), so this degrades rather than corrupts, but it's worth tracking as an explicit follow-up issue so the gap isn't forgotten.

Technical details
# Rebind restarted structured workers

## Affected sites
- `src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts` — the comment that names the gap ("NOT yet handled, and deliberately follow-up: rebinding a restarted runtime to a structured worker's hold and redrive subscription").

## Required outcome
- On startup recovery, re-establish the `orchestration:dispatch:<id>` hold and the `orchestration:redrive:<sessionId>` subscription for any structured worker that still owns a live session.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 15198c3e-dfde-4c47-8f61-b81472a5c2ab

📥 Commits

Reviewing files that changed from the base of the PR and between 8aed3e9 and c3a0cb9.

📒 Files selected for processing (1)
  • src/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.ts

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


📝 Walkthrough

Walkthrough

The PR adds native structured worker startup for local Claude and Codex sessions. It introduces structured worker identities, authority checks, child environment variables, lifecycle operations, journal reads, archives, and mailbox pointer delivery. Worker RPCs now support structured worker start, stop, abandon, observation, release, and output reads. The orchestration database adds structured pointer operations and structured journal archives. Terminal resolution can require an unambiguous result. The native chat paused notice and its localization are removed.

Merge Risk: 🟡 Moderate · up to c3a0c

Structured workers add session-based orchestration, delivery, persistence, and lifecycle behavior. Known issues can strand worker mail after restart or rejection, affect existing database upgrades, mislabel archived output, and leave UI tab state inconsistent; these should be resolved before merge.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.59% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 123 functions across 78 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ⚠️ Warning The required Linked Issue section contains only Fixes # and does not identify an issue. Add a valid linked issue reference, such as Fixes #12345``, under the Linked Issue section.
Description check ⚠️ Warning The description provides extensive technical context, rationale, behavior changes, security details, and testing results, but it does not follow the required template completely. The mandatory Linked … Add the required template sections and complete them. Include a valid issue reference after Fixes #; add an ELI5 summary; provide before/after visual proof or write N/A with a reason; complete AI Disclosure; complete Review and the Agen…
✅ Passed checks (2 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed The changes are broadly aligned with the stated objective of supporting native-born structured Claude and Codex workers. The description also identifies related fixes and explicitly lists excluded are…
Title check ✅ Passed The title clearly summarizes the primary change: orchestration support for native-born structured chat sessions.
Full details: Description check

Explanation

The description provides extensive technical context, rationale, behavior changes, security details, and testing results, but it does not follow the required template completely. The mandatory Linked Issue section has no issue reference, and required sections such as ELI5, Visual Proof, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist are missing or not completed in the specified format.

Resolution

Add the required template sections and complete them. Include a valid issue reference after Fixes #; add an ELI5 summary; provide before/after visual proof or write N/A with a reason; complete AI Disclosure; complete Review and the Agent skill upstream boundary checkbox; add Notes covering the listed risks; and complete the Checklist, including testing and cross-platform considerations.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 8


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 234009d4-2f41-46e4-b4ed-b45c9009a705

📥 Commits

Reviewing files that changed from the base of the PR and between af82126 and 2ef4be9.

📒 Files selected for processing (74)
  • src/cli/handlers/orchestration/terminal-identity.ts
  • src/cli/handlers/orchestration/worker-launch-handler.ts
  • src/cli/selectors.ts
  • src/cli/specs/orchestration-worker-specs.ts
  • src/main/claude/claude-structured-launch-resolution.ts
  • src/main/codex/codex-structured-child-environment.test.ts
  • src/main/codex/codex-structured-child-environment.ts
  • src/main/codex/codex-structured-session-acquire.ts
  • src/main/runtime/orca-runtime-adopt-terminal-orphans-from-inventory.ts
  • src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.ts
  • src/main/runtime/orca-runtime-get-pty-record-for-pane-key.ts
  • src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts
  • src/main/runtime/orca-runtime-stop-requested-pty-ids.ts
  • src/main/runtime/orca-runtime-subscribe-to-terminal-resize.ts
  • src/main/runtime/orca-runtime-write-orchestration-pointer-pty.ts
  • src/main/runtime/orchestration/adopted-structured-pointer-delivery.test.ts
  • src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/contract-constants.ts
  • src/main/runtime/orchestration/db/dispatch-row-writer-boundary.test.ts
  • src/main/runtime/orchestration/db/messages/structured-pointer-operation-store.ts
  • src/main/runtime/orchestration/db/orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts
  • src/main/runtime/orchestration/db/schema/migrate-v13-latest.ts
  • src/main/runtime/orchestration/db/schema/migrate.ts
  • src/main/runtime/orchestration/db/schema/structured-pointer-schema-migration.test.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts
  • src/main/runtime/orchestration/mailbox-delivery-target.ts
  • src/main/runtime/orchestration/mailbox-notification-coordinator.ts
  • src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.ts
  • src/main/runtime/orchestration/structured-mailbox-pointer-delivery.test.ts
  • src/main/runtime/orchestration/structured-mailbox-pointer-delivery.ts
  • src/main/runtime/orchestration/structured-mailbox-pointer-host.ts
  • src/main/runtime/orchestration/structured-pointer-operation-id.test.ts
  • src/main/runtime/orchestration/structured-pointer-operation-id.ts
  • src/main/runtime/orchestration/structured-session-pointer-delivery.test.ts
  • src/main/runtime/orchestration/structured-session-pointer-delivery.ts
  • src/main/runtime/orchestration/structured-worker-journal-archive.ts
  • src/main/runtime/orchestration/worker-output-archive.ts
  • src/main/runtime/orchestration/worker-terminal-ownership.ts
  • src/main/runtime/rpc/methods/orchestration-local-worker-start.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-abandon.test.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-lifecycle.test.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-lifecycle.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-session.test.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-session.ts
  • src/main/runtime/rpc/methods/orchestration-worker-archive-read.ts
  • src/main/runtime/rpc/methods/orchestration-worker-control.ts
  • src/main/runtime/rpc/methods/orchestration-worker-legacy-federated-read.ts
  • src/main/runtime/rpc/methods/orchestration-worker-observation.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-receipts.ts
  • src/main/runtime/rpc/methods/orchestration-worker-start-schema.ts
  • src/main/runtime/rpc/methods/orchestration-worker-stop.ts
  • src/main/runtime/rpc/methods/orchestration-worker-topology.ts
  • src/main/runtime/rpc/methods/orchestration-workers.ts
  • src/main/runtime/rpc/methods/structured-agent-session-create.ts
  • src/main/runtime/rpc/methods/structured-agent-session.ts
  • src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts
  • src/main/runtime/rpc/methods/terminal/unary-schemas.ts
  • src/main/runtime/structured-worker-authority.ts
  • src/main/runtime/structured-worker-child-identity-env.ts
  • src/main/runtime/structured-worker-hook-attestation.test.ts
  • src/main/runtime/structured-worker-identity.test.ts
  • src/main/runtime/structured-worker-identity.ts
  • src/main/runtime/structured-worker-mail-routing.test.ts
  • src/renderer/src/components/native-chat/NativeChatOrchestrationPausedNotice.test.tsx
  • src/renderer/src/components/native-chat/NativeChatOrchestrationPausedNotice.tsx
  • src/renderer/src/components/native-chat/NativeChatResolvedView.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
  • src/renderer/src/components/native-chat/NativeChatView.tsx
  • src/renderer/src/components/native-chat/native-chat-view-types.ts
  • src/renderer/src/components/terminal-pane/TerminalPaneNativeChatPortal.tsx
  • src/renderer/src/i18n/locales/en.json
💤 Files with no reviewable changes (5)
  • src/renderer/src/components/native-chat/NativeChatOrchestrationPausedNotice.tsx
  • src/renderer/src/components/terminal-pane/TerminalPaneNativeChatPortal.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/components/native-chat/NativeChatOrchestrationPausedNotice.test.tsx

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

Comment on lines +231 to +238
if (!structuredDispatchDelivered(outcome.state)) {
this.retain(
mailboxHandle,
sessionId,
retainReasonForDispatch(outcome.state as Exclude<StructuredDispatchState, 'accepted'>),
reservedTypes
)
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Discard the stored operation after a rejected dispatch.

resolveStructuredPointerOperation reuses the same ID for the same session and payload. The host only redispatches IDs whose journal state is unknown; a rejected ID replays its failed ledger outcome. Retained mail can therefore remain blocked until the ID expires or the payload changes.

Delete the operation for rejected, but retain it for unknown to prevent duplicate turns. Add a regression test for rejected retries.

Proposed fix
     if (!structuredDispatchDelivered(outcome.state)) {
+      if (outcome.state === 'rejected') {
+        db.deleteStructuredPointerOperation(mailboxHandle)
+      }
       this.retain(
         mailboxHandle,
         sessionId,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!structuredDispatchDelivered(outcome.state)) {
this.retain(
mailboxHandle,
sessionId,
retainReasonForDispatch(outcome.state as Exclude<StructuredDispatchState, 'accepted'>),
reservedTypes
)
return
if (!structuredDispatchDelivered(outcome.state)) {
if (outcome.state === 'rejected') {
db.deleteStructuredPointerOperation(mailboxHandle)
}
this.retain(
mailboxHandle,
sessionId,
retainReasonForDispatch(outcome.state as Exclude<StructuredDispatchState, 'accepted'>),
reservedTypes
)
return

if (args.structuredWorker) {
const content = captureStructuredWorkerArchive(
args.structuredWorker,
args.structuredWorker.agent ?? 'claude'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Recover the provider from the durable session record.

rehydrate creates StructuredWorkerIdentity.agent as null. Startup release recovery then reaches captureWorkerOutputArchive, which stores claude in the archive when the durable provider is Codex. The journal messages remain unchanged, but archived provider metadata is incorrect. Read record.provider with readStructuredAgentSessionRecord(identity.sessionId). If the record is unavailable, fail with archive_failed so the worker remains retained instead of guessing.

Comment on lines +75 to +78
// NOT yet handled, and deliberately follow-up: rebinding a restarted runtime to a structured
// worker's hold and redrive subscription. Until that exists, a worker that survives a restart
// keeps no hold, so its child is evictable and its parked mail waits for the next arrival
// rather than a settle edge.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Restore the structured worker hold and journal redrive during restart recovery.

ensureStructuredAgentSessionHost() creates empty in-memory holds, while OrchestrationStructuredMailboxPointerDelivery stores parked mail only in parkedUntilTurnSettle and retries it from onTurnSettled(). Restart recovery does not restore either resource. A surviving worker can therefore become evictable, and parked mail can remain unread until a later arrival or explicit check. Rebind the hold and journal-settle redrive for each restored session before recovery completes.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Isolated Electron QA — native-born structured workers (PR 18827)

Isolated qa-struct instance from this worktree at 2ef4be9cb15. CDP 9338 / renderer 5185 / --use-mock-keychain. Ownership proven (/@fs 200 this worktree, 403 pompano; getIdentity() names structured-orch-qa).

Exercised orca-dev orchestration worker-start --structured --worktree current for claude and codex.

Passed (seen, not inferred)

  • Both starts returned ready / input_accepted with structworker_ handles.
  • Both appeared as structured chat tabs (Claude Chat / Codex Chat), composer “Send a message…”, not a PTY.
  • Dispatch preamble was visible in both chats.
  • Orchestration mail was consumed; each agent produced a new turn and sent worker_done. worker-show → dispatch.status=completed, worker.state=succeeded.
  • worker-read returned source=transcript journal (preamble + mail + worker_done) for both.
  • worker-stop reported already settled; worker-release closed the agent session and archived the transcript.
  • “Orchestration paused” banner is gone (document.body.innerText did not contain it).

Gaps (do not overstate)

  • Host session.tabs.listAll listed the agent-session tabs immediately, but renderer unifiedTabsByWorktree did not auto-mirror them until the local structured-session version fence was reset and the inventory reapplied. tabsByWorktree never had them (viewMode lives on unified tabs; these native-born tabs are contentType: agent-session, not viewMode: chat).
  • Mail delivery was via orchestration check --wait then a new assistant turn. I did not see a separate user-role bubble of the mail body in the accessibility tree.

Claude

Claude structured chat with dispatch preamble
Claude after mail: worker_done sent
Claude worker_done settled

Codex

Codex structured chat with dispatch preamble
Codex worker_done after QA mail

Full writeup: /tmp/qa-struct-proof/REPORT.md on the QA machine.

Merge Sim added 2 commits September 5, 2026 04:38
Orchestration resolves every worker through a terminal handle and a pane key
backed by a live PTY. A session created directly as structured has neither, so
it was not refused by orchestration — it was invisible. A coordinator could not
start one, address one, or receive `worker_done` from one.

Add a second authority source rather than a parameter channel. A registry maps a
session id to the same three facts the PTY path supplies — a bearer handle, a
pane key and a host scope — and the four runtime getters consult it before
giving up on `ptysById`. `orchestration.send` and `verifyDispatchCapability` are
untouched: authority stays host-derived and the CLI still cannot assert who it
is. PTY handles short-circuit on the handle prefix, so the terminal path is
unchanged.

Mail travels as a session turn instead of as bytes, on a sibling lane that keeps
the PTY lane's outstanding-run, waiter, reserved-type and batch rules.
Orchestration's database stays the source of truth; the send is best-effort,
exactly as the byte write is, and mail is consumed only on a proven-accepted
dispatch. Delivery waits for the session to be between turns, because one
provider refuses a mid-turn start outright and the other cannot acknowledge one
inside the ack window.

Security properties, each pinned by test: the pane key's leaf is random and
persisted rather than derived, since `check` is identity-gated and accepts a
caller-supplied pane key; the handle is a random bearer token; the child env
carries no pane key, which would otherwise flow into hook pipelines that assume
a PTY leaf; hook attestation stays closed for structured handles; and process
continuity comes from record lineage, never the runtime fence, which the host
bumps during its own crash recovery.

Also remove the "Orchestration paused" notice, which gated only on dispatch
status and rendered over bridge chat where orchestration always worked; refuse
the implicit-sender fallback when a worktree has more than one candidate leaf
instead of guessing; and collapse the archive kinds to one named type with a
compile-time assertion that the capture set cannot drift ahead of the storable
set.
…timeline

The structured pointer gate read a bounded 40-item tail page. A settled turn is
tombstoned rather than rewritten, so an idle worker with any real history carries
no turnLifecycle item at all and the "full page, no lifecycle item" guard read it
as busy forever: every nudge after the worker's first substantial turn parked on a
settle edge that had already passed, and the preamble tells workers not to poll.
The attention gate had the mirror bug — a prompt older than the tail window was
missed and the nudge was delivered into a session blocked on a human.

Both facts now come from `journal.snapshot()`, the fully reduced timeline, via a
new narrow `readGateFacts` host read; the policy module stays pure and still
projects through the shared helpers the chat view reads.

Also:
- Park `session-not-attached` on the journal edge, so mail that arrives during a
  transient detach is redriven by the re-attach reset instead of sitting unread.
- Resolve a structured worker's provider from the durable agent-session record
  when the registry entry was rehydrated, so a restarted Codex worker is no longer
  reported and archived as Claude.
- Clear `structured_pointer_operations` in every `orchestration reset` scope.
- Drop the per-chat-pane dispatch-status store subscription left behind by the
  removed paused notice, and re-pin the two terminal-pane ratchets it moves.
- Hoist the identical pointer batch selection out of both delivery lanes into
  `selectOrchestrationPointerBatch`.
- Refuse the pre-graph-ready focus-based guess for `requireUnambiguous` callers,
  matching the ready path.
- Move the host teardown phase list into the teardown module it belongs to, which
  is what keeps the host inside its max-lines budget.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/orchestration-structured-delivery branch from 2ef4be9 to 0ae89d4 Compare September 5, 2026 12:06
@coderabbitai

coderabbitai Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

The follow-up commit since the prior review fixes the structured idle gate, resolves the restarted-worker provider gap, and removes the orphaned renderer subscription.

  • Fixed the idle gate to read the full reduced timeline — structuredSessionIsBetweenTurns(items, pageMayHaveMore) became structuredSessionGateFacts(items) over host.journalSnapshot(), so an idle worker with real history is no longer read as busy forever, and a pending approval/question scrolled out of the tail window is no longer missed.
  • Parked session-not-attached on the journal edge — mail arriving during a transient detach is now redriven by the re-attach reset event (onTurnSettled → onJournalActivity, parkedUntilTurnSettle → parkedUntilJournalEdge).
  • Resolved the provider off the durable record — structuredWorkerAgent reads a rehydrated worker's provider from the agent-session record, so a restarted Codex worker is no longer archived/reported as Claude.
  • Cleared structured_pointer_operations in every reset scope, with tests covering each.
  • Removed the orphaned chatPaneDispatchStatus subscription and its plumbing, re-pinning the two terminal-pane ratchet tests.
  • Hoisted selectOrchestrationPointerBatch into mailbox-pointer-eligibility.ts, shared by both delivery lanes.
  • Refused the focus-based guess for requireUnambiguous callers, matching the ready path.
  • Moved the host teardown phase list into structured-agent-session-host-teardown.ts (behavior-preserving).

Both prior concerns are resolved: the orphaned subscription is gone, and the restarted-worker provider mislabel is fixed. The restart hold/redrive rebind gap remains the documented deliberate follow-up, which is unchanged and out of scope here.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Merge Sim added 7 commits September 5, 2026 05:24
…settled unknown

`commitStructuredAgentSessionCreate` answers `agent_session_operation_unknown` when
`attach` SUCCEEDED and only the tab publish failed, so `created.ok === false` is not
proof that nothing exists. The worker start read it that way and skipped
`discardCreatedSession`, leaving a live provider child that took no hold, has no
`bindingsByDispatchId` entry and no published tab — the outer
`releaseStructuredWorkerSession` no-ops without a binding, and a session that never had
a holder never starts the eviction clock, so nothing in the runtime ever retires it. A
throw out of the commit half is past `attach` for the same reason; the pre-commit half
refuses rather than throwing. Cleanup now asks whether the create MAY have committed,
via the existing `isDefinitiveAgentSessionCreateRefusal` predicate.

Also:
- Strengthen the pre-ready `requireUnambiguous` test so it actually pins the guard: the
  snapshot now carries a focused terminal, so deleting the `? [] :` ternary turns the
  test red instead of leaving the refusal to the ambiguous `listTerminals` fallback.
- Correct the guard's justification comment, which cited `orchestration check` as
  covered. `check` resolves through the `--terminal` scope and still guesses; the
  guard covers the implicit `--from` sender, and a structured worker is covered by the
  `ORCA_TERMINAL_HANDLE` baked into its child.
…rantees the code does not give

The send-time owner re-check reads `target.refusal`, the snapshot the resolver
already admitted, so `decideStructuredPointerDelivery` can only agree with the
resolve-time answer and `owner-not-settled-native` is unreachable from that call
site. What actually fences an owner that moved is `expectedRuntimeFence`, which a
handoff bumps. Say that, so nobody later drops the fence trusting a re-check that
is structurally a tautology.

`discardCreatedSession` was credited with retiring "a published background tab
that no dispatch owns". It hides the DURABLE tab reference and closes the
session; the live tab snapshot keeps the row, so the background tab this start
published stays on screen until the app restarts. Same for stop and release. The
comment now describes what the two calls do — including that both are no-ops on a
session that was never attached, which is what makes the non-definitive-refusal
path safe to reach unconditionally.
…rker settles

Starting a structured worker always publishes a real `agent-session:<id>` tab, but
every settlement path only called `setSessionTabVisibility(sessionId, false)` plus
`host.close(sessionId)`. That clears the DURABLE restore index and leaves the LIVE
snapshot untouched, so stop, release and the half-started discard all left a dead
"Claude Chat" / "Codex Chat" tab in the worktree's tab bar for the rest of the app
session — five dispatches, five dead tabs — and opening one re-attached the released
session, respawning a provider child outside orchestration's hold accounting.

The snapshot-pruning half of `closeStructuredAgentSessionTab` is extracted into
`structured-agent-session-tab-retirement.ts` and exposed on the runtime as
`retireStructuredAgentSessionTabFromSnapshot`, so the user-initiated tab close and
the three settlements share one implementation instead of a second copy.

The settlement side is best-effort BY CONSTRUCTION: it runs only after the close is
already proven, calls the runtime method optionally, and swallows any throw. It
talks to no renderer, so the startup release reconciler can call it too. Nothing
here can turn a proven stop into `release_unknown`.
…veness from lying

Five defects in the structured-worker lanes, each with the same shape: a check
that answered from something other than what it claimed to measure.

- The pointer lane gated a WORKER's `dispatch:` mailbox on its RUN's outstanding
  delivery. Delivery rows exist only for a `run:` address, so that row belongs to
  the coordinator — and a coordinator holds one for exactly as long as it is
  acting on received mail, which is when it replies to its workers. The gate is
  gone; there is no coordinator mailbox in this lane to protect.
- `dispatch-rejected` now parks on the journal edge. A rejection consumes no mail
  and nothing else redrives the mailbox, so an unparked pointer left the worker
  idle on durable mail until unrelated mail happened to arrive.
- The released journal archive bounded forward — keeping the HEAD — before
  capping newest-first, so a long worker's archive ended at its early exploration
  and dropped the answer it was released for, under a warning that said the
  oldest messages had gone. One newest-first pass now, and the warning is true.
- The durable pointer operation id was reused on a matching BODY fingerprint, and
  the body names only the unread count. Two unrelated same-size batches collided,
  the host replayed its ledger answer as `accepted` with no turn sent, and the
  lane marked the new mail delivered. Reuse is keyed on the batch's message ids.
- `worker-read` on a structured worker hardcoded `terminal: 'running'` and
  emitted no `liveness`, so a runtime that could not see the session reported the
  worker as alive. It now carries the observed verdict, as the PTY branch does.

Also: the live journal cursor is an index into a re-derived tail window, so the
page's oldest item joins its source identity — a slid window now answers
`source_changed` instead of silently resuming past the items it skipped. And a
stop that reached no host reports `processAction: 'none'`, after installing the
host the way release already does.
…se that never landed

`worker-read` on a released structured worker hardcoded `liveness: 'exited'`. The
archive is frozen BEFORE the close, so it proves nothing about the provider child,
and the read is served for `release_state` in `releasing` / `unknown` too — the two
states that exist precisely to record a close that did NOT land. A coordinator that
read `exited` from a `release_unknown` worker would start a replacement over the same
worktree while the original child was still attached, which is the outcome
docs/reference/ssh-execution-boundary.md rule 2 exists to prevent, and it contradicts
the release receipt's own "the structured session close was not proven" text.

The verdict now comes from the resource row the read already holds: only a settled
`released` row is `exited`, everything else is `unverifiable` — which the existing
mapping renders as `terminal: 'unknown'`, the same way the live branch does.
…le it never delivered

Two ways a structured `worker-start` handed the coordinator a receipt that did not
describe the worker it got.

`sendStructuredWorkerPreamble` threw only on a refusal and on `rejected`, so a
submission that settled `unknown` fell through as success: the start pushed
`dispatch_input: accepted` and marked the dispatch ready. `unknown` is not rare —
`dispatchSafely` converts ANY thrown adapter call (provider child gone, transport
dropped, ack window missed) into it, and `performSend` still returns ok. The worker
then has no task spec while its coordinator blocks in `check --wait --types
worker_done` until timeout. This PR's own mail lane already states the rule —
"`pending` is not yet an acknowledgement; only `accepted` may consume mail" — so the
preamble now applies it too, and raises `operation_unknown` for the states that
prove neither delivery nor failure, which is the code `failWorkerStartWithReceipt`
turns into the `outcome_unknown` receipt whose nextCommands send the coordinator to
look. `rejected` stays a proven failure.

`--structured` also accepted `--model` / `--effort` and dropped them: structured
session creation takes no launch preferences, while `launch.receipt.effective`
echoes whatever was requested either way, so `--model opus` ran on the workspace
default and the receipt still said `opus`. Refused now, for the same reason
`--terminal` refuses them, and the spec note records that refusal along with the
new-child/new-top-level one it never mentioned.

Tests: the refusal guard had no coverage at all, and `structured-mailbox-pointer-host`
— where the full-timeline gate read lives — had none either; reinstating the bounded
tail there left the whole repo green. Both are covered now, and the vacuous
"never selects an exact provider session" case is re-pointed at the absent
`ORCA_PANE_KEY` that actually keeps that selector shut.
…LI, and stop four settlements lying

A structured worker's provider child runs `orca orchestration ...` exactly like a PTY worker's
agent does, but it was handed the ambient PATH. On packaged Linux the CLI installs as `orca-ide`
so it never claims GNOME Orca's /usr/bin/orca (#7904), so bare `orca` execs the screen reader and
the worker can never read mail, reply or send worker_done; on packaged macOS/Windows the bundled
launcher is only reachable from the app's own resources dir. The PTY lane already solves this
inside `buildPtyHostEnv`; that block is now its own module and both lanes call it.

Also:
- a worker start that fails AFTER its session exists now discards the session, so a failed start
  stops stranding a dead chat tab that the durable restore index republishes on every launch;
- a structured worker's resource reconciles to `released` after settlement forgot its identity,
  instead of answering `unverifiable` for the life of the DB;
- `closeAttempted` is set only once a close is issued, so a tab-visibility failure can no longer
  report `closed_agent_terminal` for a running child;
- `forgetSession` prunes only what the settled worker parked, not every sibling whose target
  momentarily fails to resolve;
- release settles with an explicitly empty, warned archive when the journal is unreadable AND the
  session is proven exited — closing the chat tab is routine, and `archive_failed` there wedged
  release on evidence that could never arrive;
- the new migration test uses mkdtemp and cleans up, so it stops failing Windows CI and leaking.
@greptile-apps

greptile-apps Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

Too many files changed for review (174 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: 8 rounds of adversarial review, 20 defects found and fixed

This branch went through a repeated review-and-fix loop, each round run by a fresh reviewer against the previous round's output. Every round found real defects — including defects in the previous round's own fixes — so the loop was continued until a round came back with nothing material. Two full readiness reviews bracket the session.

The branch was also rebased onto current main (it was conflicting). The conflict was with #18697, which had introduced a pre-commit/commit boundary in agentSession.create so a client can distinguish "nothing was created" from "the outcome is unknown". This PR had extracted that block into a module, which collapsed the boundary. The resolution pushes the boundary into the extracted module as a prepare + commit split, so the orchestration start path now gains that guarantee too rather than losing it.

The defect that mattered most

The idle gate read every settled worker as permanently busy. The delivery gate asked a bounded 40-item journal tail page whether a turn was running. But a settled turn is tombstoned, not rewritten to completed, so an idle session carries no lifecycle item at all — and the "a full page with no lifecycle item is busy" guard therefore fired on the normal steady state of a working agent. Any structured worker whose journal passed ~40 items was parked turn-unsettled forever, on a settle edge that had already passed. Mail was retained, not lost, but the preamble tells workers not to poll, so nothing woke them. In other words: the feature stopped working after a worker's first substantial turn.

Both facts now come from journal.snapshot() — the fully reduced timeline, tombstones applied — through a narrow readGateFacts host read. The attention gate had the mirror bug (a pending approval scrolled out of the tail was missed, and the nudge was delivered into a session blocked on a human) and is fixed the same way.

Also found and fixed

Delivery and mail

  • A mis-ported hasOutstandingRunDelivery gate applied the coordinator's run state to a worker's mailbox and dropped the nudge with no retry edge — so a coordinator replying to a structured worker during its own unacked window deadlocked against a worker sitting on unread mail.
  • The durable pointer operation id was keyed on the unread count, so a replayed id could answer accepted without sending a turn while the lane marked new mail delivered. Now keyed on real batch identity.
  • session-not-attached and dispatch-rejected now park on the journal edge; a transient detach is redriven on re-attach.
  • forgetSession pruned every worker's parked mail when the DB reference was momentarily null.

Lifecycle and honesty

  • A create that settled unknown after attach stranded a live provider child that nothing could ever retire.
  • Structured worker chat tabs were never removed from the live workspace snapshot on stop/release/discard — dead tabs accumulated per dispatch, and opening one respawned a provider child outside orchestration's accounting. A failed start leaked one too.
  • worker-read reported running for a worker the runtime could not see, and the archived read asserted exited for a release whose close was never proven — the "could not look, therefore it is dead/alive" inversion docs/reference/ssh-execution-boundary.md exists to prevent.
  • worker-stop claimed closed_agent_terminal when no close was issued.
  • A worker start reported a preamble it never delivered, so a worker could be ready with no task.
  • --structured --model/--effort was silently discarded while the receipt claimed it applied; now refused.
  • Release wedged on archive_failed when the worker's chat tab had been closed — a routine user action. It now settles with an explicitly empty, warned archive when the session is proven exited.
  • A restarted Codex worker was reported and archived as Claude.

Platform

  • ORCA_CLI_COMMAND: 'orca' was handed to the structured child with the ambient PATH. On packaged Linux the CLI installs as orca-ide precisely so it never claims GNOME Orca's /usr/bin/orca ([Bug]: Launching Orca starts the GNOME Orca screen reader on Ubuntu (CLI installs as orca, colliding with /usr/bin/orca) #7904) — so the worker's first orca orchestration check would have exec'd the screen reader and it could never read mail, reply, or send worker_done. On packaged macOS/Windows it reached the bundled CLI only if the user had separately registered it globally. The PTY lane already solved this inside buildPtyHostEnv; that block is now its own module and both lanes call it, so the two cannot drift.

Hygiene

  • orchestration reset now clears structured_pointer_operations; the released-worker archive keeps the worker's final answer instead of a middle window; a dead per-chat-pane store subscription left by the removed notice is gone (two terminal-pane ratchets re-pinned); duplicated mail selection hoisted into one shared function; the new migration test no longer fails Windows CI or leaks DB files.
  • Three tests were found to be tautological — they passed even with the code under test broken — and were re-pointed at the real mechanism. Notably createStructuredMailboxPointerHost, where the idle-gate fix lives, had no coverage at all.

Security invariants

All eight were re-verified every round and hold at HEAD: the pane key's leaf is random and persisted (never derived — orchestration.check is identity-gated and accepts a caller-supplied pane key); the handle is random and not term_-prefixed; ORCA_PANE_KEY stays out of the structured child env; hook attestation stays closed; getLiveTerminalPaneKey gates on real liveness; the dispatch hold is released on every settlement; incarnation comes from record lineage, never the runtime fence; and mail is consumed only on accepted. orchestration.send and verifyDispatchCapability remain untouched, and the shipped PTY lane was diffed line-by-line through every shared refactor.

Worth a reviewer's attention before merge

  • Behavior change beyond structured workers: the implicit-sender fallback now refuses when a worktree has more than one candidate leaf instead of picking an arbitrary first one. This closes a real misattribution (a bare send --type worker_done could settle a sibling's context-only dispatch), but it changes existing PTY CLI behavior and deserves a release note.
  • Accepted follow-ups: worker-read paging uses a bounded window rather than an absolute journal offset — a slid window is now loud via source_changed rather than silently skipping, with the absolute offset left as a follow-up. A structured worker improvising a bare orchestration command without --from gets a misleading "run inside a live Orca terminal" message; the taught commands all pass --from, so it is bounded.

Verification at 54a446424d1

tsc --noEmit clean on all three projects; oxlint clean; oxfmt clean; max-lines, ts-nocheck and runtime-electron ratchets all unchanged (no suppression added anywhere — oversized files were split instead). Full local suites green: src/main 3205 files, src/cli + src/shared + renderer panes 1295 files. Every behavior fix is pinned by a red-then-green ablation — the test was confirmed to fail against the old code before being accepted.

Two unrelated local failures, both confirmed not caused by this branch: structured-agent-session-lease-renewer and structured-agent-session-surface-lifetime are teardown/timing flakes that pass in isolation, and ssh-multi-factor-authentication fails deterministically on this machine but its test file and every one of its imports are byte-identical to origin/main, with no dependency change on the branch.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Seven fix commits landed since the prior review (0ae89d460a). Each addresses a real defect in the initial structured-worker implementation, and every fix carries an exact test with the reasoning pinned in a comment.

  • CLI reachability extracted and applied to structured workers — prependOrcaCliDirToChildPath was factored out of buildPtyHostEnv and reused in structuredWorkerChildIdentityEnv, so a structured worker's provider child reaches Orca's own CLI (not GNOME's /usr/bin/orca on packaged Linux) while an ordinary chat session's env passes through untouched.
  • Settlement receipts no longer lie — stopStructuredWorker returns closeAttempted, so stop/release receipts report none when no close was issued; the archived read keys exited off the settled release row; liveness is read off the durable agent-session record rather than the in-memory registry, and the structured host is reinstalled before a post-restart stop.
  • Nudge idempotency re-keyed on the batch — operation-id reuse now hashes the message IDs rather than the pointer body, closing the silent-mail-loss path where two same-size batches shared a fingerprint and the host answered accepted from its ledger without sending a turn.
  • Parked mailboxes remember their session — forgetSession drops only the settled worker's own parked entries (no longer pruning siblings), and a rejected dispatch now parks on the journal edge.
  • Archive bounds the tail, not the head — boundWorkerTranscriptTail preserves the worker's final answer, and a session already closed settles with an empty warned archive instead of wedging release.
  • Chat-tab retirement on settlement — a pure structured-agent-session-tab-retirement.ts shared across stop/release/discard/user close, plus discard of a half-started session whose create settled unknown.
  • --model/--effort refused for structured starts, matching the launch options a structured session cannot honour.

The restart hold/redrive rebind gap remains the documented deliberate follow-up and is unchanged by these commits.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main/runtime/orchestration/structured-mailbox-pointer-delivery.ts (1)

228-235: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Discard the structured pointer operation after a rejected dispatch.

A journal-edge retry reuses the stored operation ID. The session API replays rejected submissions instead of redispatching them, so the mail remains unread. Delete the stored operation or mint a new operation ID when dispatch returns rejected, before parking the retry.

src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts (1)

75-78: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Restore both structured-worker resources during restart recovery.

completeWorkerTerminalReleaseOnce installs only the host. Restart restoration does not recreate the bindingsByDispatchId entry that provides host.hold(...) and subscribeForRedrive(...). A recovered dispatch has no hold and no orchestration:redrive:${sessionId} subscriber. The child can be evicted, and parked mail can remain undelivered because journal activity no longer calls onJournalActivity. Add a recovery-specific rebind for both resources and route settlement through the existing cleanup path.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 6133958e-bed4-44ac-979f-e5db0d19656e

📥 Commits

Reviewing files that changed from the base of the PR and between 0ae89d4 and 54a4464.

📒 Files selected for processing (47)
  • src/cli/specs/orchestration-worker-specs.ts
  • src/main/claude/claude-structured-launch-resolution.ts
  • src/main/cli/orca-cli-child-path.test.ts
  • src/main/cli/orca-cli-child-path.ts
  • src/main/codex/codex-structured-child-environment.ts
  • src/main/ipc/pty/host-env/assembly.ts
  • src/main/ipc/pty/host-env/path.ts
  • src/main/runtime/orca-runtime-adopt-terminal-orphans-from-inventory.ts
  • src/main/runtime/orca-runtime-close-mobile-session-tab.ts
  • src/main/runtime/orca-runtime-close-structured-agent-session-tab.ts
  • src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts
  • src/main/runtime/orca-runtime-subscribe-to-terminal-resize.ts
  • src/main/runtime/orchestration/db/messages/structured-pointer-operation-store.ts
  • src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts
  • src/main/runtime/orchestration/db/schema/migrate-v13-latest.ts
  • src/main/runtime/orchestration/db/schema/structured-pointer-schema-migration.test.ts
  • src/main/runtime/orchestration/orchestration-reset-db.test.ts
  • src/main/runtime/orchestration/structured-mailbox-pointer-delivery.test.ts
  • src/main/runtime/orchestration/structured-mailbox-pointer-delivery.ts
  • src/main/runtime/orchestration/structured-mailbox-pointer-host.test.ts
  • src/main/runtime/orchestration/structured-pointer-operation-id.test.ts
  • src/main/runtime/orchestration/structured-pointer-operation-id.ts
  • src/main/runtime/orchestration/structured-session-pointer-delivery.test.ts
  • src/main/runtime/orchestration/structured-session-pointer-delivery.ts
  • src/main/runtime/orchestration/structured-worker-journal-archive.test.ts
  • src/main/runtime/orchestration/structured-worker-journal-archive.ts
  • src/main/runtime/orchestration/worker-transcript-payload.ts
  • src/main/runtime/rpc/methods/orchestration-local-worker-start.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-lifecycle.test.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-lifecycle.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-session.test.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-session.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-start-failure.test.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-start-refusals.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-archive-read.ts
  • src/main/runtime/rpc/methods/orchestration-worker-control.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
  • src/main/runtime/rpc/methods/orchestration-worker-stop.ts
  • src/main/runtime/rpc/methods/orchestration-workers.ts
  • src/main/runtime/rpc/methods/structured-worker-stop-receipt.test.ts
  • src/main/runtime/rpc/methods/structured-worker-tab-retirement.test.ts
  • src/main/runtime/structured-agent-session-tab-retirement.ts
  • src/main/runtime/structured-worker-authority.ts
  • src/main/runtime/structured-worker-child-identity-env.test.ts
  • src/main/runtime/structured-worker-child-identity-env.ts
  • src/main/runtime/structured-worker-identity.test.ts
  • src/main/runtime/structured-worker-mail-routing.test.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • src/main/runtime/orchestration/db/schema/migrate-v13-latest.ts
  • src/main/runtime/orca-runtime-subscribe-to-terminal-resize.ts
  • src/main/runtime/structured-worker-mail-routing.test.ts
  • src/main/runtime/rpc/methods/orchestration-local-worker-start.ts
  • src/main/runtime/rpc/methods/orchestration-structured-worker-session.test.ts
  • src/main/runtime/orchestration/structured-pointer-operation-id.ts
  • src/main/runtime/orchestration/structured-session-pointer-delivery.test.ts
  • src/cli/specs/orchestration-worker-specs.ts
  • src/main/runtime/orchestration/db/messages/structured-pointer-operation-store.ts
  • src/main/runtime/orchestration/orchestration-reset-db.test.ts
  • src/main/runtime/orchestration/structured-pointer-operation-id.test.ts
  • src/main/runtime/orca-runtime-adopt-terminal-orphans-from-inventory.ts

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

const platform = opts.platform ?? process.platform
// Why: matches node:path's `delimiter` for the running platform, but stays correct when a test
// drives a foreign platform through the seam.
const pathDelimiter = platform === 'win32' ? ';' : delimiter

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- src/main/cli/orca-cli-child-path.ts ---'
cat -n src/main/cli/orca-cli-child-path.ts | sed -n '1,90p'
printf '%s\n' '--- related test ---'
cat -n src/main/cli/orca-cli-child-path.test.ts | sed -n '70,120p'
printf '%s\n' '--- package/runtime declarations for delimiter and platform seam ---'
rg -n --glob '*.ts' --glob '*.json' 'from .node:path|from .path.|delimiter|platform' src/main/cli package.json tsconfig.json 2>/dev/null | head -120

Repository: stablyai/orca

Length of output: 17342


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 31562


Use the selected platform for the delimiter.

When platform is "linux" or "darwin", use ':' instead of the host delimiter. Windows hosts otherwise produce ';' for simulated POSIX paths.

Proposed fix
-  const pathDelimiter = platform === 'win32' ? ';' : delimiter
+  const pathDelimiter = platform === 'win32' ? ';' : ':'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const pathDelimiter = platform === 'win32' ? ';' : delimiter
const pathDelimiter = platform === 'win32' ? ';' : ':'

mailbox_handle TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
operation_id TEXT NOT NULL,
batch_fingerprint TEXT NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Description: Verify migrations for the renamed pointer column and the widened archive CHECK.
set -euo pipefail

fd -t f -g '*migrate*' src/main/runtime/orchestration/db/schema | while IFS= read -r file; do
  echo "===== $file"
  rg -n -C 6 'structured_pointer_operations|batch_fingerprint|body_fingerprint|worker_terminal_archives|structured_journal' "$file" || true
done

echo "===== pointer operation store SQL"
fd -t f -g 'structured-pointer-operation-store*' src | while IFS= read -r file; do
  echo "===== $file"
  rg -n -C 4 'batch_fingerprint|body_fingerprint|INSERT|SELECT' "$file"
done

echo "===== any remaining references to the old column name"
rg -n 'body_fingerprint' src || echo 'none'

Repository: stablyai/orca

Length of output: 3647


Add a migration for existing structured_pointer_operations tables.

The archive table already has a rebuild for the widened kind CHECK. However, CREATE TABLE IF NOT EXISTS structured_pointer_operations does not rename an existing body_fingerprint column. On upgraded databases, putStructuredPointerOperation writes batch_fingerprint and fails because that column is missing. Add an explicit rename or table migration for existing structured_pointer_operations tables.

Comment on lines +44 to +49
const active = nextTabs.find((candidate) => candidate.isActive) ?? nextTabs[0] ?? null
return {
...snapshot,
snapshotVersion: snapshot.snapshotVersion + 1,
activeTabId: active?.id ?? null,
activeTabType: active?.type ?? null,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Description: Compare the extracted retirement helper with the original close path and its consumers.
set -euo pipefail

echo "===== original close path"
fd -t f -g 'orca-runtime-close-structured-agent-session-tab*' src | while IFS= read -r file; do
  echo "----- $file"
  cat -n "$file"
done

echo "===== other snapshot mutators: do they rewrite isActive when promoting?"
rg -n -C 6 'isActive' src/main/runtime --glob '*.ts' --glob '!*.test.ts'

echo "===== consumers of activeTabId vs isActive"
rg -n -C 4 'activeTabId' src/renderer src/shared mobile --glob '*.ts' --glob '*.tsx' --glob '!*.test.*' | head -80

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "===== retirement helper"
cat -n src/main/runtime/structured-agent-session-tab-retirement.ts

echo "===== helper tests and direct callers"
rg -n -C 8 'retireStructuredAgentSessionTabFrom|retireStructuredAgentSessionTabFromSnapshot' src --glob '*.{ts,tsx}' --glob '!*.test.*'
fd -t f -e ts -e tsx src | rg 'structured-agent-session-tab-retirement|structured-agent.*retire|close-structured-agent'

Repository: stablyai/orca

Length of output: 17047


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "===== snapshot storage and emission definitions"
rg -n -C 12 'storeMobileSessionSnapshot|emitMobileSessionTabsSnapshot' src/main/runtime --glob '*.ts' | head -160

echo "===== projection finalization callers"
rg -n -C 10 'finalizeRuntimeMobileSessionTabsResult' src/main/runtime --glob '*.ts'

Repository: stablyai/orca

Length of output: 23205


Set the promoted tab’s isActive flag.

When the retired tab is active, retireStructuredAgentSessionTabFrom falls back to nextTabs[0] and writes its ID to activeTabId, but leaves every tab’s isActive value unchanged. The stored and emitted snapshot can therefore contain conflicting active-tab state. Map nextTabs so only active.id has isActive: true.

Source: Linters/SAST tools

Merge Sim added 2 commits September 5, 2026 08:14
The release-completion module imported ./orchestration-worker-release-receipts
twice, which trips import/no-duplicates in audit:code-quality:native. The
changed-file gate does not load that config, so only whole-tree CI saw it.
…no-op

The activate:false branch for an already-published session returns without
writing the snapshot or emitting, so it cannot re-surface a client whose
mirror lost the tab. Orchestration is safe from this only incidentally.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Re-validation of PR #18827 at 8aed3e9. This run supersedes the earlier QA at 2ef4be9cb15. Settings (experimentalNativeChat, openAgentTabsInChatByDefault, experimentalStructuredNativeChat) were seeded in the isolated profile before first paint and confirmed true at first paint.

Open question — background structured worker tab, unaided: NO (both claude and codex). worker-start --structured succeeded with surface: "background", but the agent-session tab did not appear in window.__store.getState().unifiedTabsByWorktree or the tab bar (no inventory refresh, no fence reset, no reload). Only Terminal 1 remained. Resume in Worktree from session history also did not mount a tab.

Item Claude Codex
worker-start --structured ready pass pass
Tab appears unaided fail fail
Dispatch preamble visible pass (session history + worker-read) pass (same)
Mail into chat, not queued partial: worker was on check --wait; mail arrived via CLI inbox, no user-role mail body in transcript pass (nudge): after idle, chat got a user turn You have 1 orchestration message. Run \orca orchestration check`.`
worker_done settles pass (completed) pass (completed)
worker-read / stop / release pass pass
"Orchestration paused" banner absent absent

Full writeup: /tmp/orca-qa-struct2-evidence/qa-18827-8aed3e9787.md.

First paint (settings already on)

01-first-paint.png

Claude: tab bar immediately after background worker-start (no agent-session tab)

03-claude-immediate-tab-bar.png

Claude: preamble in Agents session history (not a chat tab)

05-claude-chat-after-aided-open.png

Claude settled — no Orchestration paused banner

07-claude-settled-no-paused-banner.png

Codex: tab bar immediately after background worker-start (no agent-session tab)

08-codex-immediate-tab-bar.png

Codex settled — no Orchestration paused banner

09-codex-settled-no-paused-banner.png

Agents history after both workers

10-agents-after-both-workers.png

… a flag

`worker-start --structured` was an explicit opt-in that REFUSED --on, --terminal,
--model/--effort and worktree-creating placements. The flag, its spec entry and the
`structured` RPC param are gone: the mode now follows the user's setting for new agent
tabs, so a local claude/codex worker is a structured chat session whenever the user's
own default says agent tabs open as one.

A setting is a preference, not a demand, so none of those combinations refuses any more.
A dispatch that cannot be structured starts an ordinary PTY terminal worker and the
receipt names the mode that ran and why, so the fallback is never silent:

- a remote --on, an existing --terminal, a new-child/new-top-level worktree and
  --model/--effort are decided from the request;
- the agent, TUI launch customization, Codex-on-Windows and the runtime capability are
  decided by the shared launch route;
- WSL, remoteness and the Windows start-time gate are settled by the executing host's own
  agentSession.createSupport, asked once the worktree resolves and before anything is
  created, so a refusal is a terminal worker rather than a failed start.

The decision is the renderer's, lifted rather than copied: `resolveAgentLaunchRoute`'s
structured half and the settings predicate now live in
shared/structured-native-chat-launch-route, which both surfaces call, and the TUI launch
customization test moves to shared beside it. `getClientSettings` gains the two native-chat
default booleans it was missing.

No security invariant moves: the structured worker registry, bearer handle, persisted pane
key, the absence of ORCA_PANE_KEY from the child env, hook attestation and lineage-derived
process incarnation are untouched.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Since the prior review, the worker mode became the user's own default rather than a --structured flag.

  • Made the worker mode settings-driven — removed --structured and assertStructuredWorkerStartSupported; orchestration-worker-start-mode.ts now derives the mode from the settings default (decideWorkerStartMode), then re-checks the resolved worktree against the executing host (resolveWorkerStartModeOnHost / downgradeWorkerStartModeForHost) before anything is created, so a refusal degrades to a terminal worker instead of a failed start.
  • Extracted the shared launch route — structured-native-chat-launch-route.ts holds prefersStructuredNativeChatByDefault and resolveStructuredNativeChatSupport, and tui-agent-launch-customization.ts holds the custom-command/args/env check, both used by orchestration and the renderer so the two surfaces cannot drift.
  • Refactored the renderer onto the shared module — resolveAgentLaunchRoute and decideInitialAgentTabViewMode now call the shared predicates; I diffed the old inline conjuncts against the new shared checks and the behavior is preserved point-for-point.
  • Made the fallback non-silent — the start and failure receipts carry a mode field (mode / preferred / reason / detail), and the CLI always prints the human line naming which mode ran and why.

The settings-driven fallback is a deliberate product choice documented in the PR and the CLI spec notes, and each reason maps to a tested case (orchestration-worker-start-mode.test.ts). The two prior Pullfrog concerns (orphaned chatPaneDispatchStatus subscription, restarted-worker provider relabeling) remain resolved; the restart hold/redrive rebind gap is still the documented deliberate follow-up and is unchanged here.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Merge Sim added 2 commits September 5, 2026 14:28
The mode a worker runs in is a runtime implementation detail. An agent should be
taught the same verbs, run the same commands and read the same receipts whether it
is a structured chat session or a PTY terminal — otherwise a settings-driven
fallback silently changes what the agent can do.

The real leak was `canDispatchSubWorkers`, which was forced false for a structured
worker. That was not a wording choice: `worker-start` resolved `--from` through
`showTerminal`, which needs a live PTY or renderer leaf, so a `structworker_`
coordinator genuinely could not dispatch. Rather than withhold the capability, the
one fact the command needs from `--from` — its worktree id — now comes from
`getOrchestrationDispatchAuthority`, the same authority the pane-key and
process-incarnation getters already answer structured handles from. Sub-dispatch is
gated on depth alone, identically for both modes.

`showTerminal` itself is deliberately NOT taught structured handles: it returns a
ptyId, a leaf id and a pane runtime id, and synthesising those for a session with no
PTY would hand every caller of a public terminal verb something that looks writable
and is not. `inspectWorkerTerminal` already returns `terminal: null` for exactly
that reason.

Also neutralised three agent-visible refusals that named the worker's kind: a
`worker-read --source terminal` on a worker with no terminal now names the sources
that do work, and both archive refusals say "transcript output" rather than
"structured chat output" (the PTY `transcript_pin` branch said "structured" too).

New tests pin both properties: the two preambles are byte-identical once the handle
and per-dispatch ids are normalised, and a structured coordinator starts a worker
with `showTerminal` rejecting.
… a prompt

worker-show reported observation.agentWait: null for every structured worker. The
field's own contract says null means Orca looked and found no wait, and absent means
it never looked — and nothing looks here: a structured worker parks on a journal
question item, which no terminal prompt scan can see.

So null was a false negative on the one field a coordinator is explicitly told to
read, and it was mode-dependent: the same worker as a PTY would have reported the
wait. Absent is both the honest value and a state a PTY worker already reaches (an
older host, an unreadable pane, a probe that did not answer), so it discloses
nothing about which mode ran.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

This commit stops the worker mode from leaking into the agent contract: a worker is now taught the same verbs and reads the same receipts whether it runs as a structured chat session or a PTY terminal.

  • Lifted the structured sub-dispatch gate — canDispatchSubWorkers is now gated on depth alone for both modes, instead of being forced false for a structured worker.
  • Resolved --from through the dispatch authority — new resolveDispatchCallerWorktreeId (orchestration-caller-workspace.ts) pulls a structworker_ coordinator's worktree id from getOrchestrationDispatchAuthority, the same authority the pane-key and process-incarnation getters already answer structured handles from, so a structured coordinator can actually dispatch sub-workers. showTerminal is deliberately left unaware of structured handles.
  • Neutralised three agent-visible refusals — worker-read --source terminal and both archive refusals now name the sources that do work ("transcript output") instead of disclosing the worker's kind.
  • Pinned mode opacity by test — orchestration-worker-mode-opacity.test.ts asserts the two preambles are byte-identical after normalising the handle and per-dispatch ids, and that a structured coordinator starts a sub-worker with showTerminal rejecting.

The pre-existing restart hold/redrive rebind gap remains the documented deliberate follow-up and is unchanged here.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

… kind

The note said "the receipt mode field names the mode used and why", which is an
instruction to read a field no verb behaves differently for — the one thing the
mode was not supposed to become. It now says what a caller actually needs: the
dispatch always starts, the options passed are the ones honoured, and every worker
is driven the same way. The receipt still carries the mode for operators and
telemetry; nothing tells an agent to look at it.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

This commit stops a structured worker's observation from falsely claiming it was checked for a human-answerable prompt.

  • agentWait is now absent, not null, for structured workers — inspectWorkerTerminal's structured branch dropped agentWait: null. Null is the contract's "Orca looked and found no wait", but nothing ever looks for a structured worker's parked journal question (it is invisible to every terminal prompt scan), so null was a false negative a coordinator could act on. Absence correctly signals "never looked", matching the field's documented semantics.
  • Pinned by test — a new opacity test asserts 'agentWait' in observation === false for a structured worker, the exact distinction the contract draws between absent and null.

The consumers already handle absence (observation.agentWait !== undefined ? … : {}), and the CLI spec documents the absent-vs-null distinction, so the change is consistent end to end.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Two commits since the prior review (3fb592d087). Both close agent-visible gaps in the structured-worker surface, and each is pinned by an exact test.

  • Reached structured workers through group addresses — @all, @idle, @codex, and @worktree:<id> now enumerate live structured workers alongside listTerminals. resolveGroupAddress widened to the smaller OrchestrationAddressableAgent shape rather than teaching listTerminals about sessions it cannot summarize (its result is published to paired clients under remote-wire-compatibility), and @idle/@codex status reads the full reduced journal via structuredWorkerAgentStatus, so a busy worker is never woken mid-turn and an unreadable session never reads as idle.
  • Made getAgentStatusForHandle answer structured handles — it short-circuits to the journal-derived status instead of returning null from the PTY probe, which is what silently dropped every structured worker from @idle.
  • Refused rather than guessed for a session with no identity — a non-worker structured session's child now carries ORCA_STRUCTURED_SESSION (a marker that names nothing), and the CLI's resolveOrchestrationTerminalHandle refuses with no_active_sender_terminal instead of guessing a sibling pane — a destructive check previously consumed that sibling's oldest unread batch, and requireUnambiguous did not save it because with a single terminal pane the guess still resolved. Explicit --from/--terminal and ORCA_TERMINAL_HANDLE (every worker child) are unaffected.
  • Extracted readStructuredSessionGateFacts into structured-mailbox-pointer-host.ts so the pointer lane and group addressing cannot disagree about the idle gate.

Delivery of a bare structworker_ recipient handle is already covered by the direct-mail lane (resolveStructuredWorkerDirectMailboxTarget), so a group send to a between-dispatch worker still lands as a session turn.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one minor test-coverage nit inline.

Reviewed changes

One commit since the prior review (61577d7a). It stops two surfaces from lying about a worker that has no terminal.

  • Gave terminal verbs a truthful refusal for a structured handle — getLiveLeafForHandle now throws structuredWorkerTerminalRefusal (terminal_unsupported_for_agent_session) for a live structured worker instead of terminal_handle_stale, which falsely claimed the handle died and sent callers hunting for a remint that cannot exist. A PTY handle, or a structured handle this runtime no longer owns, still gets the stale error; the new code is passed through by rpc/errors.ts and the message names the structured equivalents (orca terminal read, worker-read --source transcript, orca orchestration send).
  • Reworded the worker-start spec notes — dropped the false promise of "the same worker-read sources" and instead states "not every worker has a terminal" with the always-working alternatives (--source auto/--source transcript), keeping the worker kind unnamed so mode opacity is preserved.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment on lines +86 to +88
registerWorker()
hostRef.current = null
expect(structuredWorkerTerminalRefusal('term_gone', null).message).toBe('terminal_handle_stale')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This case does not exercise what its name and comment claim. It registers a structworker_ worker and nulls the host, but then calls structuredWorkerTerminalRefusal('term_gone', ...) — a PTY-style handle that short-circuits isStructuredWorkerHandle before the record lookup, so the assertion is identical to the preceding PTY test. It would still pass if the "no longer owns" branch regressed to returning terminal_unsupported_for_agent_session for a released structured handle.

Suggested change
registerWorker()
hostRef.current = null
expect(structuredWorkerTerminalRefusal('term_gone', null).message).toBe('terminal_handle_stale')
const handle = registerWorker()
hostRef.current = null
expect(structuredWorkerTerminalRefusal(handle, null).message).toBe('terminal_handle_stale')

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Isolated Electron QA @ 5b3e4de1cb

Isolated qa-parity instance (CDP 9345, renderer 5191, --use-mock-keychain in ARGV). /@fs this worktree 200, pompano 403. Three structured-chat settings were true at first paint. Worker started as mode: structured / user_default.

Handles: PTY term_aabab304-0b80-40c8-9099-dadeec2f196d, structured Claude structworker_48f3d742-e789-4a43-976b-390b03a8a2d2.

# Check Verdict What I saw
1 Self-identity (run-current / task-list from worker, no --from) PASS Env ORCA_TERMINAL_HANDLE=structworker_…, no --from. run-current exit 0 (ok: true). Never no_active_sender_terminal. After the worker bound its own Run, task-list exit 0. Live worker also ran orca orchestration check from its own Bash tool.
2 Sub-dispatch (task-create then worker-start, no --from) FAIL (nesting, not identity) task-create succeeded (created_by_terminal_handle = structured handle). worker-start failed: Sub-worker dispatch is not permitted at depth 2 (max 1). Identity worked; this worker was already depth 1.
3 Group addressing @all / @idle PASS Both sends exit 0. Live structured worker received both (qa-parity-all, qa-parity-idle) and said so in chat. Receipt to_handle was run:run_bbfc2c0cecdc (the Run it bound), not a raw structworker_ handle. terminal list still lists only the PTY.
4 worktree rm without --force PASS (refused; different guard) Exit 1: Refusing to delete protected worktree path: …/structured-orch-qa. Did not --force. Live-session teardown copy was not reached (this checkout is the running app).
5 dispatch --inject PASS Did not return no_agent_detected. Returned: already has active dispatch ctx_bb075a81373e.
6 terminal read PASS ok: true, status: running, journal tail (preamble + assistant + tool results). Not terminal_handle_stale.
7 terminal send --text hi PASS terminal_unsupported_for_agent_session: agent session, not a terminal — points at terminal read / worker-read --source transcript / orchestration send. Not handle stale.

Renderer console: 0 errors.

First paint (settings seeded, empty profile)

01-first-paint.png

Project loaded

02-project-loaded.png

Structured Claude worker (group-address receipt visible)

03-structured-chat.png

PTY coordinator tab (qa-pty) next to Claude Chat

04-pty-tab.png

Structured chat after focusing the tab

05-structured-chat-messages.png

Merge Sim added 2 commits September 6, 2026 03:14
…y work

Four defects and two follow-ups from the delta review.

The `worktree rm` refusal was a dead end in the desktop UI. Its message matched
no matcher in `classifyWorktreeForceDeleteReason`, and an ordinary desktop delete
already passes `force=true` for the dirty-file skip, so classification returned
null unconditionally: the toast showed raw CLI wording with no Force Delete
button, and a user with a live chat session was stuck unless they knew to reach
for the CLI. That is the #11960 shape `shared/worktree/removal.ts` documents, so
the refusal now has its own prefix, matcher, `WorktreeForceDeleteReason` and
toast copy, classified BEFORE the `force` guard and nulled once the waiver is
spent — exactly how `unstopped-pty` is handled, with matcher and hint kept in
the same file as that contract requires. The copy says Force Delete will close a
running conversation rather than borrowing the "could not confirm" wording,
because Orca watched these sessions stay attached; there is no doubt to waive.

Structured `terminal read` cursors were unsound and are now refused. The PTY
cursor indexes an append-only completed-line buffer with a monotone count; a
session journal is a BOUNDED tail re-projected on every read, so a saved index
addressed different lines as the journal grew — and `truncated` could never fire
to say so, because it tests `cursor < oldestCursor` and `oldestCursor` was always
0. A poller got wrong or duplicated lines under `truncated:false`. Separately, a
streaming turn's lines counted as completed with `partialLine` hardcoded empty,
so a mid-turn cursor consumed a half-written line whose growth was never
redelivered — the `"hel"`/`"hello"` hazard the PTY reader guards against. The
journal does have stable item identity, but `terminal.read`'s cursor is a number
on the wire and cannot carry it, so a cursor read now refuses and names
`worker-read --source transcript`, which already has that contract including
`source_changed`. No cursor space is advertised either: `nextCursor` is null and
the cursor fields are absent, rather than claiming an index the next read cannot
honour. The header claim that all four fields kept their meanings was true of the
shape and false of the invariants; it now says which ones hold.

Two fixes had no test at their real seam, which is the same failure that produced
this whole set — the runtime tested directly, the seam tested by neither. The
group-addressing test hand-composed the recipient list itself, so deleting the
composition at the call site left it green; it now drives `sendGroupMessage` with
no PTY terminals at all. Nothing referenced `isLiveStructuredAgent`, so the
`dispatch --inject` fix had no red-then-green at all; it now has one driving
`RuntimeTerminalAgentPresence.isRunning`. Both were ablated and confirmed red.

Folder-workspace removals sweep and kill PTYs without `requirePhysicalStop`, so
the structured sweep no-opped there and left a live session bound to a workspace
about to be forgotten. They now close best-effort under an explicit
`closeStructuredSessions` flag, kept separate from `requirePhysicalStop` because
the two questions differ: that one asks whether a stop must be PROVEN before
files are touched, and it is what licenses a refusal. These paths do not refuse —
the root is shared so no checkout vanishes under the child, and one of them is a
never-throw forget a refusal would wedge. Reconciliation sweeps set neither and
still close nothing.

Also: the force close is raced against the same sweep deadline every PTY surface
is bounded by, so a wedged provider close reports the timeout instead of hanging
`worktree rm --force` forever; and the refusal now prints a count and the
providers instead of raw session ids, which our own marker rationale treats as
one tab-id hop from a credential.
The folder and orphan removal callers now pass closeStructuredSessions so a
live structured session is closed best-effort rather than left bound to a
workspace Orca has forgotten. These three exact-args characterizations describe
that call and had not been updated.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

Two must-address issues on this delta: a missing i18n key that fails verify:localization-catalog, and a --force timeout that throws instead of warning.

Reviewed changes

  • Closed the worktree rm refusal's desktop dead end — the running-agent-session refusal now has its own RUNNING_AGENT_SESSION_REMOVAL_PREFIX, a running-agent-session classifier branch (decided before the force guard, nulled once the waiver is spent) and Force-Delete toast copy, matching unstopped-pty.
  • Refused structured terminal read cursors — a numeric cursor can't be re-anchored to a re-projected journal tail, so cursor reads now throw and name worker-read --source transcript; no cursor space is advertised (nextCursor: null, cursor fields absent), and a mid-turn read no longer counts a growing line as completed.
  • Closed the two test seams that had no test at their real boundary — group addressing now drives sendGroupMessage with zero PTY terminals, and agent presence drives RuntimeTerminalAgentPresence.isRunning against isLiveStructuredAgent.
  • Made folder-workspace removals close structured sessions best-effort — a new closeStructuredSessions dep, kept separate from requirePhysicalStop, so the sweep no longer no-ops on a path that forgets the workspace.
  • Raced the force close against the sweep deadline and dropped raw session ids from the refusal copy (count + providers instead, since a session id is one tab-id hop from the pane-key credential).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

// provider round trip, and a wedged one would otherwise hang `worktree rm --force` forever with
// no timeout error at all. On expiry the force path reports the timeout exactly as the PTY
// sweeps do rather than proceeding as if the sessions had closed.
const { closed, unstopped } = await settleBeforeDeadline(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Passing deadlineError unconditionally makes the structured sweep fail-closed under --force. Under allowUnverifiedStop the three PTY sweeps also pass deadlineError, but their timeouts are caught by settleSweepsForForcedRemoval (line 203) and turned into a warning plus continued removal. This sweep is awaited directly at line 106, so a structured host.close that outlives the deadline throws Timed out waiting for physical PTY teardown: … Retry with force delete (--force), which the classifier maps to unstopped-pty and tells a user who already forced to force again — the #11960 wedge this path exists to prevent.

Technical details
# Fold the structured sweep into forced settlement

## Affected sites
- src/main/runtime/worktree-teardown.ts:321 — `settleBeforeDeadline(..., deadline, deadlineError)` passes `deadlineError` unconditionally, so a timeout throws even when `allowUnverifiedStop` is set.
- src/main/runtime/worktree-teardown.ts:106 — the sweep is awaited directly, so that throw bypasses the `allowUnverifiedStop` handling below.
- src/main/runtime/forced-sweep-settlement.ts:75 — `settleSweepsForForcedRemoval` reconciles only the three PTY sweeps; the structured sweep is not a member.

## Required outcome
- Under `--force` (`requirePhysicalStop && allowUnverifiedStop`), a structured-session close that exceeds the sweep deadline must warn and let removal continue (matching the PTY sweeps), never throw a timeout that fails `worktree rm --force`.

## Suggested approach (optional)
- Pass `deps.requirePhysicalStop && !deps.allowUnverifiedStop ? deadlineError : undefined` (or otherwise gate on the waiver) so the force path falls back to `{ closed: 0, unstopped: live }`, or add the structured sweep as a fourth member of `settleSweepsForForcedRemoval`.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Live worktree rm structured-session refusal QA @ 45e23ee

Isolated dev instance from structured-orch-qa (CDP 9347 / renderer 5194, --use-mock-keychain in ARGV, /@fs 200 here vs 403 pompano). Throwaway worktrees created through Orca — never the app checkout, never pompano.

Step Result
1. Create throwaway git worktree through Orca PASS
2. worker-start --agent claude → mode.mode = "structured" and session live PASS
3. worktree rm without --force names count + provider, no session id PASS
4. Worktree still on disk; worker still alive PASS
5. worktree rm --force succeeds and actually closes the provider child PASS
6. Desktop delete toast offers Force Delete (not raw-error-only) PASS

Step 3 exact refusal

Refusing to remove worktree with running agent sessions: 45be2f43-fe63-4452-8da9-7b7be7b9a509::/Users/brennanbenson/orca/workspaces/main/qa-rm-throwaway — 1 running agent session (claude). Retry with force delete (--force) to remove it anyway.

This is not Refusing to delete protected worktree path. Count + provider (1 running agent session (claude)), no session id.

Step 5

--force returned {"removed":true}. Disk gone. Claude child PID 27440 (claude --session-id=059a0d4e-…, parent = isolated Electron) gone. worker-show observation went live → exited. worktree show → selector_not_found.

Step 6 desktop toast

Triggered via the Delete Workspace dialog (not CLI). Store: canForceDelete: true, forceDeleteReason: "running-agent-session".

Force Delete toast

Copy: This workspace still has running agent sessions, so Orca stopped before deleting any files. Force Delete will close them and discard any work they hold. Buttons: View + Force Delete.

Merge Sim added 2 commits September 6, 2026 10:52
…ing silently

`worker-read --source transcript` for a structured worker fingerprinted only the
oldest item's id, so `source_changed` fired when the window slid off the front
and could NOT fire when the page's contents changed under a stable oldest item —
which is the normal case, because the journal is a reduced, mutable timeline. A
`running` tool item gains its `[tool result]` at its original sequence once later
items exist, the 60ms delta coalescer revises a message in place, settlement can
rewrite an item smaller, and a pending approval projects to null until it
resolves and then appears in the MIDDLE of the array.

Two silent failures followed, both returning ok. Omission: a caller handed a
coalesced `hel`, resuming past it, never received the revision to `hello world`
— the same defect we refused to ship on the terminal read path, already shipped
here. Duplication: a resolved approval inserted ahead of a saved index, which was
still accepted, so the caller re-read content it already had. The blast radius is
the coordinator polling loop, the verb's primary consumer.

The anchor is now the oldest item PLUS every item whose projected message sits
below the caller's position, by id and revision. `createWorkerOutputSourceIdentity`
already takes an arbitrary string array and the cursor is already opaque
base64url carrying its own position, so neither the wire shape nor the
`source_changed` contract changes.

Prefix-scoped rather than whole-page deliberately: fingerprinting every item on
the page would flip the identity every 60ms with the coalescer window during an
active turn, making the cursor unusable exactly while the worker is working —
that trades a silent bug for a useless verb. Tail growth the caller has not read
cannot invalidate; any change to what it already holds does. Position-dependence
is safe because `p` rides in the same opaque payload as the identity, and the
returned cursor is stamped with the identity of its own end, which is precisely
what the next read recomputes. The frozen archive keeps a constant identity: no
item can be revised under a caller there, so it has no prefix to fingerprint.

Both silent shapes are pinned across a page boundary with the journal mutating
between reads — a static-journal test passes either way. Two ablations at the
real call site: reverting to the oldest-item-only anchor turns both red, and
widening the prefix to the whole page turns the tail-growth case red, which is
what proves the scoping is real in both directions.
…ending a dead end

The refusal told a peer to "page it with `orca orchestration worker-read
--source transcript`", which is wrong three ways and this file said so itself:
its own header explains that this verb exists BECAUSE `worker-read` demands a
dispatch id and coordinator standing "a peer does not have" — and then the
refusal sent that same peer there. The verb it named is also a window index over
the same bounded page, so it is not a paging answer even for a caller who can
reach it; under load it now answers `source_changed` on most polls, which is
better than the silent hole it had before but still not what the sentence
promised.

The refusal now says what actually works — the tail is bounded and newest-last,
so poll it and diff — and names no alternative, because there is none. That is
the honest framing: a durable cursor is not achievable here at all, rather than
blocked on the wire shape. The journal is a reduced, MUTABLE timeline: an item's
projected text changes at its original sequence after later items exist, the
delta coalescer revises repeatedly, settlement can rewrite an item smaller, a
pending approval renders as nothing and then as something, and `sequence` resets
on epoch rollover. No index, numeric or opaque, survives that.

So the docstring's "pagination with a real anchor lives on `worker-read --source
transcript`" is gone too — there is no real anchor there — and the file now
records why no windowed alternative should be built later: a broken cursor fails
UNSAFE, as a silent hole in a poller's output, while diffing a bounded tail fails
safe as a harmless re-read, and a second paging-shaped verb would invite the PTY
assumptions this one cannot honour.

The test asserted the old advice, so it now pins the contract instead: the
refusal explains the working approach and must never name `worker-read`.
`worker-read --source transcript` remains a good bounded snapshot for a
coordinator reading a worker it dispatched; only the "or page it with" clause was
false.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The cursor fix in this delta is clean and I found no new issues in it. I'm withholding approval because two must-address findings from the prior review are still open and unchanged by this commit: the runningAgentSession i18n key is still missing from en.json (fails verify:localization-catalog, part of pnpm lint), and the structured sweep still passes deadlineError unconditionally so a --force close that outlives the deadline throws instead of warning. A third open thread (the structured-worker-terminal-refusal.test.ts "no longer owns" case still passing 'term_gone') is a test-coverage nit. These are tracked in the existing threads and are not re-raised inline.

Reviewed changes

The single commit since the prior review (45e23ee) fixes a silent misdelivery in the structured worker-read --source transcript cursor.

  • Re-anchored the source_changed identity on the held prefix — the old anchor fingerprinted only the oldest journal item's id, so an in-place revision under a stable oldest item (a running tool gaining its [tool result], the delta coalescer revising a message) resumed past the revision with no error, and a resolved approval inserting into the middle of the array re-served already-delivered content. structuredJournalPrefixIdentity now fingerprints the oldest item (the window-slide detector) plus every projected item below the cursor position by itemId and revision, scoped to the prefix the caller already holds rather than the whole page so the coalescer's 60ms tail revisions don't invalidate the cursor mid-turn.
  • Stamped the returned cursor with its own end — pageMessages now writes identityAt(end), so the next read's check recomputes exactly the prefix a caller was handed and catches both omission and duplication.
  • Kept the archive path position-independent — archived reads use a constant identityAt: () => sourceIdentity since the archive is frozen before close and nothing can revise under a caller.
  • Pinned the mutating-journal cases by test — structured-worker-read-cursor.test.ts mutates the journal between reads across five cases (in-place revision, mid-array insertion, allowed tail-only growth, exactly-once delivery, window slide); a static-journal test would pass under either anchor.

I traced the index-alignment claim the prefix identity depends on: projectStructuredItemToNativeChat(item) !== null selects exactly the items projectStructuredItemsToNativeChat keeps, in order, and boundWorkerTranscriptMessages returns a head prefix of that array, so message index i maps to item i for every index a cursor can name. The implementation is consistent, and the new test file passes (5/5).

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No new issues in this delta. It corrects a misleading refusal message; approval remains held by the three open threads from the prior review (each unchanged by this commit).

Reviewed changes

  • Stopped the terminal read cursor refusal from steering a peer at a dead end — the message previously recommended worker-read --source transcript, which a peer reaching terminal read cannot run (no dispatch id, no coordinator standing) and which is a window index over the same bounded tail rather than an append-only anchor. It now says to read without --cursor and poll-and-diff, names no paging alternative, and the header documents why the refusal is permanent: a broken cursor fails unsafe (a silent hole in a poller's output) while diffing a bounded newest-last tail fails safe (a harmless re-read).
  • Pinned the new wording by test — the cursor-refusal test now asserts the message still says not line-addressable, that it instructs poll it and diff, and that it never mentions worker-read.

The change is message- and comment-scoped (structured-worker-terminal-read.ts + its test). The sibling structured-worker-terminal-refusal.ts (terminal.show surface) still names worker-read --source transcript, which is correct there — that caller has dispatch context — so the fix is scoped to the one surface where the redirect was wrong. structured-worker-terminal-read.test.ts passes (9/9).

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Merge Sim added 2 commits September 6, 2026 11:08
Carries main's #19040 through this branch's two extractions, which would
otherwise have silently reverted it: both conflicts are the same shape,
where main fixed code this branch had already moved elsewhere.

- resolveStructuredNativeChatSupport no longer refuses a launch that has
  saved session options. Main removed that term from resolveAgentLaunchRoute
  directly; this branch had lifted the whole predicate into the shared
  module, so taking either conflict side kept the refusal alive. The blocker
  member, the unused input field, the orchestration blocker-to-reason entry
  and the case pinning it are removed with it. Main's own routing test failed
  on this merge before the port and passes after, which is what proves the
  port is load-bearing rather than cosmetic.

- The structured create fingerprint now goes through attachFingerprintFields.
  Same shape again: main replaced the inline field list in
  structured-agent-session.ts, but this branch had moved that computation
  into structured-agent-session-create.ts. Options stay out of the digest,
  which is main's point: they are the session's initial state, not its
  identity, so a retry after the user reselects a model replays instead of
  conflicting.
The structured-session removal refusal introduced a translate() key with no
en.json entry. Nothing local catches that: typecheck passes, and the full
suite passes, because a missing key falls back to its inline default at
runtime. Only verify:localization-catalog fails on it, which is why CI's
static analysis reddened on a branch that was green everywhere else.

Fallback wording mirrors the sibling unstoppedPtyLive string, since the two
refusals differ only in what is still running and what Force Delete does to it.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

This delta is a clean origin/main merge with no new issues, but I'm withholding approval because two must-address findings from prior reviews remain open and unchanged by the merge: the runningAgentSession i18n key is still absent from src/renderer/src/i18n/locales/en.json (fails verify:localization-catalog, part of pnpm lint), and the structured sweep still passes deadlineError unconditionally so a --force close that outlives the deadline throws instead of warning. A third minor test-coverage thread (structured-worker-terminal-refusal.test.ts "no longer owns" case still passing 'term_gone') is also still open. All three are tracked in their existing threads and are not re-raised here.

Reviewed changes

The single commit since the prior review is a merge of origin/main into the branch. The net reconciliation in PR-owned files is mechanical and correct:

  • Adopted main's extracted attachFingerprintFields — the create path (structured-agent-session-create.ts) now computes its host fingerprint via the shared helper instead of an inline copy that hardcoded expectedRuntimeFence: null and omitted providerHandle. This aligns the create fingerprint with what admitAttachOrRefuse recomputes on the attach path; the old inline form would have diverged for a non-null fence. I traced resolveStructuredAgentSessionCreateIntent → full AgentSessionAttachParams, so attachFingerprintFields({ ...resolved, envelope }) reconstructs a valid params shape.
  • Picked up the initial-session-options removal (#19040) — resolveStructuredNativeChatSupport no longer blocks structured routing on saved session options, and the worker-start mode decision (orchestration-worker-start-mode.ts) follows suit, keeping the shared launch-route module in lockstep with main.

The remainder of the merge is main's own CI/SSH/WSL/cloud/relay commits and is out of scope.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Merge Sim added 3 commits September 6, 2026 11:52
…red child

The refuse-rather-than-guess marker landed after these expectations were
written, and all three assert exact env equality on the unregistered path —
the one branch that now carries ORCA_STRUCTURED_SESSION. One of the two files
was added by this same branch, so this is a self-inflicted drift; the other
predates the branch and was broken by it.

The marker's presence is still pinned positively by
structured-worker-child-identity-env.test.ts and the CLI's
orchestration-structured-session-no-identity.test.ts, so relaxing these three
exact-equality checks loses no coverage of the security property.
Carries the durable multi-agent workflow work (#16904) through this branch.
Both PRs touch the same subsystem, so most of this is deciding which of two
independent solutions to the same problem survives. #16904 did not generalize
past the PTY assumption anywhere, so nothing here is redundant: it hardens the
first authority source, this branch adds a second under the same contracts.

Schema. Both sides independently wrote a `current < 31` migration from a shared
base of 30, with different bodies, and main went on to 38. Version 31 therefore
means two different schemas, and the skew checker asserts main's five v31
columns for anything stamped >= 31 — so a database written by this branch failed
the completeness check and replayed the whole chain from v6. That is the checker
working correctly, not a defect, and the replay is row-safe (every DROP in the
chain is a copy-forward rebuild gated on shape, and there is no DELETE or
TRUNCATE anywhere in it). Nothing shipped stamped 31 with this branch's content:
the commit is in no tag and no release branch. So the migration renumbers to 39
in its own file. It no longer creates `structured_pointer_operations` — that is
redundant, because `createTables` runs unconditionally on every open, ahead of
migration. Only the widened archive CHECK needs a migration, since IF NOT EXISTS
cannot widen a constraint on an existing table. The gratuitous rename of
migrate-v13-v30.ts is reverted, which removes a conflict outright.

Batch selection. Both sides changed the same region: this branch extracted it
verbatim into `selectOrchestrationPointerBatch`, main edited it in place and
dropped the JS post-filter. Main is right, and provably so — the unfiltered
waiter returns early, so every surviving waiter contributes a concrete type list
that SQL excludes byte-exactly (`messages.type` is TEXT with no NOCASE
collation), and the trailing slice sits behind an identical SQL LIMIT. Nothing
can reach the post-pass in a filtering state, for either lane, and selection is
synchronous throughout so no waiter can register inside it. The extraction
survives and main's lane now calls it, so the two lanes cannot drift again. The
docblock claimed the post-filter caught a mid-selection waiter; that hazard does
not exist and the claim is gone. Nothing covered this, so it now has tests
against a real database rather than a stub.

Delivery gate. This branch gated only `run:` mailboxes, on the premise that a
delivery row exists only for a `run:` address. Main made that false — deliveries
are keyed by any mailbox handle — and generalized correctly, keying the lookup
on the exact handle being nudged, so a coordinator's run delivery cannot
suppress the nudges it sends its workers. Adopted. It is worth more here than in
the PTY lane: a structured nudge costs a whole provider turn.

Archive kind. Main's new `summarizeWorkerOutputArchive` is a two-way switch that
JSON-parses every non-transcript_pin kind as a terminal tail, so this branch's
`structured_journal` reached `content.lines.every(...)` and threw, at three live
call sites. A structured session's journal reports as `transcript`: it IS the
session's transcript, and a third source value would both leak the
structured/terminal split into a CLI surface this PR keeps uniform and widen a
shape that reaches paired clients.

PTY pointer refusal. Main shipped the same fix independently and narrower, so
this branch's hunk is dropped. Its guard fires only when a session is bound,
which is exactly the set the blanket refusal covered — an unbound pty is always
admitted, so a denial implies a binding.

Also: this branch's release-receipt extraction gives way to main's, with the
structured lease check moved into main's lease module; the worker RPC tree moves
into main's orchestration/{worker,messaging,federation} layout, with this
branch's structured branches replayed into the new homes.

pnpm tc clean. Verified by grepping the MERGED files, not the diffs, that main's
migration registrations, its six durability attach calls, its reset delete, its
fleet-status additions and its dispatch-pointer support all survived — each of
those would have been dropped silently by a keep-ours resolution, with no
conflict marker and a green typecheck.

Both merged files crossed the 300-line cap, which must be split rather than
disabled. Four extractions, each a whole step rather than an arbitrary cut:
assertExplicitWorkerTerminalUsable (the three refusals that must happen before
anything is created), deliverWorkerDispatchPreamble (one preamble, two
transports), tearDownFailedWorkerStart (undo what a failed start created), and
stopStructuredWorkerForRelease (the close half of a release for a worker with no
terminal to close).

One thing this merge restores rather than adds: `canDispatchSubWorkers` on the
local worker's dispatch preamble. The shared ancestor passed it; main's
extraction of startLocalWorker does not, and `buildDispatchPreamble` treats its
absence as false, so a locally started worker on main is no longer taught the
sub-dispatch verbs. With the default nested depth of 1 that section applied to
every first-generation worker, and main still passes the same argument at three
other call sites, so this reads as a line lost while moving ~300 lines rather
than a decision. Restored here for both lanes, since a worker is taught the same
verbs whichever mode it runs in.
Ten commits, of which six are store/selector performance work that touches
nothing here. Two conflicts, both in skill-guide expectations, and both taken
from main: they assert the wording of a guide rewrite that main has now
reverted (#19126), and this branch never authored them — the only commit on
this side that touches those files is the previous merge, which carried main's
own content at the time.

Worth noting for the PR description rather than the code: main's #19121 makes
worker lineage survive an app restart, which is the limitation this branch
documents as deferred. Whether it closes that gap for a structured worker needs
checking separately; the structured lane keeps no hold across a restart for its
own reasons, so the two are not obviously the same fix.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The merge reconciliation in this delta is clean and I found no new issues in it. I'm withholding approval because one must-address finding from an earlier commit is still open and unchanged by these merges — it stays tracked in its existing thread and is not re-raised inline.

Reviewed changes

  • Merged origin/main twice (ed25b3efd7, 4cc4395781), pulling in #16904 (durable multi-agent workflows — the orchestration RPC methods move into orchestration/worker, messaging, runs, federation subdirectories, plus schema v31–v38), #19121 (worker lineage across restart), #18986, #18741, and a batch of perf/test commits.
  • Ported the structured-worker branches onto the re-organized structure — startLocalWorker still resolves a structured coordinator's worktree through resolveDispatchCallerWorktreeId (never showTerminal), and the take-over RPC resolves sessionId→pane key with the resume-fence sweep gated on changed > 0.
  • Moved the journal-archive rebuild to schema v39 — migrate-v39.ts rebuilds worker_terminal_archives to admit structured_journal; structured_pointer_operations stays in createTables; the migration test stamps user_version = 38 so only v39 runs and proves old rows survive.
  • Re-keyed the structured delivery gate onto hasOutstandingMailboxDelivery, keyed on the exact handle being nudged (an improvement over the old run:-only check), and corrected the archive-source mapping so structured_journal reports as a transcript source.

The reconciliation preserves structured-worker behavior: 57 targeted tests across the touched paths pass, including the mode-opacity, delivery, lifecycle, abandon, and schema-migration suites.

⚠️ worktree rm --force can still throw on a slow structured close

sweepStructuredSessions still passes deadlineError unconditionally to settleBeforeDeadline (worktree-teardown.ts:325), and that sweep is awaited directly at line 106 before settleSweepsForForcedRemoval runs — so a structured host.close that outlives the sweep deadline throws Timed out waiting for physical PTY teardown… and fails worktree rm --force, violating the #11960 "force never wedges" contract, whereas the three PTY sweeps reconcile their timeouts under force into a warning + continued removal. This was raised in a prior review and is unchanged by these merges; it is the sole remaining blocker. The minor test-coverage nit in structured-worker-terminal-refusal.test.ts (the "no longer owns" case passes 'term_gone') is also still open.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

This delta's change is clean and I found no new issues in it. I'm withholding approval because the sole remaining blocker from earlier commits — sweepStructuredSessions passing deadlineError unconditionally, so a --force close that outlives the deadline throws instead of warning (worktree-teardown.ts:321) — is still open and unchanged by this commit; it stays in its existing thread and is not re-raised here. The minor test-coverage nit in structured-worker-terminal-refusal.test.ts is likewise still open.

Reviewed changes

  • Required positive exit evidence before settling a structured close — closeStructuredAgentSessionChild now settles only when observeStructuredWorker(...).status === 'exited' (a released claim with death evidence), where it previously settled for anything that was not live. An unverifiable observation — no durable record, a terminal owner, an uninstalled host, or a restarted session with no attached child — is no longer reported as stopped: true with its tab retired on unproven death, and the observation's reason is now surfaced on the retained outcome.
  • Pinned each retention path by test — the lifecycle suite's it.each covers hasSession: false, runtimeKind: 'tui', claimStatus: 'released', and record: null; the stop-receipt suite adds the restarted-worker case (close with no attached session reports stop_unknown while still issuing the close); the teardown harness now records release + death evidence on close so its assertions mirror the real host.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

This delta is a clean origin/main merge with no new issues, but approval stays withheld: the sole remaining blocker from earlier commits — sweepStructuredSessions passing deadlineError unconditionally (worktree-teardown.ts:325), so a --force close that outlives the deadline throws instead of warning — is still open and unchanged by the merge. The minor test-coverage nit in structured-worker-terminal-refusal.test.ts is likewise still open. Both stay in their existing threads and are not re-raised here.

Reviewed changes

The single commit since the prior review (d70eb61b2f) is a merge of origin/main into the branch. The net reconciliation in PR-owned files is mechanical and correct:

  • Adopted main's late-dispatch settlement in the shared host — structured-agent-session-host.ts picks up settleStructuredAgentSessionLateDispatch (main's #19140) exposed as settleLateDispatch, plus the statusFeed onStatusChanged callback, the replay: true restore publish, and the attachContext → lifetimeContext() collapse. The PR's own journalSnapshot method and structuredAgentSessionHostTeardownPhases extraction are preserved verbatim (both still resolve from requireSession(...).journal.snapshot() and the extracted teardown module).
  • Renderer link-action popover flows in — NativeChatResolvedView.tsx and NativeChatStructuredSession.tsx swap to useNativeChatLinkActions (main's #19130). The PR's removal of the "Orchestration paused" notice is intact; NativeChatOrchestrationPausedNotice no longer exists anywhere in src/.

No PR-authored commits and no behavioral surface to the PR's own orchestration logic in this delta — the PR-owned structured-worker-* and orchestration/* files are untouched by the merge.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Reviewed through 5f74aa23dd078446b592ca8183f06534fb8aa870 and pushed one focused fix: structured-session close now requires positive exited evidence before reporting success and retiring the tab. An unattached or otherwise unverifiable session keeps the existing unknown-stop outcome. Added five regression cases across four test files.

Merged main in 5f74aa23dd to include its journal activity API and matching fixtures, resolving the merge-result journal.lastActivityAt test mismatch without a workaround.

Same-model review/fix/re-review and independent initial/final readiness, plus a fresh merged-head integration review, found no remaining proven in-scope issue. Historical severity review classified the fixed issue as P2. The fix adds no observer calls, polling, subprocesses, or retained state.

Validation:

  • 483 tests across 56 changed test files passed; 21 host lifecycle tests also passed.
  • Full pnpm tc and changed-code-quality checks passed with zero new findings. After merging main, full typecheck and six affected suites / 111 tests passed again.
  • Independent nine-scenario close matrix and worker-stop RPC/DB regression passed; four negative tests failed before the fix.
  • Real Linux SSH QA exercised authenticated Codex terminal fallback, mailbox/completion, disconnect survival, reconnect, release, and archived exit evidence. The disposable environment was cleaned up. A container login-shell PATH issue required the absolute relay launcher; comparison did not establish a PR regression.

Grok validated the isolated background Electron app at d70eb61b2f: native structured Claude and Codex start, accepted preamble, between-turn mailbox pointer/ACK, worker_done, journal reads, and release with a captured transcript and closed tab. Both structured chats and a neighboring adopted PTY chat rendered without the obsolete paused banner. The disposable app/profile/repo and SSH environment were cleaned up.

Full-app evidence from the adopted PTY chat (no paused banner; this frame does not prove mailbox consumption):

Adopted PTY chat without paused banner

Provider screenshots containing worker identifiers were excluded from this comment. The improved latest Claude ACK screenshot and a stop before worker completion were not finished when Grok stalled; those are explicit accepted gaps. The observed stop calls were post-completion no-ops, while release performed the close. Live Electron/SSH QA was not repeated after the main merge.

CI is green on 5f74aa23dd: 25 passed, 14 skipped, none pending or failed, including all eight test shards, verification, packaging, wire compatibility, changed E2E specs and SSH Docker watcher isolation. PR Checks run.

Coverage limits: native Windows/WSL was not run (accepted for this review), nor live mobile/older-client compatibility or an exhaustive restart/network-fault matrix. No merge performed.

@brennanb2025
brennanb2025 merged commit 68dd390 into main Sep 7, 2026
39 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#18827)

* feat(orchestration): orchestrate native-born structured chat sessions

Orchestration resolves every worker through a terminal handle and a pane key
backed by a live PTY. A session created directly as structured has neither, so
it was not refused by orchestration — it was invisible. A coordinator could not
start one, address one, or receive `worker_done` from one.

Add a second authority source rather than a parameter channel. A registry maps a
session id to the same three facts the PTY path supplies — a bearer handle, a
pane key and a host scope — and the four runtime getters consult it before
giving up on `ptysById`. `orchestration.send` and `verifyDispatchCapability` are
untouched: authority stays host-derived and the CLI still cannot assert who it
is. PTY handles short-circuit on the handle prefix, so the terminal path is
unchanged.

Mail travels as a session turn instead of as bytes, on a sibling lane that keeps
the PTY lane's outstanding-run, waiter, reserved-type and batch rules.
Orchestration's database stays the source of truth; the send is best-effort,
exactly as the byte write is, and mail is consumed only on a proven-accepted
dispatch. Delivery waits for the session to be between turns, because one
provider refuses a mid-turn start outright and the other cannot acknowledge one
inside the ack window.

Security properties, each pinned by test: the pane key's leaf is random and
persisted rather than derived, since `check` is identity-gated and accepts a
caller-supplied pane key; the handle is a random bearer token; the child env
carries no pane key, which would otherwise flow into hook pipelines that assume
a PTY leaf; hook attestation stays closed for structured handles; and process
continuity comes from record lineage, never the runtime fence, which the host
bumps during its own crash recovery.

Also remove the "Orchestration paused" notice, which gated only on dispatch
status and rendered over bridge chat where orchestration always worked; refuse
the implicit-sender fallback when a worktree has more than one candidate leaf
instead of guessing; and collapse the archive kinds to one named type with a
compile-time assertion that the capture set cannot drift ahead of the storable
set.

* fix(orchestration): answer the structured idle gate from the reduced timeline

The structured pointer gate read a bounded 40-item tail page. A settled turn is
tombstoned rather than rewritten, so an idle worker with any real history carries
no turnLifecycle item at all and the "full page, no lifecycle item" guard read it
as busy forever: every nudge after the worker's first substantial turn parked on a
settle edge that had already passed, and the preamble tells workers not to poll.
The attention gate had the mirror bug — a prompt older than the tail window was
missed and the nudge was delivered into a session blocked on a human.

Both facts now come from `journal.snapshot()`, the fully reduced timeline, via a
new narrow `readGateFacts` host read; the policy module stays pure and still
projects through the shared helpers the chat view reads.

Also:
- Park `session-not-attached` on the journal edge, so mail that arrives during a
  transient detach is redriven by the re-attach reset instead of sitting unread.
- Resolve a structured worker's provider from the durable agent-session record
  when the registry entry was rehydrated, so a restarted Codex worker is no longer
  reported and archived as Claude.
- Clear `structured_pointer_operations` in every `orchestration reset` scope.
- Drop the per-chat-pane dispatch-status store subscription left behind by the
  removed paused notice, and re-pin the two terminal-pane ratchets it moves.
- Hoist the identical pointer batch selection out of both delivery lanes into
  `selectOrchestrationPointerBatch`.
- Refuse the pre-graph-ready focus-based guess for `requireUnambiguous` callers,
  matching the ready path.
- Move the host teardown phase list into the teardown module it belongs to, which
  is what keeps the host inside its max-lines budget.

* fix(orchestration): discard a structured worker session whose create settled unknown

`commitStructuredAgentSessionCreate` answers `agent_session_operation_unknown` when
`attach` SUCCEEDED and only the tab publish failed, so `created.ok === false` is not
proof that nothing exists. The worker start read it that way and skipped
`discardCreatedSession`, leaving a live provider child that took no hold, has no
`bindingsByDispatchId` entry and no published tab — the outer
`releaseStructuredWorkerSession` no-ops without a binding, and a session that never had
a holder never starts the eviction clock, so nothing in the runtime ever retires it. A
throw out of the commit half is past `attach` for the same reason; the pre-commit half
refuses rather than throwing. Cleanup now asks whether the create MAY have committed,
via the existing `isDefinitiveAgentSessionCreateRefusal` predicate.

Also:
- Strengthen the pre-ready `requireUnambiguous` test so it actually pins the guard: the
  snapshot now carries a focused terminal, so deleting the `? [] :` ternary turns the
  test red instead of leaving the refusal to the ambiguous `listTerminals` fallback.
- Correct the guard's justification comment, which cited `orchestration check` as
  covered. `check` resolves through the `--terminal` scope and still guesses; the
  guard covers the implicit `--from` sender, and a structured worker is covered by the
  `ORCA_TERMINAL_HANDLE` baked into its child.

* docs(orchestration): stop two structured-worker comments claiming guarantees the code does not give

The send-time owner re-check reads `target.refusal`, the snapshot the resolver
already admitted, so `decideStructuredPointerDelivery` can only agree with the
resolve-time answer and `owner-not-settled-native` is unreachable from that call
site. What actually fences an owner that moved is `expectedRuntimeFence`, which a
handoff bumps. Say that, so nobody later drops the fence trusting a re-check that
is structurally a tautology.

`discardCreatedSession` was credited with retiring "a published background tab
that no dispatch owns". It hides the DURABLE tab reference and closes the
session; the live tab snapshot keeps the row, so the background tab this start
published stays on screen until the app restarts. Same for stop and release. The
comment now describes what the two calls do — including that both are no-ops on a
session that was never attached, which is what makes the non-definitive-refusal
path safe to reach unconditionally.

* fix(orchestration): retire a structured worker's chat tab when the worker settles

Starting a structured worker always publishes a real `agent-session:<id>` tab, but
every settlement path only called `setSessionTabVisibility(sessionId, false)` plus
`host.close(sessionId)`. That clears the DURABLE restore index and leaves the LIVE
snapshot untouched, so stop, release and the half-started discard all left a dead
"Claude Chat" / "Codex Chat" tab in the worktree's tab bar for the rest of the app
session — five dispatches, five dead tabs — and opening one re-attached the released
session, respawning a provider child outside orchestration's hold accounting.

The snapshot-pruning half of `closeStructuredAgentSessionTab` is extracted into
`structured-agent-session-tab-retirement.ts` and exposed on the runtime as
`retireStructuredAgentSessionTabFromSnapshot`, so the user-initiated tab close and
the three settlements share one implementation instead of a second copy.

The settlement side is best-effort BY CONSTRUCTION: it runs only after the close is
already proven, calls the runtime method optionally, and swallows any throw. It
talks to no renderer, so the startup release reconciler can call it too. Nothing
here can turn a proven stop into `release_unknown`.

* fix(orchestration): stop a structured worker's nudges, archive and liveness from lying

Five defects in the structured-worker lanes, each with the same shape: a check
that answered from something other than what it claimed to measure.

- The pointer lane gated a WORKER's `dispatch:` mailbox on its RUN's outstanding
  delivery. Delivery rows exist only for a `run:` address, so that row belongs to
  the coordinator — and a coordinator holds one for exactly as long as it is
  acting on received mail, which is when it replies to its workers. The gate is
  gone; there is no coordinator mailbox in this lane to protect.
- `dispatch-rejected` now parks on the journal edge. A rejection consumes no mail
  and nothing else redrives the mailbox, so an unparked pointer left the worker
  idle on durable mail until unrelated mail happened to arrive.
- The released journal archive bounded forward — keeping the HEAD — before
  capping newest-first, so a long worker's archive ended at its early exploration
  and dropped the answer it was released for, under a warning that said the
  oldest messages had gone. One newest-first pass now, and the warning is true.
- The durable pointer operation id was reused on a matching BODY fingerprint, and
  the body names only the unread count. Two unrelated same-size batches collided,
  the host replayed its ledger answer as `accepted` with no turn sent, and the
  lane marked the new mail delivered. Reuse is keyed on the batch's message ids.
- `worker-read` on a structured worker hardcoded `terminal: 'running'` and
  emitted no `liveness`, so a runtime that could not see the session reported the
  worker as alive. It now carries the observed verdict, as the PTY branch does.

Also: the live journal cursor is an index into a re-derived tail window, so the
page's oldest item joins its source identity — a slid window now answers
`source_changed` instead of silently resuming past the items it skipped. And a
stop that reached no host reports `processAction: 'none'`, after installing the
host the way release already does.

* fix(orchestration): stop a released structured archive claiming a close that never landed

`worker-read` on a released structured worker hardcoded `liveness: 'exited'`. The
archive is frozen BEFORE the close, so it proves nothing about the provider child,
and the read is served for `release_state` in `releasing` / `unknown` too — the two
states that exist precisely to record a close that did NOT land. A coordinator that
read `exited` from a `release_unknown` worker would start a replacement over the same
worktree while the original child was still attached, which is the outcome
docs/reference/ssh-execution-boundary.md rule 2 exists to prevent, and it contradicts
the release receipt's own "the structured session close was not proven" text.

The verdict now comes from the resource row the read already holds: only a settled
`released` row is `exited`, everything else is `unverifiable` — which the existing
mapping renders as `terminal: 'unknown'`, the same way the live branch does.

* fix(orchestration): stop a structured worker-start reporting a preamble it never delivered

Two ways a structured `worker-start` handed the coordinator a receipt that did not
describe the worker it got.

`sendStructuredWorkerPreamble` threw only on a refusal and on `rejected`, so a
submission that settled `unknown` fell through as success: the start pushed
`dispatch_input: accepted` and marked the dispatch ready. `unknown` is not rare —
`dispatchSafely` converts ANY thrown adapter call (provider child gone, transport
dropped, ack window missed) into it, and `performSend` still returns ok. The worker
then has no task spec while its coordinator blocks in `check --wait --types
worker_done` until timeout. This PR's own mail lane already states the rule —
"`pending` is not yet an acknowledgement; only `accepted` may consume mail" — so the
preamble now applies it too, and raises `operation_unknown` for the states that
prove neither delivery nor failure, which is the code `failWorkerStartWithReceipt`
turns into the `outcome_unknown` receipt whose nextCommands send the coordinator to
look. `rejected` stays a proven failure.

`--structured` also accepted `--model` / `--effort` and dropped them: structured
session creation takes no launch preferences, while `launch.receipt.effective`
echoes whatever was requested either way, so `--model opus` ran on the workspace
default and the receipt still said `opus`. Refused now, for the same reason
`--terminal` refuses them, and the spec note records that refusal along with the
new-child/new-top-level one it never mentioned.

Tests: the refusal guard had no coverage at all, and `structured-mailbox-pointer-host`
— where the full-timeline gate read lives — had none either; reinstating the bounded
tail there left the whole repo green. Both are covered now, and the vacuous
"never selects an exact provider session" case is re-pointed at the absent
`ORCA_PANE_KEY` that actually keeps that selector shut.

* fix(orchestration): let a structured worker actually reach the Orca CLI, and stop four settlements lying

A structured worker's provider child runs `orca orchestration ...` exactly like a PTY worker's
agent does, but it was handed the ambient PATH. On packaged Linux the CLI installs as `orca-ide`
so it never claims GNOME Orca's /usr/bin/orca (stablyai#7904), so bare `orca` execs the screen reader and
the worker can never read mail, reply or send worker_done; on packaged macOS/Windows the bundled
launcher is only reachable from the app's own resources dir. The PTY lane already solves this
inside `buildPtyHostEnv`; that block is now its own module and both lanes call it.

Also:
- a worker start that fails AFTER its session exists now discards the session, so a failed start
  stops stranding a dead chat tab that the durable restore index republishes on every launch;
- a structured worker's resource reconciles to `released` after settlement forgot its identity,
  instead of answering `unverifiable` for the life of the DB;
- `closeAttempted` is set only once a close is issued, so a tab-visibility failure can no longer
  report `closed_agent_terminal` for a running child;
- `forgetSession` prunes only what the settled worker parked, not every sibling whose target
  momentarily fails to resolve;
- release settles with an explicitly empty, warned archive when the journal is unreadable AND the
  session is proven exited — closing the chat tab is routine, and `archive_failed` there wedged
  release on evidence that could never arrive;
- the new migration test uses mkdtemp and cleans up, so it stops failing Windows CI and leaking.

* fix(orchestration): merge the duplicated release-receipts import

The release-completion module imported ./orchestration-worker-release-receipts
twice, which trips import/no-duplicates in audit:code-quality:native. The
changed-file gate does not load that config, so only whole-tree CI saw it.

* docs(runtime): note that a background structured tab re-publish is a no-op

The activate:false branch for an already-published session returns without
writing the snapshot or emitting, so it cannot re-surface a client whose
mirror lost the tab. Orchestration is safe from this only incidentally.

* feat(orchestration): make the worker mode the user's own default, not a flag

`worker-start --structured` was an explicit opt-in that REFUSED --on, --terminal,
--model/--effort and worktree-creating placements. The flag, its spec entry and the
`structured` RPC param are gone: the mode now follows the user's setting for new agent
tabs, so a local claude/codex worker is a structured chat session whenever the user's
own default says agent tabs open as one.

A setting is a preference, not a demand, so none of those combinations refuses any more.
A dispatch that cannot be structured starts an ordinary PTY terminal worker and the
receipt names the mode that ran and why, so the fallback is never silent:

- a remote --on, an existing --terminal, a new-child/new-top-level worktree and
  --model/--effort are decided from the request;
- the agent, TUI launch customization, Codex-on-Windows and the runtime capability are
  decided by the shared launch route;
- WSL, remoteness and the Windows start-time gate are settled by the executing host's own
  agentSession.createSupport, asked once the worktree resolves and before anything is
  created, so a refusal is a terminal worker rather than a failed start.

The decision is the renderer's, lifted rather than copied: `resolveAgentLaunchRoute`'s
structured half and the settings predicate now live in
shared/structured-native-chat-launch-route, which both surfaces call, and the TUI launch
customization test moves to shared beside it. `getClientSettings` gains the two native-chat
default booleans it was missing.

No security invariant moves: the structured worker registry, bearer handle, persisted pane
key, the absence of ORCA_PANE_KEY from the child env, hook attestation and lineage-derived
process incarnation are untouched.

* fix(orchestration): stop the worker mode leaking into the agent contract

The mode a worker runs in is a runtime implementation detail. An agent should be
taught the same verbs, run the same commands and read the same receipts whether it
is a structured chat session or a PTY terminal — otherwise a settings-driven
fallback silently changes what the agent can do.

The real leak was `canDispatchSubWorkers`, which was forced false for a structured
worker. That was not a wording choice: `worker-start` resolved `--from` through
`showTerminal`, which needs a live PTY or renderer leaf, so a `structworker_`
coordinator genuinely could not dispatch. Rather than withhold the capability, the
one fact the command needs from `--from` — its worktree id — now comes from
`getOrchestrationDispatchAuthority`, the same authority the pane-key and
process-incarnation getters already answer structured handles from. Sub-dispatch is
gated on depth alone, identically for both modes.

`showTerminal` itself is deliberately NOT taught structured handles: it returns a
ptyId, a leaf id and a pane runtime id, and synthesising those for a session with no
PTY would hand every caller of a public terminal verb something that looks writable
and is not. `inspectWorkerTerminal` already returns `terminal: null` for exactly
that reason.

Also neutralised three agent-visible refusals that named the worker's kind: a
`worker-read --source terminal` on a worker with no terminal now names the sources
that do work, and both archive refusals say "transcript output" rather than
"structured chat output" (the PTY `transcript_pin` branch said "structured" too).

New tests pin both properties: the two preambles are byte-identical once the handle
and per-dispatch ids are normalised, and a structured coordinator starts a worker
with `showTerminal` rejecting.

* fix(orchestration): stop claiming a structured worker was checked for a prompt

worker-show reported observation.agentWait: null for every structured worker. The
field's own contract says null means Orca looked and found no wait, and absent means
it never looked — and nothing looks here: a structured worker parks on a journal
question item, which no terminal prompt scan can see.

So null was a false negative on the one field a coordinator is explicitly told to
read, and it was mode-dependent: the same worker as a PTY would have reported the
wait. Absent is both the honest value and a state a PTY worker already reaches (an
older host, an unreadable pane, a probe that did not answer), so it discloses
nothing about which mode ran.

* docs(cli): stop the worker-start spec pointing a caller at the worker kind

The note said "the receipt mode field names the mode used and why", which is an
instruction to read a field no verb behaves differently for — the one thing the
mode was not supposed to become. It now says what a caller actually needs: the
dispatch always starts, the options passed are the ones honoured, and every worker
is driven the same way. The receipt still carries the mode for operators and
telemetry; nothing tells an agent to look at it.

* perf(orchestration): coalesce the structured redrive edge

Every journal batch is a redrive candidate, because a settled turn is tombstoned
rather than rewritten — there is no completed row to watch for. That is free while
nothing is parked on the session, but once mail IS parked each batch re-resolved the
dispatch, queried unread mail and read the host's gate facts, only to re-park because
the turn was still running. A turn streaming tool calls paid that per batch.

The edge now coalesces on a 300ms quiet window with a 2s starvation cap, so a
streaming turn costs a handful of evaluations instead of one per batch and a settled
turn still nudges promptly. Delivery semantics are untouched: the gate, the
accepted/rejected/unknown handling and the retain rules all still run exactly as
before, just fewer times. Nor is this the path fresh mail takes to an idle worker —
that is `deliverForHandle` at enqueue time, which this does not touch — so the
common case gains no latency.

The mechanism is the session.tabs notify coalescer, generalised into
`keyed-trailing-edge-coalescer` and called by both rather than duplicated; the
session.tabs windows stay where they were, since 50ms is right for a spinner title
and far too tight for a journal stream. Disposal drops the pending timer rather than
flushing it, on the existing subscription disposer that every settlement already
reaches, so a redrive can never fire for a session no dispatch owns.

* fix(orchestration): deliver direct peer mail to a structured worker, and let a peer read it

Two agent-to-agent verbs had no answer for a worker that IS a structured agent
session, and both failed quietly.

Mail addressed to a worker's own bearer handle — how agents mail each other
outside a dispatch — fell between the lanes. The send stored durably and
reported success, `getLiveTerminalPaneKey` resolved the recipient, and then
neither lane claimed the mailbox: the structured resolver answered only
`dispatch:` addresses, and the PTY lane refuses a structured handle outright.
Nothing errored and nothing logged, so the worker never reacted and the peer
waiting on a reply hung. The resolver now also answers a bare worker handle,
preferring that worker's active dispatch so peer and coordinator nudges share
one operation-ledger budget. A worker BETWEEN dispatches is still nudged, under
a session-scoped key: a dispatch says nothing about whether delivery is safe —
the idle gate and the lease fence do — and its own `check` reads exactly the
direct mailbox the mail is sitting in. The dispatch caller key is left
byte-identical, because the ledger is keyed on (callerKey, operationId) and
reshaping it would re-mint nudges already in flight as second turns.

`terminal read` had no structured branch, so the only peer-accessible read verb
answered `terminal_handle_stale` for a live worker; `worker-read` is closed to a
peer, which holds neither coordinator standing nor a dispatch id. It now serves
the session's journal, projected to LINES and paged by the same reader the PTY
tail uses, so the result stays a plain RuntimeTerminalRead and nothing an agent
reads discloses which kind of worker answered. Bounding and dispatch-capability
redaction are the archive path's, reused rather than rebuilt. A session that is
not attached refuses with the existing not-attached code rather than returning
an empty tail, which would read as "this worker has said nothing".

`terminal.show` still refuses a structured handle. This is read-only on purpose:
synthesising a ptyId/leafId/paneRuntimeId would hand every public terminal verb
something that looks writable and is not.

* fix(orchestration): stop three PTY-only probes answering for structured sessions

Three defects, one shape: a probe that enumerates PTYs or resolves a pane was
standing in for a question that is not about panes at all.

`worktree rm` destroyed a live structured worker. `killAllProcessesForWorktree`
sweeps the renderer graph, the provider session list and the local pty-registry,
and a structured session is registered on none of them — so all three counted
zero, nothing errored, and removal deleted the checkout out from under a running
provider child, which kept running with its `cwd` gone while the dispatch still
reported the worker live and exact. A fourth sweep now asks what the other three
cannot: membership by `location.workspaceId`, which covers a plain chat session
as well as a dispatched worker, and liveness by the same
`live`/`unverifiable`/`exited` observation the rest of the structured surface
uses. It REFUSES a destructive removal rather than auto-closing, on the same
bargain and the same `--force` escape hatch as the unstopped-PTY gate — this is
the verb that deletes a user's work, and a running agent is exactly what they
would want to be told about. Force closes the sessions properly instead of
orphaning a child. Best-effort reconciliation callers are excluded: they repair
state, delete nothing, and must never be failed closed.

Twelve coordinator verbs failed for a structured worker running as itself.
`isLiveTerminalHandle` validated `ORCA_TERMINAL_HANDLE` with `terminal.show`, a
PTY verb whose leaf lookup misses for a session that never had a pane; the pane
remint that would have recovered it needs `ORCA_PANE_KEY`, which a structured
child deliberately does not carry, so every one of them died on
`no_active_sender_terminal` — including the ones the worker's own dispatch
preamble tells it to run. The identity question gets its own probe,
`terminal.resolveIdentity`: a handle and a boolean and nothing writable.
`terminal.show` still refuses a structured handle, because synthesising
ptyId/leafId/paneRuntimeId would hand every public terminal verb something that
looks writable and is not. The PTY half is byte-for-byte today's check,
`getLiveLeafForHandle` included, so its `rendererGraphEpoch` re-check still runs
— that check is the whole reason the sender is validated at all, and a cheaper
probe would have quietly started passing stale post-reload handles. A host that
predates the method answers `method_not_found` and the client falls back to
`terminal.show`, which is correct for that host: one without the identity probe
has no structured workers to miss.

`dispatch --inject` reported `no_agent_detected` for a structured worker, because
`isTerminalRunningAgent` reaches `getLiveLeaf`, throws, and the catch returns
false. A structured session IS the agent; there is no foreground process to
recognise, so it answers before the PTY probes rather than through them.

Also: a Run whose coordinator is structured now gets its `run:` mail. Both lanes
declined and neither logged — the PTY lane because the owner is structured, the
structured lane because the mailbox was not `dispatch:` — so each half believed
the other owned it. The PTY lane's reasoning (a coordinator blocks in
`check --wait`, where a waiter preempts pointer delivery) does not transfer: a
structured coordinator is a chat session whose turn ends. Its `run:` deliveries
take the `hasOutstandingRunDelivery` gate the PTY lane applies for exactly that
mailbox, and only for that mailbox.

The test that would have caught the twelve drives the CLI with
`ORCA_TERMINAL_HANDLE=structworker_…` and no `--from`. Every existing
orchestration CLI test passes `--from` explicitly, so the resolver a real worker
goes through was never exercised — which is why the suite stayed green while the
preamble failed on its first line.

Two files crossed their line ceiling and are split rather than waived:
`worktree-teardown.ts` sheds its two PTY-surface sweeps and the deadline
arithmetic they share, and `orchestration.test.ts` — which sat exactly on 800 —
sheds the two caller-identity suites this change rewrote.

* fix(orchestration): arm the takeover signal for structured chat input

`worker-release` closed a structured session a user had taken over, losing work
mid-conversation, while `orchestration-worker-specs.ts:106` promised "Never
closes … user-taken-over terminals".

Every guard was already correct and simply never armed.
`reportWorkerTerminalUserInput` has exactly one call site — the real-user-input
signal on a PTY connection — so structured chat input never reached
`orchestration.workerTerminalUserInput`, `markWorkerTerminalUserOwned` never ran,
ownership stayed `owned` instead of `user_owned`, `retainedReason` never returned
`user_takeover`, and `stopStructuredWorker` proceeded. The durable flag is reused
as-is rather than given a parallel mechanism: it exists precisely so a restart,
an SSH drop or a renderer remount cannot erase a takeover.

Addressed by SESSION, never by pane key. A structured worker's pane key is a
random identity credential — anyone holding it can read and consume that worker's
mailbox, and session ids are embedded in tab ids in plain text — so it stays in
main and the runtime resolves the session to it. Handing it to a renderer to echo
back would make it learnable by anyone who can see a chat pane. The RPC gains an
optional `sessionId` alongside `paneKey`; a host that predates it rejects the
call, and the report is already best-effort with a catch, so that host degrades
to exactly today's behaviour rather than failing a send.

The signal fires from the composer send hook and only past `accepted`: the outbox
dispatcher retries, and orchestration's own pointer nudges never pass through the
composer at all — so neither can be mistaken for a user takeover.

* fix(orchestration): reach structured workers through group addresses

`orca orchestration send --to @all` — and `@idle`, `@claude`, `@codex`,
`@worktree:<id>` — silently skipped every structured worker. Recipients came
from `listTerminals`, which enumerates leaves and PTYs, and a structured session
is on neither. The exclusion happened BEFORE per-recipient resolution, so the
`SendRecipientWarning` machinery never ran: the caller got exit 0 and a receipt
naming the workers that did resolve, and a broadcast "stop work" or "base moved"
reached the PTY workers and nobody else. With every worker structured it
degraded to `terminal_not_found`, which reads as "the group was empty".

Fixed at the group-resolution site rather than inside `listTerminals`. That
result is published to paired mobile and remote clients and to consumers that
assume a summary carries a `ptyId` or is writable, so widening it is its own
change under `docs/reference/remote-wire-compatibility.md`. Group addressing
reads exactly three fields off a recipient, and `RuntimeTerminalSummary` already
satisfies them structurally, so the resolver widens to that smaller shape and
nothing here invents a `worktreePath` or a `branch`. Candidates are liveness-
gated on the same observation the rest of the structured surface uses — mail
addressed to a settled worker would be stored for a lane that will never deliver
it — and once a worker IS a candidate, the existing per-recipient warnings cover
it, so an unresolvable one is reported rather than dropped.

`@idle` needed more than enumeration: `getAgentStatusForHandle` reaches a PTY
probe that throws for a handle with no pane, so a structured worker would have
been enumerated and then silently dropped from the one group address that
selects on status. It now answers from the session's journal — and off the FULL
reduced timeline, never a bounded tail. Settlement tombstones the running turn's
lifecycle item rather than rewriting it, so on any page-sized read a long
tool-calling turn looks identical to an idle session; `@idle` would then
broadcast into a running turn, which Codex answers with `turn already running`
and Claude queues behind. An unreadable session answers null, never idle.

`terminal list` and `worktree ps` still omit structured workers; that is the
wire-visible half and is deliberately not in this change.

* fix(orchestration): refuse rather than guess when a chat session has no identity

An ordinary structured chat session — not a dispatched worker — is spawned with
no `ORCA_TERMINAL_HANDLE`, because `structuredWorkerChildIdentityEnv` early-
returns for any session outside the worker registry. `orca orchestration check`
then fell through to `terminal.resolveActive`, which picks the focused tab's
active leaf or the first leaf in the worktree. It returned a valid handle, so
nothing errored — and `check` is destructive by default, so it consumed another
pane's oldest unacknowledged batch and marked it read. The rightful worker never
saw that mail.

`requireUnambiguous` does not fix this, only narrows it: it refuses when MULTIPLE
leaves could be meant, and with exactly one terminal pane in the worktree the
guess still resolves — to a sibling. "One terminal pane plus one chat tab" is a
normal layout, so the common case stayed broken. The pinned test is that case.

So the child now carries `ORCA_STRUCTURED_SESSION`, and every remaining route
that would GUESS an implicit terminal refuses on it with an error naming the flag
to pass. The marker names NOTHING — no handle, no pane key, no session id, no
token — which is the whole reason it is safe: it cannot be replayed, cannot
impersonate, and cannot flow into the hook-attestation, agent-row or
mobile-projection pipelines the way a pane key would. That makes it a different
decision from withholding `ORCA_PANE_KEY`, not a reversal of it. It also grants
no CLI reachability, so packaged builds keep exactly today's exposure.

The comment at `orca-runtime-adopt-terminal-orphans-from-inventory.ts` that
justified the guess — "a structured worker is covered instead by the
`ORCA_TERMINAL_HANDLE` its child is spawned with" — was true only for dispatched
workers and false for every other structured session, a population this branch
creates. It now says which case it covers and which case it does not.

* fix(orchestration): stop two surfaces lying about a worker with no terminal

`orca terminal <verb>` answered `terminal_handle_stale` for a structured
worker's handle. Nothing went stale: the session is live and simply has no
terminal, and it never had one — so callers acted on a false claim and went
hunting for a remint that cannot exist. The refusal now carries its own code and
names the structured equivalents (`orca terminal read`, `worker-read --source
transcript`, `orca orchestration send`), so an agent that lands there learns
what to run rather than what failed. A PTY handle that really did go stale keeps
the old error, and so does a session this runtime no longer owns — that handle
IS dead. `terminal.show` stays non-resolving: synthesising a
ptyId/leafId/paneRuntimeId would hand every public terminal verb something that
looks writable and is not.

`orchestration-worker-specs.ts` promised "the same verbs, the same handle, and
the same worker-read sources", and all three clauses were false for a worker with
no terminal. A spec agents read must not carry a false promise, so it now states
the limitation and the alternative that always works.

Note this had to be reconciled with an invariant this branch already holds: the
worker MODE must stay opaque, or a coordinator starts branching on something no
verb it runs behaves differently for. So the note says "not every worker has a
terminal" and points at `--source auto`/`--source transcript` WITHOUT naming a
kind — the same mode-neutral wording `readStructuredWorkerOutput` already uses
when it refuses `--source terminal`. Both properties are now pinned by tests, so
neither can be restored by breaking the other.

* fix(orchestration): close the review findings on the structured parity work

Four defects and two follow-ups from the delta review.

The `worktree rm` refusal was a dead end in the desktop UI. Its message matched
no matcher in `classifyWorktreeForceDeleteReason`, and an ordinary desktop delete
already passes `force=true` for the dirty-file skip, so classification returned
null unconditionally: the toast showed raw CLI wording with no Force Delete
button, and a user with a live chat session was stuck unless they knew to reach
for the CLI. That is the stablyai#11960 shape `shared/worktree/removal.ts` documents, so
the refusal now has its own prefix, matcher, `WorktreeForceDeleteReason` and
toast copy, classified BEFORE the `force` guard and nulled once the waiver is
spent — exactly how `unstopped-pty` is handled, with matcher and hint kept in
the same file as that contract requires. The copy says Force Delete will close a
running conversation rather than borrowing the "could not confirm" wording,
because Orca watched these sessions stay attached; there is no doubt to waive.

Structured `terminal read` cursors were unsound and are now refused. The PTY
cursor indexes an append-only completed-line buffer with a monotone count; a
session journal is a BOUNDED tail re-projected on every read, so a saved index
addressed different lines as the journal grew — and `truncated` could never fire
to say so, because it tests `cursor < oldestCursor` and `oldestCursor` was always
0. A poller got wrong or duplicated lines under `truncated:false`. Separately, a
streaming turn's lines counted as completed with `partialLine` hardcoded empty,
so a mid-turn cursor consumed a half-written line whose growth was never
redelivered — the `"hel"`/`"hello"` hazard the PTY reader guards against. The
journal does have stable item identity, but `terminal.read`'s cursor is a number
on the wire and cannot carry it, so a cursor read now refuses and names
`worker-read --source transcript`, which already has that contract including
`source_changed`. No cursor space is advertised either: `nextCursor` is null and
the cursor fields are absent, rather than claiming an index the next read cannot
honour. The header claim that all four fields kept their meanings was true of the
shape and false of the invariants; it now says which ones hold.

Two fixes had no test at their real seam, which is the same failure that produced
this whole set — the runtime tested directly, the seam tested by neither. The
group-addressing test hand-composed the recipient list itself, so deleting the
composition at the call site left it green; it now drives `sendGroupMessage` with
no PTY terminals at all. Nothing referenced `isLiveStructuredAgent`, so the
`dispatch --inject` fix had no red-then-green at all; it now has one driving
`RuntimeTerminalAgentPresence.isRunning`. Both were ablated and confirmed red.

Folder-workspace removals sweep and kill PTYs without `requirePhysicalStop`, so
the structured sweep no-opped there and left a live session bound to a workspace
about to be forgotten. They now close best-effort under an explicit
`closeStructuredSessions` flag, kept separate from `requirePhysicalStop` because
the two questions differ: that one asks whether a stop must be PROVEN before
files are touched, and it is what licenses a refusal. These paths do not refuse —
the root is shared so no checkout vanishes under the child, and one of them is a
never-throw forget a refusal would wedge. Reconciliation sweeps set neither and
still close nothing.

Also: the force close is raced against the same sweep deadline every PTY surface
is bounded by, so a wedged provider close reports the timeout instead of hanging
`worktree rm --force` forever; and the refusal now prints a count and the
providers instead of raw session ids, which our own marker rationale treats as
one tab-id hop from a credential.

* test: pin structured-session close on the folder-workspace removal path

The folder and orphan removal callers now pass closeStructuredSessions so a
live structured session is closed best-effort rather than left bound to a
workspace Orca has forgotten. These three exact-args characterizations describe
that call and had not been updated.

* fix(orchestration): stop the structured worker-read cursor misdelivering silently

`worker-read --source transcript` for a structured worker fingerprinted only the
oldest item's id, so `source_changed` fired when the window slid off the front
and could NOT fire when the page's contents changed under a stable oldest item —
which is the normal case, because the journal is a reduced, mutable timeline. A
`running` tool item gains its `[tool result]` at its original sequence once later
items exist, the 60ms delta coalescer revises a message in place, settlement can
rewrite an item smaller, and a pending approval projects to null until it
resolves and then appears in the MIDDLE of the array.

Two silent failures followed, both returning ok. Omission: a caller handed a
coalesced `hel`, resuming past it, never received the revision to `hello world`
— the same defect we refused to ship on the terminal read path, already shipped
here. Duplication: a resolved approval inserted ahead of a saved index, which was
still accepted, so the caller re-read content it already had. The blast radius is
the coordinator polling loop, the verb's primary consumer.

The anchor is now the oldest item PLUS every item whose projected message sits
below the caller's position, by id and revision. `createWorkerOutputSourceIdentity`
already takes an arbitrary string array and the cursor is already opaque
base64url carrying its own position, so neither the wire shape nor the
`source_changed` contract changes.

Prefix-scoped rather than whole-page deliberately: fingerprinting every item on
the page would flip the identity every 60ms with the coalescer window during an
active turn, making the cursor unusable exactly while the worker is working —
that trades a silent bug for a useless verb. Tail growth the caller has not read
cannot invalidate; any change to what it already holds does. Position-dependence
is safe because `p` rides in the same opaque payload as the identity, and the
returned cursor is stamped with the identity of its own end, which is precisely
what the next read recomputes. The frozen archive keeps a constant identity: no
item can be revised under a caller there, so it has no prefix to fingerprint.

Both silent shapes are pinned across a page boundary with the journal mutating
between reads — a static-journal test passes either way. Two ablations at the
real call site: reverting to the oldest-item-only anchor turns both red, and
widening the prefix to the whole page turns the tail-growth case red, which is
what proves the scoping is real in both directions.

* docs(orchestration): stop the structured terminal-read refusal recommending a dead end

The refusal told a peer to "page it with `orca orchestration worker-read
--source transcript`", which is wrong three ways and this file said so itself:
its own header explains that this verb exists BECAUSE `worker-read` demands a
dispatch id and coordinator standing "a peer does not have" — and then the
refusal sent that same peer there. The verb it named is also a window index over
the same bounded page, so it is not a paging answer even for a caller who can
reach it; under load it now answers `source_changed` on most polls, which is
better than the silent hole it had before but still not what the sentence
promised.

The refusal now says what actually works — the tail is bounded and newest-last,
so poll it and diff — and names no alternative, because there is none. That is
the honest framing: a durable cursor is not achievable here at all, rather than
blocked on the wire shape. The journal is a reduced, MUTABLE timeline: an item's
projected text changes at its original sequence after later items exist, the
delta coalescer revises repeatedly, settlement can rewrite an item smaller, a
pending approval renders as nothing and then as something, and `sequence` resets
on epoch rollover. No index, numeric or opaque, survives that.

So the docstring's "pagination with a real anchor lives on `worker-read --source
transcript`" is gone too — there is no real anchor there — and the file now
records why no windowed alternative should be built later: a broken cursor fails
UNSAFE, as a silent hole in a poller's output, while diffing a bounded tail fails
safe as a harmless re-read, and a second paging-shaped verb would invite the PTY
assumptions this one cannot honour.

The test asserted the old advice, so it now pins the contract instead: the
refusal explains the working approach and must never name `worker-read`.
`worker-read --source transcript` remains a good bounded snapshot for a
coordinator reading a worker it dispatched; only the "or page it with" clause was
false.

* fix(i18n): add the missing worktree-removal agent-session refusal string

The structured-session removal refusal introduced a translate() key with no
en.json entry. Nothing local catches that: typecheck passes, and the full
suite passes, because a missing key falls back to its inline default at
runtime. Only verify:localization-catalog fails on it, which is why CI's
static analysis reddened on a branch that was green everywhere else.

Fallback wording mirrors the sibling unstoppedPtyLive string, since the two
refusals differ only in what is still running and what Force Delete does to it.

* test(codex): expect the no-identity marker on an unregistered structured child

The refuse-rather-than-guess marker landed after these expectations were
written, and all three assert exact env equality on the unregistered path —
the one branch that now carries ORCA_STRUCTURED_SESSION. One of the two files
was added by this same branch, so this is a self-inflicted drift; the other
predates the branch and was broken by it.

The marker's presence is still pinned positively by
structured-worker-child-identity-env.test.ts and the CLI's
orchestration-structured-session-no-identity.test.ts, so relaxing these three
exact-equality checks loses no coverage of the security property.

* fix(orchestration): require exit evidence before settling structured close

---------

Co-authored-by: Merge Sim <sim@local>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant