Skip to content

feat(orchestration): deliver worker results to a structured chat coordinator - #22631

Merged
brennanb2025 merged 48 commits into
mainfrom
brennanb2025/d4-coordinator-delivery
Sep 29, 2026
Merged

brennanb2025 merged 48 commits into
mainfrom
brennanb2025/d4-coordinator-delivery

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2115 $\color{#cf222e}{\Huge{\mathbf{−}}}$​32 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2083
Prod 28 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​948 $\color{#cf222e}{\Huge{\mathbf{−}}}$​107 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​841

What this changes for you

Who hits it: anyone who runs Orca orchestration from a native (structured) Claude or Codex chat, with the chat acting as the coordinator that starts workers and waits for their results.

Before: a chat coordinator could create a Run and start workers, but when a worker finished and sent its worker_done, nothing told the chat. The result sat unread in the chat's mailbox until you noticed and told the chat to run orca orchestration check. A terminal coordinator in the same situation is told automatically.

Situation Before After
A worker finishes while the coordinator chat is idle Nothing happens; the result sits unread Within a second the chat gets the same short message a terminal coordinator gets ("You have 1 orchestration message. Run orca orchestration check …") as a real turn, runs check by itself and reports the result
The coordinator chat's agent is not running (Orca stopped it while idle) Nothing happens That message starts the agent, the same way your own message would
The coordinator chat's agent cannot start (it crashes on start, or you are not signed in) Nothing happens Orca tries once. It does not restart the agent over and over while the mail is unread. The mail is offered again when the next worker result arrives, when your next message in that chat runs, or after Orca restarts
You press Stop while that message is starting the agent n/a It stays stopped until new mail arrives or your next message runs
Someone sends mail to a live chat by its address session:<id> Stored, never announced to the chat Announced the same way
The coordinator chat is cleared with /clear Its Runs and mail stay with the old address The chat keeps its orchestration address, so its Runs and mail follow it

Not affected: terminal agents (their delivery code is unchanged), SSH and WSL sessions (a chat's mail lane is local only; mail to a session on another host is refused), mobile, and stored data (no schema change).

Known gap, not fixed here: if the one start attempt fails, the chat does not show the announcement or the failure notice; only the tab's red "Failed" dot shows it. That is an existing display rule on main (a refused message is hidden unless this window sent it, and the failure line folds into the previous finished turn). It already applies to structured workers today; this PR makes it visible on a chat you watch. It needs a renderer change and is a separate follow-up.

The plan this PR belongs to

Six steps let a native chat take part in Orca orchestration the same way a terminal agent does:

  1. refactor(orchestration): give structured sessions an orchestration actor column #22522 (merged): give structured sessions an orchestration identity column.
  2. refactor(orchestration): resolve every caller and target to one orchestration party, keyed by the Orca session id #22555 (merged): resolve every caller and target to one orchestration party, keyed by the Orca session id.
  3. feat(orchestration): let a structured chat run orchestration as itself #22568 (merged): a structured chat can run orchestration commands as itself.
  4. This PR is step 4: a chat coordinator hears back from its workers.
  5. feat(orchestration): tell each agent its own orchestration address #22636 (stacked on this branch): tell each agent its own orchestration address.
  6. feat(orchestration): a native chat can be a dispatch worker, like a terminal agent #22972 (stacked on feat(orchestration): tell each agent its own orchestration address #22636): a native chat can be a dispatch worker, like a terminal agent.

What Changed

  1. A Run whose coordinator is a chat delivers to that chat. A Run created by a chat has no terminal handle; its coordinator is the chat's Orca session id. The structured-session mail target now resolves such a Run to the chat, so exactly one delivery lane claims each mailbox.
  2. The message is the terminal lane's text, byte for byte. Both lanes call formatMessagePointer with the same local CLI name (localOrchestrationCliCommand: orca, or orca-dev in a dev build).
  3. Delivery is a normal chat send, retried under one operation id. Each mailbox's pending announcement has one stored operation id (the structured_pointer_operations row main already had). Sending again under the same id makes the host replay the recorded result without touching the agent, so a retry of a failed attempt cannot start the agent again. A new id is minted only when:
    • the batch of unread mail changed (new mail arrived);
    • a turn has run in that chat since the id was minted (the agent has proven it can run);
    • an earlier Orca process minted it (once per restart);
    • the host never recorded it and would now refuse it as too old (24 hours).
      Mail is marked announced only when the host accepts the send.
  4. What triggers an attempt: new mail, and every structured session's idle edge (the moment a chat's status settles). The idle edge opens the orchestration database lazily, only if its file already exists. These triggers can fire freely because of item 3.
  5. Unacknowledged mail follows the terminal rule. While the chat holds a batch it read with check but has not acknowledged, it is not announced newer mail, exactly like a terminal coordinator.
  6. session:<id> is a valid mail address for a chat. Live or stopped chats accept it; a closed chat, an unknown id, a provider's own id, or a session on another host is refused with the existing refusal codes.
  7. A chat keeps its address across /clear. /clear creates a replacement session. The id hook canonicalOrcaSessionId (which main left as a no-op with a comment that lineage plugs in there) now walks the recorded replacement chain back to its first session, so the cleared chat, its Runs and its mail keep one address. A cleared structured worker keeps acting as its worker. The CLI forwards a restated session: address to the host, which accepts the chat's own lineage and refuses anyone else before any effect (consumer_fenced).
  8. A failed mail redrive is logged and no longer skips a chat's first-turn workspace rename.

Why

  • Why announce instead of pasting the result: the mailbox owns read and acknowledgement state, and terminal coordinators already work this way; the chat reads its mail with the same check a terminal agent uses.
  • Why one operation id per attempt instead of a "don't retry" rule: an earlier version of this PR retried on every status change and added a rule that held mail when the last send failed for certain reasons. It missed cases: a Codex agent that died while starting its turn recorded a different reason and was restarted about three times a second. The same rule also held every later result after one transient crash, including for structured workers with nobody to type, and it did not keep a user's Stop. Reusing the id removes that whole class of bug: a failed attempt can only be retried by replay, which starts nothing, and a new attempt needs a new fact. It also let us delete the claim-restore scan the earlier version needed after a restart.
  • Why follow the terminal rule for unacknowledged mail: chats and terminals should behave the same. Announcing past an unacknowledged batch would make check replay the old batch anyway. If agents skipping the acknowledgement turns out to be a real problem, it should be fixed once, for both lanes.
  • Why a lineage walk for /clear: /clear already records a replacement session on main. Deriving the address from that chain at read time stores nothing new and rewrites nothing.

Linked Issue

Part of the orchestration-for-native-chats plan above; no separate issue.

Visual Proof

Claude: live in a dev build on a separate Mac with a real Claude agent, hidden window driven over the DevTools protocol. Before is main at c49388cd339, after is this PR at 0105f570641, same prompt in both. Every worker was a native chat.

Before: the coordinator's reply tells you to run check yourself, and 5.5 minutes after the worker finished the chat is unchanged; the result is still unread.

Before: the coordinator tells the user to run check later

Before: 5.5 minutes after worker_done the chat is unchanged

After: about 0.05 s after the worker's worker_done, the announcement arrives as a turn; Claude runs check, reports the line counts, releases the worker and acknowledges the mail.

After: the announcement arrives as a turn and the result table follows

After: the turn ran check, released the worker and acknowledged

Agent that cannot start: the coordinator's agent was stopped and set to fail every start ("not signed in"). When the worker finished, Orca tried exactly once; the start log stayed at one attempt at +1, +2 and +3 minutes. The chat shows only the red "Failed" dot (the known gap above).

After: one attempt only; the chat shows the red Failed dot

After the agent could start again, "Carry on." ran and the held result was read and reported.

After: the held result is read after the next message

Stop: Stop pressed while the announcement was starting the agent; two minutes later nothing was re-sent.

After: two minutes after Stop, nothing re-sent

Codex: the same check with a real Codex coordinator (hidden dev build with that Mac's own Codex login, before main at c49388cd339, after this PR at 0105f570641, each with the unrelated open #23552 merged locally only for the test rig). On main nothing arrived in 6 minutes 20 seconds. With this PR, exactly one announcement was sent in the same second as the worker's worker_done, and Codex ran check by itself; no duplicate after a full app restart.

Codex, before: 6 minutes after worker_done the coordinator chat is unchanged

Codex, after: the announcement arrives as a turn and Codex runs check

Codex, after: the turn finished and reports the worker_done it read

Testing

  • I manually tested these changes locally (live QA above, real Claude and real Codex; macOS only)
  • Automated tests added/updated

New or changed tests (11 files), all passing at 0105f570641:

  • structured-chat-coordinator-mail.test.ts (real session host, real journal and orchestration database, fake Codex app server): the coordinator gets exactly one announcement with the terminal text; an agent that dies on every start, at initialize, before acknowledging, with its turn start in flight, or after acknowledging, is started at most once across many status edges; a new worker result after a transient crash is announced once; Stop is kept; a restart re-offers once; a rewind that dropped the send, and a send the host never recorded that is past 24 hours, are both recovered after the next turn; not-signed-in and account-switch refusals add no extra rows over five edges.
  • structured-pointer-operation-id.test.ts and structured-mailbox-pointer-delivery.test.ts: the mint / reuse / stamp / park decision table, including a backward clock step.
  • structured-session-mail-target.test.ts, orchestration-session-recipient.test.ts, orchestration-session-caller.test.ts, orchestration-session-caller-cli.test.ts: mail targets, session:<id> recipients and refusals, /clear lineage, and the CLI's caller forwarding including gate-list --run / task-list --run.

Each regression test added in review was run against the code before its fix and failed there (for example, the in-flight crash started the agent 3 to 4 times, and a backward clock step re-minted on every edge).

Checks: tc:node passes at 0105f570641, tc:cli at ed12df519e9 (no CLI change after it); oxlint clean on changed files; no lockfile, schema or renderer changes.

Not verified: Windows, Linux, SSH and mobile live runs; a live /clear of a coordinator mid-run (covered by tests only).

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance.

  • Security: a chat can only act as its own address or its own /clear lineage; any other address is refused on the host before any effect.
  • Mixed versions: no new wire fields; new refusal codes on send carry readable messages.
  • Performance: nothing polls. Work per idle edge is indexed queries plus one journal read when there is unread mail not yet announced. The /clear lineage lookup scans session records in memory on each call; cheap today, worth watching as records accumulate.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Checklist

  • This PR is small and focused (about 900 production lines; a split of the /clear address work into its own PR is proposed in the review status comment)
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • 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)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — three test-strength suggestions inline.

Reviewed changes

Read all 20 changed files across the 7 commits at 3d12695 against base brennanb2025/d3-cli-injection (51f9685).

  • Handle-less coordinator delivery — handleLessCoordinatorSessionId resolves a Run's coordinator from coordinator_actor only when coordinator_handle is null, so a chat coordinator's run: mailbox now reaches the session instead of falling between the two lanes.
  • session:<id> recipients — readSessionRecipient / refuseUndeliverableSessionRecipient make any reachable session addressable, reusing the existing session_caller_* codes and storing at session:<id> before pointing it as a turn.
  • Wake on eviction — the pointer lane takes a transient host.hold around each attempt and releases it in finally, resuming a chat the release clock evicted and handing it back afterwards.
  • Idle-edge redrive — onStructuredSessionStatusForMail retries parked mail and re-derives the Runs plus direct mailbox a session owns on every non-working status edge, host-wide rather than per-dispatch.
  • Terminal-view ownership — a terminal view speaks for its session: the mailbox owner takes the session's Run/Dispatch, and the delivery target resolves the PTY the write gate binds to that session.
  • Shared session rules — structured-session-mail-address.ts centralizes reach, delivery view and sessionOrchestrationIdentity, consumed by both the caller resolver and mail delivery.
  • Worker preamble settlement — sendStructuredWorkerPreamble waits out a pending first answer via waitForSendSettlement instead of discarding a worker whose turn had begun.

I traced the wake/hold pair against the real StructuredAgentSessionHolds and release clock (resume works, the holder is always removed, release lands after send, and an active turn re-arms the clock rather than evicting), and audited the visibleSessionIds writers (a released lease does not remove the id, so a backgrounded or non-active-workspace chat stays reachable). The remaining notes are about test strength, not production behavior.

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

{ dispatchState: 'accepted', reason: null }
)
)
).resolves.toBeUndefined()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This asserts the resolved outcome but never that waitForSendSettlement was awaited, so a pending → return short-circuit (claiming delivered before the provider echo) would also resolve undefined and pass. A toHaveBeenCalledWith(sessionId, 'c1') assertion on the host's settlement method is what the test name promises.

