You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(orchestration): refuse mail to a terminal working another Orca's Task before storing it - #51336
Sometimes a terminal on a server is busy doing a job for another computer. While it does that job, it only reads mail from that other computer. Until now, if someone on the server sent it a message, the server said "sent" and stored the message where the terminal would not look until the job was over. Now the server says no right away, explains why, and stores nothing, so the sender knows to ask the job's owner instead.
Files
Added
Deleted
Net
Test
2
$\color{#1a7f37}{\Huge{\mathbf{+}}}$223
$\color{#cf222e}{\Huge{\mathbf{−}}}$2
$\color{#1a7f37}{\Huge{\mathbf{+}}}$221
Prod
15
$\color{#1a7f37}{\Huge{\mathbf{+}}}$256
$\color{#cf222e}{\Huge{\mathbf{−}}}$39
$\color{#1a7f37}{\Huge{\mathbf{+}}}$217
What Changed
Before: on a server, mail to a terminal that is working a Task for another Orca (a legacy remote attachment, which a desktop older than v1.4.258 still places) was stored in that terminal's own mailbox. The sender got a receipt warning that the mail "can't be read in that terminal", and the worker didn't see it until its Task settled.
After: an upgraded server refuses that mail before writing anything, with effectsApplied: false:
capability_unsupported while the attachment is ready: "term_X is working a Task for another Orca; mail can't reach it there. Message that Task's coordinator. Nothing was sent."
dispatch_inactive while it is starting, stopping, or its outcome is unknown, with the same next step.
This removes the false delivery. It is not mail parity for legacy workers: a legacy worker still can't receive server-local or --on mail, and the sender is told so at send time. Two upgraded Orcas place workers through server-owned placement, which this change doesn't touch.
Mechanism: one resolver step in resolveBareOrchestrationRecipient (new legacy-attachment-recipient-refusal.ts). It runs after bound Runs and local Dispatches, and before historical Run owners and the bare-terminal fallback. It finds the attachment by the terminal's live pane, or by an exact lookup of the terminal handle the attachment recorded. As a result, local Run and Dispatch precedence stays as it was, including explicit --run against them, and the terminal-agent orca_session_id: refusal still runs first. A handle whose only owner is a historical Run is now refused while the attachment is live, before --run is matched against that Run.
Covered:
Point send from a server-local agent.
Group fan-out: a refused member becomes a warning and the other members are still delivered. The receipt lists both the deliveries and the refused members, so a caller won't retry delivered members. If every member is refused, the send fails with this refusal reason instead of "no recipient resolved".
Reply to a message from such a terminal. The reply waits between routing and storing, so inside the storing transaction it checks two things again: the chosen destination, and the original sender, resolved again. A reply is refused if the sender took another Orca's Task during the wait. That holds whether routing had picked the sender's terminal or its former Run mailbox. A reply still routed to the terminal is refused even if a local Dispatch also took it during the wait. A reply routed to the former Run follows the Dispatch's precedence instead.
--on receiver: keeps its refusal, now through the shared resolver step and wording; its store-time pane check stays, for replies to a client ask, which keep main's routing. Its code changes from invalid_argument to the two codes above.
workerStart from a paired caller with on: main already refuses this in the shared access check (peer-run-access.ts:173-193), so this PR only adds a regression test for it.
Unchanged:
Mail coming home to this Orca's own sender keeps main's routing: peer-mail replies, unpair notices, replies to a paired server's client ask, and bot-request outcome notices.
worker_done and report handback, server-owned placement, ordinary terminal routing once the attachment has settled, and local behavior. There is no wire, schema, capability or protocol change.
Release note: Today an old server stores mail for an attached worker in its terminal, and the terminal reads it once the Task settles. An upgraded server refuses that mail at send time instead.
Why
A sender who is told "sent" retries nothing and waits for an answer that can't arrive until the Task ends. Refusing before write, on the server only, closes that for every upgraded server. It needs no protocol, schema or capability change and nothing on the desktop. Legacy attachments come only from older desktops, or from older servers that run their own code. Delivering mail to them would take a new two-sided protocol that no currently supported pairing would negotiate.
Limits:
An old server keeps today's behavior: it queues the mail with the existing "can't be read in that terminal" warning. Upgrading the desktop can't change what an old server does.
Mail stored before the upgrade stays in that terminal's inbox.
Linked Issue
N/A (internal maintainer work).
Visual Proof
N/A: there is no UI change. The change is in the CLI and RPC refusal text, which the tests below assert exactly.
Testing
legacy-attachment-recipient-refusal.test.ts uses a real OrchestrationDb and the registered orchestration RPC handlers, including the access check, with no mailbox mocks.
Fail-before was run off this Mac against the merge-base's production code. Every case except the last fails, because main stores the mail.
Point send: refused with nothing stored. This holds whether the ready attachment is found by its live pane or by its recorded handle. Once the attachment settles, the same send is stored normally.
Starting attachment: gives dispatch_inactive. A local Dispatch on the same pane still takes precedence.
Group send: the other delivery is kept and the refused member is reported. An all-refused group fails with the reason.
Reply race: a reply is refused when the attachment goes live after routing and before the insert. This holds for a bare-terminal route, for a route to the sender's former Run, and when a local Dispatch also took the terminal. Each recheck alone fails one of these cases.
Paired-caller workerStart --on: still refused. This is a regression guard only; main already refuses it.
--on peer mail is covered through the real RPC entry point by peer-mail.test.ts "refuses mail to a worker another Orca coordinates", which now expects capability_unsupported and fails on main.
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Every added test fails without this change and avoids the test anti-patterns (the controls are marked as controls and pass on main by design)
Performance
None measurable, because each bare-terminal resolution adds at most two indexed single-row lookups (attachment by pane, then by terminal handle), and only when no bound Run or local Dispatch matched first. A group send does this per member, which it already does for routing.
Risk
Level: Low
The riskiest part: a terminal whose attachment row is stuck in a potentially-live state (for example stop_unknown) now refuses direct mail until that row settles. Before, such mail was stored where the worker didn't read it. The refusal tells the sender to message that Task's coordinator.
The receiving server's version decides the behavior. An upgraded receiver refuses --on mail with the new codes whatever the sender's version. An old receiver keeps its old behavior.
Deferred:
Crew's recipient availability still lists such a terminal as reachable, though a send to it is now refused clearly. Aligning Crew needs a batched lookup in its projection, which is its own small change.
A bot-request send to such a terminal is refused through the same resolver, but without effectsApplied: false on the error.
Backing out is a plain revert. The change writes no data.
AI Disclosure
Review
Agent skill upstream boundary
Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.
Notes
Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
Checklist
This PR is small and focused
I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
I stated the risk: what could break, for whom, and how to back it out
Before/after screenshots or videos attached for UI changes, or N/A with reason
Self-reviewed for correctness, security, and performance
Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)
…Task before storing it
On an upgraded server, a point send, a group member and a reply to a terminal
held by a legacy remote attachment are refused before write
(capability_unsupported when ready, dispatch_inactive otherwise), instead of
being stored where the worker never reads them. The --on receiver uses the
same check and wording.
Performance review: PASS. No introduced performance regression found by source tracing 08e46298fd6..78ea138b6659e86db6178ba9a9be05bb78a9e58b.
Added work, triggers, populations and bounds (runtime RPC/receiving-server main thread; invocation lifetime):
Added work
Trigger and population
Work and bound
Shared refusal callback and attachment reads
Each bare-recipient resolution reaching past current Run/Dispatch ownership; point send, reply, group member/sender, bot admission, peer import/reply and unpair notices
One callback; zero reads for nonterminal identities or current local owners; otherwise at most one active-pane lookup plus one retained-handle lookup. Each returns at most one row.
Refusal/error construction
Each refused recipient
Two-code membership check, five-state liveness check, one error/warning; text proportional to handle length. Other refusal hints retain their existing behavior.
All-undeliverable group explanation
One send with zero unique deliverable recipients; M resolved members
One M-entry pass, at most M refusal references, then one pass/join over refused messages; O(M + output bytes), invocation-local storage. Mixed groups retain their existing per-member warning delivery.
Reply store-time recheck
One ordinary reply after the answer-turn await, before insertion
Canonical Run/Dispatch addresses exit immediately; otherwise one live-pane resolution plus at most two attachment reads inside the existing transaction. Including initial routing: at most four attachment reads. No additional transaction, write or notification.
Peer receiver guard replacement
Each first-store delivery after duplicate/admission gates
Initial resolver plus store guard: at most four attachment reads, versus the previous single store-time pane read (maximum +3). The two live-pane resolutions already existed. Refused delivery writes/notifies nothing.
Guide text and module wiring
CLI guide materialization / runtime module load
One additional guide line; small local helper module and type-only imports, no new SDK, startup I/O, resource owner or repeating task.
Evidence at the target: src/main/runtime/rpc/methods/orchestration/messaging/legacy-attachment-recipient-refusal.ts:19, recipient-owner-selection.ts:38, recipient-routing.ts:275, send-group.ts:268, reply-method.ts:180; receiver: src/main/runtime/rpc/methods/orchestration/federation/peer-mail-agent-store.ts:67 (abbreviated messaging filenames share the first directory).
Read bounds: src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-stop.ts:92 uses exact handle + newest rowid + LIMIT 1; its pane reader uses exact/leaf-suffix predicates and the same potentially-live states as the partial indexes. src/main/runtime/orchestration/db/schema/schema-column-probes.ts:43 supplies the handle index on both create/migrate paths; create-graph-tables-sql.ts:79 supplies active-pane indexes. These are indexed seeks, not whole attachment-history inventories. Up to two existing full row projections are materialized per guard, including their existing text fields; bytes depend on those rows, not total transcript/message history. Explicit projections reuse the bounded 256-statement cache in src/main/sqlite/sync-database.ts:36.
Fleet pricing (operation counts, not timings): use 300 terminals / 100+ agents / 750 worktrees, then 3,000 / 1,000+ / 7,500. One point resolution adds <=2 attachment reads at either size; ordinary reply <=4 total; peer receiver <=3 added. At an illustrative 12 CLI callers every 3 seconds (4 requests/s), those are <=8 added reads/s for point mail, <=16 for ordinary replies, <=12 for peer receipt. No multiplication by unrelated worktrees, repositories, refs or history bytes. A worktree group with M=300/3,000 eligible terminal members adds <=602/6,002 reads including its sender; this is one required ownership decision per addressed member. Unpair/re-pair adds <=2Q reads for Q affected open questions, once per change, not per idle tick.
Lifecycle and consumers: active local Run/Dispatch ownership returns before the new callback; canonical reply/store addresses skip rechecks. Ready/starting/unknown/stopping attachment states refuse; success/failure/stop settlement exits the live-state set, allowing retained terminal mail again. Authority attachment is serialized; removal/reset deletes rows; there is no new negative cache, listener, retained registry or cleanup debt. Run takeover/mail promotion remains in src/main/runtime/orchestration/db/runs/run-binding.ts:212 and legacy-coordinator-mail-takeover.ts:4, outside the refusal path. Peer replies and unpair notices preserve their existing fallback/store/settlement behavior; bot admission preserves its refusal-before-store behavior.
Six scan questions:
Admission before work: checked; local-owner/canonical gates precede added reads; refusal precedes message construction/write/nudge. Group failure text is built only after zero deliverable recipients.
Multiplication/ownership: checked; per addressed member or affected question, no mounted-row/pane ownership or new resource recreation. Temporary results end with the invocation.
Thread/storage: checked; synchronous SQLite on runtime main, indexed LIMIT-1 reads and cached statements. No added write/WAL/index maintenance, spawn, remote round trip or full history serialization.
Growth/progress: checked; constant query count per recipient, linear required group error output; no new retry/frontier. Existing duplicate, relay settlement and question-settlement gates remain in place.
Execution host: source-reviewed local and receiving-server routes, including SSH compatibility lookup; no new host probes or platform-specific code. No runtime host measurements were made.
Obsolete work: checked; synchronous guards finish or throw, failures perform no message write/nudge, state changes are reread on each invocation. Added steady-idle timer/poll/IPC wakeups: 0/s before and after in main, renderer and daemon by source inspection; no new publication/subscription, so no new listener census.
Touched regression classes: sync SQLite and repeated reads—matched, bounded/indexed above; fan-out/hot-path scans—matched, added work is linear in required recipients/output; per-entity retention—no added retained owner; eager imports—small local helper only, no new startup I/O. No other recurring class has matching added code.
Pre-existing amplification, not introduced here: src/main/runtime/rpc/methods/orchestration/messaging/send-group.ts:233 searches candidates for each selected handle (<=MC comparisons per group: <=90,000 at M=C=300; <=9,000,000 at 3,000). Its Run-candidate identity fallback at line 84 similarly allows <=WA comparisons when handle matches miss. The existing @idle status fan-out can issue C concurrent status reads on each of at most three candidate-refresh attempts. This diff neither broadens these audiences nor adds attempts.
Evidence limits: source counts/index definitions and caller/lifecycle tracing only. The new test assertions cover live/retained/starting refusal, mixed/all-refused groups, reply recheck, receiver, local-owner precedence and settled recovery; they were inspected, not executed. No tests, typechecks, builds or package commands were run. Query plans, wall time, CPU and heap were not measured; no latency claim is made. Native UI/startup rendering is unaffected by these changed mail triggers.
The change adds no timers, polls, listeners, subprocesses, retained maps or startup imports. All added work runs inside an existing send, reply or delivery RPC, or an existing peer-mail pull. It is at most two indexed SQLite point reads per bare-terminal resolution, plus one extra resolver pass per local reply.
every resolveBareOrchestrationRecipient call that falls past run-bound and active-dispatch owners and names a terminal
1 resolution
Lazy: it runs only after boundRuns/dispatches miss, and it does no reads when terminalHandle === null or keepLegacyAttachedRouting is set. It makes ≤2 reads. The first is findActiveRemoteAttachmentForPane, which uses the partial index idx_remote_dispatch_attachments_active_pane / _suffix (live states only), so its size is the number of live attachments, not history. The second is findLatestRemoteAttachmentForTerminal, run only on a pane miss: terminal_handle = ? ORDER BY rowid DESC LIMIT 1 over idx_crew_remote_handle, one index seek.
Point send (send-methods.ts)
orchestration.send RPC
1 recipient
Same ≤2 reads. sendRecipientRefusal is only on the error path.
Group fan-out (send-group.ts)
group orchestration.send (@all etc.)
each member without a pre-resolved mailbox, plus the sender
≤2 reads per member. At the reference fleet (a few hundred terminals in one group) that is ≤~600 indexed point reads per group send, alongside the ~4–6 indexed reads per member the base already does. Each member needs its own routing decision, so this is required per-member work, linear and sync on main once per send. It doesn't repeat per status update or keystroke. The new flatMap over resolvedRecipients runs only when uniqueRecipients.length === 0, i.e. an error-path pass over members that is already O(members).
Reply store-time recheck (reply-method.ts)
local orchestration.reply
1 reply
Inside the existing reply_with_answer write transaction: one refuseLegacyAttachedRecipient (≤2 reads, skipped for run:/dispatch:) and one full resolveBareOrchestrationRecipient for the original sender (skipped for run:/dispatch:). It reuses the already-awaited terminalRecipient. It is sync, with no await, so the lock is held a few more indexed reads. readSessionRecipient does no listRecords scan (point getRecord lookup only). The cost is constant per reply and doesn't grow with history or fleet.
orchestration.peerMailDeliver RPC, and each client_reply item in a peer-mail pull
1 item
The inline pane check becomes refuseLegacyAttachedRecipient, which adds one handle seek on a pane miss. The resolver call above it also gains the ≤2-read step, so ≤4 indexed reads per item, up from 1. A refusal throws into the existing per-conversation hold (HeldPeerConversations.failed, exponential federationRelayRetryDelayMs, MAX_HELD_BACK 50). So a refused item retries with backoff, not a hot loop. It moves forward once the attachment leaves a live state, because both lookups then miss.
storePeerReply, tellUnpairedPeerQuestions
peer reply import; unpair/server change
1 item / each unsettled question
keepLegacyAttachedRouting: true, so the step short-circuits with 0 added reads.
Crew recipient view (crew-recipient-inputs.ts)
crew listing
n/a
Doesn't pass legacyAttachment, so nothing is added.
Regression classes touched
Sync SQLite on Electron main: matched and disproved. The added reads are indexed point lookups, once per send, reply or delivery RPC (agent-paced: a dozen agents calling the CLI every few seconds is roughly 4 RPCs/s fleet-wide). The only fleet-sized case is group fan-out, which pays ≤2 reads per required recipient. Nothing runs per keystroke, PTY chunk, status update or poll.
Subprocess per item or per event: no matching code (no spawns).
Fixed-cadence poll / new idle wakeups: no matching code. The only retry is the existing peer-mail hold with backoff, and an idle server does 0 added work.
Expensive code newly reachable past a gate: matched and disproved. keepLegacyAttachedRouting is a new skip, not a removed gate. The new reachability is two indexed reads behind the existing owner checks.
Per-entity state outlives the entity: no matching code (no new maps, sets or listeners).
Unbounded fan-out or queues: matched and disproved. Group resolution is a sync .map with no added concurrency.
Eager startup imports: matched and disproved. The new module imports only in-repo orchestration modules already on that graph.
Six questions
Unused work before the skip gate: reviewed. The step is a lazy callback placed after the local-owner checks, and it short-circuits before any read for non-terminal handles and the keep-routing callers.
Ownership multiplication: reviewed. There are no per-pane, row or host owners: one evaluation per resolution, and per member only in group sends, where each member is a required output.
Thread and storage: reviewed. All work is sync node:sqlite on the runtime main thread, using indexed seeks (partial live-state pane index, terminal_handle index). The reply adds a few reads inside its existing write transaction.
Growth and progress: reviewed. Pane lookups grow with live attachments, not history, and handle lookups are a LIMIT 1 index seek. Refused peer-mail items back off and move forward once the attachment ends.
Execution host: reviewed. Everything runs on the server's runtime DB, with no SSH or transport round trips and no platform-specific calls added.
Obsolete work and teardown: not applicable. Nothing outlives the request; the only deferred retry is the pre-existing held-conversation backoff.
Coverage and gaps: I read the source only (no timing runs). I traced point send, group send, local reply, the --on/peerMailDeliver receiver, the paired-server client_reply import, peer reply store, unpaired-question notices and crew selection. I didn't inspect findRemoteAttachmentForPane query plans with EXPLAIN on a large real-shaped DB; the bound above comes from the index definitions.
Verdict: clean. No P0/P1 findings. All added work is on Electron main, inside existing orchestration RPC handlers. It runs once per call or once per recipient. It adds no timer, poll or subscription, and nothing grows with history.
Added work
Added work
Trigger
Population
Bound
legacyAttachedRecipient step in selectBareRecipientOwner (recipient-routing.ts, recipient-owner-selection.ts)
Each bare-recipient resolution: orchestration.send, each group member, reply-recipient resolution, --on receiver (peer-mail-agent-store.ts)
Runs only when explicit-run, bound-run and active-dispatch owners all miss. Skipped when terminalHandle === null or keepLegacyAttachedRouting
≤2 indexed SQLite point reads: findActiveRemoteAttachmentForPane uses the partial pane_key index. findLatestRemoteAttachmentForTerminal uses idx_crew_remote_handle(terminal_handle) with ORDER BY rowid DESC LIMIT 1, served from the index order. Reuses the paneKey the resolver already computed, so no extra getLiveTerminalPaneKey
reply-method.ts: refuseLegacyAttachedRecipient + refuseNewlyLegacyAttachedSender inside the reply_with_answer write transaction
Each orchestration.reply with a bare (non-run:/dispatch:) recipient/sender
1 reply RPC. Reference fleet: a dozen CLI agents, each every few seconds, ≲5/s total
+1 full resolveBareOrchestrationRecipient (the same handful of indexed per-handle queries as before, not fleet-wide), +1 getLiveTerminalPaneKey, ≤4 indexed point reads. A constant multiple of existing per-reply work. It holds the write transaction a little longer but scans nothing
send-group.ts: flatMap over resolvedRecipients
Only when no member resolved (uniqueRecipients.length === 0)
Group size (up to a few hundred terminals)
One linear pass on the error path. Resolution already visits each member once
send-methods.ts: sendRecipientRefusal
Refused point send only
1
Same as the previous withDispatchPrefixHint path, or a string concat
bot-request-sender-notice.ts: legacyAttachmentRefusal in reachableSender's catch
Only when reply-recipient resolution has already thrown
1 per bot-request notice
1 getLiveTerminalPaneKey + ≤2 indexed point reads
Retry for bot-request notices (new 'unverified' population)
A legacy-attached sender now returns 'unverified', so the notice is held instead of being dropped. Retries are event-driven only:
Questions:QuestionReconciler.chatObserved re-requests held takers once per newly observed session id. Per-status observations cost one Set.has.
Handoffs: retried at the bot's next turn end.
No timer or backoff loop is added, so idle wakeups/s on main, renderer and daemon are unchanged at 0. The seenSinceUnverified Set already exists. It is bounded by the distinct chat sessions first seen while a taker is held, and cleared when none are held. The population added here is narrow: bot-request senders that are terminals working another Orca's Task, which is rare because bot requests normally come from chats or workers.
Regression classes touched
Sync SQLite on Electron main: matched, disproved. Indexed point lookups, per RPC/recipient, constant per call at N and 10N terminals.
Hot-path rescans: no matching code. No new .find/.filter over a same-size collection inside a loop. The group flatMap is a single pass on the error path.
Fixed-cadence poll / new idle wakeups: no matching code.
Expensive code newly reachable past a gate: no gate removed. keepLegacyAttachedRouting only skips work. The removed inline check in peer-mail-agent-store.ts moved into the resolver.
Per-entity state outlives entity: no new maps or listeners.
Unbounded fan-out: no matching code. Group fan-out is unchanged except the step above.
Six questions
Work paid before the skip gate: reviewed. The new step is a lazy closure evaluated after cheaper local owners, so a local-owner hit pays nothing.
Ownership multiplication: N/A. No per-pane or per-row owners. Per recipient only.
Thread/storage: reviewed. Main thread, node:sqlite, all reads indexed. The reply recheck adds a few µs-scale reads inside an existing write transaction.
Growth / progress: reviewed. Constant per call. The 'unverified' retry advances once the attachment leaves the potentially-live states.
Execution host: reviewed. Same SQLite queries on all platforms. No SSH round trips or subprocesses added.
Obsolete work stops: reviewed. No timers or handles to release. Held notices are retried only on edges.
Not measured: no runtime profiling was done. The costs above are source-proven query and call counts.
Verdict: clean. No P0/P1 findings. The diff adds no timers, polls, subscriptions, IPC, subprocesses, retained maps or startup imports. The only new work is a few indexed SQLite point reads on main, triggered per send/reply/deliver RPC or per bot-request settlement.
Added work: trigger → population → bound
Added work
Trigger
Population
Bound
Resolver step legacyAttachedRecipient (recipient-owner-selection.ts, recipient-routing.ts): findActiveRemoteAttachmentForPane(paneKey), plus findLatestRemoteAttachmentForTerminal(handle) on a miss
Each resolveBareOrchestrationRecipient call. It runs only after the bound-run and active-dispatch checks miss, and only for a terminal handle without keepLegacyAttachedRouting
One handle per point send. One per member for group fan-out
≤2 point queries per handle, both on partial or plain indexes (idx_remote_dispatch_attachments_active_pane/_suffix, idx_crew_remote_handle) with ORDER BY rowid DESC LIMIT 1. Statements come from the sync-database statement cache. The pane key is reused from the resolver, so getLiveTerminalPaneKey isn't called again. Each member already pays ≥3 owner queries, so this adds a constant per member and nothing that grows with history
Group fan-out (send-group.ts)
Group send, only when zero recipients are deliverable (the error path)
Resolved members
One flatMap over the existing array, then a throw. O(members) once per failing send
Point send (send-methods.ts)
A refused send
1
Swaps one error constructor for another (sendRecipientRefusal)
Reply store-time rechecks (reply-method.ts): refuseLegacyAttachedRecipient (1 getLiveTerminalPaneKey + ≤2 indexed reads) and refuseNewlyLegacyAttachedSender (one full resolve, about 4–6 indexed reads, in-memory session store)
Each orchestration.reply RPC, inside the reply_with_answer write transaction
1 recipient + 1 sender
Fixed per reply. Lengthens the write transaction by a few point reads. No fs or subprocess calls
--on receiver (peer-mail-agent-store.ts)
Each peer-mail delivery to an agent
1
Net neutral: the old inline getLiveTerminalPaneKey + findActiveRemoteAttachmentForPane is replaced by the same calls plus ≤1 handle-indexed read on a miss
Bot-request notice (bot-request-sender-notice.ts)
tellSender → reachableSender, only when resolveReplyRecipient throws
1 request per settlement (bot-request outcome, question notices, paired-ask removal)
≤2 indexed reads + 1 getLiveTerminalPaneKey, plus one re-resolve when the sender is legacy-attached. The 'unverified'/retry return is unchanged: the new branch either routes the notice or falls through to the old gone/unverified logic, so it adds no retry loop
Zero added work. The flag skips the step before any query
Price at reference fleet
A dozen agents calling the CLI every few seconds gives ~4 RPCs/s. Each RPC adds ≤2 indexed point reads (reply: about 8). That's tens of SQLite point reads per second on Electron main, each in the microsecond range. A worst-case group send to ~300 terminal members adds ≤600 indexed point reads once per send, on top of the ≥900 owner reads it already pays. None of this scales with worktrees, history bytes or idle time. At 10× fleet the per-call cost stays the same, because every lookup is an index probe with LIMIT 1.
Regression classes touched
Sync SQLite on Electron main: matched. Dismissed: per-RPC/per-settlement indexed point reads, statements cached, constant per handle (numbers above).
Hot-path rescans / per-item work in a loop (group fan-out, unpaired-question loop): matched. Dismissed: O(1) indexed reads per member. The unpaired loop skips via the flag.
Expensive code reachable past a gate: none. The new step sits after the existing bound-run/dispatch gates, and the opt-out flag short-circuits before any query.
New idle wakeups, polls, retention, unbounded fan-out, publication, eager imports: no matching code.
Six questions
Unused work before the gate: reviewed. The step is lazy (a thunk in selectBareRecipientOwner) and runs only after local owners miss. Flagged callers skip it.
Ownership multiplication: not applicable. There are no per-row/pane owners, just per-call RPC work.
Thread/storage: reviewed. Electron main, sync node:sqlite, indexed point reads, cached statements. The reply rechecks run inside an existing write transaction (a fixed few reads).
Growth/progress: reviewed. Index probes with LIMIT 1 don't grow with attachment history. The bot-notice retry path is unchanged.
Execution host: not applicable. No subprocess, fs or SSH round trips. getLiveTerminalPaneKey is in-memory runtime state.
Obsolete work/release: not applicable. Nothing is started, retained or left in flight.
Coverage and gaps
Source-only review at the head SHA. I read the full diff plus the callers of resolveBareOrchestrationRecipient and tellSender, the attachment query SQL and indexes, getLiveTerminalPaneKey and the statement cache. I ran no timing or benchmarks, so the impact above is stated as call counts, not milliseconds.
Verdict: clean. I found no regressions. I traced this from source only and took no runtime timings. All added work is a few indexed SQLite point lookups (each returns at most one row) or in-memory map lookups, run on Electron main, once per send, reply or delivery command. It adds no timers, polls, listeners, retained maps or new subprocesses.
Added work: trigger, population, bound
Added work
Trigger
Population
Bound
Resolver step legacyAttachedRecipient in selectBareRecipientOwner (recipient-owner-selection.ts, recipient-routing.ts)
Every bare-recipient resolve that no bound Run or active Dispatch claims first. It is lazy and runs after boundRuns/dispatches. It is skipped when terminalHandle === null or keepLegacyAttachedRouting is set.
One resolve per point send; one per group member plus one for the sender in fan-out
≤2 point queries. findActiveRemoteAttachmentForPane uses the partial indexes idx_remote_dispatch_attachments_active_pane[_suffix]. findLatestRemoteAttachmentForTerminal uses idx_crew_remote_handle (ORDER BY rowid DESC LIMIT 1 with an index seek). The pane key is reused from the resolver, so there is no extra pane lookup.
Group fan-out (send-group.ts)
Each send --to group CLI or RPC call
Members of the group, possibly a few hundred terminals at reference fleet
≤2 indexed lookups per member, on top of the ~4–5 queries per member the resolver already ran. Same order of growth, constant factor. The added refusal join runs only on the error path where zero recipients remain, O(members) once.
Point send (send-methods.ts)
Each send
1
Just changes how the error is built (sendRecipientRefusal). No new queries on the success path.
Reply store-time recheck (reply-method.ts)
Each orchestration.reply, inside the reply_with_answer write transaction
1 recipient + 1 original sender
refuseLegacyAttachedRecipient: skipped for run:/dispatch:; otherwise 1 in-memory getLiveTerminalPaneKey plus ≤2 indexed lookups. refuseNewlyLegacyAttachedSender: the same cheap gate first, and the full re-resolve only when the sender has a live attachment. That adds ≤4 point reads to the write lock per reply.
--on receiver (peer-mail-agent-store.ts)
Each peer-mail deliver item
1 per item
The resolver step plus the store-time recheck, ≤4 indexed lookups, where the old code did 1. Constant per item.
Bot-request notice (bot-request-sender-notice.ts)
tellSender when settling, dropping or unpairing a bot request, error branch only
1 per settled request whose sender resolve threw
1 cached gate check (≤2 lookups) plus at most one more resolve. It adds no retry loop: the existing 'unverified' return still decides whether a later end retries, and that logic is unchanged.
keepLegacyAttachedRouting: true short-circuits the step before any query, so zero added work, including inside the tellUnpairedPeerQuestions row loop.
Skill-guide text (bundled-skill-guides.ts)
CLI skill install/read
—
A few lines of static string. Negligible.
getLiveTerminalPaneKey is made only of map lookups (structured-worker authority, slept pane, handles/leaves/ptysById). It does not scan all terminals.
Regression classes touched
Sync fs/SQLite on Electron main: matched, disproved. These are indexed point reads per command (not per keystroke, PTY chunk or poll), ≤4 per reply or delivery and ≤2 per group member. At 10× fleet that is still one CLI-triggered fan-out over the members, as before.
Hot-path rescans: matched (flatMap over resolved recipients), disproved. It runs once, only on the zero-recipient error path.
Expensive code newly reachable past a gate: matched, disproved. The resolver step is gated after bound-Run/Dispatch ownership and by keepLegacyAttachedRouting, and the reply re-resolve sits behind the cheap attachment check. Neither reaches the existing heavy paths at a new rate.
Unused work before the gate: reviewed. The step is lazy (a thunk) and ordered after the cheaper local-owner checks, and the peer/import callers opt out before querying.
Ownership multiplication: not applicable. No per-row or per-pane owners or subscriptions.
Thread/storage: reviewed. Main-thread node:sqlite point reads on indexed columns, ≤4 extra reads inside the reply write transaction.
Growth / progress: reviewed. Work grows with group size only, as it already did, and nothing grows with history (LIMIT 1 index seeks). The notice path adds no new retry cursor.
Execution host: not applicable. Local DB and in-memory lookups only; no SSH or subprocess work.
Obsolete work: not applicable. Nothing started, retained or cancelled.
Paths examined: point send, group fan-out (members + sender), reply transaction, the --on peer-mail deliver receiver, bot-request tellSender (unanswered/dropped/unpaired callers), peer reply store, unpaired-questions loop, paired-server import, and the attachment lookup SQL and indexes. No runtime measurement, so I make no timing claims.
Perf scan — head cf2286ffe2a81143066e8367538e151baacee4cc (vs 08e46298fd6)
Verdict: clean. No P0 or P1. The diff adds only bounded, indexed SQLite point reads on paths that already run per RPC. It adds no timers, polls, listeners, subprocesses or retained per-entity state.
Added work: trigger → population → bound
Piece of work
Trigger
Population
Bound / cost
legacyAttachedRecipient step in resolveBareOrchestrationRecipient (recipient-routing.ts, recipient-owner-selection.ts)
Each bare-recipient resolution, reached only when no bound Run and no active Dispatch matched. It is skipped entirely with keepLegacyAttachedRouting or when the handle has no terminal.
1 per resolved recipient
≤ 2 indexed point reads: findActiveRemoteAttachmentForPane (partial index idx_remote_dispatch_attachments_active_pane / _suffix, LIMIT 1), then, only if that misses, findLatestRemoteAttachmentForTerminal (idx_crew_remote_handle, LIMIT 1). getLiveTerminalPaneKey was already computed by the resolver and is reused.
Point send refusal mapping (send-methods.ts → sendRecipientRefusal)
Refused orchestration.send
1 per refused send
Array includes over 2 codes. Only the non-legacy branch keeps the existing withDispatchPrefixHint.
Group fan-out (send-group.ts)
send to a group
Group members (at a 100+ agent fleet, about 100)
Resolver step above, once per member that has no Run/Dispatch owner: ≤ 200 indexed point reads for a group of 100, i.e. one per required output and constant per member. The new flatMap over resolutions runs only on the zero-recipient error path, O(members).
Reply store-time recheck (reply-method.ts)
Each local orchestration.reply
1 recipient and 1 original sender
Inside the existing reply_with_answer write transaction: refuseLegacyAttachedRecipient makes ≤ 2 point reads (skipped for run:/dispatch:). refuseNewlyLegacyAttachedSender makes ≤ 2 point reads for a terminal sender. For a session-address sender it does one more full bare resolve (in-memory session store plus the resolver's existing indexed queries). That is constant per user-initiated reply, with no fleet scaling and no repeated trigger.
--on receiver (peer-mail-agent-store.ts)
Each inbound peer-mail delivery to an agent
1 per delivered item
Replaces the existing single pane lookup with the shared check: the same pane read plus, only on a miss, one terminal_handle point read. Paired-server ask import keeps routing via keepLegacyAttachedRouting, so it adds 0 reads.
Peer reply store / unpaired-question tell (peer-reply-store.ts, peer-questions-out.ts)
Peer reply import; unpair
1 per item
keepLegacyAttachedRouting: true short-circuits the new step, so it adds 0 reads.
A bot-request end (unanswered/dropped) whose resolveReplyRecipient threw
1 per settling request
Error branch only: ≤ 2 point reads plus one bare resolve. The branch converts a would-be gone/unverified into a delivered notice, so it never addsunverified retries and creates no new retry loop.
Thread: everything runs synchronously on Electron main through node:sqlite (sync-database.ts), which is the same thread and DB as the existing resolver queries. At the reference fleet (a dozen agents calling the CLI every few seconds), that is a few extra µs-scale indexed lookups per send/reply. The cost stays constant at 10× because each lookup is a LIMIT 1 probe on an index, independent of attachment, message or worktree counts.
Regression classes touched
Sync SQLite on Electron main: matched. Disproved: indexed LIMIT 1 point reads, per RPC/item only, never per poll, keystroke or status update.
Hot-path rescans / per-item queries in a loop (group fan-out): matched. Disproved: one bounded lookup per member, which is the required per-recipient resolution. No collection-wide scan inside the loop.
Unbounded fan-out / retries: matched (bot-request notice "retried later"). Disproved: the new branch only resolves a notice that would otherwise be dropped or deferred. It adds no retry admission.
Expensive code newly reachable past a gate: matched (keepLegacyAttachedRouting gate). Disproved: the gate removes work on the peer paths; the newly reached code is the indexed probes above.
Every other class (store identity, selectors, streaming, polls/idle wakeups, subprocesses, whole-file rewrites, per-entity maps, startup imports): no matching code. The only new module is a small value import already on the messaging RPC graph.
Six questions
Unused work before the gate: reviewed. The legacy probe runs after the Run/Dispatch owner checks and is skipped under keepLegacyAttachedRouting or a null terminal handle. The second (terminal_handle) read runs only when the pane read misses.
Ownership multiplication: reviewed. There are no per-pane/row owners; the work is once per resolution.
Thread / storage: reviewed. Main-thread sync SQLite, indexed point reads. The reply recheck adds ≤ 4 reads plus at most one resolve inside an existing write transaction, so lock hold time grows only by µs-scale work.
Growth / progress: reviewed. There is no history- or fleet-scaled work, and the notice path does not strand or loop.
Execution host: not applicable. This is server-side main-process DB work with no host probes, SSH round trips or platform-specific calls.
Obsolete work / teardown: reviewed. No retained state, timers or listeners. When an attachment leaves the potentially-live states, the probes return nothing, so removal and promotion need no cleanup.
Coverage and evidence
Paths examined: recipient-routing.ts, recipient-owner-selection.ts, legacy-attachment-recipient-refusal.ts, send-methods.ts, send-group.ts, reply-method.ts, bot-request-sender-notice.ts, peer-mail-agent-store.ts, peer-reply-store.ts, peer-questions-out.ts, paired-server-ask-import.ts, remote-dispatch-attachment-stop.ts, remote-attachment-liveness.ts, the schema index definitions, and bundled-skill-guides.ts (copy only).
Evidence type: source-proven query counts and index coverage. Nothing was executed and no timing was measured.
Perf scan — head fd50849ce6e3c31f70a8a0fd9abcd82d4b92266f
Diff 08e46298fd6..fd50849ce6e. Surface: hot-path (orchestration send, group, reply, peer-mail store, and bot-request notice RPCs on Electron main, sync SQLite). Verdict: clean. I found no P0 or P1.
Added work: trigger, population, bound
#
Added work
Trigger
Population
Bound
1
legacyAttachedRecipient step in selectBareRecipientOwner (recipient-routing.ts:280, recipient-owner-selection.ts:38). It runs findActiveRemoteAttachmentForPane(paneKey) when a live pane exists, then falls back to findLatestRemoteAttachmentForTerminal(handle)
Each bare-handle resolution that gets past the bound-run and active-dispatch checks: orchestration.send, group members, reply, --on peer-mail store
1 recipient, or 1 per group member
≤2 point SELECTs LIMIT 1. The pane lookup uses the partial index idx_remote_dispatch_attachments_active_pane (or the _suffix index). The handle lookup uses idx_crew_remote_handle(terminal_handle), and ORDER BY rowid DESC LIMIT 1 walks that index backwards, so cost doesn't grow with attachment history. Resolutions with keepLegacyAttachedRouting or a null terminal handle skip it with no query
1 in-memory getLiveTerminalPaneKey plus ≤2 point SELECTs. It returns at once for run:/dispatch:. In peer-mail-agent-store it replaces the old 1-query check, a net change of +0 to +1 point query
3
refuseNewlyLegacyAttachedSender (reply-method.ts:224), inside the reply_with_answer write transaction
1 per reply RPC
1 original sender
Plain terminal sender: ≤2 point SELECTs. Session-address sender, or a sender that is now attached: 1 extra full resolveBareOrchestrationRecipient. That is the same work the reply already does once in resolveReplyRecipient (record-store getRecord and the alias index, plus indexed owner queries), so it doubles a constant per-RPC cost and doesn't add per-fleet work. It holds the write lock for a few more point reads
Only on the catch branch, when a bare sender's resolution returns a legacy-attachment refusal. Fires once per request outcome (end, drop, unpair)
1 sender
1 extra resolve with keepLegacyAttachedRouting, so its legacy step runs no query. It doesn't retry and adds no timer
5
Group-refusal message (send-group.ts:268)
Only when uniqueRecipients.length === 0, which is already the error path
Already-resolved members (no new I/O)
One flatMap over the resolutions already in memory
6
keepLegacyAttachedRouting: true on peer-reply-store, peer-questions-out, paired-server-ask-import
Existing triggers
—
Skips step 1, so 0 added queries. This matters for the tellUnpairedPeerQuestions loop over unpaired questions, which stays at its base cost
Fleet pricing (a dozen agents each calling the CLI every few seconds, 100+ agents, groups of about 100 members): send adds ≤2 indexed point reads per call, which is a few per second fleet-wide. A 100-member group send adds ≤200 indexed point reads once per send RPC, linear in the group members the send already resolves. There is no work per status update, per keystroke or per PTY chunk, and none that grows with history.
Regression classes touched
Sync fs or SQLite on Electron main: matched and disproved. The new queries are indexed LIMIT 1 point reads, fired once per user or agent RPC (once per member for a group), with no poll or loop caller. The one loop caller (peer-questions-out) opts out.
Hot-path rescans: matched and disproved. The group flatMap runs once and only on the error path. LEGACY_ATTACHMENT_REFUSAL_CODES.includes checks a 2-element constant.
Expensive code newly reachable past a gate: reviewed. The legacy step sits after the bound-run and dispatch owners and before ownerRunIds. It adds only the point reads above, and no existing expensive path is newly reached.
Fixed-cadence poll, new steady-idle wakeups: no matching code. No timers, intervals or subscriptions were added, so idle wakeups/s on main, renderer and daemon are unchanged from base (0 added).
Per-entity state outlives the entity: no matching code. No new Map, Set or listener.
Six questions
Unused work before the gate: reviewed. The legacy step is skipped (no query) for keepLegacyAttachedRouting and for null terminal handles. The reply sender check tries the cheap point reads before any full resolve.
Ownership multiplying work: not applicable. There is no per-mounted-owner work. All of it runs per RPC.
Thread and storage layer: reviewed. Sync node:sqlite point reads on main, indexed as listed above. The reply check adds ≤2 reads, or one more constant-cost resolve, inside an existing write transaction.
Growth and progress: reviewed. Lookups are LIMIT 1 on indexes, so they stay flat as attachment history grows. The bot notice either settles with main's routing or follows the existing unverified retry. It adds no new retry loop.
Execution host: not applicable. The checks are local SQLite plus an in-memory pane map, with no subprocesses or SSH round trips. They run the same on mac, linux and windows.
Obsolete work and teardown: not applicable. Nothing is retained or scheduled, and the refusals throw before any write.
Coverage and evidence
Evidence: source-proven query counts and indexes at the target ref, with callers traced to the RPC entry points. I didn't measure any runtime timing.
Residual gap: I didn't run EXPLAIN QUERY PLAN. That idx_crew_remote_handle exists relies on schema-column-probes.ts running on every open where the terminal_handle column exists.
Messaging now detects terminal recipients attached to another Orca’s Task and refuses delivery in the affected routing paths. Refusal errors state when nothing was sent. Federated mail paths can retain legacy attached routing where configured, and peer-mail storage rechecks recipients before delivery. The orchestration guides now specify Dispatch-ID addressing for remote workers and direct users to the Task’s coordinator when delivery is refused.
Merge Risk: Low · up to 8ba93
This change refuses mail to a terminal working another Orca's Task before it is stored. It tells the sender to contact that Task's coordinator. The remaining concerns are wording in the orchestration guides: one fallback instruction could lead an agent to start a duplicate remote worker. They do not affect runtime behavior, so the risk is low and a documentation follow-up is enough.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: on an upgraded server, mail to a terminal working another Orca's Task is refused before storage. The changeset adds the refusal in the resolver and send/reply/group pa…
Description check
The description follows the template: it has ELI5, What Changed (before/after and mechanism), Why, Testing with checkboxes, Performance, Risk with level, and a Checklist. It also gives a linked-issue …
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title names the main change: on an upgraded server, mail to a terminal working another Orca's Task is refused before storage. The changeset adds the refusal in the resolver and send/reply/group paths, and the title's prefix matches the fix. The title is specific and single-sentence, so it passes.
Full details: Description check
Explanation
The description follows the template: it has ELI5, What Changed (before/after and mechanism), Why, Testing with checkboxes, Performance, Risk with level, and a Checklist. It also gives a linked-issue note (N/A, internal maintainer work), a Visual Proof N/A with reason, and an upstream-boundary checkbox. Several template items are weak: the Linked Issue section has no 'Fixes #' issue and the N/A rationale is thin for a non-maintainer template, the AI Disclosure section is empty, and the 'Review' heading is blank. The pnpm lint/typecheck/test/build checkbox is unchecked and the Testing section does not say it was run locally. The description is mostly complete, so it passes, but the author should fill in the AI Disclosure and clarify the Linked Issue and test-run status.
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Files skipped from review as they are similar to previous changes: 1
src/cli/skills/bundled-skill-guides.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Problem: on a server, mail addressed to a terminal that is working a Task for another Orca (a legacy remote attachment, placed by a desktop older than v1.4.258) was stored where that worker never reads it, and the sender was told it was queued.
Change: an upgraded server now refuses that mail before storing anything:
capability_unsupported while the attachment is ready.
dispatch_inactive while it is starting or finishing.
Both refusals set effectsApplied: false and tell the sender to message that Task's coordinator. This covers point send, group send (refused members become warnings and the others are delivered), reply (rechecked at store time) and --on peer mail. Mail coming home to this Orca's own sender keeps main's routing. This is not mail parity for legacy workers; it removes the false delivery.
Fixed during review:
Peer-mail replies, unpair notices, client-ask replies and bot-request notices for such a sender keep main's routing. An earlier attempt deferred bot notices, which could strand them. That was replaced by main's routing.
The reply recheck covers both the stored destination and the original sender. A cheap attachment check runs first, so ordinary replies don't repeat the bound-Run lookup.
A session-address sender is resolved in full in both the reply and the bot-notice paths.
The dispatch_inactive refusal names a next step.
The skill-guide lines about dispatch_inactive are scoped to the home Orca's send --to dispatch:<id>.
Deferred:
Crew's recipient availability still lists such a terminal as reachable. A send to it is refused clearly. Aligning Crew needs a batched lookup in its projection.
A bot-request send to such a terminal is refused without effectsApplied: false.
An all-refused group error names only the members refused for this reason.
The workerStart --on regression-guard test passes on main by design. Main already refuses that call in the shared access check, and the test guards against losing that refusal. One reviewer flagged it against the repo's test rules. It was kept on purpose.
Verified:
Fail-before: the new tests were run off this machine against the merge-base's production code. Every case except the workerStart guard fails there. Each reply recheck alone fails one of the reply-race cases.
Paired QA on fd50849: real agents, the released v1.4.257 desktop as coordinator, a server built from this PR, and a third Orca as the --on sender.
Refused with the exact text, nothing stored: server-local point send, group send, --on mail and replies to the legacy worker. Row counts were checked before and after.
worker_done settled once. After settle, mail to the same terminal handle was stored and read.
A local worker smoke test passed. Server-owned placement passed on the first QA run, and that code hasn't changed since.
Not exercised: the dispatch_inactive wording, because no flow reached a starting or finishing attachment.
Reviews: the blinded regression audit is SAFE. The final Codex and Claude reviews found no blocking issues. The perf scan is clean: each resolution adds at most two indexed single-row reads, with no new timers, polls or listeners.
Checks:pnpm check:changed passed off this machine, and CI is green.
No screenshots: every changed flow is CLI or server-side, and the command outputs and row counts were the evidence.
Verdict: clean (no findings). Range 08e46298fd6..154e826990c. The scan was static and limited to the changed triggers and their callers. No runtime timing was taken, so every cost below is a source-proven count.
Added work: trigger → population → bound
Added work
Trigger
Population
Bound
legacyAttachedRecipient step in selectBareRecipientOwner (recipient-owner-selection.ts, recipient-routing.ts)
each resolveBareOrchestrationRecipient call (point send, group fan-out per member, reply, bot-request admit, peer-mail delivery)
one bare recipient
Lazy thunk that runs only when no bound Run or active Dispatch owns the handle. It costs ≤2 indexed LIMIT 1 point reads: findActiveRemoteAttachmentForPane (partial index idx_remote_dispatch_attachments_active_pane[_suffix]) and findLatestRemoteAttachmentForTerminal (idx_crew_remote_handle on terminal_handle; ORDER BY rowid DESC LIMIT 1 is served by the index order). It does nothing when terminalHandle === null or keepLegacyAttachedRouting is set.
Group fan-out (send-group.ts)
one orchestration.send to a group
members already resolved by the existing per-member loop
+≤2 point reads per member, inside the existing per-member resolution. The new flatMap over resolvedRecipients runs only on the error path where zero recipients resolved, and is O(members) once.
Reply store-time recheck (reply-method.ts)
one orchestration.reply (inside its existing write transaction)
1 recipient + 1 original sender
refuseLegacyAttachedRecipient costs ≤2 point reads plus 1 getLiveTerminalPaneKey. refuseNewlyLegacyAttachedSender uses the same cheap gate first, and runs a full resolver again only for a session-address sender or a confirmed attachment. Constant per reply. When the recipient and the sender are the same bare handle, the lookup runs twice. That is a small constant redundancy, not fleet-scaled.
Peer-mail delivery (peer-mail-agent-store.ts)
one inbound peer-mail deliver RPC
1 recipient
The base did 1 live-pane lookup plus 1 pane read. Now: the resolver step (≤2 reads) plus a recheck (≤2 reads). A paired-server ask import (keepLegacyAttachedRouting) keeps the base's pane-only check: 1 read.
tellSender on a notice whose sender's reply resolution threw a legacy-attachment code
1 sender per notice
At most one more resolver pass, on the error path only. It returns main's routing, so it adds no new retry debt. Non-legacy failures still return gone/unverified exactly as on base.
peer-reply-store.ts, peer-questions-out.ts (loop over unpaired peer questions)
peer reply arrival; unpair
rows per unpair
keepLegacyAttachedRouting: true short-circuits the new step before any query: 0 added work, including inside the per-row loop.
send-methods.tssendRecipientRefusal
refused point send
1
Builds the error only. withDispatchPrefixHint is skipped for the legacy codes (slightly less work).
Six questions
Unused work before the skip gate: not applicable. Nothing is published or rendered. The new step is a lazy thunk that runs after the bound-run and dispatch owners and before ownerRunIds, and is skipped by the keepLegacyAttachedRouting / null-terminal gates before any read.
Ownership multiplication: none. There are no new listeners, maps, subscriptions or per-owner resources.
Thread/storage: the added reads are sync node:sqlite on Electron main, per RPC, reached only from send/reply/deliver/notice handlers. Each is an indexed point read. With a dozen agents calling the CLI every few seconds, that is a handful of extra point reads per second (µs scale). No writes are added. The reply checks run inside an existing write transaction and add no extra transaction.
Growth/progress: each lookup is LIMIT 1 on an index, so it is O(log attachments) and does not grow with history. Group work is linear in members, the same as the existing resolution. There are no retries or cursors, and the notice path returns a resolved target instead of adding retry debt.
Execution host: no new host probes or subprocesses. getLiveTerminalPaneKey is the existing in-memory runtime lookup (it already falls back to the SSH-compat terminal record without a round trip), called ≤2 extra times per reply.
Obsolete work/teardown: none created. There is no state to release on attachment stop or promotion. The liveness check reuses isPotentiallyLiveRemoteAttachment / the same state set as the SQL filter, so a stopped or finished attachment stops refusing at once.
Regression classes touched
Sync fs/SQLite on Electron main: matched and disproved. The diff adds ≤2–4 indexed point reads per send/reply/deliver RPC and ≤2 per group member, with no per-keystroke, per-chunk, poll or idle trigger, and all reads are covered by the indexes above.
Hot-path rescans: matched (LEGACY_ATTACHMENT_REFUSAL_CODES.includes over 2 constants, group flatMap on the error path) and disproved: constant work, or O(members) once.
New idle wakeups / fixed-cadence polls / newly reachable gated work: no matching code. The diff adds no timers or intervals, removes no gates, and adds only error-path callers.
Residual: no runtime measurement was taken, so the impact is stated as the counts above. Docs/skill-guide changes (skill-guides/, src/cli/skills/bundled-skill-guides.ts) are text only.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Paired QA evidence (CLI, PR server with a v1.4.257 desktop as coordinator)
Every changed flow is CLI or server-side, so the evidence is the exact command output on the PR-build server. The worker term_05c1… was placed by the old desktop through a legacy attachment. Paths are shortened to <worktree>.
$ orca orchestration send --to term_05c1848d-… --subject 'flow2 point' --body 'point mail to legacy worker'
error: capability_unsupported: term_05c1848d-… is working a Task for another Orca; mail can't reach it there. Message that Task's coordinator. Nothing was sent.
$ orca orchestration send --to '@worktree:<worktree>' --subject 'flow3 only worker' ...
error: capability_unsupported: term_05c1848d-… is working a Task for another Orca; mail can't reach it there. Message that Task's coordinator. Nothing was sent.
$ orca orchestration send --to '@worktree:<worktree>' --subject 'flow3 mixed' ... # worker + an ordinary shell
messageIds=msg_bb0ac25e92cf recipients=1 warnings="term_05c1848d-… is working a Task for another Orca; mail can't reach it there. Message that Task's coordinator.","term_cc17fa4d-… is a live terminal-only mailbox. ..."
$ orca orchestration send --on qa-server --to term_05c1848d-… --subject 'flow4 on' ... # from a third Orca
error: capability_unsupported: term_05c1848d-… is working a Task for another Orca; mail can't reach it there. Message that Task's coordinator. Nothing was delivered.
$ orca orchestration reply --id msg_qa5rerun002 --body 'Answer from SA'
error: capability_unsupported: term_05c1848d-… is working a Task for another Orca; mail can't reach it there. Message that Task's coordinator. No reply was sent.
# after the worker's worker_done settled the Task once on the old desktop:
$ orca orchestration send --to term_05c1848d-… --subject 'flow6 post-settle' --body 'after settle'
messageId=msg_3fefb06f4706 warnings="term_05c1848d-… is a live terminal-only mailbox. ..."
Row counts were checked before and after each refused call, and none changed. The QA ran on fd50849. The one later commit changes only a reply coming home from a paired server's client ask, which none of these flows use, and the guide text.
QA evidence: paired QA with real agents, a v1.4.257 desktop as coordinator and a PR-build server. Point send, group send, --on mail and replies to the legacy worker were refused with nothing stored. worker_done settled once, and mail to the same terminal was stored after settle. The exact CLI outputs are in #51336 (comment). This change has no screen: every flow is CLI or server-side.
[Medium impact] The PR appears safe to merge; no actionable issue was found.
Summary
Refuses mail to terminals working another Orca’s Task before storing it.
The server refuses mail to a terminal held by another Orca’s live Task.
Group sends keep reachable deliveries and report terminals that cannot receive mail.
Replies stop if the destination or original sender becomes attached to another Orca’s Task.
Acknowledged by brennanb2025: Crew’s availability list remains unchanged, and bot-request refusals can omit effectsApplied: false; both are explicitly deferred. Potentially live attachment rows intentionally keep refusing mail until they settle.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Bare recipient] --> B{Bound local Run?}
B -->|Yes| C[Route to Run]
B -->|No| D{Local Dispatch?}
D -->|Yes| E[Route to Dispatch]
D -->|No| F{Live legacy attachment?}
F -->|Yes| G[Refuse without storing]
F -->|No| H[Historical Run or terminal fallback]
4932-4933: Minor · Functional Correctness · Quick win
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Document local Dispatch precedence.
A terminal with a starting remote attachment can also have a local Dispatch. The supplied test shows that a send to that terminal then succeeds and targets the local Dispatch. The unconditional refusal statement can mislead a sender about where the mail went. State that a local Dispatch takes precedence.
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 191c1990-03d6-4802-9758-5498263c9f53
Commits
Reviewing files that changed from the base of the PR and between 154e826 and 8ba9386.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
ELI5
Sometimes a terminal on a server is busy doing a job for another computer. While it does that job, it only reads mail from that other computer. Until now, if someone on the server sent it a message, the server said "sent" and stored the message where the terminal would not look until the job was over. Now the server says no right away, explains why, and stores nothing, so the sender knows to ask the job's owner instead.
What Changed
Before: on a server, mail to a terminal that is working a Task for another Orca (a legacy remote attachment, which a desktop older than v1.4.258 still places) was stored in that terminal's own mailbox. The sender got a receipt warning that the mail "can't be read in that terminal", and the worker didn't see it until its Task settled.
After: an upgraded server refuses that mail before writing anything, with
effectsApplied: false:capability_unsupportedwhile the attachment isready: "term_X is working a Task for another Orca; mail can't reach it there. Message that Task's coordinator. Nothing was sent."dispatch_inactivewhile it is starting, stopping, or its outcome is unknown, with the same next step.This removes the false delivery. It is not mail parity for legacy workers: a legacy worker still can't receive server-local or
--onmail, and the sender is told so at send time. Two upgraded Orcas place workers through server-owned placement, which this change doesn't touch.Mechanism: one resolver step in
resolveBareOrchestrationRecipient(newlegacy-attachment-recipient-refusal.ts). It runs after bound Runs and local Dispatches, and before historical Run owners and the bare-terminal fallback. It finds the attachment by the terminal's live pane, or by an exact lookup of the terminal handle the attachment recorded. As a result, local Run and Dispatch precedence stays as it was, including explicit--runagainst them, and the terminal-agentorca_session_id:refusal still runs first. A handle whose only owner is a historical Run is now refused while the attachment is live, before--runis matched against that Run.Covered:
--onreceiver: keeps its refusal, now through the shared resolver step and wording; its store-time pane check stays, for replies to a client ask, which keep main's routing. Its code changes frominvalid_argumentto the two codes above.workerStartfrom a paired caller withon: main already refuses this in the shared access check (peer-run-access.ts:173-193), so this PR only adds a regression test for it.Unchanged:
Release note: Today an old server stores mail for an attached worker in its terminal, and the terminal reads it once the Task settles. An upgraded server refuses that mail at send time instead.
Why
A sender who is told "sent" retries nothing and waits for an answer that can't arrive until the Task ends. Refusing before write, on the server only, closes that for every upgraded server. It needs no protocol, schema or capability change and nothing on the desktop. Legacy attachments come only from older desktops, or from older servers that run their own code. Delivering mail to them would take a new two-sided protocol that no currently supported pairing would negotiate.
Limits:
Linked Issue
N/A (internal maintainer work).
Visual Proof
N/A: there is no UI change. The change is in the CLI and RPC refusal text, which the tests below assert exactly.
Testing
legacy-attachment-recipient-refusal.test.tsuses a realOrchestrationDband the registered orchestration RPC handlers, including the access check, with no mailbox mocks.Fail-before was run off this Mac against the merge-base's production code. Every case except the last fails, because main stores the mail.
dispatch_inactive. A local Dispatch on the same pane still takes precedence.workerStart --on: still refused. This is a regression guard only; main already refuses it.--onpeer mail is covered through the real RPC entry point bypeer-mail.test.ts"refuses mail to a worker another Orca coordinates", which now expectscapability_unsupportedand fails on main.Performance
None measurable, because each bare-terminal resolution adds at most two indexed single-row lookups (attachment by pane, then by terminal handle), and only when no bound Run or local Dispatch matched first. A group send does this per member, which it already does for routing.
Risk
Level: Low
The riskiest part: a terminal whose attachment row is stuck in a potentially-live state (for example
stop_unknown) now refuses direct mail until that row settles. Before, such mail was stored where the worker didn't read it. The refusal tells the sender to message that Task's coordinator.The receiving server's version decides the behavior. An upgraded receiver refuses
--onmail with the new codes whatever the sender's version. An old receiver keeps its old behavior.Deferred:
effectsApplied: falseon the error.Backing out is a plain revert. The change writes no data.
AI Disclosure
Review
Agent skill upstream boundary
Notes
Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)