Skip to content

fix(agent-hooks): keep each pane's agent conversation through sleep and wake - #43529

Merged
brennanb2025 merged 140 commits into
mainfrom
brennanb2025/sleep-pane-agent-identity
Nov 19, 2026
Merged

brennanb2025 merged 140 commits into
mainfrom
brennanb2025/sleep-pane-agent-identity

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Sleeping a workspace could lose an idle conversation, hide its agent after another sleep, or replace an interrupted turn with a false completion during wake. And a Codex resumed by a wake, then quit with /quit, came back as codex resume <id> at the next wake instead of staying a shell.

User-facing change

  • Claude and Codex keep their conversation and their last turn through sleep, wake and sleep again, including an idle Claude whose hook row is gone (STA-15387) and an idle resumed Codex across two sleeps (Keep a woken Codex terminal's saved session when its workspace sleeps again #42864).
  • An agent slept during a turn shows the existing "Interrupted" state while asleep and after wake, until a real next turn changes it, with no false completion notification. If the resumed agent itself reports work while it starts up, the pane shows that work, as main does.
  • Quitting an agent after a wake leaves the pane a shell at every later wake and after an app restart, including in Windows shells that send no command marks. Suspending it with Ctrl-Z, running other commands (or listing workspaces) and returning with fg keeps it resumable.
  • An agent running inside tmux in a local or WSL pane (Claude or Codex; tmux attached or detached) is never resumed a second time beside itself: no checkpoint is written for it, at sleep, quit or app restart, so wake leaves the pane a plain shell and the conversation alive in tmux. The same holds for an OpenCode attach/serve conversation, whose server also outlives the pane. A checkpoint an earlier build already wrote for such a conversation can still be resumed once, as on main. On SSH hosts the relay doesn't carry the hook's tmux pane yet, so that case is unchanged from main.

Change

One owner for a pane's agent. paneAgentIdentity answers "which agent conversation is in this pane, and has it ended". It reads the pane's hook row in any at-rest shape, otherwise its saved conversation, minus an exit recorded since. It is a pure read. Sleep capture, the sleep gate, stopping protection, process listing, quit capture and restore all use it, and their separate live-row and placeholder filters are deleted. worktree ps lists a saved record's agent only when the record is a sleep's; a live checkpoint is recovery, not a running agent.

Who runs the conversation is recorded once, on the hook row. executionHost: 'pane-owned' | 'shared' | 'unverifiable' is set when the hook row is written. A Claude or Codex hook reports the tmux pane it ran in; a PTY spawned while Orca itself runs inside tmux carries ORCA_INHERITED_TMUX, so a hook doesn't mistake Orca's own tmux pane for a host. OpenCode's own attach/serve evidence decides the rest. The field follows the conversation's binding, an unverified writer can't claim pane-owned, and only shared is persisted (a pane-owned claim is proven again by its next hook). The window receives the same field and writes no checkpoint for a shared conversation. This replaces the sleep-time tmux probe.

Exit is proven by the host, not guessed from a mark. When a command finishes at the shell (OSC 133;D) in a pane whose agent has no process the presence probe can check, the agent ends only once the host proves the shell is alone: one fresh process table, the PTY's shell at or beneath its root (macOS roots at /usr/bin/login), in the foreground, with no stopped or background job running the pane's own agent. If the proof fails (a shell nested in the live agent finished a command, or the agent is stopped with Ctrl-Z), the pane is tracked in unproven-agent-exits.ts and a later mark re-proves it, one proof per pane at a time. A proof doesn't count if input reached the PTY while it ran. An agent typed at the prompt (no launch held) is tracked the same way. A sleep settles every pane's pending proof together before it captures. Remote and Windows panes give no proof, so a mark ends the agent there, as on main; a hookless Windows quit is proven by the host's job census. A proven exit durably deletes the pane's saved sleep record, through the same session write path as every session save on main.

This carries #42922's change (its commits are included), per the review council, and supersedes it. Tracked in #42542 and STA-15387. Carries the saved-conversation regression from #42391, with contributor credit in the commit.

Design choices kept, and why

A final design review proposed three alternatives. Each would add a regression, so they are not taken:

  1. Strip TMUX/TMUX_PANE from every PTY's environment instead of marking an inherited tmux. This changes the environment of every user who runs Orca inside tmux (their shells and tools would stop seeing the tmux they are actually in).
  2. Check at wake whether the agent's process is still alive instead of recording the shared host. Codex reports no process identity, so the check can't see a tmux-hosted Codex; a wake resumes it a second time beside itself (the double resume QA found before this design).
  3. A per-pane generation token instead of the per-pane proof queue. A token drops the queued re-proof, so a nested shell's mark inside a live Codex could end it, and its real /quit afterwards would never be proven.

Known limits

  • A TUI agent sent to the background with bg stops itself on its next terminal read (SIGTTIN/SIGTTOU), so the proof sees it stopped and it stays resumable.
  • An agent launched from a nested interactive shell that emits its own OSC 133 marks is not proved to exit while that nested shell remains.
  • A PTY created before this upgrade, under a daemon that inherited TMUX, lacks ORCA_INHERITED_TMUX, so a Codex in it can be treated as shared until that PTY ends.
  • A tmux session set to destroy-unattached (not the default) loses recovery: a shared host is never checkpointed.
  • On Windows and SSH, a nested shell's mark inside a live process-less agent ends it, as on main (no host proof there).
  • A typed codex left idle with no prompt is not seen until its first hook.

No new regressions vs main

Every automated-review finding and every known limit was checked against main's code. Where the behavior was new with this PR, it is fixed here with a test.

Item Status vs main
A dismissed but still-running agent reappeared as done in status snapshots and worktree.ps New with this PR. Fixed: resume-only rows stay out of status readers, as on main
Hidden resume rows reached idle/permission readers New. Fixed (same change)
A finished main-agent verdict was recorded as cancelled at sleep New. Fixed
A sleep replay suppressed an unseen completion (clean, or a finished main agent with interrupted children) New. Fixed
A stale launch row of another agent suppressed a completion notification New. Fixed
An asleep pane's saved working record was rewritten as a quit record on quit New. Fixed: only live panes are quit-captured
A same-second replay hid an exit New. Fixed: the exit is compared with the evidence time
Hookless terminal work after a wake (e.g. /context) was hidden New. Fixed by a council ruling: terminal work after a wake is shown as on main
Daemon routers drop the shell-alone option Ruled unreachable by a council (the daemon proof needs an established shell owner); forwarded through the degraded provider anyway
A new finished turn right after a wake was folded into the slept turn New. Fixed: only a restated done keeps the slept verdict
A kept post-wake row held a relay's connection, so its disconnect removed the row New. Fixed: the row takes the incoming connection
Quit promoted a saved live checkpoint with no status row into a quit record New. Fixed: left as saved, as on main
Sleep marked a pane with a finished main agent and running children as interrupted New. Fixed
tmux row replaced during suspension; SSH tmux duplicate Same as main
A conversation in tmux checkpointed by an earlier build resumes once more Same as main (the new build writes none)
A renderer save could restore a retired record; hookless Windows exit before start Same as main (main never retires these records)
Launch flags dropped after Ctrl-Z, a command and fg Same as main (main retires the launch on every command finish)
Claude /compact shows Done while compacting; a dismissed agent's sidebar row reads Idle Same as main

Validation

  • CI green on the PR; pnpm check:changed on Linux through remote-check on each head.
  • New tests sit at the layer that owns each decision: the runtime → server → persistence sleep path (Done and mid-turn Interrupted for Claude and Codex through sleep, idle wake and sleep again; Ctrl-Z kept; a later command exit retires), the shell-alone proof and its re-proof tracker, tmux and OpenCode host recording, the window's checkpoint rule for a shared host, and worktree ps listing.
  • Real-app QA (isolated copy on Linux, real Claude and Codex, CDP driver), last run on 750c77a, all PASS:
    • Claude and Codex in tmux, client attached and detached, across sleep/wake and an app restart: never resumed beside the tmux original.
    • Codex resumed by a wake, then /quit: stays a shell at every later wake and after restart. A nested shell command inside a live Codex doesn't end it; its real /quit afterwards does.
    • Claude and Codex from +: sleep/wake resumes the same id with exact recall.
  • Earlier QA on macOS (M4Air): Ctrl-Z / fg, quit after wake, idle Claude with no hook row (STA-15387), mid-turn Interrupted. PASS.
  • Not covered by real-app QA: Windows and SSH (unit-tested only).
Files Added Deleted Net
Test 33 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2626 $\color{#cf222e}{\Huge{\mathbf{−}}}$​158 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2468
Prod 84 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2010 $\color{#cf222e}{\Huge{\mathbf{−}}}$​408 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1602

brennanb2025 and others added 30 commits November 15, 2026 17:26
…shell

A Codex resumed by a wake sends no hooks while idle, so the shell-confirmed
reconcile kept its resume row without exit evidence and the next sleep
captured it again. Derive the ended presence from the pane's row (the shape
sleep settle already builds), and let a later Orca launch forget an exit
that predates it.
A row with a proved process gets its exit from the presence probe, and a
same-session relaunch replaces an ended resume row.
Co-authored-by: d.bondarev <d.bondarev@crm-onebox.com>
…ke' into brennanb2025/sleep-pane-agent-identity

# Conflicts:
#	src/main/agent-hooks/server/server-ingest-terminal.ts
#	src/main/agent-hooks/server/server-pane-sleep.ts
#	src/main/agent-hooks/server/testing/persistence/server-pane-sleep.test.ts
… command finish

QA showed main's own command-finished retirement clears a hookless Codex's
row before the renderer's shell-return reconcile lands, so neither recorded
an exit. Pass confirmedExit through that path (command finish only, not PTY
exit).
A Ctrl-Z'd agent finishes its shell command with a stop status while its
process lives on; only record the exit for other statuses. Drop the
renderer reconcile's confirmedExit, whose message can't tell a suspend.
A Ctrl-Z stop status isn't the launch command finishing, so don't retire the
launch for it; the agent's real finish after fg then still records the exit.
…ke' into brennanb2025/sleep-pane-agent-identity
…it-after-wake

# Conflicts:
#	src/main/runtime/terminal/surface/slept-pane-exit-status-main.test.ts
…ke' into brennanb2025/sleep-pane-agent-identity
…ne-agent-identity

# Conflicts:
#	src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts
#	src/main/runtime/terminal/surface/slept-pane-exit-status-main.test.ts
…a conversation, replacing the binding symbol and the persisted sharedHost flag
@brennanb2025

Copy link
Copy Markdown
Contributor Author

PERF PASS — no introduced P0/P1 performance blocker found.

Fresh independent review of the full PR diff 44803c895a9140d88056fd0c8e1d07f6f2424a08...bf91f7f3f84507db9ffd6b2b18c0eca147bcfcd4, following .agents/skills/perf-scan/SKILL.md and its applicable scenario, lifecycle and platform references. perf-surface-detect --pr 43529 reports hot-path,publish,startup-migration. Prior reports were context; this verdict comes from the current diff, production callers, persistence/publication consumers, cleanup, and the checks below.

The changes after 750c77a add one sleep-record admission check to listing, and replace symbol/persisted-boolean topology with executionHost. The latter copies the baseline's field only for its identical provider-session binding, carries one scalar through existing row transformations, and persists only shared. This adds constant field work per status and per already-visited persistence row; it adds no new listener, scan, probe, timer or write cadence.

Work ledger: W=worktrees, R=repo/host-routing candidates, T=live terminals, A=hook rows, S=saved records in a host partition, Q=panes being captured, K=one PTY's bindings, L=legacy aliases, P=host processes, D=one root's descendants. Reference workload: W=750, R≈12, T≈300, A≈100; dimensions considered independently at 10×. S/P/D are variables, not claimed fleet caps. Unless stated otherwise, bookkeeping runs in Electron main; capture I/O is asynchronous, while projection, parsing, indexing and copies still consume main-thread CPU.

Changed work and target evidence Trigger/frequency → population/work Bound, ownership, invalidation; spawns / process-table reads
Command-mark routing: src/main/runtime/terminal/lifecycle/daemon-launch-note.ts:51, terminal-orchestration-authority.ts:184, src/main/agent-hooks/server/agent-hook-server.ts:161 Each 133;D mark → one PTY lookup, its K indexed leaves and pane lookups. No row and no tracked proof returns before saved-record routing. O(K), independent of T/W. Ordinary shells, verifiable/shared/ended owners: 0 added spawns, 0 added table reads. No scan on output chunks lacking a mark.
POSIX shell-alone proof: src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts:173, src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts:34, src/main/providers/foreground/agent-process.ts:88 One eligible process-less command return or quiet return → published root-PID lookup, fresh host table/index, this root's descendants. Two descendant traversals and shell-candidate sorts give O(D log D) upper bound after the shared P-row index. Recognized pane agents, including stopped/background agents, prevent retirement. Root lookup is O(1) in the existing PTY registry, removed by normal unregister. No terminal inventory, cold PID fallback, Q² batch matching, or new 64-entry root cache exists here. Missing published PID: 0 captures. Present PID: 1 fresh capture per request wave, shared index, not two captures per proof. Existing 32 MiB capture ceiling / 15 s timeout remain. Spawn accounting below.
Retry state: src/main/agent-hooks/server/unproven-agent-exits.ts:42, agent-hook-server.ts:108 A failed proof retains one pane entry. Later marks or explicit sleep can retry; concurrent marks set one again bit. One active proof plus one pending bit per current entry; no idle retry timer or growing request queue. Success/close/forget remove it; next mark/sleep forgets verifiable/shared/ended ownership. Entry-identity check at 58–59 prevents late failed completions from reviving forgotten/replaced entries. Sleep waits current proof and an already-queued rerun, without waiting for an unlimited future mark stream.
Quiet reconciliation: src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts:72, src/main/agent-hooks/server/server-tab-cleanup.ts:91, renderer pane-agent-shell-lifecycle.ts:7 Shell-settle and row-retire callbacks → one in-flight reconcile per pane and one rerun bit. Tracked panes await their existing proof; verifiable owners use existing presence checks; ended/shared identities skip the shell proof. Successful first reconciliation makes its duplicate proof-free. A mid-flight report is retained. IPC entries delete on completion. Quiet typed agents without held launches pay one admitted proof, whereas main previously retired renderer recovery without that proof. This adds no mount/focus polling cadence.
Identity and lifecycle gates: src/main/agent-hooks/server/server-state.ts:75, server-state.ts:174, server-pane-sleep.ts:29, src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts:68 Read this pane's legacy/canonical row; only an unsupplied, rowless identity falls back to saved-record routing. Physical sleep checks ownership/reversible stop first. Spawn/non-stopping checks pass null; startup's already-read missing record is null. O(one pane's subjects/fields); rowless fallback can pay the existing O(R) route once. known carries pre-proof identity into reconciliation. Fixed-field projections reuse strings/provider objects. 0 spawns/tables/transcript reads from projection itself. Suspension check reuses the already-collected pane keys and runs only on an unverifiable verdict.
Explicit sleep capture and annotation: src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts:122, worktree-sleep-resume-records.ts:66, src/main/agent-hooks/server/server-pane-sleep.ts:86 Sleep → Q pane bindings. Settle tracked proofs concurrently, route host once, perform keyed before/after saved reads around existing presence checks, produce each pane's record or retirement. Physical stop preserves verdict or records interruption. O(Q) required owner/output work. Fresh shell-proof requests share a capture wave; an earlier-running proof/queued rerun can require a subsequent wave. No Q terminal inventories or Q host-route scans. Second saved read preserves writes that occurred during presence checking. Ended/shared owners create no recovery record. Existing batch persistence; no periodic checkpoint or sleep-time tmux command.
Quit/reopen: src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts:262, src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts:33 Quit → A rows plus S saved candidates. Reopen checks one pane's ended/shared identity before existing claim/resume logic. One TerminalIdentityReadContext shares indexes across saved-candidate live checks and launch lookups, avoiding a terminal/leaf population scan per record. No new shell proof during quit, startup-wide process discovery, SDK import or network client. Existing resume-claim/session comparisons remain.
Proven exit retirement: src/main/agent-hooks/server/server-state.ts:116, src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts:51, src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts:108 Proven exit → alias collection, routed retirement per applicable alias, saved record read through that same route; delete only an old-enough saved record. Alias collection O(L) already existed for exit reconciliation. One retirement host route per alias, not separate read and delete routes. Absent/newer records exit before publication. Real deletion copies S map references but skips terminal topology ordering, then uses existing coalesced save scheduling. 0 added synchronous disk/SQLite calls, spawns or tables. Local renderer no longer performs the previous eager duplicate-record cleanup; confirmed host clear owns retirement.
Hook/OSC/launch acceptance, topology and persistence: src/main/agent-hooks/server/cli-writer-observation.ts:114, pane-agent-turn-continuity.ts:8, server-status-row-mutation.ts:13, server-ingest-launch.ts:14, server-persistence.ts:89, server-hydration.ts:98 Existing hook/OSC/launch event → compare this owner/session, preserve accepted turn, carry one host field; existing persistence/hydration loops include shared host. Constant extra row/session-field checks and shallow row copies; no fleet traversal or tmux subprocess. Restoring a saved launch can route its saved identity once when no row exists. Codex hook capture/header and spawn inherited-tmux stamp use shell parameter operations / in-memory fields: 0 added child processes. Retry clearing removes timer bookkeeping; no new timer.
Status publication and renderer consumers: src/main/startup/main-window/main-window-agent-status.ts:54, renderer agent-status-partial-updates.ts:50, agent-status-live-entry-builder.ts:222, forget-refused-pane-resume.ts:28, dispatch-terminal-notification.ts:109, agent-status-recovery-collection.ts:41 Status → scalar topology propagation, replay/admission guards, existing main-window/dashboard sends. Confirmed clear checks the exact pane record/turn; manual sleep promotes records in its existing worktree-indexed pass. Ended identity-only statuses skip forwarding; shared identity-only statuses skip checkpointing. No new broad store selector/effect, per-mounted-pane resource, full-message processing or publication consumer. Absent/mismatched retirement returns existing store state. Pending-event pruning was already tied to relevant clears. 0 added process reads/spawns.
Requested process listing/snapshots: src/main/runtime/construction/runtime-agent-status-sources.ts:36, src/main/runtime/workspaces/process-listing/runtime-worktree-ps-activity.ts:231, workspace-process-listing.ts:134 Existing worktree.ps/fleet request → gather S saved records once in existing host/session walk; Set join with A hook rows; use supplied records for eligible saved-only sleep identities. O(A+S), not A×S; output each pane once. The new isPaneSleepRecord gate is a field check before identity derivation. No per-record host routing, transcript reads, table captures, RPCs, or new cadence. Necessary enumeration to include saved-only sleeping agents in an already population-sized listing.
Providers and teardown: src/main/providers/local-pty/local-pty-session-operations.ts:127, src/main/ipc/pty/provider/state-cleanup.ts:78, src/main/agent-hooks/server/server-tab-cleanup.ts:166 Targeted listProcesses → requested PTY map entries. Pane/tab cleanup forgets proof debt; PTY cleanup unregisters PID. Targeted list improves from whole inventory/filter to O(requested PTYs); new POSIX proof does not call it. Tab close adds one tracked-proof pass to existing tab-wide cleanup. No new enduring native resource/listener. Test fixtures/allowlist change test selection only, adding no app work or CI job.

The additional host-wide proof is real work beyond main's renderer-only retirement. For P=2,000/20,000, an isolated eligible return pays one 2,000/20,000-row capture/index plus its D descendants. At one eligible return/s this means one capture/s and 2,000/20,000 indexed rows/s, not a timing claim. It does not mean each ordinary hook update or command mark visits 300/3,000 terminals. Separate process-less owners require separate descendant judgments to avoid retiring live/stopped agents; their concurrent host-table inputs share a capture. These necessary event-driven proofs have no extra fleet multiplier or autonomous polling loop.

Per-capture spawn accounting: macOS normally uses 0 children through the native reader. Foreign unreadable argv can add one batched recovery ps under the existing burst-2 / one-per-2-s budget; native failure uses the existing fallback budget (burst 4, then one/s). A late failure can follow argv work, so this is not an unconditional one-child ceiling. Linux uses one ps, plus the existing /proc/<pid>/stat reads for terminal-bearing rows. These are existing capture implementations, newly invoked only at admitted proof boundaries. Windows/WSL command marks add no table proof. Windows quiet-return confirmation uses existing foreground/job census, possibly followed by provider inspection; it can need native table evidence, not a POSIX ps. SSH/remote PTYs return before local table reads; renderer remote retirement retains the existing path. No added per-item SSH round trips.

Pre-existing costs kept separate from regressions: resume reads/hook-status writes already resolve the workspace-session host, potentially O(R), and real immutable saved-map edits already copy S references. With R≈12/120, a saved-only exit can pay one initial identity route and one retirement route; it does not route five times or route once per captured pane. The untouched run-terminal-client-use.ts:59 fallback can inventory terminals before calling the changed shell-alone helper; no new caller to that fallback was added, and this helper now shares its one fresh capture with foreground confirmation. Existing alias scans, full listing enumeration and persistence scheduling are not new per-status fleet work.

Executed evidence on this head (no install, app build, typecheck, broad vitest or GUI run):

  • TC_GATE_POOL=test tc-gate node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/unproven-agent-exits.test.ts src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.test.ts src/main/ipc/pty/pane/terminal-pane-status-lifecycle.test.ts — 3 files / 23 tests passed. Covers stopped/background agents, unreadable comm/zombies, input/launch invalidation, no-launch quiet return, Windows census decisions and queued sleep proof behavior. Platform mocks are not live cross-platform evidence.
  • Read-only Node/tsx harness through tc-gate, importing the current production classes: at 100 and 1,000 panes, eleven marks per pane during a running proof produced 200 and 2,000 proofs, exactly original + coalesced rerun; success left 0 tracked panes. Forgetting panes with queued marks before late failed completions produced 0 extra retries and 0 retained panes at both sizes.
  • Current createProcessTableSnapshotReader with injected capture: 100/1,000 same-tick callers → 1 capture. A second same-size burst after capture start waits and produces one subsequent capture, 2 total, preserving freshness. Index harness visited 100/1,000 input rows once and confirmed repeated same-array lookup reuses the index. These verify counts, not live OS latency or entire sleep integration.
  • Full merge-base git diff --check passed; workspace remained unchanged.

Recurring-class screen (matched and disproved unless otherwise stated):

Class touched Disposition
Work before skip gates; hot-path rescans/nested matching Plain-shell/physical-sleep/ended/shared/verifiable gates precede new proof admission; keyed PID/pane/saved reads; listing uses a Set; one shared quit context. No new repeated fleet scan per status.
Subprocess per item; rereading unchanged input No PTY inventory for root proof, no new tmux command; one fresh capture wave shared across proof callers. Freshness is required after a return; ordinary status/marks do not request it.
Per-entity state outliving entity; unbounded queues/retry One entry/pending bit per pane, identity-fenced completion, teardown forget, no autonomous retry. N/10N late-failure counts above.
No-op store churn; whole-snapshot publication; whole-file rewrite Exact record/time checks precede mutations. Real deletion copies existing keyed map, skips topology sorting, and uses existing coalesced persistence. Status consumers/cadence unchanged; shared/ended guards remove work.
Sync-main I/O; eager startup imports New paths add no synchronous fs/SQLite operation, eager SDK or new startup census. Main-thread capture parsing/indexing and immutable-copy costs are explicitly priced above.
Hidden/per-instance work; fixed poll/loop No new effect, visibility-owned client/resource, timer or poll. Background proof serves durable pane ownership; it is event-driven and bounded by existing capture completion.
Per-row global derivation Listing projections are keyed per row and visit A+S once for requested output, not all rows on each status or each mounted consumer.

Six-question disposition: (1) reviewed producer admission through renderer/store no-op handling; (2) reviewed ownership, consumers, capture/index sharing and per-pane retry bounds; (3) reviewed main-thread copies/parsing versus asynchronous capture and coalesced storage; (4) reviewed A/S/Q/T/P/D/R/L growth, freshness and retry progress; (5) reviewed source-level macOS/Linux/Windows/WSL/SSH/mobile/folder-workspace gates and spawn paths; (6) reviewed close/forget, entry/row/incarnation/input invalidation, bounded sleep waiting and IPC-map cleanup, with deterministic teardown counts.

Validation limits: no live Linux/Windows/WSL/SSH capture, packaged-app CPU/heap/frame measurement, or rendered sleep/wake QA. This is a performance-count/source review, not a measured responsiveness or complete functional QA claim. No unresolved source-proven amplification is being deferred as a measurement gap. No code edited, committed or pushed.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

PERF PASS — no introduced P0/P1 performance blocker found.

Independent review of the complete PR diff from merge base 44803c895a9140d88056fd0c8e1d07f6f2424a08 to a19560651d82a344fb6477658da16caa9bb4d044, using .agents/skills/perf-scan/SKILL.md, its performance scenarios, and terminal lifecycle/platform references. perf-surface-detect --pr 43529 reports hot-path,publish,startup-migration. I inspected production callers, consumers, persistence and invalidation, rather than grading only the changes since the earlier PASS.

The latest change (pane-agent-turn-continuity.ts:43) selects the resuming hook's execution host, retaining the prior host only when the binding is reused. This adds constant field comparisons and one scalar to an existing row copy. The serialized executionHost refactor similarly adds no traversal, listener, polling cadence or process discovery; persistence retains only shared.

Work ledger: W=worktrees, R=repositories, H=host partitions, T=live terminals, A=hook rows, S=saved records, Q=captured panes, K=bindings belonging to one PTY, L=legacy aliases, P=host processes, D=descendants of one root. Reference fleet: W=750, R≈12, T≈300, A≈100; each population considered separately at 10×. S, P, D, K and L are populations, not alleged fixed caps. Main-side projections/copies/parsing/indexing consume Electron-main CPU; asynchronous process/native/file capture is identified separately. Unless stated otherwise, rows below add zero subprocesses and zero process-table reads.

New/changed work → trigger Population and bound; ownership, invalidation and cost versus main
Command-mark admission — src/main/runtime/terminal/lifecycle/daemon-launch-note.ts:51, terminal-orchestration-authority.ts:184, src/main/agent-hooks/server/agent-hook-server.ts:161 → each 133;D Indexed PTY and K leaf/pane lookups, O(K), not O(T/W). The no-row/no-tracked-proof gate precedes saved-record lookup. Shared, ended and verifiable owners skip shell-proof admission. No new population work on chunks without a command mark. An ordinary shell mark adds no capture.
Root PID and POSIX proof — src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts:173, src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts:34, src/main/providers/foreground/agent-process.ts:88 → eligible process-less agent's command return or quiet return Root lookup is O(1) in the existing spawn/adoption PTY registry, whose normal unregister removes it. No terminal inventory or cold-PID fallback exists on this path, including hosts publishing no PID. Missing PID requests zero captures. A published PID requests one fresh host snapshot; concurrent callers before capture starts share it, and share its P-row index by array identity. Each proof traverses its own D descendants twice, with shell-candidate sorts: O(D log D) upper bound. The foreground confirmation receives that same index, so it does not capture again. Recognized stopped/background pane agents block retirement. Capture/spawn accounting is below.
Proof retry debt — src/main/agent-hooks/server/unproven-agent-exits.ts:42, agent-hook-server.ts:108 → failed proof, later mark, explicit sleep One entry, one active proof and one pending again bit per tracked pane; additional marks collapse into the bit. There is no retry timer. Success/forget/close removes the entry; a mark/sleep also forgets debt after ownership becomes verifiable/shared/ended. The entry-identity check at 58 prevents a late failed completion from rearming forgotten or replaced entries. Sleep waits the active proof and an already-queued rerun, not an unlimited stream of later marks. Deterministic 100/1,000-pane teardown check passed.
Quiet-exit IPC — src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts:71, src/main/agent-hooks/server/server-tab-cleanup.ts:91 → renderer shell-settle/row-retire reports One reconcile plus one rerun bit per pane; map entry deleted in finally. A tracked pane awaits its mark's proof. A verifiable agent uses existing presence checking. Ended/shared identities skip the new proof; after successful first retirement, the duplicate report is proof-free. A typed process-less agent without launch evidence can pay one admitted proof where main previously cleared renderer recovery without proof. No extra poll or mount-owned process census.
Pane identity and lifecycle gates — src/main/agent-hooks/server/server-state.ts:75, server-pane-sleep.ts:29, src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts:68, src/main/runtime/terminal/input/terminal-agent-status-and-submission.ts:102 → identity read, spawn, stop, resume, exit confirmation Read only this pane's legacy/canonical subjects and row fields; reuse provider/message references. Only rowless, unsupplied identities read saved recovery through the existing host route. Null means already read and absent. Spawn and non-stopping checks pass null; physical stop checks same PTY/reversible stop first. Pre-proof identity passes through known; suspension checks reuse collected pane keys and run only on an unverifiable verdict. Thus no population route is hidden before the common skip gates.
Sleep capture — src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts:122, worktree-sleep-resume-records.ts:66, src/main/agent-hooks/server/server-pane-sleep.ts:86 → explicit sleep Q required pane outputs. Settle all tracked proofs concurrently before sequential per-pane reads, so fresh requests coalesce. An earlier-running proof or a prequeued rerun may require a subsequent wave. Resolve capture host once, then keyed saved reads before/after existing presence checks, preserving a newer saved conversation. No Q inventories or Q host-resolution scans. Physical stop annotates each changed owner once and clears its process facets/rechecks; shared owners keep their surviving identity. Existing batched/coalesced persistence remains. No sleep-time tmux subprocess.
Quit and reopen — src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts:262, src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts:33 → quit checkpoint or pane restore Quit enumerates A rows and S saved candidates; one TerminalIdentityReadContext shares terminal/leaf indexes across live checks and launch lookups. No independent whole-terminal index rebuild per saved candidate. Reopen reads the pane's identity before existing ownership/resume decisions. No new startup-wide process census, quit shell proof, transcript discovery or SDK/client initialization.
Proven-exit recovery retirement — src/main/agent-hooks/server/server-state.ts:116, src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts:51, src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts:108 → confirmed exit Existing O(L) alias collection, then one retirement host route per applicable alias; that route also supplies the saved record. An absent/newer record returns before mutation. Actual deletion copies S map references and publishes through existing save scheduling, explicitly skipping terminal-row sorting. No new synchronous disk/SQLite call or per-record save. The local renderer no longer eagerly performs its earlier duplicate-record cleanup; host-confirmed retirement owns the change.
Hook/OSC/launch turn continuity — src/main/agent-hooks/server/pane-agent-turn-continuity.ts:8, server-status-row-mutation.ts:13, server-status-update.ts:199, server-ingest-launch.ts:14, server-status-application.ts:89, cancel-verdict latch → existing owner event Fixed owner/session/turn comparisons and shallow row transforms; preserve accepted verdict across resume. Saved launch identity is routed only when no previous row exists. No scan of all agents, transcripts or sessions, and no new timer/retry cadence.
Host topology capture and persistence — src/main/agent-hooks/server/cli-writer-observation.ts:45, cli-writer-topology.ts:6, server-ingest-normalization.ts:137, server-status-retries.ts:243, server-persistence.ts:89, server-hydration.ts:98 → existing hook/poll, persist, hydrate Compare this binding/owner; carry one executionHost field. Hook scripts capture tmux hints with shell parameter operations; local/daemon spawn stamps inherited tmux with in-memory string work. Zero added child processes, including Codex hook capture. Existing persistence/hydration loops add one scalar test per already-visited row, not an extra pass or whole-file write cadence.
Main-window status publication — src/main/startup/main-window/main-window-agent-status.ts:55 → accepted status Constant topology derivation and scalar metadata on existing main-window/dashboard messages. Ended identity-only statuses return before sending. Existing launch/config/context lookups and recipient count remain. No full-fleet publication added.
Renderer status, completion and retirement — renderer agent-status-partial-updates.ts:50, agent-status-live-entry-builder.ts:222, agent-status-routing.ts:55, forget-refused-pane-resume.ts:28, dispatch-terminal-notification.ts:109, pane-agent-shell-lifecycle.ts:7 → status, clear or shell return Fixed replay/shared-host/turn guards; exact keyed saved record and live status checks. Absent/mismatched retirement returns existing state. Shared identity-only statuses skip checkpoint writes, launch restatements skip duplicate completion notifications. Existing relevant-clear pending-event pruning remains. No new broad selector, effect, mounted-pane resource or hidden polling owner. Remote shell retirement retains its prior behavior; local quiet return can send the bounded reconcile above.
Saved recovery promotion — renderer agent-status-recovery-collection.ts:41, shared promote-saved-live-resume-record.ts:8, agent-pane-sleep-status.ts:6, agent-resume-record-from-status.ts:55, main hook-status-resume-records.ts:67 → manual sleep or existing record conversion Promote/annotate only records already enumerated for the requested workspace, compare fixed provider metadata and carry shared-host eligibility through an existing conversion. No transcript read or new enumeration. Shared-host records are rejected before creating pane recovery.
Requested worktree/process listing — src/main/runtime/construction/runtime-agent-status-sources.ts:36, src/main/runtime/workspaces/process-listing/runtime-worktree-ps-activity.ts:231, workspace-process-listing.ts:134, row/source selection modules → existing listing request Gather S saved records once in the existing H-host/session walk; Set-join with A hook rows, project each eligible pane once. O(A+S), not A×S; supplied saved records avoid per-record host routing. Only a sleep record passes the new field gate. Necessary output enumeration for sleeping agents on a request already producing population-sized output; no extra cadence, subprocess, process table or per-row RPC.
Provider requests and teardown — src/main/providers/local-pty/local-pty-session-operations.ts:127, src/main/ipc/pty/provider/state-cleanup.ts:78, src/main/agent-hooks/server/server-tab-cleanup.ts:166, src/main/memory/pty-registry.ts:30 → targeted list or close Targeted listing now reads requested PTY map entries rather than building/filtering every row: O(requested PTYs). New POSIX proof does not invoke it. Tab close adds one tracked-debt pass to existing tab-wide cleanup; pane cleanup forgets its proof and normal PTY unregister releases PID ownership. No new persistent native handle/listener/cache. Contracts/wiring add fields/callbacks only. Test fixtures and the runtime allowlist affect test selection, not app cadence or CI job count.

Price and host accounting. The new proof is real work beyond main's renderer-only retirement: at P=2,000/20,000, an isolated eligible return needs one 2,000/20,000-row capture/index plus D-local traversal. At one eligible return/s, that is one capture/s and 2,000/20,000 indexed rows/s, not a CPU-time claim. It is necessary evidence to avoid retiring a live/stopped process-less agent, shares its host input among concurrent owners, and introduces no autonomous polling or all-terminal multiplier. At 100/1,000 concurrent callers, the source-module count check below observed one capture per cohort. Ordinary status events/ordinary shell marks request zero of these new captures.

On macOS the shell-tier reader avoids unused tty/start fields and normally captures natively with 0 children. Unreadable foreign argv can invoke one batched recovery ps, through the existing burst-2 / one-per-2-second budget. A native failure uses the existing fallback budget (burst 4 then one/second); failure after argv recovery can pay both stages, so an unconditional one-child maximum would be inaccurate. Linux uses one ps per capture plus existing /proc/<pid>/stat reads for terminal-bearing rows. Shared capture limits remain 32 MiB and 15 seconds; parsing/indexing still occupy main. Windows/WSL command marks request zero new table proofs. Windows quiet-return proof uses existing foreground/job census and, if needed, provider inspection/native evidence. Remote PTYs skip local captures; no per-item SSH round trips are added. Mobile input participates in the same input-stamp invalidation; folder-workspace routing is retained.

Pre-existing scaling kept separate. Main already routes workspace-session reads and hook resume writes through repository/host selection (potential O(R), R≈12/120) and copies immutable S-record maps on real saved-state edits. An exit can pay one initial rowless identity route plus one retirement route per applicable alias, not five repeated routes; sleep resolves its host once for all Q panes. With S=300/3,000, a real saved deletion copies up to 300/3,000 references, absent deletion copies zero. Existing status writes/map edits and coalesced persistence already have this cost; this change removes renderer eager duplicate cleanup and avoids topology ordering. Existing alias scans and requested full listings are also pre-existing population paths. The untouched terminal-client-use caller can still perform its existing provider lookup before calling the changed shell-alone helper; this PR adds no caller to that fallback. These are not new fleet work on every status.

Executed evidence on this head:

  • Through ORCA_BACKGROUND_LAUNCH=1 TC_GATE_POOL=test tc-gate, the five named files unproven-agent-exits.test.ts, terminal-pane-status-lifecycle.test.ts, run-terminal-shell-alone.test.ts, pane-agent-turn-continuity.test.ts, and cli-writer-topology.test.ts: 5 files / 26 tests passed. These exercise queued proof/sleep behavior, shell ownership, stopped/background agents, unreadable comm/zombies, input/launch invalidation, Windows census decisions and host-binding continuity. Platform mocks do not establish live host latency.
  • Read-only count harness through tc-gate, evaluating the current production UnprovenAgentExits class and createProcessTableSnapshotReader with injected capture: 100 and 1,000 simultaneous fresh requests each produced 1 capture. Eleven marks per pane while its proof was pending produced 100/1,000 active proofs. Forgetting every pane before the failed completions settled produced 0 extra retries and 0 retained entries. This validates module counts and stale completion fencing, not full sleep integration or live OS timings.
  • Full merge-base git diff --check passed. No repository edits, commits, pushes, install, app build, typecheck, broad vitest or GUI work.

Recurring regression classes: matched and disproved by the ledger/counts: work before admission gates; per-row global derivation/hot rescans; subprocess per item/re-reading input; per-entity state surviving teardown; unbounded retries/queues; no-op store identity churn; whole-snapshot/publication or whole-file persistence amplification; synchronous main-thread I/O/eager startup imports; hidden/per-mounted-owner activity and fixed polls. No added streaming full-message reprocessing or shared-context fanout matched. Required fresh proof input is intentionally re-read after an eligible return; coalescing preserves that freshness rather than reusing an older answer.

Six-question disposition: (1) reviewed admission through producer, projection, publication and renderer no-op guards; (2) reviewed pane/host ownership, recipients and sharing; (3) reviewed main-thread parsing/copies versus asynchronous capture and coalesced saves; (4) reviewed independent W/R/H/T/A/S/Q/K/L/P/D growth and retry progress; (5) reviewed local/daemon/macOS/Linux/Windows/WSL/SSH/mobile/folder routing in source; (6) reviewed close/forget, entry/row/PTY-incarnation/input invalidation, finite sleep wait and IPC-map cleanup, with teardown counts at N/10N. No confirmed new unnecessary population-scaled work remains.

Limits: no packaged-app CPU/frame/heap profile, live Linux/Windows/WSL/SSH capture, or rendered sleep/wake QA. This grade is based on inspected source bounds and deterministic counts, not measured responsiveness or a claim of complete functional QA.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

PERF PASS — no introduced P0/P1 performance blocker found.

Reviewed the full PR diff from merge base 44803c895a9140d88056fd0c8e1d07f6f2424a08 to bac860d0c9bff3153eb245ac6fff95b37af723f1, following .agents/skills/perf-scan/SKILL.md and its performance, terminal-lifecycle and platform references. perf-surface-detect --pr 43529 reports hot-path,publish,startup-migration. GitHub's current PR head matches the requested revision. The delta since a195606 is a mechanical rename of pane identity/IPC host metadata to executionHost; it adds scalar comparisons, with no new traversal or cadence. The grade below covers the complete PR, not just that delta.

The earlier late-completion failure is fenced by entry identity in unproven-agent-exits.ts:58. The earlier root-PID inventory path is now absent altogether: terminal-pane-status-lifecycle.ts:184 reads the existing spawn/adoption registry in O(1); an unpublished PID produces no table request. There is no 64-entry root-PID eviction cycle on the current proof path.

Work ledger: W=worktrees, R=repos, H=host partitions, T=terminals, A=hook rows, S=saved records, Q=panes captured, K=bindings/leaves of one PTY, L=legacy aliases, P=host processes, D=one root's descendants. Reference fleet: W=750, R≈12, T≈300, A≈100; consider each independently at 10×. S/P/D/K/L are populations, not fixed caps. Projections, parsing, indexing and immutable copies run on Electron main or the renderer as identified; async capture does not make their CPU cost disappear. Unless explicitly stated, the following work adds zero subprocesses and zero process-table reads.

Changed work and production trigger Population, lifetime/bound and comparison with main
Command marks, src/main/runtime/terminal/lifecycle/daemon-launch-note.ts:51, terminal-orchestration-authority.ts:184, src/main/agent-hooks/server/agent-hook-server.ts:161 — each 133;D Indexed PTY plus K associated leaves/pane keys, O(K), with no T/W inventory. A shell with neither row nor proof debt returns before saved identity routing. Ended, shared and verifiable agents skip shell-proof admission. Existing title/transient-fact callers supply the mark; no per-byte work is added to chunks without that fact.
POSIX exit proof, src/main/ipc/pty/pane/terminal-pane-status-lifecycle.ts:173, src/main/runtime/terminal/lifecycle/run-terminal-shell-alone.ts:34, src/main/providers/foreground/agent-process.ts:88 — eligible process-less agent's command/quiet return One keyed root-PID read; zero provider inventories, including cold/missing PID. A published PID requests one fresh host snapshot, shared by callers admitted before its capture begins. The P-row index is weakly memoized by snapshot identity. Each proof walks its D descendants twice and sorts shell candidates, O(D log D) upper bound. Foreground confirmation receives that index, so it does not capture again. Snapshot/native preparation remains population work, detailed below.
Retry debt, src/main/agent-hooks/server/unproven-agent-exits.ts:14,42,72, agent-hook-server.ts:108 — failed proof, subsequent mark or explicit sleep One entry, one active proof and one pending rerun bit per tracked pane. Marks collapse while pending; no retry timer. Success/forget/close removes debt; marks/sleep forget it after the agent becomes verifiable/shared/ended. Completion checks exact entry identity, so a forgotten/replaced entry cannot rearm itself. Sleep waits its current proof and an already-queued rerun, without waiting for an unlimited stream of future marks.
Quiet-return reconciliation, src/main/ipc/agent-hooks/agent-status-row-teardown-ipc.ts:71, src/main/agent-hooks/server/server-tab-cleanup.ts:91, renderer pane-agent-shell-lifecycle.ts:7 — shell-settle/row-retire callbacks One reconcile and one rerun bit per pane, removed in finally. Tracked panes await their existing mark proof; verifiable agents use existing presence probing; ended/shared identities skip the new proof. After a successful retirement, a duplicate report requires no second proof. A launchless typed agent can pay one proof where main previously cleared recovery without host evidence. No new poll or per-mounted-pane census.
Pane identity and spawn/stop/resume admission, src/main/agent-hooks/server/server-state.ts:75, pane-agent-identity.ts:17, server-pane-sleep.ts:29,86, src/main/runtime/session-lifecycle/projection/agent-session-resume-ownership.ts:68 — owner reads and lifecycle events Own-row/own-subject lookup and fixed shallow transforms, retaining provider/message references. Only a rowless identity with no supplied answer routes a saved-record read. Null carries “read and absent.” Spawn/non-stopping checks avoid that fallback; physical stop checks ownership, incarnation and reversible-stop eligibility first. Suspension checks in terminal-agent-status-and-submission.ts:102 reuse collected pane keys and run only for an unverifiable verdict. No new fleet scan before these common skip gates.
Sleep capture, src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts:122, worktree-sleep-resume-records.ts:66 — explicit workspace sleep Q required outputs. Settle all tracked proof requests concurrently, allowing one fresh capture wave, before sequential pane capture. An earlier-running proof or prequeued rerun can need a following wave. Resolve the workspace host once; keyed saved reads before/after presence protect newer conversations. Pass null for absence and reuse identity. No Q terminal inventories or Q fresh host-route scans. Physical stop retains each accepted conversation once and clears its obsolete process facets/timers. No sleep-time tmux process is added.
Quit/reopen, src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts:262, src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts:33 — quit checkpoint or pane restore Enumerate A rows and S saved candidates once. A single TerminalIdentityReadContext shares lazy PTY/leaf indexes between all live checks and launch lookups, avoiding Q×T rebuilding. Reopen checks this pane's identity before existing resume decisions. No new quit shell proof, transcript discovery, startup census or client initialization.
Proven-exit retirement, src/main/agent-hooks/server/server-state.ts:116, src/main/runtime/terminal/stop/worktree-sleep-resume-recording.ts:51, src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts:108 — confirmed exit O(L) alias collection, then a retirement route per applicable key; that route also returns the saved record. Pre-proof identity is passed through known, avoiding repeated reads. Absent/newer records return before copying or publishing. A real deletion copies S references, skips terminal-topology sorting and uses existing coalesced save scheduling. Local renderer eager duplicate-record cleanup is removed in favor of host-confirmed retirement. No new synchronous disk/SQLite operation or per-record immediate flush.
Turn continuity and launch identity, src/main/agent-hooks/server/pane-agent-turn-continuity.ts:8, server-status-row-mutation.ts:13, server-status-update.ts:199, server-status-application.ts:89, server-ingest-launch.ts:14, shared cancel-verdict latch — existing hook/OSC/launch Fixed session/owner/clock comparisons and shallow row copies. Preserve an accepted turn across resume; the incoming binding supplies its execution host. Saved launch identity is read only without a previous row. No transcript/history scan, new timer or additional retry cadence.
Topology capture/persistence, src/main/agent-hooks/server/cli-writer-observation.ts:45,63,111, cli-writer-topology.ts:6, ingest normalization/status retries, server persistence/hydration — existing hook/poll/save/load Carry one serialized host field and validate only this binding/owner. Existing row loops gain a scalar check; persistence writes only shared. Codex/Claude tmux capture uses shell parameter operations, and local/daemon spawn stamping uses in-memory strings: zero additional children, zero tmux commands. No new file rewrite cadence. Moving root-evidence wiring between server layers adds no runtime owner.
Status publication, src/main/startup/main-window/main-window-agent-status.ts:55, src/main/agent-hooks/server/server-status-identity.ts:71 — accepted status Constant topology derivation and one scalar on the existing main-window/dashboard messages. Ended identity-only statuses skip sending; shared identity-only statuses skip renderer checkpointing. Existing launch/config/context lookup and recipient count remain. No new whole-fleet snapshot or per-row notification fanout.
Renderer status/completion/clear, renderer agent-status-partial-updates.ts:50, agent-status-live-entry-builder.ts:222, agent-status-routing.ts:55, normalize-agent-status-event.ts:37, forget-refused-pane-resume.ts:28, dispatch-terminal-notification.ts:109 — existing status, replay, clear or completion Fixed host/turn/replay guards and exact saved/live keyed checks. A refused/absent/mismatched clear preserves current state; real changes use existing map mutation. Existing relevant-clear pending-event pruning remains; no new queue, broad selector, effect, listener or mounted-pane resource. Resume restatements skip duplicate completion notification. Remote shell cleanup retains prior behavior; local quiet returns send the bounded reconcile described above.
Saved recovery conversion, renderer agent-status-recovery-collection.ts:41, shared promote-saved-live-resume-record.ts:8, agent-pane-sleep-status.ts:6, agent-resume-record-from-status.ts:55, main hook-status-resume-records.ts:67 — manual sleep or existing status-to-record conversion Transform records already enumerated for the requested workspace; fixed provider metadata and verdict checks. Preserve or interrupt the accepted turn and reject shared-host pane checkpoints. No extra enumeration or transcript read.
Requested worktree/process listing, src/main/runtime/construction/runtime-agent-status-sources.ts:36, src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts:20, process-listing runtime-worktree-ps-activity.ts:231, workspace-process-listing.ts:134 and row/source selection — existing list request Collect S saved records during the existing H-host/session walk; Set-join against A rows and project eligible pane identities. O(A+S), not A×S. Supplied records avoid per-record routing; only sleep records stand for an otherwise missing agent. This is necessary enumeration for population-sized output, with no added request cadence, process capture, per-row subprocess or remote RPC.
Provider targeting/teardown and wiring, src/main/providers/local-pty/local-pty-session-operations.ts:127, local provider, src/main/memory/pty-registry.ts:30, PTY publication/adoption/cleanup, server tab cleanup, contracts/construction/startup — targeted listing, spawn or close Targeted local lists now visit only requested PTY map entries; the new POSIX proof never calls them. Root ownership lives in the existing PTY registry, populated at spawn/adoption and unregistered on teardown. Pane cleanup forgets debt; tab close adds one debt-map walk to existing tab-wide cleanup. No new native resource or timer. Contract additions are fields/callbacks. Test changes and one node-runtime allowlist entry add test coverage/selection, not app cadence or extra CI jobs.

Process and scale accounting. The new proof is real work beyond main's renderer-only recovery retirement, and is necessary to distinguish a returning shell from an agent that is stopped, backgrounded or hosting a nested shell. At an illustrative P=2,000/20,000 processes and one eligible return/s, it requests one capture/s and indexes 2,000/20,000 rows/s, plus D-local work. Native formatting may sort P rows; this is a count/complexity statement, not a measured CPU-time claim. Ordinary shell marks and ordinary status updates request zero of these new shell proofs. At 100/1,000 concurrent fresh callers the executed reader harness produced one capture per cohort. It does not assert that callers arriving after capture start can reuse pre-request evidence.

  • macOS POSIX: normally one shell-tier native capture with 0 children; avoids full-capture tty/start-time work. Unreadable foreign argv can invoke one batched recovery ps (existing budget: burst 2, then one/2s). Native failure uses existing fallback ps budgeting (burst 4, then one/s); recovery followed by failure may pay both stages. Unsupported/missing addon uses the reader's subprocess fallback. No unconditional zero/one-child claim is made across failures. All these paths are shared-capture paths, not a child per terminal.
  • Linux POSIX: one ps per capture plus existing /proc/<pid>/stat reads for terminal-bearing rows. Capture has the existing 32 MiB/15-second ceiling. Parse/index CPU remains on main.
  • Windows/WSL command marks: zero new table proofs; the mark stands as before. Windows quiet returns: one existing foreground/job confirmation, then at most one provider inspection if needed. For the local provider the conservative call bound is up to three fresh table requests: first identity confirmation, inspection's detailed foreground view, and child-evidence identity view; the common successful first confirmation stops after one. Native tables use no child; missing-native CIM uses one PowerShell child per actual table capture. Recognized foreground candidate filtering can additionally launch one console-list helper. This is bounded event-driven evidence, not a new poll; no live Windows timing was measured. Current daemon providers forward the same bounded operations to their owner.
  • Remote PTYs: return before local process capture; no per-pane SSH process-table round trip is added. Missing published PID requests zero captures. Desktop/CLI/mobile input invalidates a pending proof via the same input stamp; row, launch and PTY-incarnation checks reject stale results. Folder workspace routing remains through the existing host resolver.

Existing population costs, kept separate: repository/twin-host routing can be O(R), about 12/120 repo visits per route. A rowless quit can pay one initial identity route plus one retirement route per applicable alias; this no longer repeats the route five times, and matches main's existing per-hook/resume event routing class. A real saved deletion copies up to S references (illustratively 300/3,000), as existing immutable resume edits do; absent deletion copies zero. Alias collection is O(L), as on the existing exit-cleanup path. The unchanged run-terminal-client-use.ts:59 fallback still inventories T process records before its existing shell-alone helper call; this PR adds no caller/cadence to that fallback. These are not new all-worktree/terminal scans on each status event.

Executed evidence on this head:

  • perf-surface-detect --pr 43529; full merge-base diff and production caller/consumer/cleanup inspection; git diff --check passed.
  • Via ORCA_BACKGROUND_LAUNCH=1 TC_GATE_POOL=test tc-gate node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts, exactly five files: unproven-agent-exits.test.ts, terminal-pane-status-lifecycle.test.ts, run-terminal-shell-alone.test.ts, pane-agent-turn-continuity.test.ts, cli-writer-topology.test.ts: 5 files, 26 tests passed. These cover proof/sleep ordering, foreground/stopped/background agents, unreadable comm/zombies, input/launch invalidation, Windows decision mocks and host-binding continuity.
  • A read-only source-module harness through tc-gate, with injected capture: 100 and 1,000 simultaneous fresh requests each caused 1 capture. Eleven marks per pending pane caused 100/1,000 proofs; forgetting all panes before failures completed caused 0 further proofs and 0 retained entries. An old failed completion behind a newly armed same-key entry caused no extra proof and did not remove the successor. Node's strip-only TypeScript loader required expanding the constructor parameter-property assignment in the harness; production method bodies were unchanged. These are deterministic module counts, not full app or OS timings.
  • No code edits, commits, pushes, installs, builds, typechecks, broad vitest or GUI actions. Working tree remains clean. Prior PASS comments were context, not substituted for this head's source/count review.

Recurring regression classes touched: matched and disproved by admission gates, keyed ownership and the bounds above: per-row global derivation/hot-path rescans; subprocess-per-item and re-reading unchanged input (fresh evidence is required after a return, coalesced before capture); no-op store identity churn; whole-snapshot/publication amplification; whole-file persistence/synchronous-main I/O; per-entity state outliving teardown; unbounded retry/queue admission; hidden/mounted-owner work and fixed polling; eager startup imports. Existing topology/save scheduling remains, and no SDK/heavy adapter was added to eager startup. No new whole-message streaming processing, broad selector or React effect matched.

Six scan questions: (1) reviewed producer-to-publication skip gates, including rowless shells and renderer no-ops; (2) reviewed pane/host ownership, duplicate reports and snapshot sharing; (3) reviewed main/renderer CPU, native/subprocess capture and coalesced persistence; (4) reviewed independent W/R/H/T/A/S/Q/K/L/P/D growth and retry progress; (5) reviewed local/daemon, macOS/Linux, Windows/WSL, remote/mobile and folder paths in source, with platform mocks explicitly distinguished; (6) reviewed close/forget, row/input/PTY/launch invalidation, finite sleep waiting and IPC-map release, with N/10N teardown counts.

No confirmed new unnecessary population-scaled repeated work remains. Limits: no packaged-app CPU/frame/heap profile, live Linux/Windows/WSL/SSH capture or rendered sleep/wake QA; this performance grade establishes inspected bounds and deterministic counts, not measured responsiveness or complete functional QA. The session-ownership invariant is that sleep retains the pane's accepted conversation while proven exit retires only that conversation's recovery; full rendered/provider correctness remains outside this requested performance-only pass.

brennanb2025 added a commit that referenced this pull request Nov 19, 2026
Replays #41746 (brennanb2025/omh-slept-coordinator-wake @ b82ff2d) onto the
into main's notifyAgentSessionStoreCacheChanges; cold-restore resume-record
handler kept in pane-resume-record.ts with #43529's edits; mail-wake guard
added to #43529's refused-resume predicate; new files moved to main's folders.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

PERF PASS — no introduced P0/P1 performance blocker found at efe23d7.

Independent review of the full PR diff, merge base 44803c895a9140d88056fd0c8e1d07f6f2424a08 → requested head, using .agents/skills/perf-scan/SKILL.md, its performance reference, and the terminal-lifecycle/platform checklists. perf-surface-detect --pr 43529 reports hot-path,publish,startup-migration. GitHub's head matches. Prior verdicts were context; the findings below come from this head's code, callers, consumers and cleanup paths.

The change since bac860d is one keyed connectionId comparison in exitProofOwed plus a focused WSL test. A WSL PID no longer suppresses launchless-mark handling: Windows returns null from confirmShellAlone before process inspection, so this adds no process-table read or subprocess. The previous two blockers remain resolved: late proof completion checks the exact retry-entry identity (unproven-agent-exits.ts:58), and POSIX proof gets the PID from getRegisteredPtyPid (terminal-pane-status-lifecycle.ts:182). There is no root-PID inventory fallback or 64-entry root-PID eviction cycle on this head.

Work ledger. W=worktrees, R=repos, H=host partitions, T=terminals, A=hook rows, S=saved records, Q=panes being captured, K=one PTY's associated leaves/keys, L=legacy aliases, P=host process rows, D=one root's descendants. Reference fleet: W≥750, R≈12, T≈300, A≥100; consider each independently at 10×. Unless the table explicitly says otherwise, changed work requests zero process captures and zero subprocesses. These bounds describe work, not measured latency.

New/changed work; trigger and owner Population, repetition, bound and comparison with main
Launchless command marks — each 133;D; main runtime and hook server (daemon-launch-note.ts:51, terminal-orchestration-authority.ts:184, agent-hook-server.ts:162) PTY map lookup plus K indexed leaves and deduplicated keys, O(K), not a T/W inventory. With no row and no retry debt the hook server returns before saved-record routing. Ended/shared/local-verifiable identities skip proof admission. Other PTY bytes add no proof work.
POSIX shell-alone proof — eligible command mark or quiet shell return (terminal-pane-status-lifecycle.ts:173, run-terminal-shell-alone.ts:34, providers/foreground/agent-process.ts:88) O(1) registry PID lookup; missing PID requests zero captures. Otherwise one fresh host snapshot request. A P-row index is shared by snapshot identity; each pane walks only D descendants twice, with shell-candidate sorts bounded by O(D log D). Passing processIndex to foreground confirmation prevents a second capture. Row/input/PTY incarnation/launch fences reject stale evidence.
Failed proof/retry debt — launch retirement, later mark, explicit sleep; pane lifetime (unproven-agent-exits.ts:14,42,72, agent-hook-server.ts:108) One entry, one active proof and one pending-rerun bit per tracked pane. No retry timer or idle polling. Success/forget/close deletes debt; the next mark/sleep forgets it after the identity becomes shared, ended or locally verifiable. Old completion cannot resurrect forgotten debt or modify its successor. Sleep waits the current proof and a rerun already queued, without waiting for an unlimited stream of later marks.
Quiet-return IPC and renderer callbacks — shell-settle/row-retire event (agent-status-row-teardown-ipc.ts:71, server-tab-cleanup.ts:91, renderer pane-agent-shell-lifecycle.ts:7) One reconcile plus a rerun bit per pane, released in finally. A tracked pane awaits its existing proof; a verifiable agent uses existing presence probing; ended/shared identities skip shell proof. A duplicate after successful retirement does not pay another shell proof. Typed agents without a launch can pay one proof where main previously retired recovery without host evidence. No new poll or mounted-pane inventory.
Pane identity, spawn, stop and restore gates — lifecycle/identity reads (server-state.ts:75, pane-agent-identity.ts:17, server-pane-sleep.ts:29,86, agent-session-resume-ownership.ts:68) Fixed row/subject lookups and shallow projections. Only a rowless identity without a supplied answer reads saved recovery through the existing host route. Null means already read and absent. Plain spawn and non-stopping checks avoid saved reads; physical stop checks ownership and reversible stop first. Suspension checks reuse collected PTY pane keys and run only for an unverifiable presence verdict (terminal-agent-status-and-submission.ts:102).
Sleep capture and physical settlement — explicit workspace sleep (worktree-sleep-resume-recording.ts:122, worktree-sleep-resume-records.ts:66, server-pane-sleep.ts:86) Q required pane outputs. Settle tracked proofs concurrently before pane capture so requests coalesce into a capture wave; earlier-running proofs/prequeued reruns can require a following wave. Resolve workspace host once. Two keyed saved reads around presence preserve newer writes; supplied records/null prevent Q host reroutes. Physical settlement retains/interrupts one accepted turn and clears obsolete process facets/timers. No sleep-time tmux process.
Quit checkpoint and reopen — explicit quit/restore (worktree-sleep-resume-recording.ts:262, main-layout-agent-launch-tabs.ts:33) One A+S candidate enumeration. A shared TerminalIdentityReadContext supplies lazy PTY/leaf indexes to all live checks and launch lookups, avoiding Q×T rebuilding. Own identity is checked before resume. No new quit proof, transcript discovery, native client or startup census.
Proven-exit retirement and persistence — confirmed exit (server-state.ts:116, worktree-sleep-resume-recording.ts:51, session-snapshot-operations.ts:108) O(L) alias collection, then one host route per applicable key, returning the saved record through that same route. known passes pre-proof identity into reconciliation. Absent/newer records skip immutable copying/publication. A real deletion copies S record references, skips topology sorting, and uses existing coalesced saving. Local eager renderer duplicate cleanup is replaced by host-confirmed retirement. No new synchronous disk/SQLite call or immediate per-record flush.
Turn/launch continuity — existing hook, OSC or launch (pane-agent-turn-continuity.ts:8, server-status-row-mutation.ts:13, server-status-update.ts:199, server-status-application.ts:89, server-ingest-launch.ts:14, shared cancel latch) Fixed owner/session/clock checks and shallow copies; incoming binding supplies execution host. Saved launch identity is read only without a previous row. Existing row commit, notification and coalesced persistence mechanisms handle the accepted update. No history scan, new timer or retry cadence.
Execution-host capture, propagation, persistence and hydration — existing hooks, transcript Stop polling, PTY spawn, load/save (cli-writer-observation.ts:45,63,114, cli-writer-topology.ts:6, ingest/retries/persistence/hydration, inherited-tmux-env.ts:4) One scalar field and this binding's equality checks. Existing persistence/hydration loops gain constant work per row; only shared persists. Claude/Codex tmux capture uses shell parameter operations; environment stamping uses strings. Zero new tmux commands/children and no added polling or rewrite cadence. Root-evidence wiring moved layers without a new owner.
Main-window publication and renderer status/clear/completion — existing accepted status, replay, clear, notification (main-window-agent-status.ts:55, server-status-identity.ts:71, renderer partial updates, routing, normalization, live builder, refused-resume and notification paths) Constant host/turn checks and one scalar on existing messages to the same main/dashboard recipients. Ended identity-only status skips sending; shared identity-only status skips checkpointing. Exact saved/live lookups preserve mismatched/newer state. Existing relevant-clear pending-event pruning remains. No new whole-fleet snapshot, broad selector/effect, mounted resource or notification fanout. Resume restatements suppress duplicate completion work.
Saved-record promotion and verdict conversion — manual sleep or existing status-to-record conversion (renderer recovery collection; shared promote-saved-live-resume-record.ts:8, agent-pane-sleep-status.ts:6, resume-record conversion; main hook-status-resume-records.ts:67) Fixed checks/copies for records already enumerated for the requested workspace; reject shared-host checkpoints. No extra record/history traversal.
Worktree/process listing — existing requested listing (runtime-agent-status-sources.ts:36, agent-hook-runtime-deps.ts:20, process-listing activity/source/row selection and workspace-process-listing.ts:134) Collect S records during the existing H-host/session traversal; Set-join A row keys and project eligible identities, O(A+S), not A×S. Only sleep records synthesize missing status. Supplied records avoid a host route per saved row. Necessary population-sized output, no new request cadence, table capture, per-row child or remote RPC. At A/S=100/300 versus 1,000/3,000, the additional join visits 400 versus 4,000 candidates per full list.
Provider targeting, registry, teardown and contract wiring — targeted listing, spawn/adopt/close; provider/pane lifetimes Local targeted lists now do requested map lookups instead of enumerating every PTY (local-pty-session-operations.ts:127). The proof does not call inventory. Root PID lives in the existing spawn/adoption registry and is unregistered at teardown. Pane cleanup forgets debt; tab close adds one debt-map walk to existing tab-wide cleanup. Construction/contracts add callbacks/fields, no new resource or heavy startup adapter. Test changes and one node-runtime allowlist entry alter coverage/selection, not app runtime or CI job cadence.

Process reads and spawns per proof. This PR intentionally adds fresh host evidence for process-less local exits: a returning shell alone cannot distinguish a stopped/backgrounded agent or its nested shell. That is necessary work for this behavior, not proof of zero added cost. At illustrative P=2,000/20,000 and one eligible return per second, the request bound is one capture/s with 2,000/20,000 index rows/s plus D-local work; native formatting can sort P rows. There is no T×P index rebuilding for a shared snapshot. Ordinary shell marks without identity/debt and ordinary status updates request zero of these new shell captures.

  • macOS: normally one native shell-tier table capture, zero child processes; drops tty/start-time columns. Unreadable foreign argv can add one batched recovery ps (existing burst 2, refill one/2s). Native failure uses existing fallback ps budgeting (burst 4, refill one/s); recovery then failure can pay both stages. Unsupported/missing addon uses subprocess fallback. No claim that every failure path has zero children.
  • Linux: one ps per actual capture, plus existing /proc/<pid>/stat reads for terminal-bearing rows. The existing process capture has a 32 MiB output ceiling and 15-second ps timeout. Snapshot parsing/indexing and proof projections still consume main-thread CPU.
  • Windows/WSL command marks: zero new process-table reads/children; confirmShellAlone returns null before inspection. Windows quiet return: one provider shell/job confirmation, then at most one provider inspection if it does not confirm. The local provider can request up to three fresh table views across the first confirmation, detailed foreground and child identity evidence; common successful first confirmation stops after one. Native table views spawn zero children; missing-native CIM uses PowerShell for an actual capture. Recognized candidate filtering can additionally launch one console-list helper (existing 3s timeout). Daemon providers delegate these operations to the owner. This remains event-driven, with no new steady poll.
  • SSH/remote PTYs: return before local process capture, no new per-pane SSH process-table round trip. Desktop, CLI and mobile input share the proof-invalidating input stamp. Folder workspaces use the existing host resolver.

Pre-existing population work, distinguished from regressions: host/twin-repo resolution can visit R repos (about 12/120); a saved-only quiet exit can need its initial identity route and its retirement route per applicable alias. Main already routes per hook-resume write/read; the new retirement performs one route and reuses its saved answer. Alias collection is O(L), already present in exit cleanup. Real immutable recovery edits copy S references (illustratively 300/3,000); absent deletion copies zero and no extra topology sort occurs. The unchanged run-terminal-client-use.ts:59 fallback inventories T records before its shell proof; this span adds no caller/cadence there. These costs are not multiplied into all-worktree scans on each status/chunk.

Executed evidence:

  • Full merge-base diff, production caller/consumer/cleanup tracing, surface detector, head verification and git diff --check.
  • Through ORCA_BACKGROUND_LAUNCH=1 TC_GATE_POOL=test tc-gate node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts, exactly four named files: unproven-agent-exits.test.ts, run-terminal-shell-alone.test.ts, terminal-pane-status-lifecycle.test.ts, server-wsl-launchless-exit.test.ts: 4 files / 24 tests passed. These test proof/sleep ordering, foreground/stopped/background agents, unreadable comm/zombies, input/launch invalidation, Windows decision mocks and WSL handling.
  • A read-only source-module harness through tc-gate: at 100 and 1,000 callers, two successive fresh-request cohorts each produced one capture per cohort. Eleven marks per pending pane produced 100/1,000 initial proofs; forgetting every pane before failures completed left zero entries and zero extra proofs. A stale failure behind a same-key successor neither started another proof nor removed the successor; the successor could settle normally. The harness injected capture, used the production reader factory/method bodies, and expanded only TypeScript's constructor parameter-property assignment for Node's strip-only loader. Two initial harness attempts hit loader/API limitations before executing assertions; the corrected run passed. These are module counts, not OS or full-app timings. Requests arriving after capture starts can require a new capture; concurrent callers are not allowed to reuse pre-request evidence.

Recurring regression classes touched: matched and disproved by the gates/counts above: per-row global derivation and hot-path rescans; subprocess-per-item/repeated reads (fresh proof input is required and shared); no-op identity churn; publication/whole-snapshot amplification; whole-file persistence and synchronous main I/O; per-entity retention; unbounded retry/queue work; hidden/mounted-owner and fixed-cadence work; eager startup imports. No new broad keyed-map selector, React effect, or whole-message streaming transform matched. Meaningful lifecycle updates still use existing commits/saves; skip gates do not truncate required outputs.

Six questions: (1) reviewed skip gates before identity/proof/payload work; (2) reviewed pane/PTY/host ownership and duplicate callbacks; (3) reviewed main/renderer CPU, native/child capture and coalesced storage; (4) checked W/R/H/T/A/S/Q/K/L/P/D growth and retry progress; (5) inspected macOS/Linux/Windows, local/daemon/WSL/SSH, mobile input and folder routing, distinguishing mocks from live evidence; (6) checked close/forget, stale row/input/PTY/launch results, finite sleep waiting, retry-entry identity and IPC-map final release, including N/10N counts.

No confirmed unnecessary population-scaled repeated work remains. Limits: no packaged-app CPU/frame/heap measurement, live Linux/Windows/WSL/SSH capture, or rendered sleep/wake QA. This is a source/count performance grade, not measured responsiveness or complete functional QA. The relevant ownership invariant is that sleep retains each pane's accepted conversation while a proven exit retires that conversation's recovery. No code changes, installs, typechecks, broad tests, builds, commits, pushes or GUI actions; working tree remains clean.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

PERF PASS — #43529 at 463ed3b044949ea51db8dad1f1c36daee114169c. No P0/P1 performance blockers found.

Independent full-diff review against merge base 44803c895a9140d88056fd0c8e1d07f6f2424a08 (git diff $(git merge-base origin/main HEAD) HEAD), including production callers, consumers, invalidation, and teardown. GitHub's head matches the reviewed commit. perf-surface-detect --pr 43529 reports hot-path,publish,startup-migration. Earlier PASS reports are context, not evidence for this verdict.

The PR does add necessary process observation on an actual process-less agent exit, where main previously accepted the returning shell without that proof. That is not constant in host process count. It is gated to an agent needing proof, coalesced across concurrent requests, and no longer multiplied by terminal inventories. I found no unnecessary new fleet scan per ordinary prompt, PTY chunk, hook status, or mounted pane.

Cost notation: W = workspaces, R = repos, T = live terminals, A = hook rows, S = saved resume records in the relevant partition, Q = panes/keys in the affected capture, P = host processes, D = descendants of the particular PTY root, K = aliases/placements of that PTY, E = retained exit evidence. Reference sizing: W=750, R≈12, T≈300, A≈100; growth sizing multiplies each independently by 10. Bounds below are source counts, not measured latency.

New/changed work and production trigger Owner, population, work and bound Process spawns / table reads; comparison with main
Hook capture and execution-host metadata: every Claude/Codex hook, PTY spawn, accepted/replayed status Hook shell/main/renderer. Tmux capture uses shell variables, case/comparison and parameter expansion. stampInheritedTmuxEnv, topology derivation, session equality and resumedAcceptedTurn inspect the one binding/row, with scalar/string work. executionHost follows that binding; only shared persists. No new resource owner or timer. 0 added spawns, 0 added tables for metadata. Existing hook posting/process capture stays existing. No sleep-time tmux subprocess was introduced. Files: hook scripts, cli-writer-observation.ts, cli-writer-topology.ts, pane-agent-turn-continuity.ts, environment builders and status mutation/serialization.
Pane identity: status/snapshot reads, launch seeding, spawn retirement, stop and reconciliation Main hook server. server-state.ts:75 reads the alias/row/tmux selection and exit evidence by key. A present row prevents saved-record routing. Caller-supplied null means already-read-and-absent. Rowless fallback resolves the saved record's host once; route can inspect R repos/host partitions. Spawn's shared-row test passes null; reversible-stop/ownership gates precede the saved read. Status payload construction copies one row's fields, not all rows. 0 added spawns/tables. No R-route on ordinary row-backed status reads. A genuinely rowless identity read can cost the existing host resolver, explicitly accounted for rather than called O(1).
Launchless 133;D: every finished shell command, through byte-tracker or daemon fact Runtime reads ptysById and indexed leaves for this PTY: O(K). agent-hook-server.ts:165 first tests row/tracked membership. Plain shell: no saved read/proof. Ended/shared/local verifiable owner: forget tracked debt. One identity read for an admitted owner. Ordinary prompt: 0 inventories, 0 tables, 0 spawns. At 300/3,000 independent plain prompt marks per second this is 300/3,000 local key/placement checks, not 90,000/9,000,000 terminal visits. Existing presence recheck remains the owner for a locally verifiable process.
POSIX proof: process-less pane-owned agent's marked exit, tracked retry, or quiet shell return terminal-pane-status-lifecycle.ts:173 gets published root PID from existing pty-registry map. No provider listProcesses fallback. Missing PID returns null before capture. run-terminal-shell-alone.ts:34 takes one fresh snapshot, uses a WeakMap-shared O(P) index, examines its own D subtree, and passes the same index into foreground confirmation. Two subtree materializations / shell-candidate sorts bound local work by O(D log D), not T×P. Agent recognition is per descendant; stopped/background matching agents block proof. Per admitted POSIX proof: 1 fresh-table request, shared when concurrent; 0 PTY inventories/root-lookup RPCs. Darwin normally 0 children, with at most one batched argv-recovery ps when required, or a whole-table ps fallback; Linux 1 ps per physical capture, plus existing /proc/<tty-pid>/stat reads. Capture ceiling 32 MiB and timeout 15 s. Existing run-terminal client-use caller now also reuses one snapshot instead of taking a second foreground snapshot.
Windows, WSL, SSH and remote-runtime proof routing Native command marks return null before provider/table inspection on win32. WSL's newly admitted launchless mark therefore does no Windows/guest process-table read. Remote PTY IDs return null before local PID/table work. A quiet Windows exit may use one existing provider shell/job proof and, if unanswered, one provider inspection; it is not a process per pane subprocess implementation. WSL/Windows command marks and SSH/remote proof branch: 0 added spawns/tables. Quiet native Windows proof can use existing host job/process inspection, not PowerShell or wsl.exe. No new per-item SSH round trip. Host behavior inspected in source; cross-host timing was not measured.
Retry debt: launch retirement, later marks, sleep, clear/close, late completion unproven-agent-exits.ts:42,58,74: one entry and one running proof per tracked pane; any number of marks while running becomes one boolean follow-up. Failed proof with no new mark stays dormant. Success/clear/tab close deletes debt; entry-identity comparison prevents a late failure from reviving a deleted/replaced entry. Verifiable/shared/ended transitions forget debt at the next mark/sleep. Sleep awaits its initial proof and an already-queued follow-up, not an unlimited stream of future marks. No retry interval/background scan. Repeated active marks can require further proofs (fresh evidence), but no automatic failure spin. Map size O(current unresolved panes); tab-close forgetWhere is one O(tracked panes) pass on close. An already-started shared capture may finish after close, but it cannot create new retry work.
Quiet-return IPC from shell-settle and row-retire callbacks Main agent-status-row-teardown-ipc.ts:69 keeps one running reconciliation plus one rerun bit per pane; finally removes the entry. server-tab-cleanup.ts:93 awaits tracked proof instead of duplicating it, uses the normal presence probe for a verifiable owner, and skips proof for ended/shared identities. Row/launch/input/PTY-incarnation changes invalidate old evidence. Two callbacks for one successfully proved exit produce one proof; rerun sees ended identity. Failed/invalidated proof plus a new report can require one subsequent proof. No unbounded callback queue or timer.
Host-driven sleep capture and physical stop worktree-sleep-resume-recording.ts:122 gathers affected keys, settles their proofs concurrently, then resolves capture host once. worktree-sleep-resume-records.ts:66 reads saved state before/after existing presence checks and passes absent as null. Launch evidence uses ptysById, not repeated terminal-population searches. Physical sleep transforms one accepted row, cancels pane rechecks/facets and preserves shared ownership; topology placement examines that workspace's tabs and the pane layout. At Q=100/1,000 simultaneously admitted fresh proofs: one initial physical table capture, not Q captures; later proof waves need later captures. Per-capture index O(P), per-pane own-subtree work; pre-existing per-process presence checks remain. The host route is once per capture, not Q×R. No new tmux probe or per-pane process launch.
Proven exit, persisted resume retirement, clear publication server-state.ts:116 gathers aliases once (existing O(alias population) reconciliation class), records evidence, and retires one exact saved record per key. retireExitedPaneResume resolves host once and returns that record; proof passes its known identity into reconciliation. session-snapshot-operations.ts:108 skips absent/newer records, copies S record references only for an actual removal, skips topology sorting, then uses existing coalesced save. Renderer clear checks one expected record/status and existing pending-event queue, preserving newer evidence. 0 new subprocesses/tables for retirement. One R-route per retired key, not duplicated reads/routes. O(S) immutable record replacement is acknowledged; main already copies this record map for status-based writes and renderer shell-return removal. No added whole-layout normalization or immediate full-profile disk flush per mark. Actual removals publish required pane clears to at most the existing main/dashboard windows.
Status snapshots and worktree ps / mobile consumers Snapshot projection is O(A). runtime-agent-status-sources.ts:36 builds one pane-key Set, visits supplied saved records once O(S), and only promotes unseen sleep records. Row identities prevent saved-host lookups; supplied records prevent fallback reads. runtime-worktree-ps-activity.ts passes saved records from its existing once-per-host session inventory; downstream maps match rows to summaries. 0 new subprocesses/table captures for this projection. O(A+S), not O(A×S), A×R, or one full inventory per worktree. At A/S=100/100 versus 1,000/1,000: 200 versus 2,000 candidate visits per required listing pass. Existing full listing/liveness work remains population-scaled.
Wake/resume startup and quit checkpoint Startup reads one pane's saved identity and refuses ended/shared recovery before launch. Quit gathers A/S candidates and shares one TerminalIdentityReadContext for live-terminal and launch lookups (worktree-sleep-resume-recording.ts:262). Its lazy terminal/leaf indexes build once per context, not once per record. Renderer recovery reuses the existing per-worktree saved-record index and shared promotion rule. 0 added observation subprocesses/tables just to select records. Actual resume launches are the required per-pane agent launches. Checkpoint/capture work is lifecycle-triggered, not a new idle poll. No new startup SDK/service imports or awaits unrelated to the requested capture.
Window/renderer status, replay and notification changes One executionHost field per existing event/entry; existing main/dashboard fanout stays at two. Identity-only ended statuses and shared identity-only checkpoints are skipped. Replay/notification gates add scalar predicates. Refused-resume removal still uses expected pane/turn and existing store mechanisms. 0 added spawns/tables/listeners/polls. No new per-row mounted effects, broad store subscriptions, whole-status-frame publication, or layout/CSS work.
Hydration validation / final commit and test configuration server-persistence-validation.ts:157 removes the boundary predicate, retaining the already-parsed paneSleep field for a done boundary row. Existing hydration pass/TTL handling is unchanged; no second pass, probe, or new persistent collection. Other hydration/persistence edits copy one shared-host enum through existing row machinery. Test config adds one named file to the node-runtime lane. 0 new hydration subprocesses/tables. Test routing and added fixtures/tests affect test execution, not application cadence. Diff since efe23d7 is this predicate plus its fixture assertion.

Verification: four explicitly named Vitest files through TC_GATE_POOL=test tc-gate with ORCA_BACKGROUND_LAUNCH=1: unproven-agent-exits.test.ts, run-terminal-shell-alone.test.ts, terminal-pane-status-lifecycle.test.ts, and server-wsl-launchless-exit.test.ts — 4 files / 24 tests passed. No install, build, typecheck, broad test run, or app launch.

Also executed a small isolated count harness through tc-gate, loading production UnprovenAgentExits and the production snapshot-reader factory (TypeScript syntax stripped; constructor parameter property expanded equivalently). At both 100 and 1,000 panes, eleven marks per pane while the initial proof was pending started exactly 100/1,000 proofs. Forgetting every pane and then failing every outstanding proof left zero tracked entries and zero retries, including subsequent unarmed marks. 100/1,000 concurrent fresh requests caused one capture; a second wave after capture submission caused exactly one further capture, preserving freshness. This exercises admission/lifetime counts with controlled promises, not real native process latency or a rendered sleep flow.

The previously reported late-failure resurrection is therefore closed by both source identity guard and count evidence. The root-inventory regression is closed by source: the proof calls getRegisteredPtyPid, with no inventory fallback at all. No 64-entry cache can cycle this path. The current registry already belongs to live PTYs and is removed by state-cleanup.ts at teardown.

All six scan questions were assessed:

Question Disposition
1. Work before skip gate Reviewed: plain-shell, ended/shared/verifiable, ownership/reversible-stop and already-read-absent gates precede saved reads/proofs. Necessary one-row serialization remains.
2. Ownership multiplication Reviewed: one retry/IPC owner per pane, shared capture/index per wave, finite window fanout; no mounted-owner polling or new subscribers.
3. Thread/storage Reviewed: main does maps, parsing/indexing and subtree work; native capture runs on existing worker, ps asynchronously. Saved-map copy, coalesced session saves and changed-row SQLite persistence remain accounted for. No new synchronous filesystem/database call on typing/status.
4. Growth/progress Reviewed: O(A+S) required listing; O(P) per shared physical capture, O(D log D) per root; no terminal inventory for one root. Mark debt coalesces, failure goes dormant, fresh later wave advances evidence.
5. Execution host Reviewed in source: local/daemon Darwin/Linux, native Windows, WSL relay, SSH/remote-runtime, folder workspaces and mobile-triggered input freshness. No cross-host timing claim.
6. Obsolete work Reviewed and counted: clear/tab close prevents retry resurrection; PTY registry unregisters; finally releases IPC entries; shared process capture is finite and may complete for other consumers after caller teardown.

Touched regression classes: unused producer work / hot-path rescans — gated/indexed as above; subprocess-per-event/item / unchanged rereads — necessary fresh exit proof only, shared physical capture, no inventory; fixed polling / hidden-owner work — no new cadence, unresolved debt dormant; collection fanout / unbounded queues — Sets/maps, one pending bit, sleep requests share capture; entity state outliving owner — teardown plus late-result identity guard; publication/store churn / whole snapshots / whole-file rewrites — existing event fanout and coalesced persistence, one enum added, absent retirement is a no-op; sync main-thread I/O / startup imports — no added matching costly operation. Each matched class was checked and disproved as an introduced waste regression; none is a finding.

Pre-existing population work remains visible: workspace host routing may inspect R repos/host partitions; main-window launch-context lookup already uses terminal identity resolution per status; reconciliation already visits alias state; status/resume writes already replace record maps, and dirty exit persistence serializes E retained exit records. This span does not introduce a higher-cadence fleet scan for those paths. Necessary new exit/sleep outputs use those existing owners. At 10× fleet those existing paths still scale; this PASS does not claim they are constant or benchmark them away.

Limits: this is a source/count-based performance verdict. No packaged Electron frame/CPU/heap profile, real 1,000-terminal sleep, Windows/WSL/SSH runtime timing, or cold-start timing was collected. Native capture latency and actual per-host subtree sizes remain unmeasured; no millisecond/CPU claim is made. The recovery invariant being screened is that a physical sleep preserves the pane's conversation, while shared/ended identities do not launch another copy (#42542 / STA-15387). Full cross-platform correctness certification is outside this independent performance pass.

brennanb2025 added a commit that referenced this pull request Nov 19, 2026
Replays #41746 (brennanb2025/omh-slept-coordinator-wake @ b82ff2d) onto the
into main's notifyAgentSessionStoreCacheChanges; cold-restore resume-record
handler kept in pane-resume-record.ts with #43529's edits; mail-wake guard
added to #43529's refused-resume predicate; new files moved to main's folders.
brennanb2025 added a commit that referenced this pull request Nov 19, 2026
Replays #41746 (brennanb2025/omh-slept-coordinator-wake @ b82ff2d) onto the
into main's notifyAgentSessionStoreCacheChanges; cold-restore resume-record
handler kept in pane-resume-record.ts with #43529's edits; mail-wake guard
added to #43529's refused-resume predicate; new files moved to main's folders.
brennanb2025 added a commit that referenced this pull request Nov 19, 2026
Replays #41746 (brennanb2025/omh-slept-coordinator-wake @ b82ff2d) onto the
into main's notifyAgentSessionStoreCacheChanges; cold-restore resume-record
handler kept in pane-resume-record.ts with #43529's edits; mail-wake guard
added to #43529's refused-resume predicate; new files moved to main's folders.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review loop, final round (6f3a93f → 463ed3b).

What changed. An external design review asked for a rework. The PR body has the current design and its known limits.

  • Who runs a conversation is now one serialized field on the hook row, executionHost. It is written when the hook row is written, and only shared is persisted. The window receives the same field and writes no checkpoint for a shared conversation. This replaces the sleep-time tmux probe.
  • A command mark (OSC 133;D) ends a process-less agent only once the host proves the pane's shell is alone. A pane whose proof failed, such as a nested shell's mark inside a live Codex or a Ctrl-Z, is re-proved at the next mark.
  • worktree ps lists a saved record's agent only for a sleep's record.

Repairs found by this round's reviewers (each with a test that fails when the fix is reverted):

  • A resumed turn took its host from the previous row. A pane-owned claude --resume after a tmux row of the same session was treated as shared, so it got no checkpoint. It now takes the host from the resuming hook, and keeps the row's host when the hook reuses the row's own binding.
  • A typed WSL agent never ended at its returning shell mark. The agent reported a Linux PID that main can't probe, and that PID excused the shell proof. Only a local row's process excuses it now.
  • A slept conversation with no turn yet read as quit after an app restart. Hydration dropped its sleep marker but kept the ended presence the sleep writes. Hydration now keeps the marker for such rows too.

Design choices kept (the PR body has details). Each alternative would regress current behavior:

  1. Stripping TMUX from every pane changes the environment of users who run Orca inside tmux.
  2. A wake-time PID liveness check can't see Codex, which reports no process identity. That is the double resume QA found before this design.
  3. A generation token in place of the per-pane proof queue drops the queued re-proof that keeps a nested shell's mark from ending a live Codex.

Council re-check on 463ed3b (diff plus the regression notes, against the reference tools):

  • Codex seat: VERDICT: STANDARD, OPTIMAL: YES.
  • Claude seat: VERDICT: MIXED, OPTIMAL: YES. The only departure it names is keeping the inherited TMUX with a marker, where two references strip it; it calls keeping it defensible for this PR.
  • On a195606, before the last repairs, the seats split: Codex STANDARD/YES, Claude MIXED/NO. The Claude seat's point was that tmux detection covers only Claude, Codex and OpenCode, so other agents run in tmux can still be resumed twice. That is the same as main, and it is moving to a separate follow-up PR. The re-check on 463ed3b judged this PR on its own scope and agreed with the split.

Verified.

  • Review pair on 463ed3b: fresh Opus and Codex reviewers both READY, no P0/P1. Open P2s are the same as main or need a narrow race: a WSL pane replaced mid-proof follows the no-proof rule (known item f), and rows saved by earlier QA builds of this PR used an old field name.
  • Perf-scan on 463ed3b: PASS (comment 7015694305).
  • pnpm check:changed on Linux at 463ed3b: 42/42 passed. CI: green on 463ed3b.
  • Real-app QA r6 (Omarchy, ticket 8206) at efe23d7, with real Claude Opus 5.5 and Codex: all PASS.
    • A. tmux Claude and tmux Codex leave no sleep record at any of 43 snapshots. Both are recorded executionHost: shared on disk and in the window. Wake leaves a plain shell, and tmux attach recalls each token.
    • B. Electron main SIGKILLed while asleep, then relaunched and woken: plain shell, no second agent.
    • C. Claude from + and a typed Codex resume with recall. After /quit, a sleep and wake leave a shell.
    • D. A pane-owned claude --resume after a tmux row of the same session gets a checkpoint, and wake resumes it with recall.
    • The only later commit, 463ed3b, changes hydration of a no-turn sleep row; its restart test covers it.

Screenshots:

  • B: tmux Claude workspace after wake, a plain shell (the tmux Claude stays the only one).
  • D: pane-owned resume after a tmux row, recall after wake.
  • C: Claude from + recalls after wake.
  • C: typed Codex after /quit, then sleep and wake: a plain shell.

tmux Claude workspace after wake: plain shell

Pane-owned resume after a tmux row: recall after wake

Claude from + recalls after wake

Typed Codex after /quit, sleep and wake: plain shell

@brennanb2025
brennanb2025 merged commit b080468 into main Nov 19, 2026
74 of 76 checks passed
brennanb2025 added a commit that referenced this pull request Nov 19, 2026
Replays #41746 (brennanb2025/omh-slept-coordinator-wake @ b82ff2d) onto the
into main's notifyAgentSessionStoreCacheChanges; cold-restore resume-record
handler kept in pane-resume-record.ts with #43529's edits; mail-wake guard
added to #43529's refused-resume predicate; new files moved to main's folders.
brennanb2025 added a commit that referenced this pull request Nov 19, 2026
Replays #41746 (brennanb2025/omh-slept-coordinator-wake @ b82ff2d) onto the
into main's notifyAgentSessionStoreCacheChanges; cold-restore resume-record
handler kept in pane-resume-record.ts with #43529's edits; mail-wake guard
added to #43529's refused-resume predicate; new files moved to main's folders.
brennanb2025 added a commit that referenced this pull request Nov 19, 2026
Replays #41746 (brennanb2025/omh-slept-coordinator-wake @ b82ff2d) onto the
into main's notifyAgentSessionStoreCacheChanges; cold-restore resume-record
handler kept in pane-resume-record.ts with #43529's edits; mail-wake guard
added to #43529's refused-resume predicate; new files moved to main's folders.
brennanb2025 added a commit that referenced this pull request Nov 19, 2026
Replays #41746 (brennanb2025/omh-slept-coordinator-wake @ b82ff2d) onto the
into main's notifyAgentSessionStoreCacheChanges; cold-restore resume-record
handler kept in pane-resume-record.ts with #43529's edits; mail-wake guard
added to #43529's refused-resume predicate; new files moved to main's folders.
brennanb2025 added a commit that referenced this pull request Nov 19, 2026
Replays #41746 (brennanb2025/omh-slept-coordinator-wake @ b82ff2d) onto the
into main's notifyAgentSessionStoreCacheChanges; cold-restore resume-record
handler kept in pane-resume-record.ts with #43529's edits; mail-wake guard
added to #43529's refused-resume predicate; new files moved to main's folders.
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