await host.flushStreamedEvents(COORDINATOR)

await finishWorker(taskId)
await new Promise((resolve) => setTimeout(resolve, 20))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The fixed 20 ms sleep is the only thing separating "retained mid-turn" from "folded into the running turn" — if the pointer send lands just after this check, the test still ends green with two turns, and the assertion at line 417 cannot tell the difference. Synchronize on a delivery marker (or assert the pointer is still parked) instead of wall-clock.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The new pointer constant is a POSIX-only shell expansion applied to every structured session, including Windows where it is shell-invalid. It is anchorable, so the detail lives inline.

Reviewed changes

Re-reviewed the delta since the prior pullfrog review (3d12695). The branch was rebased onto #22568 (c0767e101a), rewriting SHAs, so the net change is one commit, a7f58f3, plus #22568 dropping out of the PR diff.

  • CLI named by its env var in the pointer turn — added STRUCTURED_SESSION_CLI_COMMAND = '"$ORCA_CLI_COMMAND"' and pass it from the structured pointer lane, so a login shell that rebuilds PATH (Codex's zsh -lc) cannot reroute a bare orca to a global install.
  • formatMessagePointer widened — its cliCommand parameter now accepts OrchestrationCliCommand | typeof STRUCTURED_SESSION_CLI_COMMAND; the PTY lane's resolved command and the default are unchanged.
  • Integration test updated — the real-host test's POINTER regex and the peer-chat assertion now expect the env-var form.

The three open threads from the prior review (the eviction-retention test's missing wake assertion, the preamble test's missing waitForSendSettlement assertion, and the fixed 20 ms mid-turn discriminator) are unchanged by this commit and left open.

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

@brennanb2025
brennanb2025 force-pushed the brennanb2025/d4-coordinator-delivery branch from a7f58f3 to 1c08143 Compare September 24, 2026 09:17

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The pointer now renders the Windows form for Codex, but the win32 + Claude arm still assumes Git Bash unconditionally — an assumption Orca's own Claude hook code does not make.

Reviewed changes

Re-reviewed the delta since the prior pullfrog review (a7f58f3): three commits (a520e9b8f2..1c08143) across 12 files, after the branch was rebased onto #22568.

  • Per-shell pointer invocation — the fixed STRUCTURED_SESSION_CLI_COMMAND constant became structuredSessionCliInvocation({ platform, provider }); the structured pointer lane reads the provider off the session record and now renders & $env:ORCA_CLI_COMMAND for Windows Codex alongside the POSIX form.
  • Session recipients addressed where their check reads — a session:<id> or bare-id recipient for a structured worker now resolves to the worker's own handle/Dispatch mailbox (sessionOrchestrationIdentity().address) instead of the session:<id> mailbox its check never reads.
  • Released-lease caller wording — a released lease now refuses as "is not running right now … retry then" rather than "has ended", matching the fact that mail can revive it.
  • Idle-edge redrive wiring pinned — a new test pins the runtime's own onSessionStatusChanged → onStructuredSessionStatusForMail line, which the integration test's own callback had previously masked.

I traced the worker-address change through resolveBareOrchestrationRecipient (it reaches the Dispatch branch via the worker's paneKey, and the flagless check reads both the handle and Dispatch mailboxes), and confirmed the 42 tests in the four touched suites pass.

ℹ️ Nitpicks

  • SessionRecipient.actor (session-recipient.ts:28) is written but never read — recipient-routing.ts and refuseUndeliverableSessionRecipient consume only sessionId.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one design question in the body and one stale comment inline.

Reviewed changes

Re-reviewed the delta since the prior pullfrog review (1c08143): six commits across 18 files. This run covers the /clear adoption path, the pointer-eligibility rework, and the wake diagnostic.

  • /clear adoption — adoptClearedPredecessorMail rebinds a cleared predecessor's Runs to the successor through the ordinary bindRun (generation bump, fenced deliveries, coordinator-mail reroute) and re-addresses its unread direct mail with delivered_at = NULL; runStructuredConversationCommand reports the replacement at the commit, and the runtime redrives the successor's mail at that edge and on every idle edge.
  • Pointer eligibility reworked — the "an unacknowledged batch exists" latch is gone. The lane now excludes the batch the reader already holds, points newer mail, and names --ack <deliveryId> so the reader can release the held batch and reach the new mail.
  • pending counts as pointed — an admitted-but-not-yet-echoed send now marks the rows delivered (structuredDispatchDelivered returns true for pending); unknown still retains.
  • Wake diagnostics — a host.hold that cannot resume the session now logs the reason instead of failing silently.
  • Test budgets — coordinator-mail waits use a 10s budget.

I traced the eligibility change through check (it returns read = 0 rows regardless of delivered_at, so marking delivered never hides mail from a reader), confirmed getOrCreateMailboxDelivery only ever creates deliveries for run:/dispatch: handles (so the named --ack always reaches a check path that supports it), and verified runBoundToCoordinator restricts adoption to handle-less bindings.

ℹ️ Run mail pointed at a /clear predecessor is not re-pointed at the successor

The direct-mail half of the adoption deliberately resets the pointer fact (delivered_at = NULL) because "its old pointer, if any, went to a session nobody runs". The Run half does not: bindRun bumps the generation and fences outstanding deliveries, but leaves delivered_at set on the Run mailbox's rows. Pointer eligibility is delivered_at IS NULL, so a worker_done that was pointed at the predecessor but not read before the clear stays unprompted on the successor — the successor's idle-edge deliverPendingMessagesForHandle('run:<id>') selects nothing. The result is still readable with an explicit check --run <id>, but nothing tells the new coordinator it is there. Raising to confirm the window is intentional/accepted rather than an omission.

Technical details
# Run-mail already pointed at the predecessor is not re-pointed to the successor

## Affected sites
- `src/main/runtime/orchestration/structured-session-mail-target.ts:131-145` — `adoptClearedPredecessorMail` rebinds each Run via `bindRun`, then re-addresses *direct* mail; no step resets `delivered_at` on the Run mailbox.
- `src/main/runtime/orchestration/db/runs/run-binding.ts:119-160` — `bindRun` bumps `consumer_generation` and calls `fenceUnacknowledgedMailboxDeliveries`, but only touches the `deliveries` table, not `messages.delivered_at`.
- `src/main/runtime/orchestration/db/messages/direct-mailbox-routing.ts:189-200` — the direct-mail path *does* set `delivered_at = NULL`, which is the inconsistency.

## Why it matters
`selectOrchestrationPointerBatch` selects via `getUndeliveredUnreadMessages` (`delivered_at IS NULL`, `read = 0`). The structured pointer lane calls `markAsDelivered(staged)` as soon as `host.send` returns accepted/pending — before the provider turn reads the mail. If the pointer turn settles without the chat running `check`, then `/clear` replaces the session, the row survives the rebind as `read = 0, delivered_at` set, and the successor is never pointed at it.

## Required outcome
Decide whether a Run result pointed at a cleared predecessor should be re-pointed at the successor, matching the direct-mail path. If so, reset `delivered_at` (e.g. `markAsUndelivered`) on the rebounded Run's unread messages during adoption, before `structuredSessionOwnedMailboxes` re-derives the mailbox.

## Open questions for the human
- Is the pointer turn's read effectively guaranteed before `/clear` is admitted (making the window unreachable), or is this an accepted gap?

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

Comment on lines +354 to +355
// A pending send is not an acknowledgement, so the mail is retained and retried on every edge
// until the host confirms it: before the echo, and again at the turn's idle edge.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This comment describes the pre-delta behavior. Now that pending is a pointed state (structuredDispatchDelivered), the pointer's send marks the rows delivered immediately, so the retries at lines 356-358 are no-ops rather than the retention this comment claims to exercise. The assertion still holds; only the rationale is stale.

Suggested change
// A pending send is not an acknowledgement, so the mail is retained and retried on every edge
// until the host confirms it: before the echo, and again at the turn's idle edge.
// The pointer marks the rows delivered as soon as the host admits the turn, so these retries
// are idempotent no-ops; the test pins that they never produce a second pointer.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one design tradeoff in the body worth confirming.

Reviewed changes

Re-reviewed the 4 commits on top of the prior pullfrog review (ca9b4718): the pending-settlement give-back, the /clear observer guard, and their tests.

  • An admitted pointer is given back when its turn never settles — StructuredMailboxPointerHost.send now returns a settlement promise for pending (built from waitForSendSettlement), and settlePendingPointer deletes this send's operation row and calls markAsUndelivered + retain on any verdict other than accepted. The row is dropped so the re-point mints a fresh id instead of replaying the recorded unknown, which would land no turn at all.
  • A committed /clear no longer fails on a throwing replacement observer — runStructuredConversationCommand wraps onConversationReplaced in try/catch and warns; the idle edge re-derives adoption, so bookkeeping behind an already-committed clear cannot turn it into a failure.
  • Tests — provider death before the echo now gives the result back and re-points it once on the idle edge; a chain of clears is adopted fully and the predecessor's check reads nothing of the successor's mail; the host's settlement mapping covers echo, provider death, timeout, and a disappeared send.

I traced the give-back against the real DB semantics (getUndeliveredUnreadMessages requires delivered_at IS NULL; markAsUndelivered guards read = 0; resolveStructuredPointerOperation reuses an id only for the same mailbox+session+batch) and the real trigger paths (deliver/inFlight, onJournalActivity, the idle edge). The message-row half of the give-back has no operation_id guard, but delivered_at exclusivity plus inFlight serialization keeps a message out of two staged batches, so it cannot clobber a newer pointer's claim. structured-mailbox-pointer-delivery.test.ts, structured-mailbox-pointer-host.test.ts, and structured-conversation-command.test.ts pass (55 tests).

ℹ️ An ambiguous pending settlement can produce a second pointer turn

settlePendingPointer now gives the batch back on any non-accepted verdict, which is the right call for a dead provider — but unknown also covers the 30s waitForSendSettlement timeout, where the turn may still be queued and later echo accepted. By then the operation row is gone and the rows are undelivered again, so the accepted echo's journal edge mints a new id and sends a second pointer turn for the same mail. It is rare (a normal echo is sub-second, and the PR notes legacy clients already abandon at 15s) and strictly better than the silent strand it replaces, but the coordinator can now receive a duplicate "you have mail" turn. Confirming that is acceptable; if not, giving back only on a definitive verdict (session close, not timeout) would bound it.

Technical details
# Duplicate pointer turn on an ambiguous pending settlement

## Affected sites
- `src/main/runtime/orchestration/structured-mailbox-pointer-delivery.ts:284-325` — the `pending` branch marks rows delivered and defers; `settlePendingPointer` deletes the op row and `markAsUndelivered`s on any non-`accepted` verdict, including the timeout-derived `unknown`.
- `src/main/runtime/orchestration/structured-mailbox-pointer-host.ts:135-154` — `settlement` maps an `undefined` result (the 30s timeout) to `'unknown'`.
- `src/main/native-chat/agent-session-wire/structured-agent-session-send-settlement.ts:84-88` — the timeout resolves the waiter `undefined` even though the submission is still live; a later `publish` would have resolved it `accepted`, but the waiter is already removed.

## Why it matters
`getUndeliveredUnreadMessages` gates on `delivered_at IS NULL`. After the give-back, the accepted echo publishes a journal item → `onJournalActivity` → `deliver` finds the rows selectable again and mints a fresh operation id (the row was deleted), dispatching a second provider turn for the same batch. The mail is not lost or double-read; the cost is a redundant turn in the coordinator chat.

## Required outcome
Decide whether the duplicate turn on an ambiguous `unknown` is acceptable. If not, distinguish a timeout/waiter-cap `unknown` from a definitive dead-session verdict and only give back in the definitive case.

## Open questions for the human
- Is the duplicate turn acceptable given it replaces the prior silent strand, or should the give-back be limited to definitive failures?

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — the /clear redesign is clean; two informational notes below.

Reviewed changes

Re-reviewed the three commits since the prior pullfrog review (55692e7e6b), which replace /clear continuity handling and add a restart-recovery path.

  • /clear continuity is derived, not rewritten — structuredSessionLineage resolves any session of a clear chain to its lineage root (the conversation's stable session:<root> address) and its live end; sessionOrchestrationIdentity takes the actor from the root and the worker identity from the live session. Runs, direct mail and the caller identity all stay under one address with nothing rewritten at the clear, and adoptClearedPredecessorMail, readdressUnreadSessionMail and the onConversationReplaced wiring are removed.
  • Restart recovery for structured pointer claims — releaseRestoredStructuredPointerClaims runs when the orchestration DB opens: for each durable pointer-operation row it finds that row's stamped batch by fingerprint among the mailbox's pointed-unread rows, marks it undelivered and drops the row, so a claim whose settlement waiter died with the previous process is re-pointed by the normal undelivered scan.
  • Idle-edge redrive opens the DB itself — structuredSessionIdleEdgeMailboxes calls getOrchestrationDb() so a restarted chat's idle edge redrives mail stored before the restart; a DB that cannot open is logged rather than skipped silently.

ℹ️ The /clear section of the PR description describes the mechanism this delta removed

The PR body is the design doc here, and §6 still explains /clear continuity as a rebind of Runs plus a re-address of direct mail, driven by an onConversationReplaced observer. All three were removed by 060790e567, so a reviewer reading the body against the code will look for machinery that is gone.

Technical details
# Stale PR description for `/clear` continuity

## Affected sites
- PR body §6 "A `/clear`-replaced coordinator's Runs and mail follow the new session" — describes `bindRun` rebinding and `readdressUnreadSessionMail`, both removed.
- PR body §6 "Two edges drive it" — names the clear's commit (`onConversationReplaced`) and the successor's first status publication; the observer and its runtime wiring are gone.
- PR body "Testing" and "Ablations" — list `/clear`-predecessor, chain-adoption and `structured-conversation-command.test.ts` replacement-observer cases that no longer exist.

## Required outcome
- §6 should describe the lineage-derived conversation address (root actor for the address, live session for the delivery target, nothing rewritten at the clear); the Testing/Ablation lists should drop the removed cases.

ℹ️ Restart recovery assumes one outstanding pointer claim per mailbox

The recovery releases only the batch whose fingerprint matches the single operation row per mailbox. Because that row is an upsert keyed by mailbox, a newer batch pointed while an earlier one is still pending replaces the earlier row, and the earlier batch is then not released on restart. Worth confirming this window is accepted (it needs process death inside the pending interval).

Technical details
# An earlier pending batch is not released when a newer batch overwrote its operation row

## Affected sites
- `src/main/runtime/orchestration/structured-pointer-claim-restore.ts:28-34` — iterates `listStructuredPointerOperations()` (one row per `mailbox_handle`) and releases only the batch whose fingerprint matches that row.
- `src/main/runtime/orchestration/db/messages/structured-pointer-operation-store.ts:21-41` — `putStructuredPointerOperation` upserts on `mailbox_handle`, so a newer batch overwrites the earlier row.
- `src/main/runtime/orchestration/structured-mailbox-pointer-delivery.ts:283-297` — a `pending` send marks rows delivered and keeps the op row; a later batch on the same mailbox mints a new id and overwrites it (`resolveStructuredPointerOperation`).

## Why it matters
If batch X is admitted `pending` (rows `markAsDelivered`ed, op row = X) and batch Y is pointed before X settles, Y's `putStructuredPointerOperation` replaces the row. On restart `getPointedUnreadMessages` returns `[X, Y]`, `stampedBatch` matches only Y, and X stays `delivered_at`-stamped with no row: the undelivered scan never re-points it (it stays readable via an explicit `check`). In-process this is fine — `settlePendingPointer`'s `markAsUndelivered(staged)` is not guarded by the op-row check — so only process death inside the pending window loses X.

## Required outcome
- Confirm whether a single row per mailbox is the intended scope. If earlier batches must also be recovered, note that "stamped rows with no matching row" cannot be released wholesale: an accepted-but-unread batch legitimately has no operation row.

## Open questions for the human
- Is the multi-batch window accepted, or should each batch's claim be stored separately?

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Reviewed the one follow-up commit (e79d321f0a) on top of the prior review.

  • The idle edge no longer creates the orchestration database — a new getExistingOrchestrationDb() opens the database only when its file already exists (or it is already open), and structuredSessionIdleEdgeMailboxes takes () => OrchestrationDb | null, returning no mailboxes when there is none. A profile that never orchestrated stays without a database file and logs nothing; failing to open an existing file is still logged.
  • Tests updated — the restart test seeds a real database file under a fake userData and asserts the idle edge opens it; a new test pins that no file is created and nothing is logged.

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

@brennanb2025
brennanb2025 force-pushed the brennanb2025/d3-cli-injection branch from 0ef7f31 to 3f5f798 Compare September 24, 2026 22:11
@brennanb2025
brennanb2025 force-pushed the brennanb2025/d4-coordinator-delivery branch from e79d321 to 92ecd41 Compare September 24, 2026 22:11

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Re-reviewed the one commit on top of the prior pullfrog review (e79d321f0a). The branch was rebased, so the new commit is isolated by subject rather than ancestry.

  • A handle-less Run's coordinator actor now counts only at the Run's current generation — handleLessCoordinatorSessionId reads the coordinator through currentRunCoordinatorActor, so an actor an older binary's rebind or unbind left behind no longer routes the Run's mail. This is the same rule runCoordinatorKey, runBoundToCoordinator, runsBoundToCoordinator and the v42 backfill already apply, so delivery and ownership can no longer disagree about which session a Run is bound to.
  • Tests pin both the read and the write — structured-session-mail-target.test.ts bumps consumer_generation and asserts the run: mailbox stops resolving (this case fails against the pre-commit raw-actor read); structured-chat-coordinator-mail.test.ts asserts a cleared chat's run-create/run-use store the conversation's root actor at the Run's current generation.

I traced the write paths (createRun writes coordinator_actor_generation = 1 beside consumer_generation = 1; bindRun always writes the actor at consumer_generation or consumer_generation + 1; the backfill stamps consumer_generation) and confirmed no other production reader consumes the raw coordinator_actor column.

Four earlier Pullfrog threads remain open (they are test-strength/design notes, unchanged by this commit) and are not re-raised here.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Re-reviewed the one commit on top of the prior pullfrog review (92ecd41040, rebased so SHAs differ): 34d9401a80, which carries the base branch's "Orca session id" rename into this PR's coordinator-delivery code.

  • A session's orchestration identity is now a bare Orca session id — sessionOrchestrationIdentity returns orcaSessionId (the lineage root's) and derives its session:<id> address through formatOrcaSessionAddress; hasLostStructuredWorkerIdentity reads identity.orcaSessionId instead of parsing an actor string.
  • Coordinator resolution reads the renamed column — handleLessCoordinatorSessionId returns currentRunCoordinatorOrcaSessionId(run); structuredSessionAddressTarget and session-recipient use parseOrcaSessionAddress/isOrcaSessionId in place of the removed actor codec.
  • Session ids from records and PTY bindings are validated before becoming identities — sessionMailOwner, structuredSessionMailReach and structuredSessionOwnedMailboxes guard with isOrcaSessionId; bindDeclaredCaller accepts formatOrcaSessionAddress(caller.sessionId).
  • Tests updated — the touched suites use the testOrcaSessionId/formatOrcaSessionAddress fixtures and assert the coordinator_orca_session_id column.

I checked the rename against the removed orchestration-actor codec: isOrcaSessionId keeps the same isAgentSessionId predicate and terminal-handle refusals, and parseOrcaSessionAddress/formatOrcaSessionAddress are equivalent for session:<id> at every call site. No production file still references the deleted module or an actor field. The four earlier Pullfrog threads remain open and are unchanged by this commit (test-strength and Windows-Claude-shell notes), so this is not an approval.

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

@brennanb2025
brennanb2025 force-pushed the brennanb2025/d3-cli-injection branch from 00f4525 to 9d02ccc Compare September 25, 2026 07:44
@brennanb2025
brennanb2025 force-pushed the brennanb2025/d4-coordinator-delivery branch from 34d9401 to 5183dd5 Compare September 25, 2026 07:55
@brennanb2025
brennanb2025 force-pushed the brennanb2025/d3-cli-injection branch from 9d02ccc to 52774a0 Compare September 25, 2026 19:43
@brennanb2025
brennanb2025 force-pushed the brennanb2025/d4-coordinator-delivery branch from 5183dd5 to f75fbe4 Compare September 25, 2026 19:43
@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: dd0f7bc8-a526-4e5d-b779-fc098a5bfa16

📥 Commits

Reviewing files that changed from the base of the PR and between ed12df5 and 0105f57.

📒 Files selected for processing (2)
  • src/main/runtime/orchestration/structured-mailbox-pointer-delivery.test.ts
  • src/main/runtime/orchestration/structured-pointer-operation-id.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.


📝 Walkthrough

Walkthrough

The change adds /clear lineage lookup for structured sessions and uses it in caller identity checks and mail routing. Session-addressed recipients receive reachability checks and session-specific routing. Session status changes can trigger idle-edge mail redrive. Pointer delivery uses journal submission history to decide whether to send, reuse, stamp, or park an operation.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 0105f

No actionable merge-blocking issue remains in the supplied evidence; the change is mergeable after normal checks.

Architecture Summary

Architecture risk: 🔵 Low · up to 0105f

The change affects 1 system.

Changed systems: src

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — src (service) was modified; 39 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in src/cli/handlers/orchestration/message-send-handler.ts: senderPaneKey is now omitted for injected agent-session senders; for other senders it is still set from ORCA_PANE_KEY only when from is defined.
  • observed — Modified behavior in src/main/runtime/orca-runtime-automation-operations.ts: Imports existsSync from node:fs for checking whether the orchestration database file exists.
  • observed — Modified behavior in src/main/runtime/orca-runtime-automation-operations.ts: getOrchestrationDb() now uses a shared path helper. The new getExistingOrchestrationDb() returns the existing in-memory database or opens it only when the database file exists; otherwise it returns null. orchestrationDbPath() constructs the path from the user-data directory and orchestration.db.
  • observed — Modified behavior in src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.ts: The CLI-command import no longer includes getAppEnvironment; runtimeOrchestrationCliCommand is imported instead.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 87 functions across 39 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary change: delivering worker results to structured chat coordinators.
Description check ✅ Passed The description is detailed and covers the required user impact, implementation, rationale, testing, visual proof, compatibility considerations, and checklist items. It does not provide a separate lin…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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

❤️ Share

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

@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 2/5

[High risk] Restructures orchestration session addressing and mail delivery.

The PR does not appear safe to merge while rejected pointer sends can leave coordinator mail unpointed.

Findings

  1. P1 Clock changes can strand pointers ▶
  2. P1 Rejected pointers cannot retry ▶
  3. P1 Account switch leaves mail unpointed ▶

Summary

The PR routes worker-result pointers and direct session: mail into structured chats, derives a stable orchestration address across /clear, and redrives mail from session status changes. Since the previous review, it also changes how pointer operations are dated to handle backward clock adjustments.

  • The new timestamp rule can prevent a failed pointer from being retried under a new operation ID after the coordinator runs another turn.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Worker[Worker result] --> Mailbox[Durable orchestration mailbox]
  Mailbox --> Pointer[Structured pointer delivery]
  Pointer --> Chat[Coordinator session turn]
  Chat --> Check[Orchestration check]
  Check --> Mailbox
Loading

Reviews (5) · Last reviewed commit: "fix(orchestration): date a pointer on th..."

@greptile-apps

greptile-apps Bot commented Sep 29, 2026

Copy link
Copy Markdown

Comments Outside Diff

These findings could not be posted inline.

  • P1 Closed chats still accept mail src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts:195 ▶

    A closed chat can retain its Run binding. When mail is sent to its session:<id> address, this branch accepts the Run route before the closed-session check runs. The send succeeds and stores mail in a Run mailbox that cannot deliver a pointer to the closed chat, instead of refusing the recipient. Check whether the session is reachable before accepting its Run or Dispatch route.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Re-reviewed the three commits since the prior pullfrog review (5322945058 at 5c47b2546f), after the branch was restacked onto main (2ca4ecbc61).

  • A /cleared chat may restate its address — sessionAddressForHost now lets a session:<id> that is not this session's own spelling pass the CLI entry guard and be forwarded as the caller param; the host's canonicalOrcaSessionId / resolveOrchestrationParty check accepts the lineage root or refuses a stranger with consumer_fenced before any effect. A session send also stops carrying an inherited senderPaneKey.
  • Mail reaches a chat whose agent is not running through the plain send — main removed the host's hold/release, so the pointer lane's wake step and its log are deleted; an accepted send starts the stopped agent itself, and a non-accepted verdict is still given back.
  • Test adaptation — the coordinator-mail fixture awaits the now-async journalSnapshot and waits for the held turn's handover, so the mid-turn case no longer races the provider echo.

The prior review's structured-session-mail-target.ts:70 finding (a cleared worker's live successor unreachable once the predecessor is released) is untouched by these commits and remains open, so this is not an approval.

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

…of respawning it for mail

A pointer whose provider died before echoing it is given back. The death's own status
edge then redrove the mail, and since a send starts the agent, a provider that died on
every turn was restarted about once a second for as long as the mail was unread. The
pointer lane now reads, on every attempt, whether the session's latest send never ran
because its provider exited or could not start, and holds the mail until a later send
runs. Every trigger passes through that gate: a parked retry, the idle edge's re-derive
and new mail. A rejection for any other reason still points at the next idle edge.
…ing every failure kind

A start refused for a reason only the person can fix (not signed in, history too large,
a managed-account problem) or one the host stopped because it never came is held like a
failed start: the mail waits for the person's next message, which also retries the start.
An account switch still in progress is transient, so it stays ungated and the first edge
after the switch settles points the mail. One exhaustive record places every rejection
kind, so a new kind does not compile until it is placed.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Re-reviewed the two commits since the prior pullfrog review (5346464757 at 1719b18e1b): the new gate that holds a structured session's mail while its latest send never ran.

  • A dead provider is left stopped instead of respawned — latestSendHoldsMail reads the session's latest submission (sorted by submittedAt): an unknown doubt whose reason is provider_exited_before_acknowledgement (the marker a real provider exit writes), or a rejection in REJECTION_HOLDS_MAIL (a start that failed, or one that needs the person), holds the mailbox. readPointerGateFacts folds that into the pointer lane's gate as the new awaiting-next-turn retain, so a death's own status edge no longer re-points the mail and restarts the provider.
  • Every failure kind is placed — REJECTION_HOLDS_MAIL is satisfies Record<SubmissionRejectionKind, boolean>, and the host test asserts one behavioral expectation per AGENT_SESSION_FAILURE_KINDS entry, so a new kind cannot compile until it is classified. Only a provider death or a start that needs the person holds; a healthy agent's refused write (queueFull, writeFailed, …) still points at the next idle edge.
  • Tests — the integration suite pins the no-respawn window (a fixed 1.5s window with a provider that dies before every echo), a start the person must fix (nothing retried before the next message), an account switch settling on its own, and a healthy agent's refused write still being pointed.

The prior review's structured-session-mail-target.ts:70 finding (a cleared worker's live successor is unreachable once its predecessor lease is released) is untouched by these commits and remains open, so this is not an approval.

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

