Skip to content

fix(native-chat): every lease latch has a way to die - #22820

Merged
brennanb2025 merged 22 commits into
mainfrom
brennanb2025/chat-latches-die
Sep 26, 2026
Merged

brennanb2025 merged 22 commits into
mainfrom
brennanb2025/chat-latches-die

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 33 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1092 $\color{#cf222e}{\Huge{\mathbf{−}}}$​701 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​391
Prod 43 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​399 $\color{#cf222e}{\Huge{\mathbf{−}}}$​579 $\color{#cf222e}{\Huge{\mathbf{−}}}$​180

Scope: which chat this affects

  • Structured chat only. This PR changes the experimental structured native chat, which runs the agent through its SDK. It is behind the experimentalStructuredNativeChat setting, which is off by default (src/shared/default-global-settings.ts:137).
  • Default chat view: no change. The default chat view, backed by a terminal and reading the agent's transcript, does not use this code, and nothing about it changes.
  • Terminals: no change. Plain terminals and terminal-backed chats behave exactly as before.

Builds on #22783, which has merged; this PR now targets main.

ELI5

Orca writes down which process owns each chat, so that it never runs two agents on the same conversation. Some of those notes could get stuck. When that happened, the chat refused every message until you restarted Orca, and sometimes kept refusing after a restart too. This PR makes sure every stuck note has a way to clear itself, and the chat starts again on the next message.

What Changed

What you saw before:

  • The agent crashed in the middle of a reply, and Orca couldn't write the "the agent stopped" row to the chat (a disk or journal hiccup). From then on, every message to that chat was refused, including after a restart.
  • Orca was killed in the moment between reserving a chat and recording the agent it started. On macOS and Windows that chat then needed "manual recovery", which no button offered.
  • Orca couldn't verify an old agent's identity, for example because it couldn't read the process start time. It then asked again on every message, forever.
  • The old agent was still alive and survived both stop signals. The chat stayed blocked.

What you see now:
In every one of these cases the chat starts a fresh agent again: on the next message, or, for a chat that was still starting when Orca stopped, on Retry (a message sent before Retry waits in the chat and is answered once the agent starts). The unfinished reply from the dead agent is closed off with the exit reason the agent gave, just as it would have been if the first write had worked. The one exception is a chat still held by a terminal agent from an older version of Orca: it waits for that agent to exit, and sending or opening the chat now says so, names the agent's process, and says to quit it.

Mechanism. These deletions and changes are all in the lease record (the note of who owns a chat) and the code around it:

  • Settlement retry deleted. Before, a crash whose journal cleanup failed set a "settlement still owed" flag and a recovering stage. The start path refused while the flag was set, and nothing but a successful retry cleared it.

    • Now the release always writes no stage, and records the exit reason in the lease's existing death evidence.
    • Whatever the dead agent left running is settled from that evidence by one function, called whenever there is no live agent for the journal: when the next agent starts, and when a closed chat is reopened for reading, including at app startup.
    • Deleted: the flag and its id, the retry module, the restart disposition that preserved it, the eviction refusal, the recovery skip, the refusal text, and the flag on the provider "ended" events.
  • Reservations with no recorded process are released. A reservation that never recorded a process is released:

    • at startup;
    • after a failed start whose exit couldn't be proven, since the adapter has already closed the stdio of anything it spawned.

    Deleted: the never-set "processless" proof field, its store method and probe branch, and the unused conflict marker. Nothing writes manual-recovery any more: a record that carries it loads as recovering, mapped at decode like the removed handoff stages, so the stage and every branch that handled it (including the "manual recovery is required" status answer) are gone. A live terminal owner an older build recorded now waits in recovering.

  • Recovery always reaches a verdict.

    • A proven-dead owner is evicted, as before.
    • A live owner is stopped by identity (SIGTERM, then SIGKILL), then evicted once proven gone. If it survives the ladder, the lease is released anyway.
    • An owner whose identity can't be verified is released with no signal sent, because that pid may now belong to something else. Its transport died with the Orca that started it, so nothing can drive it.
    • A terminal agent recorded by an older build now loads as a conflicted claim, and is still waited out, never stopped, including when its identity can't be verified: a terminal keeps its transport across an Orca restart, so only proof that it exited ends that claim. Sending and opening the chat now both say the chat is still open in a terminal agent, name its process, and say to quit it. Before, sending said to reopen the chat and opening it said two runtimes claimed it. Error codes are unchanged.
  • A create retried after recovery released it continues. The client keeps a create it never heard back from and retries it under the same operation id. That create's ledger row stays pending until it expires about 24 hours later, and the replay path only continued a reservation that still existed. Recovery had just released this one, so every Retry was refused agent_session_ownership_unknown ("Chat connection could not be confirmed"), and after the row expired, agent_session_operation_expired. Now a retry whose lease nothing holds (released, no stage, reconciled) continues as a fresh reservation at the next fence under the same id, whether the row is still pending or has expired. This is derived from the lease, with no new stored field. The fence move is what stops a spawn from the old reservation committing, and a second retry while the new reservation stands re-enters it instead of spawning again. A retry whose reservation is still held (reserved, live, recovering or conflicted) is answered exactly as before.

  • Codex records its process at spawn. The Codex connection reports the child's pid before the initialize handshake. The host writes the identity to the lease right then, so a crash mid-start leaves an owner the next launch can stop by identity. The later identity commit becomes an equality check.

Why

These were latches with no way to die: a durable "work is still owed" fact that nothing re-derived. The fix removes the stored flag and derives the same answer from facts Orca already keeps:

  • what the journal still shows running;
  • how the lease was released.

Alternatives considered:

  • Keep the flag, but stop letting it gate starts. That leaves a second copy of a fact that can disagree with the journal. It also still needs a clear path; the failed-exit path also set a stage that the start path itself refused.
  • Add new death-evidence kinds (stop-unproven, identity-unverifiable). An older build rejects an unknown kind and marks the whole record unreadable, so a downgrade would lose the chat.
    • Instead, a release with nothing proving death writes no death evidence.
    • A lease released without evidence reads as unverifiable, never exited, both to workers and in the owner verdict clients receive.

Differences from the plan

Two places where the design this series follows was wrong when checked against the code, corrected here:

  • No new death-evidence kinds. The design released an unproven owner with evidence stop-unproven, identity-unverifiable, or exit-observed ("no process was recorded").
    • Older builds accept only exit-observed, pid-absent and identity-mismatch (isAgentSessionDeathEvidence, src/shared/agent-session-record.ts:280-293 on main). A new kind would put the record in the unreadable set after a downgrade.
    • exit-observed would also be false for an unproven release. It would make observeStructuredWorker answer exited (src/main/runtime/structured-worker-authority.ts:117), and turn the stale-turn verdict into interrupted.
    • So these releases write deathEvidence: null. Older builds already accept that on any lease: lease.deathEvidence === null || isAgentSessionDeathEvidence(...) at src/shared/agent-session-record.ts:334 on main, with no rule tying it to claimStatus.
    • A new cross-version test opens the record this build writes with the v1.4.211 record store. That store loads it, reconciles it, and reserves a new owner over it. Writing a new kind instead makes the same store mark the record unreadable (checked by ablation).
  • Settlement at read restore. The design routed the dead generation's running turn only to the next start. But the deleted retry also ran when a chat was restored for reading at startup (structured-agent-session-restart-restore.ts:82, retrySettlement). Without a replacement, a chat that was mid-reply when the app quit would show a running turn, and a "working" row, until the next send. The derived settlement therefore also runs at read restore, before the chat is published.

The design also said to delete the conflicted claim status because no build wrote it. #22783 now writes it when it loads a terminal owner an older build recorded, so it is kept as the claim recovery waits out and never stops. Only the unused conflict marker and the conflicted restart disposition are deleted.

Differences from the common pattern

The comparable desktop agent hosts restart a conversation's provider without proving the old one dead. At startup they settle an orphaned session's state from what they already hold (the "was running, no live runtime" projection), best effort and never blocking, and they finish a bounded kill even when the stop is unproven.

Partial matches (the part that matches, and the part that does not):

  • Settling an orphan's turn. Matches in how it decides a turn was orphaned: "was running, and no live runtime", from state already held, best effort, never blocking a send. Does not match in when and how: the comparable hosts sweep every conversation at startup and write a fixed reason; Orca settles lazily, per chat, when it is next started or opened for reading, and words the row from the lease's death evidence.
  • The stop ladder. Matches only in being bounded and then concluding anyway (signal, escalate, then proceed regardless). Does not match in what is signalled: the comparable hosts signal a process group through a child handle they still hold; Orca signals a pid it recorded before a restart, and only after verifying that pid's identity.

Deviations:

  • Orca keeps a durable owner lease with a fence, where the others bind a runtime only after it starts. So Orca records the child's identity at spawn, and has a recovery step that stops a surviving orphan by identity before starting over. The others simply start the new session.
  • A crashed turn's copy is settled at the next start or read, not in a startup sweep over every chat, because Orca opens journals lazily.
  • Releasing an unverifiable owner (no signal, no death evidence) is Orca-specific. The others never recorded that owner in the first place.

Linked Issue

Part of the native-chat "a chat never gets stuck" series.

Visual Proof

Live run in an isolated dev build on macOS. A Codex chat is killed mid-start (Orca's main process killed during the agent's startup handshake), then Orca is relaunched.

Before (base) After (this PR)
The relaunched chat is refused: the "Chat connection could not be confirmed." banner stays, and no send or Retry ever starts an agent.
Retry starts a fresh agent and it replies.

A profile the base left stuck, opened with this build: Retry starts the agent and it replies.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New tests (each written first, then shown to fail two ways: against the base's production code, and with this PR's core line deleted):

Case What it pins Deletion that turns it red
Crash mid-reply, and its settlement write fails every time The lease is released with no stage. The next send goes through, and the old turn ends at the exit time with the exit reason in its row. Delete the settlement at the next start (on the base, the stage stays recovering)
Restart eviction, and proven eviction by recovery, when the reopened journal handle never writes The next start settles the old turn as unverifiable and is never refused. Same deletion (on the base: refused ownership_unknown)
Chat restored for reading after a restart Whatever was running is settled before the chat is published. Delete the settlement at read restore
Crash after reserving, before any process was recorded (macOS: no scan) Released at restart; the next start goes ahead. Also covered for the in-process failed start. Restore manual-recovery for reservations with no owner
Codex child spawned, host crashes before thread/resume The identity is on disk. The next launch stops that exact pid, evicts it, and starts a new child. Delete the onSpawned wiring
Real Codex connection The pid is reported before the initialize handshake; failing to record it reaps the child. Delete the report before the handshake
Owner whose identity can never be verified Released without any signal; the next start goes ahead. Delete the release for an owner nothing proved gone
Owner that survives SIGTERM and SIGKILL Released after the ladder; the next start goes ahead. Same deletion
Records an older build left: conflicted with no process, manual-recovery reservation manual-recovery loads as recovering; released at startup or in recovery; the chat starts. Restore manual-recovery for reservations with no owner; delete the unproven release
A conflicted terminal owner an older build left, still running or not verifiable Waited out, never signalled, and sending or opening the chat names the process to quit. Once a probe proves it gone, the chat starts. Release a conflicted owner the probe could not verify
Record carrying the old settlement flag Settled from its evidence on the next start; the flag is gone from the record. Keep the retired fields at load
Chat mid-reply when the app quit: exit seen but not settled, or owner proven gone by a probe Reopened with no running turn (interrupted at the exit time, or unverifiable), and no published status says working. Delete the settlement at read restore; or ignore the lease's evidence there (the interrupted case goes red)
Downgrade: the record this build writes for an unproven release The v1.4.211 record store loads it (not unreadable), reconciles it, and reserves a new owner over it. Positive control: writing a new evidence kind makes the old store mark the record unreadable
Failed start that recorded no owner The owner verdict stays unverifiable, never exited. Let a release without evidence read as exited
The client's create, retried under the same operation id after a crash mid-start released its reservation: child recorded or not, row still pending or expired The create starts an agent at the next fence and settles its row succeeded; a further retry replays that answer and starts nothing. Keep refusing a replay whose reservation was released (red: agent_session_ownership_unknown pending, agent_session_operation_expired expired)
That retry at the store A late spawn from the old reservation is refused at its fence and by token; a retry while the new reservation stands re-enters it with no new spawn; a retry whose reservation is live, recovering or conflicted is refused as before. Same deletion
Sending to, and opening, a chat a terminal agent holds Both answer with the same "still open in a terminal agent (process N). Quit that agent" message. Drop the terminal case from the send admission message

Existing tests. Tests that pinned the latches were rewritten to the new behaviour. The settlement-latch test file and the retry module's tests were deleted along with the code.

Runs:

  • vitest over src/main/native-chat, src/main/runtime, src/shared/agent-session*, src/main/codex, src/main/claude and src/main/observability: 13,874 passed.
  • 7 failed, none in code this PR touches:
    • the 4 claude-structured-real-cli cases, which need the real CLI (known locally);
    • 3 timeouts on a loaded machine (structured-agent-session-refusal-retry, automation-change-publication, orchestration-all-start-versions-migration), which all pass when re-run alone.
  • pnpm tc:node and pnpm tc:web are clean. oxlint on the changed files is clean, check:code-quality:changed passes, and audit:anti-slop, audit:code-quality:native and audit:code-quality:type-aware exit 0.

Not run locally:

  • The existing cross-version wire suites. This PR changes no wire shape and no host member an RPC handler calls. The new downgrade test was run locally and passes, and is now in the cross-version CI job's file list (the sharded unit job excludes that folder, so it would otherwise never run).
  • Electron and mobile. The only UI-visible change is refusal text; the create retry was reproduced live before the fix (the chat stayed on "Chat connection could not be confirmed"), but the fix itself has not been re-run in Electron.

Review

Mixed versions and persisted data:

  • Host-only. No wire change.
  • Older records load. Legacy settlementRetryRequired, settlementRetryId and processlessAt fields are ignored, and dropped when the store loads. conflicted stays a valid value and manual-recovery loads as recovering, so these records still load, and startup re-derives them from the recorded owner. Older builds accept recovering, so a record written back after that mapping still loads after a downgrade.
  • Downgrade. Records written by this build carry only fields and values older builds accept. A released lease with no death evidence has always been a valid shape.
  • Stale latch. Dropping the legacy fields at load means a record this build writes back can never carry an old latch to an older build.

Overlaps:

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.

Notes

  • Remote hosts. The execution host still owns every probe and signal. An owner recorded on another host probes indeterminate, so it is now released rather than waited on forever. Its lease no longer reads as exited.
  • Linux orphan after a crash mid-start. A reservation whose token scan finds a live child still carrying its token is released without signalling that child. It lost its stdio with the Orca that crashed, and Codex exits within 45 seconds of stdin closing. The orphan reaper runs once when the store opens, while the lease still claims that token, so it does not stop the child on that launch.
  • One state that never clears (same as the base). A terminal agent an older build recorded with no process start time, whose pid was later reused by another process, on macOS: the probe cannot tell the new process from the terminal agent, so the chat waits for it forever. The refusal names the process only when a start time was recorded, so it never points at a reused pid. The way out is a new chat.
  • A failed first start that could not prove its child gone, with no process recorded (for example a Claude start whose cleanup could not confirm the child stopped). Its operation settles failed and the lease is released with no evidence, so it reads unverifiable. The client treats that as "may have started" and keeps retrying the same operation id, which replays the failure, so the chat shows "Chat connection could not be confirmed." until the row expires about 24 hours later; the retry then continues as above. On the base the same chat stayed in manual recovery. Ways out today: close the tab (this also discards the unsent first message), open a new chat (until Orca restarts, New tab may rejoin the stuck launch instead, also on the base), or wait out the ~24 hours. While its row is kept, a failed operation only replays its failure under its old id; only once the row has aged out does a retry of that id, like any expired one, continue when nothing holds the lease. This is removed by the planned split of creating a chat from starting its agent: once a create no longer starts the agent it cannot fail on a start, and a failed start becomes a rejected message with an error row that the next send retries under a new operation.
  • Folder workspaces. Not affected.

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)
  • 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)