…ad of gating on the failure reason

A pointer send that failed was given back and re-sent under a fresh operation id,
so every status edge after a provider death was a new send that started the provider
again. A reason-string gate held some of those deaths, but missed a Codex crash with
turn/start in flight (it settles unknown with the connection's error), latched all later
mail after one transient death, and did not keep a user's Stop.

A retry now reuses the mailbox's operation id, which the host answers by replaying the
recorded verdict without reaching the provider. The id is re-minted only for new mail,
after a later send ran, for a row an earlier process left, or once an account switch
settles. Rows are stamped only on accepted, so the admitted-stage claim, its give-back
and the restart claim-release scan are gone.
…s a terminal's

The chat lane pointed newer mail past a batch its reader had checked and not
acknowledged, while the terminal lane skips a mailbox until that batch is acked. A chat
now waits for the ack the same way a terminal does, and the lookup that let the chat lane
filter the held batch out is removed.
…ist --run would drop

The CLI entry lets a `session:` address that is not the session's own spelling through
for the host to place, but gate-list and task-list send no caller when --run names the
Run, so `--from session:<other>` was silently ignored. With --run they now refuse it
(consumer_fenced) before any request, the same as a conflicting terminal handle.
… first-turn workspace rename

A structured session's status callback redrives its mail before the first-turn workspace
auto-rename, outside any try, so a database error there threw past the rename. The redrive
now logs its failure and returns.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Re-reviewed the six PR-authored commits since the prior pullfrog review (5348746912 at 4c7e5aec48), plus a merge of main and a lockfile restore.

  • A failed pointer now retries under its own operation id — decideStructuredPointerAttempt replaces the reason-string latestSendHoldsMail hold and the pending-settlement/claim-restore machinery with mint/reuse/stamp/park, keyed on the mailbox's durable row, its batch fingerprint and the session's recorded sends. A reuse resend replays the ledger's recorded verdict (sendPlan recovers or replays and never reaches the provider), so a provider that dies on every turn is not respawned and a user's Stop stays stopped, while genuinely new mail (a new batch) is pointed normally. Rows are stamped only on accepted.
  • A chat waits for the ack like a terminal — the held-batch exclusion is removed and hasOutstandingMailboxDelivery restored, so a chat that ran check without acking is not pointed at newer results until it acks, matching the PTY lane.
  • gate-list/task-list --run refuse a session address they would otherwise drop — refuseUnsentSessionAddress throws consumer_fenced before any request when a session:<id> that is not the caller's own spelling accompanies --run; the shared error factory is extracted.
  • A failed idle-edge redrive no longer skips the first-turn workspace rename — the redrive body is wrapped in a try/catch that logs and returns.
  • Type narrowing — stamp and park get separate variants instead of a shared union member.

I traced the retry path through sendPlan/resolveAgentSessionReplayOutcome (a reused id with a failed or unknown outcome refuses or replays and never dispatches a second turn; the ledger's 48h replay window bounds this) and the restart path through the journal crash boundary (surviving submissions settle to unknown, so a pending-at-crash row is re-minted exactly once at the new lane). The focused suites pass locally: 196 unit tests plus the 20-test real-host coordinator-mail suite.

The earlier structured-session-mail-target.ts:70 finding (a cleared worker's live successor unreachable once its predecessor lease is released) is untouched by these commits and remains open, so this is not an approval.

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

Comment on lines +76 to +80
const ranSince = submissions.slice(index + 1).some((entry) => entry.dispatchState === 'accepted')
const leftByEarlierProcess = row.minted_at_ms < input.laneStartedAtMs
const accountSwitchSettling =
sent.dispatchState === 'rejected' && sent.rejection?.kind === 'accountSwitchInProgress'
return ranSince || leftByEarlierProcess || accountSwitchSettling ? 'mint' : 'reuse'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Rejected pointers cannot retry When a pointer send is rejected while the session is otherwise healthy, the next journal edge reuses the same operation ID. The host replays the rejection without sending another turn, leaving the worker result unpointed unless new mail changes the batch or another send runs.

Knowledge Base Used: Agent workspaces and sessions

… cannot strand it

A pointer row whose id had no submission in the journal was always resent under that id,
before any re-mint test ran. After a rewind rebuilt the journal, or a send refused before it
was recorded aged past the host's 24h admission window, the mail was held forever: neither
the person's next turn nor a restart pointed it again.

The re-mint tests now run first. "The agent has run since" is any accepted send submitted
after the row was minted; "an earlier process minted it" is a row whose id this lane did not
send, not a wall-clock comparison a clock step could fool; and a row the host never recorded
is re-minted once it is too old for the host to admit. The account-switch exception is gone:
nothing tells the lane when a switch ends, and each outside edge during one added another
pointer and failure to the chat. A parked pointer now retains as turn-unsettled.
…t or task-list --run names

5f753af refused any `--from session:<x>` beside --run that was not the session's own
spelling, which also refused a /clear-ed chat restating its lineage root, an address the host
accepts everywhere else. The CLI now sends that address with --run, and the host's declared
caller check accepts the root and refuses anyone else (consumer_fenced) before any effect.
Comment on lines +74 to +79
const ranSince = submissions.some(
(entry) => entry.dispatchState === 'accepted' && entry.submittedAt > row.minted_at_ms
)
const tooOldToAdmit =
!sent && input.now - row.minted_at_ms > AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS
return ranSince || !input.mintedByThisProcess || tooOldToAdmit ? 'mint' : 'reuse'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Account switch leaves mail unpointed When a pointer send is rejected because an account switch is in progress, this code reuses its operation ID on later attempts. The host replays the rejection instead of sending a new pointer. Finishing the switch does not itself add an accepted send, so the coordinator receives no pointer until someone sends another message.

Knowledge Base Used: Agent workspaces and sessions

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Re-reviewed the two commits since the prior pullfrog review (5350174468 at 1581a50582), plus a merge of main.

  • A held pointer is re-minted from facts that cannot strand it — decideStructuredPointerAttempt now runs its re-mint tests before the "reuse the row's id" fallback: a peer turn accepted after the row was minted, a row this process did not send (sentOperationIds/sentByThisProcess replaces the Date.now() lane-start comparison, so a clock step cannot fake it), or a row the host never recorded and is now past its 24h admission window all mint a fresh id. A recorded failure still replays under its id, so a provider that dies on every turn is not respawned and a Stop stays stopped. The accountSwitchInProgress mint exception is removed, and a parked pointer now retains as turn-unsettled.
  • gate-list/task-list with --run forward a session caller to the host — the client-side refuseUnsentSessionAddress refusal is deleted; runScopedSessionCaller sends a session:<id> that is not the caller's own spelling with the request, and the host's bindDeclaredCaller accepts a /clear lineage root and refuses anyone else with consumer_fenced before any effect.
  • Tests — new unit cases pin each mint boundary (including a wall-clock step and the exact 24h edge), and real-host cases cover a rewind-dropped send and a host-unrecorded send aged past admission. The CLI test now asserts the address is forwarded; the runtime test pins root-accepted/stranger-refused for both list methods.

I traced the 24h boundary against the host ledger's agent_session_operation_expired check (both use > on the same id-embedded timestamp, so they flip together), and the declared-caller path against resolveOrchestrationSessionCaller/bindDeclaredCaller (the forwarded session: address is canonicalized before resolveRunScope, which would otherwise ignore a caller for an explicit --run).

The earlier structured-session-mail-target.ts:70 finding (a cleared worker's live successor is unreachable once its predecessor lease is released) is untouched by these commits and remains open, so this is not an approval.

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

Comment on lines +149 to +152
minted_at_ms: args.submissions.reduce(
(latest, entry) => Math.max(latest, entry.submittedAt),
now
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Clock changes can strand pointers If the clock moves backward, an earlier journal submission can have a timestamp later than a new pointer operation. This code saves that future timestamp as the operation’s mint time. A user turn that actually runs afterward can then fail the retry check, so a rejected or unknown pointer keeps replaying its old operation ID instead of sending a new pointer. The mail remains unpointed until the clock catches up. The timestamp mismatch can also delay replacement of an unrecorded operation after its ID expires.

Knowledge Base Used: Agent workspaces and sessions

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Re-reviewed the one commit since the prior pullfrog review (5350502521 at ed12df519e): a journal-clock correction to how a structured pointer's operation row is dated.

  • A pointer's operation row is dated on the journal's clock — resolveStructuredPointerOperation now writes minted_at_ms = max(now, every submission.submittedAt) instead of bare now. An accepted turn recorded before the pointer can therefore no longer satisfy ranSince after a backward clock step, which previously re-minted the id on every status edge.
  • Test — a fake-Date case with an accepted person turn timestamped before the step asserts the pointer keeps a single operation id across three edges; it goes red pre-fix, because each edge mints a new id.

The earlier structured-session-mail-target.ts:70 finding (a cleared worker's live successor is unreachable once its predecessor lease is released) is untouched by this commit and remains open, so this is not an approval.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status (head 0105f570641)

The problem this PR fixes: a native Claude or Codex chat acting as an orchestration coordinator was never told when a worker finished. The worker's worker_done sat unread until someone made the chat run orca orchestration check.

What changes for the user: the chat now gets the same short message a terminal coordinator gets, as a real turn, and reads the result itself. If the chat's agent cannot start, Orca tries once instead of restarting it over and over; the mail is offered again when new mail arrives, when the person's next message runs, or after an Orca restart. Stop is respected.

Fixed in this review

  • P1, restart loop still present: the PR held mail only for failures recorded under one exact reason. A Codex agent that died while starting its turn recorded a different reason and was restarted about 3 times a second. Replaced the reason-based rule: a retry now reuses the attempt's operation id, so the host replays the recorded result and starts nothing, and a new attempt needs a new fact (new mail, a turn that ran, a restart, or the host no longer being able to admit an unrecorded id). This also fixed: one transient crash holding every later result (including for structured workers, where nobody types); Stop not being kept; and it removed the startup claim-restore scan. (e18dad2cd55, 09c5d04d772, e65bf72cfbc)
  • P2, chat and terminal behaved differently: the chat lane announced newer mail past a batch it had read but not acknowledged; terminals do not. Restored the terminal rule for chats. (5deafe9883e)
  • P2, mail could be held forever: after a rewind dropped the send from the journal, or when an unrecorded send passed the host's 24-hour window, nothing recovered it. (e65bf72cfbc)
  • P3: an account switch in progress added a message-and-failure pair to the chat on every status change (e65bf72cfbc); a backward clock step could restart the agent on every status change (0105f570641); gate-list --run / task-list --run silently ignored a conflicting --from session:…, now checked by the host (5f753af0a77, ed12df519e9); a failed mail redrive skipped the chat's first-turn workspace rename (5c3573806ba).
  • Merged current main (c49388cd339); the lockfile matches main.

Each fix has a test that fails on the code before it. tc:node passes at 0105f570641 and tc:cli at ed12df519e9; the 11 changed test files pass (308 tests). The readiness checklist on the final diff found no P0/P1 and no new P2.

Needs a decision

  • Known gap (user-visible, existing on main): when the one start attempt fails, the chat shows neither the announcement nor the failure notice, only the red "Failed" tab dot. The chat view hides a refused message unless this window sent it, and the failure line folds into the previous finished turn. main already does this for structured workers; this PR makes it show on a chat you watch. Proposed as a separate renderer follow-up of about 30–50 lines, shared by desktop and mobile.
  • Scope: keeping a chat's address across /clear (and a cleared structured worker keeping its worker identity) is its own feature and is not needed for coordinator delivery. feat(orchestration): tell each agent its own orchestration address #22636 and feat(orchestration): a native chat can be a dispatch worker, like a terminal agent #22972 build on it. Splitting it into its own PR is recommended but not done here.

Deferred (not fixed)

  • A structured worker whose single announcement failed to start waits for new mail or a restart; no error reaches its coordinator.
  • An agent that reads with check but never acknowledges gets no announcement for newer mail. This is the same for terminals; if it matters, fix it once for both.
  • Plain-text check prints a message's subject, not its body; the Codex coordinator reported "Line counts complete" without the counts. This is existing behaviour and not changed here.
  • Nits: a pointer row stays after its mail is read without an announcement (one per mailbox); canonicalOrcaSessionId scans session records in memory on each call; two clock-step edge cases can delay a re-offer (never a loop).

Verified live

  • Real Claude (separate Mac, before = main, after = this PR):
    • Before: nothing arrived in 5.5 minutes.
    • After: the announcement arrived about 0.05 s after worker_done, and Claude ran check by itself.
    • An agent that could not start was tried exactly once over 3 minutes; the person's next message then read the result.
    • Stop was kept for 2 minutes.
  • Real Codex:
    • Before: nothing arrived in 6 minutes 20 seconds.
    • After: one announcement in the same second as worker_done, check ran by itself, and there was no duplicate after an app restart.
  • Screenshots are in the description.

Not verified: Windows, Linux, SSH and mobile live runs; a live /clear of a coordinator mid-run (tests only); the Codex no-start path live (tests only).

Stacked PRs: this branch moved to 0105f570641, so #22636 and #22972 need a restack.

@brennanb2025
brennanb2025 merged commit c1628b4 into main Sep 29, 2026
40 checks passed
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