Author X handle: @BrennanKB5

@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.

Caution

Attaching or holding a chat whose lease is conflicted and names a live owner now throws RangeError: Maximum call stack size exceeded in the main process from a self-recursive refusal-message helper. Reproduced by calling structuredAgentSessionRefusalMessage('agent_session_conflict', record) directly on a conflicted record that has an ownerProcess.

Reviewed changes

  • Settlement latch removed — settlementRetryRequired / settlementRetryId are deleted; the terminal settlement a dead generation owes is now derived from the journal plus the lease's death evidence at the next acquire or read restore, and the retry module and its phase are gone.
  • Ownerless reservations released — restart adjudication and failed-acquisition settlement now release a reservation that recorded no process, carrying death evidence only when a spawn-token scan proved nothing spawned.
  • Recovery always concludes — resolveStructuredSessionRecovery evicts on proof, stops a same-host live owner by identity then evicts, and otherwise releases without sending a signal; a conflicted claim stays unresolved only while its owner is proven alive.
  • Codex records its pid at spawn — onSpawned commits the child's identity before the initialize handshake, so a crash mid-start leaves a stoppable owner, and the later identity commit is now an equality check.
  • Retired fields dropped at load — processlessAt and the settlement latch fields are stripped by the store transaction queue and removed from the lease type and validator; manual-recovery maps to recovering.

⚠️ A conflicted owner that cannot be verified is released, against the stated policy

resolveStructuredSessionRecovery returns 'unresolved' for a conflicted claim only inside the isProvenAliveProbe branch (lines 57-60). When the probe is indeterminate, the conflicted claim falls through to releaseUnprovenAgentSessionOwner (lines 64-71), which accepts claimStatus: 'conflicted' and clears the lease with deathEvidence: null. Before this change a conflicted claim was never evicted without proof of its named owner's death. The head comment says a conflicted claim "is waited out and never stopped: it is the user's own agent, and its exit is its way out" — but the indeterminate branch releases it instead. A terminal agent's transport is the user's terminal, which did not die with the crashed Orca runtime, so unlike the native-child case the "nothing can drive it" argument does not apply, and the next attach can resume the same provider thread while the terminal may still be writing. The PR description's table does say this release is intended, so this is likely a deliberate tradeoff against the stuck-chat bug; if so, please make the function's head comment and the shared reasoning say that explicitly, since this is the one branch where it does not hold.

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

}
}
mutations.push(...runningTurnLifecycleRevisions(items, verdict))
if (verdict.state === 'interrupted' && items.some(isInProgressItem)) {

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 replacement for retryLoadedStructuredAgentSessionSettlement only revises lifecycle rows. The deleted retry also retired unsettled submissions via markPendingSubmissionsUnknown, and it gated the "provider stopped while this response was in progress" row on unfinishedStructuredAgentSessionWorkWasInterrupted(...), which is true when an unsettled submission exists. The read/reveal path never opens through attachJournal — the one remaining caller of markPendingSubmissionsUnknown — so a send left pending by a crashed provider is now neither retired nor given the outcome row.

Technical details
# Stale settlement drops the submission dimension

## Affected sites
- `src/main/native-chat/agent-session-wire/structured-agent-session-dead-generation-settlement.ts:213-253` — writes no submission mutation; the status row at line 234 is gated on `items.some(isInProgressItem)` alone.
- `src/main/native-chat/agent-session-wire/structured-agent-session-restart-restore.ts:84` — the read restore calls this without ever going through `attachJournal`.
- Compare deleted `retryLoadedStructuredAgentSessionSettlement` (diff lines 1798-1928): `settleStructuredAgentSessionDeadGeneration` called `markPendingSubmissionsUnknown` / `rejectPendingSubmissions`, and `showUnexpectedExitOutcome` used `unfinishedStructuredAgentSessionWorkWasInterrupted`.

## Required outcome
- A crashed provider's unanswered send is retired on the read/reveal path too, and an observed exit that interrupted an in-flight send still earns the outcome row.

## Suggested approach (optional)
- Reuse `unfinishedStructuredAgentSessionWorkWasInterrupted(captureUnfinishedStructuredAgentSessionWork(journal), journal, verdict.completedAt)` for the status-row gate, and call `markPendingSubmissionsUnknown` here — or state explicitly that submissions are retired only at attach.

## Open questions for the human (optional)
- Is `attachJournal` the intended single choke point for retiring submissions, making the read/reveal gap acceptable?

@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.

ℹ️ Test-only follow-up commits; no new production changes. The blocking finding from the prior review — the self-recursive ownerDescription for a conflicted owner — is untouched by these commits and still applies.

Reviewed changes (delta since the prior review at ea2de58)

  • Mid-turn-at-quit coverage — structured-agent-session-wedged-profile-migration.test.ts now pins that a chat mid-turn when the app quit reopens with no running turn and no published working status, for both an observed exit that could not be settled and a probe-proven death.
  • Attach before the boot sweep — a new case pins that a restart eviction is settled through an attach that arrives before the read-restore sweep.
  • Cross-version downgrade test — new tests/e2e/cross-version-wire/agent-session-unproven-release-downgrade.unit.test.ts writes an unproven release with this build, then opens it with the pinned v1.4.211 record store and proves it loads, reconciles, and can reserve a new owner over it.

The new assertions look like they can fail against the old behavior (the mid-turn cases check the settled turn state and that no working status is published; the downgrade case checks isSessionUnreadable and a successful reserveOwner on the baseline store). Note the PR body still lists the cross-version suites as not run locally, so CI is the first real execution of the downgrade test.

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 in the new commits. The prior self-recursion finding is fixed, and the conflicted-owner recovery path now matches its stated policy.

Reviewed changes (delta since the prior pullfrog review at 78e98b2)

  • Self-recursive refusal helper fixed — ownerDescription no longer carries a conflicted-owner branch that interpolated itself; the conflicted sentence lives only in latchedMessage, so rendering a refusal for a conflicted owner returns a string instead of overflowing the stack. structured-agent-session-legacy-handoff-record.test.ts now asserts the refusal names the process to quit.
  • A conflicted owner recovery cannot verify is now waited out — resolveStructuredSessionRecovery returns unresolved for any conflicted claim with a recorded owner whose probe is not proven dead, including indeterminate, rather than releasing it; the head comment and the claim-status docs now say so explicitly. structured-agent-session-wedged-profile-migration.test.ts pins the refusal and that a later pid-absent probe lets the chat take over.
  • Cross-version downgrade test wired into CI — the new agent-session-unproven-release-downgrade.unit.test.ts joins the cross-version job's file list, and src/shared/agent-session-record joins the cross-version wire prefixes so record changes trigger that job.

The three changed test files run green (29 passed). One prior thread remains open and is untouched by this delta: the settlement replacement at structured-agent-session-dead-generation-settlement.ts:234 still does not retire pending submissions on the read/reveal path. It is 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 in the new commits.

Reviewed changes (delta since the prior pullfrog review at 8653aa4)

  • Retired manual-recovery stage mapped at decode — normalizeLegacyHandoffLease now maps manual-recovery to recovering through a shared isLegacyHandoffStage helper, AgentSessionHandoffStage is narrowed to 'new-owner-proving' | 'recovering', and leaseCarriesLegacyHandoffValues marks such records for write-back. On-disk validation still accepts manual-recovery (isPersistedAgentSessionHandoffStage), so an older record still loads and a record this build writes back can no longer carry the retired latch to an older build.
  • Dead manual-recovery branches deleted — the acquisition refusal, the lease-renewer skip, releaseUnprovenAgentSessionOwner's stage check, and the structuredAgentSessionOwnerStatus "manual recovery is required" answer (with its phase: 'failed' reply) could only ever see that stage, so they are gone. Every in-memory consumer already treated recovering and manual-recovery identically, so the mapping is behavior-preserving.
  • Orphan-reaper comment corrected — adjudicateAgentSessionRestart's comment no longer claims the store-open reaper stops a live token-carrying child on that launch; it now matches the PR's stated behavior that the reaper runs while the lease still claims the token.

The one open prior thread at structured-agent-session-dead-generation-settlement.ts:234 (the read/reveal settlement path does not retire pending submissions) is untouched by these commits and is 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 in the new commits. The retry-continuation path and the unified terminal-owner refusal are covered by store-level and host-level tests, and the fence/token compare-and-swap still holds.

Reviewed changes (delta since the prior pullfrog review at 371462a)

  • A create retried after recovery released its reservation continues — commitAgentSessionReservation now derives a continued request when the lease is released and, under the same operation id, re-reserves at the next fence for both a still-pending replay row and an already-expired (pruned) one. A late spawn from the old reservation is refused at its fence and by token, and a further retry while the new reservation stands re-enters it rather than spawning again. pendingAgentSessionOperationRow is factored out of evaluateAgentSessionOperation, and new store-level plus host-level tests pin both row states.
  • One refusal message for a terminal-owner claim — terminalOwnerRefusalMessage is now the single wording for a conflicted claim, shared by the refusal-message helper, the mutation envelope, and hold/resume, so sending and opening a chat an older build's terminal agent holds both say to quit that process.
  • Small cleanups — isResumableStructuredAgentSessionRecord delegates to agentSessionLeaseIsReleased, and the refusal helper's now-dead settlement-latch branch is removed.

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

A failed exit settlement no longer leaves the lease in recovery: the release
writes no stage and keeps the exit in its death evidence, and whatever the dead
generation left running is settled from that evidence at the next acquire or
read restore. The settlement retry flag, its disposition and every branch that
read it are gone. A reservation that recorded no process is released at
startup and after a failed start, the never-written conflicted status and the
processless proof are deleted, recovery resolution always concludes, and Codex
records its child's identity at spawn, before the handshake.
…d of recursing

Opening a chat whose terminal owner an older build recorded threw a stack
overflow instead of the refusal that names the process to quit.
…stead of releasing it

A terminal agent an older build recorded keeps its PTY across an Orca
restart, so a probe that cannot answer (a start-time read that fails on a
loaded host) is not evidence its transport is gone. Releasing it let a
native child resume the same conversation beside the live terminal agent.
Only proof of its exit now ends the claim.
The sharded unit job excludes tests/e2e/cross-version-wire, and the
cross-version job runs an explicit list that did not name the new test,
so it never ran in CI. A change to the record validator now also starts
the job.
…ering at decode

Nothing in this build writes manual-recovery, and restart reconciliation
already rewrites it. Mapping it where the other retired handoff stages are
mapped removes it from the in-memory lease type and deletes the branches
that could only see it: the acquisition refusal, the renewer skip, the
unproven-release stage check, and the handoff-status 'manual recovery is
required' answer. Older builds accept recovering, so a record written back
still loads after a downgrade.
…rvation leaves

The reaper runs once at store open, while the unreconciled lease still
claims the child's token, so it does not stop that child on this launch.
The comment claimed it did.
…ts reservation

The client retries a create it never heard back from under the same operation id.
Recovery had released that create's reservation, so the retry was refused
agent_session_ownership_unknown while its row was pending, and
agent_session_operation_expired once the row aged out, and the chat never started.
A retry whose lease nothing holds now continues as a fresh reservation at the next
fence, which also stops the old reservation's spawn from committing.
…rminal agent holds

A chat held by a terminal agent an older build recorded frees only when that agent
exits. Sending said to reopen the chat and opening it said two runtimes claimed
it; both now say the chat is open in a terminal agent, name its process, and say
to quit it. Error codes are unchanged.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/chat-latches-die branch from 6ee8ae9 to 3e65466 Compare September 25, 2026 18:30
@brennanb2025
brennanb2025 changed the base branch from brennanb2025/remove-tui-handoff to main September 25, 2026 18:31
@coderabbitai

coderabbitai Bot commented Sep 25, 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: 54582154-2031-435e-a1d6-bc7044ee3aee

📥 Commits

Reviewing files that changed from the base of the PR and between a407acb and cf40fa4.

📒 Files selected for processing (1)
  • src/main/native-chat/agent-session-wire/structured-agent-session-crash-mid-start.test.ts

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


📝 Walkthrough

Walkthrough

The changes revise structured agent-session ownership and recovery. Codex acquisition records a spawned process identity before the handshake. Recovery releases certain ownerless or unproven leases and removes settlement-retry state from lease records. Stale journal state is settled during acquisition and restoration using available death evidence. Operation admission can continue eligible retries after recovery releases a reservation. Tests cover these flows and add a cross-version downgrade check.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to cf40f

An unrelated expired request can start a new agent after a lease is released. Restrict continuation to the operation that held the reservation before merging.

Security Architecture Review

Security architecture risk: 🟠 High · up to cf40f

An interrupted structured chat can become usable again, but recovery may permit a new agent to start while the previous agent process is still present. That could undermine the guarantee that only one agent acts on a conversation. The affected chat mode is described as optional and off by default.

Retained concerns

  • High · security · inferred: Recovery can clear a recorded owner's lease without proving the owner has exited, then admit a new owner for the same conversation. Store fencing does not by itself establish that the old process has stopped acting outside the store.
Security review details

Security Blast Radius

  • inferred — The independently evidenced scope is an affected structured conversation and agent processes acting with that application's existing authority. A tenant-wide, remote-entrypoint, or cross-service expansion is not established.

Security Findings and Attack Paths

  • inferred — After a restart or interrupted acquisition, a client able to resume the conversation can obtain a new reservation after recovery releases the old one, even when the recorded process remains identity-matched. Overlapping agent actions depend on whether that old process can still perform work; this was not demonstrated.

Trust Boundaries and Controls

  • observed — The probe distinguishes PID absence from a matched or indeterminate identity, and avoids treating an unprobeable remote PID as locally dead. Nevertheless, the resolver can release an indeterminate, non-conflicted owner; it waits for proof of exit when the claim is conflicted.

Resilience and Maintainability Implications

  • observed — The stop ladder requests TERM and then KILL and reprobes, but returns its final result even when the recorded identity still matches. The release path records no death evidence in that case, preserving uncertainty about the old process.

Hardening Proposals

  • proposed — Before admitting a replacement, require proof that a recorded owner can no longer act, or an independently enforced revocation of its authority. Keep a distinct blocked recovery state when neither condition can be established, including after the stop ladder.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.14% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 51 functions across 50 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and clearly describes the primary change: preventing native-chat lease latches from remaining permanently stuck.
Description check ✅ Passed The description is comprehensive and covers scope, user-visible behavior, implementation details, rationale, testing, compatibility, visual proof, and checklist status. The Linked Issue section does n…
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.
  • 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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready for merge review

Head a222f66777, based on main (#22783 has merged; this branch was replayed onto main with no conflicts, and its diff is unchanged). CI: all green (27 pass, 4 skipped by design); mobile web app bundle needed two re-runs, failing on two different render-timing tests that also failed on an unrelated PR at the same time, and this PR changes no mobile or renderer code.

What the review did

  • Six review loops. Loops 1, 2 and 5 fixed defects, loop 3 fixed a CI lint failure, loops 4 and 6 were clean confirming passes, and a separate architecture review concluded the approach is right (keep it, with small refinements, all applied).
  • Readiness checks at the start and the end: both passed with no P0/P1. The end check's two P2s are fixed (below).
  • Live Electron QA in an isolated dev build on macOS, base vs this PR, with before/after screenshots.

Fixes pushed during review

  • A refusal message for a chat held by an older build's terminal agent called itself forever and threw instead of showing; fixed and tested.
  • A terminal agent recorded by an older build whose identity could not be verified was released, which could put a second agent on a conversation that terminal agent was still writing. It is now waited out until it is proven gone.
  • The retired manual-recovery stage is mapped to recovering when a record loads, deleting the branches that could only see it. Older builds accept recovering.
  • The new downgrade test (an older build reading a release this build writes) now runs in CI.
  • Found only by live QA: a chat that Orca was killed while creating stayed stuck even though its lease was released, because the app retries the create under the same request id and the host refused a retry whose reservation recovery had released. That retry now continues as a fresh reservation, whether the request is still pending or has expired. Tests prove one request id never produces two live agents and that the old reservation's late spawn can never commit.
  • Sending, opening and resuming a chat a terminal agent holds now all say the same thing: the chat is open in a terminal agent, quit it to continue. The process id is named only when a start time was recorded, so it never points at a reused pid.

Live QA (isolated dev build, macOS)

Scenario Base This PR
Orca killed while a Codex chat is starting, then relaunched stuck: "Chat connection could not be confirmed.", no send or Retry ever starts an agent Retry starts a fresh agent, it replies, and the chat keeps working after a clean restart
A profile the base left stuck, opened with this build — Retry starts the agent and it replies
This build's profile opened with the base (downgrade) history intact, chats reply —
Orca killed mid-reply, then relaunched reply shown ended, next send works same
New Codex and Claude chats, clean restarts, tabs, console — pass, no console errors, no duplicate tabs

Before (base), relaunched after a kill mid-start:

After (this PR), Retry starts the agent and it replies:

After a clean restart, the chat still works:

Base-stuck profile upgraded to this build, Retry replies:

New Claude chat on this build:

The QA re-run tested 6ee8ae9e34, the head before the replay onto main; the PR's diff is unchanged by the replay, and the later commit only changes the terminal-agent message text.

Validation

  • Unit and host suites for the lease, recovery, store, Codex and Claude session areas pass (the only local failures are known environment cases: real-CLI tests and one test that needs an unset shell key; one load timeout passes alone).
  • Both typechecks, oxlint on the changed files, the changed-code quality gate and the three static-analysis audits pass.
  • Ablations: deleting each core change turns its tests red for the right reason (released-reservation retry, ownerless reservation release, the refusal text).

Not covered

  • Stopping a still-running orphan by identity could not be reached live on macOS: a supervisor already kills the agent when Orca's main process dies. Unit and host tests cover it.
  • Linux, Windows, WSL and SSH hosts were not run live. The PR changes no wire shape and no remote-facing code.

Known residuals (listed in the PR Notes, none new to users)

  • A Claude chat whose first start fails before its process is recorded, with a cleanup that can't prove the process stopped, shows "could not be confirmed" for about 24 hours (then Retry works). Ways out: close the tab, a new chat, or wait. It is removed by the planned split of creating a chat from starting its agent. The base left this chat stuck for good.
  • A terminal agent an older build recorded without a start time, whose pid was later reused, waits forever (same as base). The way out is a new chat.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Ready to merge

Checked at head a222f66777: mergeable with a clean merge state against current main, 27 checks pass, 4 skipped by design.

  • Scope: matches the planned change. It covers every lease latch that could strand a chat, plus the retry of a create whose reservation was released, which is part of the same fix. It touches only the structured chat (see "Scope" above). The default chat view and terminals don't change.
  • Review: six loops, a separate architecture review that kept the approach, and readiness checks at the start and end with no P0 or P1. Both P2s are fixed.
  • Live QA: the stuck chat from a kill during create now recovers with Retry, a profile the base left stuck recovers once upgraded, and a downgrade keeps history intact.
  • mobile web app bundle: needed re-runs. It failed on render-timing tests that were failing across other PRs at the same time, and this PR changes no mobile or renderer code.
  • Residuals (listed in Notes, none new to users): a Claude chat whose first start fails before its process is recorded shows "could not be confirmed" for about 24 hours. That goes away when creating a chat stops starting its agent, which is the next planned change.

…ches-die

# Conflicts:
#	src/main/runtime/claude-structured-session-integration.test.ts
…ches-die

# Conflicts:
#	src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-host.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 756b63e8-40e9-4ddc-84b4-5fcdf3736fbe

📥 Commits

Reviewing files that changed from the base of the PR and between 1c2cf12 and a407acb.

📒 Files selected for processing (76)
  • .github/workflows/pr.yml
  • config/scripts/pr-code-change-scope.mjs
  • src/main/claude/claude-context-usage-restart.test.ts
  • src/main/claude/claude-structured-session-state.ts
  • src/main/codex/codex-app-server-connection-types.ts
  • src/main/codex/codex-app-server-connection.test.ts
  • src/main/codex/codex-app-server-connection.ts
  • src/main/codex/codex-structured-owner-identity.ts
  • src/main/codex/codex-structured-session-acquire.ts
  • src/main/codex/codex-structured-session-close.test.ts
  • src/main/codex/codex-structured-session-close.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-acquisition-options.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-acquisition.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-crash-mid-start.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-dead-generation-settlement.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-failed-create-owner-verdict.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-hold-resume.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-lease-release.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-lease-renewer.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-legacy-handoff-record.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-owner-status.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-processless-reservation.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-readable-restorer.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-readable-restorer.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-recovered-turn-clock.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-recovery-exits.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-refusal-message.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-restart-restore.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-restart-restore.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-resume-eligibility.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-reveal.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-reveal.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-send-preparation.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-settled-attach-retry.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-surface-lifetime.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-wedged-profile-migration.test.ts
  • src/main/observability/agent-session-instrumentation.ts
  • src/main/observability/instrumentation.test.ts
  • src/main/runtime/agent-session-acquisition-failure-settlement.ts
  • src/main/runtime/agent-session-eviction-settlement-latch.test.ts
  • src/main/runtime/agent-session-lease-transitions.ts
  • src/main/runtime/agent-session-process-identity-probe.ts
  • src/main/runtime/agent-session-processless-reservation.ts
  • src/main/runtime/agent-session-record-store-legacy-handoff-lease.test.ts
  • src/main/runtime/agent-session-record-store.test.ts
  • src/main/runtime/agent-session-record-store.ts
  • src/main/runtime/agent-session-released-reservation-replay.test.ts
  • src/main/runtime/agent-session-reservation-admission.test.ts
  • src/main/runtime/agent-session-reservation-admission.ts
  • src/main/runtime/agent-session-restart-lease-transitions.ts
  • src/main/runtime/agent-session-store-transaction-queue.ts
  • src/main/runtime/agent-session-surface-release-transition.ts
  • src/main/runtime/claude-structured-session-integration.test.ts
  • src/main/runtime/structured-agent-session-owner-probe.ts
  • src/main/runtime/structured-agent-session-runtime.test.ts
  • src/main/runtime/structured-claude-runtime-adapter.ts
  • src/shared/agent-session-lease-adjudication.test.ts
  • src/shared/agent-session-lease-adjudication.ts
  • src/shared/agent-session-legacy-handoff-lease.test.ts
  • src/shared/agent-session-legacy-handoff-lease.ts
  • src/shared/agent-session-mutation-envelope.ts
  • src/shared/agent-session-operation-ledger.ts
  • src/shared/agent-session-record.ts
  • tests/e2e/cross-version-wire/agent-session-unproven-release-downgrade.unit.test.ts
💤 Files with no reviewable changes (10)
  • src/main/runtime/agent-session-processless-reservation.ts
  • src/main/runtime/structured-claude-runtime-adapter.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-owner-status.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.test.ts
  • src/main/runtime/agent-session-eviction-settlement-latch.test.ts
  • src/main/claude/claude-structured-session-state.ts
  • src/main/runtime/structured-agent-session-runtime.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.ts
  • src/main/observability/agent-session-instrumentation.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-processless-reservation.test.ts

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

Comment on lines +62 to +69
await (owner && !isProvenDeadProbe(probe)
? deps.store.transitionHandoff(sessionId, (latest) =>
releaseUnprovenAgentSessionOwner({
record: latest,
expectedFence: record.lease.runtimeFence,
now: deps.now()
})
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- changed file diff ---'
git diff --unified=80 1c2cf120e32fca765b8313def90647c013c9c113 a407acbc0c0692103a71e173a6628ed145af4467 -- src/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.ts
printf '%s\n' '--- target file ---'
cat -n src/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.ts
printf '%s\n' '--- recovery symbols ---'
rg -n -C 5 'stopOwnerAndReprobe|releaseUnprovenAgentSessionOwner|isProvenDeadProbe|identity-matched|unresolved' src/main/native-chat src/main | head -n 300
printf '%s\n' '--- provider/process symbols ---'
rg -n -C 5 'stdin|SIGKILL|spawn|Codex|Claude|close|EOF|tool execution|tool_use' src/main/native-chat src/main | head -n 400

Repository: stablyai/orca

Length of output: 42136


🤖 get_repo_knowledge executed:

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

Length of output: 35265


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- relevant files ---'
git ls-files | rg '(^|/)(agent|runtime|native-chat|claude|codex|provider|process|child|lease).*\\.(ts|tsx|js|mjs)$' | head -n 400
printf '%s\n' '--- release transition and lease adjudication ---'
rg -n -C 12 'function releaseUnprovenAgentSessionOwner|releaseUnprovenAgentSessionOwner|type AgentSessionOwnerProbe|isProvenAliveProbe|isProvenDeadProbe|ownerProcess' src/shared src/main/runtime src/main/native-chat
printf '%s\n' '--- provider launch and stdin lifecycle ---'
rg -n -C 10 --glob '*.{ts,tsx,js,mjs}' '(spawn|spawnSync|fork|execFile|stdin\\.end|stdin\\.destroy|\\.stdin|SIGTERM|SIGKILL|on\\(['\"'\"'](close|exit|error)|process\\.kill|kill\\()' src/main src/shared | rg -i 'codex|claude|agent|provider|runtime|child|stdin|spawn|kill|close|exit' | head -n 500
printf '%s\n' '--- direct provider name references ---'
rg -n -C 8 --glob '*.{ts,tsx,js,mjs,json,md}' '\\b(codex|claude)\\b' src/main src/shared | head -n 500

Repository: stablyai/orca

Length of output: 45661


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- release transition ---'
rg -n -C 20 'releaseUnprovenAgentSessionOwner' src/main/runtime src/main/native-chat src/shared
printf '%s\n' '--- files containing process creation ---'
rg -l --glob '*.ts' --glob '*.tsx' --glob '*.js' --glob '*.mjs' 'spawn\(|execFile\(|fork\(' src/main src/shared | sort | head -n 150
printf '%s\n' '--- files containing provider launch names ---'
rg -l --glob '*.ts' --glob '*.tsx' --glob '*.js' --glob '*.mjs' -i 'codex|claude' src/main src/shared | sort | head -n 200
printf '%s\n' '--- lifecycle references in native-chat and runtime ---'
rg -n -C 8 --glob '*.ts' '(stdin|stdout|stderr|process\\.kill|\\.kill\\(|\\.on\\("close"|\\.on\\("exit"|\\.on\\('"'"'close'"'"'|\\.on\\('"'"'exit'"'"')' src/main/native-chat src/main/runtime | head -n 500

Repository: stablyai/orca

Length of output: 33401


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- structured session files ---'
git ls-files src/main/native-chat/agent-session-wire src/main/native-chat | grep -E 'structured-agent-session|agent-session-wire' | head -n 250
printf '%s\n' '--- structured adapter and transport references ---'
rg -n -C 10 'adapter|dispatch|send|close|stdin|transport|child|process' src/main/native-chat/agent-session-wire src/main/native-chat/structured-agent-session* 2>/dev/null | head -n 700
printf '%s\n' '--- Codex/Claude structured process files ---'
rg -l --glob '*.ts' --glob '*.tsx' 'structured|app-server|query\(|spawn|stdin|close|kill' src/main/codex src/main/claude | sort | head -n 250
printf '%s\n' '--- exact close and stdin calls in provider directories ---'
rg -n -C 8 --glob '*.ts' --glob '*.tsx' 'stdin|stdout|stderr|process\\.kill|kill\\(|\\.close\\(|\\.end\\(|\\.destroy\\(|on\\(' src/main/codex src/main/claude | head -n 700

Repository: stablyai/orca

Length of output: 42763


🏁 Script executed:

#!/bin/bash
set -eu
for f in \
  src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts \
  src/main/claude/claude-structured-session-adapter.ts \
  src/main/claude/claude-structured-session-close.ts \
  src/main/claude/claude-structured-session-exit-lifecycle.ts \
  src/main/claude/claude-agent-sdk-process-spawn.ts \
  src/main/codex/codex-app-server-process-teardown.ts \
  src/main/codex/codex-app-server-posix-supervisor.ts \
  src/main/codex/codex-app-server-connection.ts
do
  if [ -f "$f" ]; then
    printf '\n--- %s (%s lines) ---\n' "$f" "$(wc -l < "$f")"
    cat -n "$f"
  fi
done
printf '\n--- targeted provider lifecycle text ---\n'
rg -n -C 8 'stdin|close|destroy|kill|SIGTERM|SIGKILL|turn|tool|exit|terminate' \
  src/main/claude/claude-structured-session-adapter.ts \
  src/main/claude/claude-structured-session-close.ts \
  src/main/claude/claude-structured-session-exit-lifecycle.ts \
  src/main/claude/claude-agent-sdk-process-spawn.ts \
  src/main/codex/codex-app-server-process-teardown.ts \
  src/main/codex/codex-app-server-posix-supervisor.ts \
  src/main/codex/codex-app-server-connection.ts \
  src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts

Repository: stablyai/orca

Length of output: 43212


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- released lease construction ---'
sed -n '248,275p' src/main/runtime/agent-session-lease-transitions.ts
printf '%s\n' '--- Claude process and close lifecycle ---'
rg -n -C 12 'createClaudeCodeProcessSpawn|stdin|close\\(|kill\\(|SIGTERM|SIGKILL|exit' \
  src/main/claude/claude-agent-sdk-process-spawn.ts \
  src/main/claude/claude-structured-session-close.ts \
  src/main/claude/claude-structured-session-exit-lifecycle.ts \
  src/main/claude/claude-structured-session-adapter.ts
printf '%s\n' '--- Codex EOF and forced teardown ---'
rg -n -C 12 'stdin\\.end|stdin end|terminateCodexAppServerProcessTree|SIGKILL|process group|1250|1500|close\\(' \
  src/main/codex/codex-app-server-posix-supervisor.ts \
  src/main/codex/codex-app-server-process-teardown.ts \
  src/main/codex/codex-app-server-connection.ts

Repository: stablyai/orca

Length of output: 1141


Keep an identity-matched survivor unresolved.

If stopOwnerAndReprobe still returns a proven-live identity match after SIGKILL, the current branch clears ownerProcess and releases the lease without death evidence. A later attach can then grant a new owner while the old process may still execute its current turn, causing concurrent file edits and token use. Keep this case unresolved, but retain release for an indeterminate probe.

🐛 Suggested fix
   if (owner && isProvenAliveProbe(probe)) {
     if (owner.hostId !== deps.store.hostId) {
       return 'unresolved'
     }
     probe = await stopOwnerAndReprobe(deps, record, owner.pid)
   }
+  if (owner && isProvenAliveProbe(probe)) {
+    return 'unresolved'
+  }
   try {

Source: Learnings

Comment on lines 324 to +330
if (decision.decision === 'refused') {
throw new Error(decision.code)
// An aged-out row proves nothing more: a released reservation runs no effect.
if (decision.code !== 'agent_session_operation_expired' || !continued) {
throw new Error(decision.code)
}
const row = pendingAgentSessionOperationRow({ ...request.operation, now: request.now })
return reserveWithOperationRow(state, continued, row, leaseTtlMs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C4 'handoffOperationId' src/main/runtime/agent-session-lease-transitions.ts src/main/runtime/agent-session-restart-lease-transitions.ts src/main/runtime/agent-session-processless-reservation.ts

Repository: stablyai/orca

Length of output: 6396


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- changed admission outline ---'
ast-grep outline src/main/runtime/agent-session-reservation-admission.ts
printf '%s\n' '--- admission relevant source ---'
sed -n '200,370p' src/main/runtime/agent-session-reservation-admission.ts
printf '%s\n' '--- lease transition source ---'
sed -n '1,290p' src/main/runtime/agent-session-lease-transitions.ts
printf '%s\n' '--- restart transition source ---'
sed -n '1,100p' src/main/runtime/agent-session-restart-lease-transitions.ts
printf '%s\n' '--- operation and admission references ---'
rg -n -C3 'agent_session_operation_expired|pendingAgentSessionOperationRow|commitAgentSessionReservation|handoffOperationId|operationId' src/main/runtime -g '*.ts'
printf '%s\n' '--- diff from supplied merge base ---'
git diff --unified=30 1c2cf120e32fca765b8313def90647c013c9c113 a407acbc0c0692103a71e173a6628ed145af4467 -- src/main/runtime/agent-session-reservation-admission.ts src/main/runtime/agent-session-lease-transitions.ts src/main/runtime/agent-session-restart-lease-transitions.ts

Repository: stablyai/orca

Length of output: 42435


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- lease schema ---'
rg -n -C8 'export type AgentSessionLease|handoffOperationId|claimStatus|deathEvidence' src/main/shared src/main/runtime -g '*.ts'
printf '%s\n' '--- operation ledger ---'
sed -n '1,260p' src/main/shared/agent-session-operation-ledger.ts
printf '%s\n' '--- release and reservation call sites ---'
rg -n -C5 'releaseUnprovenAgentSessionOwner|evictAgentSessionOwner|applyAgentSessionRestartAdjudication|commitAgentSessionReservation' src/main -g '*.ts'
printf '%s\n' '--- focused replay tests ---'
fd -i 'agent-session-released-reservation-replay' src
fd -i 'agent-session.*replay.*test' src
rg -n -C8 'expired|released|handoffOperationId|operationId' src/main/runtime/*released* src/main/runtime/*replay* 2>/dev/null || true

Repository: stablyai/orca

Length of output: 45663


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- locate shared sources ---'
fd -t f -i 'agent-session-(record|operation-ledger|lease-adjudication).*\.ts' .
printf '%s\n' '--- operation ledger definitions ---'
ledger=$(fd -t f -i 'agent-session-operation-ledger\.ts' . | head -n1)
if [ -n "$ledger" ]; then
  cat -n "$ledger"
fi
printf '%s\n' '--- handoff operation call sites ---'
rg -n -C5 'handoffOperationId' src -g '*.ts' \
  -g '!*.test.ts' \
  | head -n 500
printf '%s\n' '--- operation request call sites ---'
rg -n -C4 'operation:\s*\{|operationId:' src/main/runtime -g '*.ts' \
  -g '!*.test.ts' | head -n 500

Repository: stablyai/orca

Length of output: 41941


Bind expired continuations to the released operation.

The continued check only tests whether the session lease is released. It does not bind the request to the operation that created that reservation. After operation X is pruned, a retry of X can create a new pending row and reserve a session whose later reservation Y was released.

Preserve the released reservation's operation ID in a durable marker. Require that marker to equal request.operation.operationId before accepting an expired continuation. The current handoffOperationId cannot provide this marker after release because the release transitions clear it. Reject the continuation when the marker is absent or does not match.

@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 in the new commits.

Reviewed changes (delta since the prior pullfrog review at 6ee8ae9e34)

  • The terminal-owner refusal names a process only when its start time can identify it — terminalOwnerRefusalMessage appends (process <pid>) only when ownerProcess.processStartTimeMs is recorded, so a conflicted (legacy terminal) refusal never points at a pid that may since belong to an unrelated process. A new unit test pins both wordings, and the existing host test still holds because its lease carries a start time.
  • origin/main merged in — two merge commits bring the branch up to main (1c2cf120e3). They change no author production code; the PR's diff against main keeps its intended removals (owner-status manual-recovery branch, settlement-retry module, mutation-envelope wording).

The one previously-flagged open thread (structured-agent-session-dead-generation-settlement.ts:234) is untouched by these commits and remains open, so this review is not an approval.

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 in the new commits. The delta is test-only, and the changed test still passes and still pins the same behavior.

Reviewed changes (delta since the prior pullfrog review at a407acb)

  • Crash simulation no longer shares one store between generations — structured-agent-session-crash-mid-start.test.ts now gives each host generation its own directory. crash() flushes the dying store's queued writes (renewLeases([])) and copies its directory to the relaunch's root (excluding .tmp/.lock), so the dying host's still-pending in-process attach cannot race or write to the store the relaunched host reads. The spawn case's waitFor now also requires the durable ownerProcess, and the never-settling attach promises get a .catch(() => {}).
  • origin/main merged in — 8081df1206 is a base-only merge; the range-diff isolates no author production change.

The one previously-flagged open thread (structured-agent-session-dead-generation-settlement.ts:234) is untouched by these commits, so this review is not an approval.

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

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