Skip to content

fix(native-chat): a dead agent's leftover work never blocks the chat; it's settled in the background when its generation ends - #26867

Closed
brennanb2025 wants to merge 26 commits into
mainfrom
brennanb2025/chat-settle-at-ownership-events
Closed

brennanb2025 wants to merge 26 commits into
mainfrom
brennanb2025/chat-settle-at-ownership-events

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Sometimes a native chat's agent stops unexpectedly: Orca quits or crashes, the agent process exits, or Orca can't tell what happened to it. Something then has to tidy up what the agent left behind: the reply it was writing, its running tools, an approval it was waiting on, and messages on their way to it.

Today that tidy-up runs when you open the chat, and the chat decides whether the agent is "working" from the same rows the tidy-up is meant to fix. If the tidy-up can't be saved, or never runs, three things go wrong:

  • the chat looks like it's working forever;
  • queued messages never go out;
  • an old approval still looks answerable.

With this PR, opening a chat only reads. The tidy-up runs in the background as soon as Orca learns the agent stopped. The host decides "working" in one place, from who actually owns the chat right now. A failed tidy-up never blocks you and never makes the chat look busy.

What Changed

The problem

  • Cleanup sat on the path of opening a chat. It ran on open, on attach and after a new owner was reserved. Each of those is a write that can fail.
  • Every reader decided "working" from raw rows. Queue, Stop, prompt answers, session lists, desktop and mobile all read the journal rows directly, so a dead agent's leftovers held the queue and showed Working until a cleanup happened to succeed.
  • Restart bookkeeping blocked sends. If converting an earlier Orca process's unsent messages failed, every queued send was rejected, including this process's own.
  • A failed startup check was never retried until you sent a message.

QA reproduced this on main. With the database locked during a relaunch, a crashed chat showed Working for over 8 minutes, and a queued message behind a dead agent was never sent.

Before and after, as you see it

Before. After an agent died mid-reply:

  • the chat could stay Working, with Stop, until you sent something;
  • queued messages didn't send;
  • the dead agent's approval still looked answerable;
  • a failed restart bookkeeping step refused fresh messages too.

After. Once Orca knows the agent stopped:

  • No more Working or Stop, even while the tidy-up is still retrying.
  • Queued messages send on their own. If saving keeps failing for about three minutes, the card shows main's "Couldn't send — press Send to retry".
  • The cut-off reply is labelled honestly. It reads interrupted when Orca has proof the agent exited (it saw the exit, or a new server replaced the old one), and "can't verify" otherwise. Partial text stays, and "Worked for" ends at the last time Orca proved the agent alive, as on main.
  • Answering a gone agent is refused plainly, for example "Claude has stopped, so your answer was not sent. Send a message to continue."
  • The app stays responsive while another program holds the database: background cleanup gives up at once and retries a second or two later instead of waiting 5 s.

There's no new UI.

How it works

  1. One view of current work.
    • Each journal item records which agent generation produced it.
    • One host projection (structured-agent-session-current-work.ts) decides what is current from three things:
      • the lease (who may act now);
      • the exits this host saw;
      • that provenance.
    • Every host reader builds it the same way, including whether this process holds a live agent for the chat. So a send, Stop or prompt answer acts on exactly what the chat shows.
    • An owner nobody has confirmed since a restart reads "can't verify" and not working, with no write. Whether a send may take over from it stays where main has it: start reconciles, resolves recovery, then runs the ownership check.
    • Desktop and mobile read two new optional fields the host publishes, working and actionablePromptIds, and fall back to today's logic against an older host.
  2. Death is recorded first. When an agent exits, the host records and publishes that before it writes anything else, so no update shows a stopped agent as working.
  3. Cleanup happens when a generation ends, in the background.
    • Every lease write that ends a generation emits one signal after commit: release, eviction, failed start, restart adjudication, and replacing a proven-dead owner. So does an exit whose release couldn't be written.
    • One retry coordinator per database connection keeps the set of chats that still owe work, with:
      • one timer;
      • one backoff (1 s, then 2 s);
      • one time budget (about 3 minutes).
    • Each visit re-derives what is owed:
      • the startup ownership check;
      • a failed release;
      • the dead generation's items, in one transaction;
      • an earlier process's unsent messages, turned into cards;
      • the queue's next automatic send.
    • When the budget runs out, it stops but keeps the owed set. The next trigger starts a fresh budget: an agent ending, an open, a send, or any successful write, which is how a lock clearing shows up. No retry state is written to disk.
  4. Background writes fail fast. The coordinator's and the automatic send's transactions run with SQLite's busy timeout at 0, restored afterwards. A person's own writes keep the normal 5 s wait.
  5. Opening a chat writes nothing. Everything open used to write moved to the coordinator, to startup, or to the first real write.

Merged with #26460 (replaced-server detection). Main proves a turn interrupted when a new server instance replaced the one that ran it. This PR keeps that detector and folds its verdicts into the one cleanup path:

  • the projection treats a replaced runtime's generations as ended, without writing;
  • the coordinator writes the settlement;
  • main's settles at open and at start are removed.

Readers. Queue hold, admission and drain, Stop and cancel, prompt answers, turns and commands, session status and Working, delivery and subscribers, the idle sweep, the orchestration mailbox, desktop and mobile all read the projection. A few read raw rows on purpose: whether this process accepted a send, cache keys, and the "worked for" timer. The full list is in the review notes.

Startup cost (real SQLite, every owner dead, about 200 rows per chat): every chat's first pass takes 245 ms at 100 chats and about 1.65 s at 1000. A send issued during the scan takes 3–5 ms, and the worst event-loop lag is about 43 ms.

Why

The common pattern settles an agent's leftover work when its generation ends: when the agent exits, or when a new host instance starts. It retries failed release records with capped backoff, and derives startup recovery from state rather than from a saved "settled" receipt. This PR follows that.

Opening a chat isn't an ownership event, so cleanup on open was both late and in the user's way.

Alternatives considered:

  • Rejected: keep cleanup on open and catch its error (the chat stays wrong); block start until cleanup succeeds (bookkeeping gates the user).
  • Rejected: a table of closed owners (feat(native-chat): keep the proof that an agent is gone after the next owner starts #26667), or a stored "settled" marker. Leftover work would still need the projection, and a wrong marker would be skipped at every startup.
  • Rejected after review: separate retry loops per chat, per startup check and per queued card. Reviews kept finding bugs between them. One coordinator removed that class.
  • Rejected after review: holding the queue while an owner is unconfirmed. It held a person's own send as a card that nothing would send, and main never held there. Instead, every reader reads one projection, and start decides the owner, as on main.

Differences from the common pattern and from main

  • INTENDED: "interrupted" needs proof of exit; otherwise "can't verify". Orca's agents can outlive the app and run over SSH.
  • INTENDED: current work is derived, not written, and one cleanup transaction covers every leftover kind.
  • INTENDED: startup replays journals in the background. It never stops an agent that survived; that stays with restoring visible tabs, attach and start, as on main.
  • INTENDED: the queue's automatic send waits out a locked database quietly, and shows "Couldn't send" only after the coordinator gives up. Main showed it on the first failed write.
  • INTENDED: background writes don't wait for a lock; a give-up lasts one episode; a chat busy with a person's action is retried shortly rather than queued behind them.
  • INTENDED: the restart heal for a replaced server runs at startup, not on open. Open reads it as interrupted at once.
  • INTENDED, safer than main: cancelling a stopped agent's Claude question only dismisses it. Main stopped the chat's new turn too.
  • INTENDED: if a new chat's very first write fails, no journal is left behind. It's reported as unreadable history, as on main.
  • INTENDED, approved by Brennan: on the failure path, an older desktop or phone may still show stale Working and Stop, or a stale approval, which the host then refuses in plain words.
  • TEMPORARY: none.
  • Pre-existing, unchanged:
    • a crashed chat's status reads "Failed";
    • an earlier process's unsent card has no "Send now";
    • session history labels OMP chats "Pi";
    • a card behind a dead agent's turn reads Steer until cleanup lands;
    • an agent dying while another program holds the database can pause the app up to 5 s per output row still being saved (usually 0–3). QA saw a 15 s-or-longer freeze at that moment on both builds;
    • a send start can't reconcile reads "Orca ran into a problem, so this didn't go through. Try again.";
    • OMP's 300 s timeout message.

Linked Issue

Root-cause follow-up to #26664 (merged). Replaces cleanup on open. #26667 (closed-owner table) stays open for a decision.

Visual Proof

Hidden, isolated dev builds with a real OMP agent and a local fake model, driven over CDP. BEFORE is main at this PR's merge base (fff0bb0d065), AFTER is this PR. Another process held a write lock on the chat database to make cleanup writes fail.

S1. Orca crashes mid-reply, then relaunches while the database is locked for 25 s.

BEFORE: still "Working", with Stop, 2 minutes after the lock cleared AFTER: during the lock, no Working AFTER: 1 s after the lock cleared
S1 before S1 after locked S1 after released

On BEFORE it never settled without a user action. On AFTER the cleanup landed 0.22 s after the lock cleared, and 1 s screenshots across that moment never showed Working.

S2b. The agent dies during the lock with a message queued behind it.

BEFORE: still Working; the queued card never sends AFTER: the card sent itself 2.1 s after the lock cleared, and was answered
S2b before S2b after

Testing

  • I manually tested these changes locally (hidden isolated dev builds, driven over CDP by a separate QA agent)

  • Automated tests added/updated, or explained why not below

  • Live QA (BEFORE main vs AFTER):

    • S1: fixed. The worst main-thread stall during startup under the lock went from 9.5 s to 11 ms.
    • S2 and S2b: the card sends 1.5–2.1 s after the lock clears; on main it never sent.
    • A fresh send right after a relaunch goes out and is answered, on both.
    • A reply cut off by a restart keeps its text and reads interrupted, on both.
    • History rows are the same on both.
  • Not verified live:

    • a send to a chat whose agent survived the restart: the rig's startup restore always stopped the survivor first;
    • S4, the hidden-tab survivor at startup;
    • SSH, WSL and Windows.
  • Automated:

    • real-SQLite tests for every failure path above, plus the startup scan at 100 and 1000 chats;
    • cross-version wire tests (old client against new host and back);
    • CI is green on the merged tree: head 3b19224a296, synced with main at be4cea1584f.
  • Final main sync (two merge commits): main moved about 300 commits since the last review. Three conflicts, all resolved by keeping both sides:

    • main's shared subagent tracker stamps when a live host saw a session end; this PR narrows cleanup to the entries the ended agent ran. One function now takes both.
    • main's command receipts for queued-card actions and question answers now commit alongside this PR's background-write flag and its current-work turn scope.
    • nothing main added settles a turn, holds the queue or decides who owns an agent, so the one-owner rule is unchanged. Main's SSH change (keep SSH chat providers alive) only reads whether a chat holds a running agent.
    • After the sync: typecheck, the chat, RPC, agent hook, Claude, Codex, orchestration and cross-version suites all pass locally.
    • Main's newer commits kept adding lines to the message list, so one small follow-up commit keeps it under its line cap (no behaviour change).
  • Review: eight review rounds and two independent architecture challenges. The last challenge confirmed that every reader uses one projection, and that "may this send take over the agent" stays with start, as on main.

AI Disclosure

Review

This PR depends only on main. The review summary is in the comments.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • SSH and WSL: the execution host owns the lease, the journal, the proof and the coordinator. Losing contact writes nothing and is never treated as death.
  • Folder workspaces: they use the same session identity, and they're tested.
  • Remote wire: this adds optional snapshot fields only, with no new stream opcode. Older clients ignore them.
  • Persisted data: an optional ownerFence on items and entries, with no migration.

Author: Brennan Benson (@BrennanKB5).

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • 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)

…ership events, and open chats read-only

Opening a chat no longer writes: the leftover-work settlement, the subagent roster correction, the
pending-send marks and the queued-message repair move to the moments that prove an owner gone
(its observed exit, startup, a new owner). One settlement plans every category in one transaction.
…cution provenance

The host decides which turn, prompts and sends belong to the agent generation that can still act,
from the lease, its own observed exits and each item's owner generation. Every host reader and the
desktop and mobile chats use that view, so a dead generation's leftover rows never hold a send,
show Working, or take a prompt answer. A generation ending publishes the view and wakes queued
cards without a journal write, and only sends this process accepted are handed over.
…kground, once per chat

Every lease write that ends a generation (a release of any kind, an eviction, a failed start, a
restart's adjudication, a new owner over a dead one) signals one in-memory reconciliation worker per
chat after commit, as do an exit whose release could not be written and a late write from an ended
generation. The worker re-derives what is owed each attempt, repairs the release and settles the
work in one transaction, backs off up to 30 s on failure, and retires when nothing is owed. Startup
scans every known chat in the background. No user action waits on it, opening a chat writes
nothing, and the stored settled-at marker is gone.
…ftover work

- restart offer at quit scoped by the host's live child, not the saved lease
- queue pause after a restart derived from where the journal opened; the reopen-mark latch is gone
- re-hand of a released lease's proof removed; acquisition is not a trigger
- a journal that can never load, or a rewind only its provider can prove, is not owed
- quit no longer waits for the startup scan; a reader's open goes ahead of it
- the startup scan reads chats as the worker's own handle: never published, never closes a reader's
- the exit settles at the dead fence before the release, so late rows still land
- stop-note refresh frames carry the host's current work
- cancelling an ended agent's card only dismisses it; a stale cancel stops the live turn plainly
- the refusal names the agent; client readers route through the host's current work
…'s share is derived

- startup no longer resolves recovery: only the visible-tab restore, start and attach decide a
  recovering lease (as before this change), and their release signals the worker
- the startup share is derived on every pass from where this process first opened the chat,
  instead of an in-memory debt that a recovering lease could strand
… a stale card's Cancel matches main

- while a lease is in recovery only the release repair and the item settlement wait; unsent sends
  from an earlier process become cards at once, as on open before this change
- the reopen mark starts at this handle's floor in the current epoch
- a card an ended generation raised: a dismiss route dismisses it only; with no route a Cancel naming
  the live turn interrupts that turn, never the chat-wide Stop
- the answer refusal names the agent only when its agent stopped
…drain waits out storage contention

- a read that had to found its journal's epoch owes nothing; a read gone stale backs off instead of
  re-running at once
- an unreconciled lease is the worker's to reconcile again, with its backoff, so a failed startup
  reconcile no longer leaves a dead turn working until the next send
- the automatic drain starts nothing while an ended child still holds the lease, and retries a
  contended write quietly before main's failed-send hold
- parked debts keep only death evidence and die with the chat's record
…e names a card only when the drain would send it

- the drain's wait on an ended child's release dies with the worker, so a give-up never strands a card
- a failed restart reconcile is retried once for the whole store, with one backoff
- an exit account judges only the generation right after it
- the published next card honours the drain's own waits, so no frame reads Working over a settled turn
…tle-at-ownership-events

# Conflicts:
#	src/main/runtime/agent-session-record-store.ts
#	src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
…ver work

- an exit records the agent's death before anything it flushes or settles, so no frame reads its
  work as running
- one connection-scoped coordinator replaces the per-chat worker backoff, the store-wide reconcile
  retry and the queue's own retry timer; give-up ends an episode, and any new trigger or a
  successful commit starts the next
- background writes fail fast on a locked database instead of holding the main thread for the
  busy timeout; a person's writes keep it
- a queued card is delivered over a child this host saw end, through acquisition's own ownership
  check; one the coordinator gives up on shows the failed-send state even when that hold cannot be
  saved
… founding reads as an unreadable journal

- each chat's background writes wait their turn and yield before the next chat, so a person's
  operation queued meanwhile runs first
- the queue's reopen mark fails fast on a locked database like the other background writes
- a generation's end publishes a frame only when it changes what a reader sees
- a held epoch whose own row cannot be written is refused as an unreadable journal, as an eager
  founding was
…dles

- the exit's settlement and release, every coordinator visit and the queue's automatic send write
  through handles whose writes always fail fast on a locked database, so none can stall the app
- a refused automatic send whose hold cannot be saved still shows as failed
- contention is counted per round, a busy chat's lane is skipped rather than waited on, and the
  retry delay is capped at 2 s while work is owed
- removes the deleted worker's leftovers
…nterrupted before its cleanup lands

- the restore's reconcile, recovery resolution and tab-index seed write as background work, and
  the retry's reconcile resolves recovery the restore had to skip
- a turn whose agent this host saw exit reads interrupted, and the queued card offers Send, from
  the moment of the exit rather than once its cleanup is written
…e tabs a restart restored

- the retry gives up after about three minutes of failure rather than ten fast rounds
- recovery the restore could not finish is retried each round, only for the chats it was asked to
  restore, so a chat only read in the background never has its agent stopped
- the phone offers Send on a card when the host says nothing is running, like the desktop
…tests the property

- reverts the card's Send label on desktop and phone to main's; pressing Steer on an idle chat
  sends, as before
- the relaunch-under-lock test asserts no foreground transaction runs while locked, with a 100 ms
  bound
…und cleanup

- every source of owed work enters through one signal; one wake runs a round, from the backoff
  timer or a successful commit; the give-up is reset only by the first wake after it
- a stopped round keeps the journals it loaded instead of replaying them next round
- recovery the restore could not finish stays with the chats latched when it ran, and a latch no
  probe can decide, or a read-only store, owes nothing
…tle-at-ownership-events

# Conflicts:
#	mobile/src/session/use-mobile-structured-agent-session.ts
#	src/main/codex/codex-background-terminals.ts
#	src/main/native-chat/agent-session-journal/journal-queued-messages.ts
#	src/main/native-chat/agent-session-journal/journal-row-writer.ts
#	src/main/native-chat/agent-session-journal/journal-store-restore.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-conversation-open.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-crash-turn-end.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-host.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-queued-messages.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-wedged-profile-migration.test.ts
#	src/main/runtime/agent-session-record-store.ts
…get keeps wall time

- A lease still unreconciled or recovering that this process holds no child for reads its turn
  unverifiable and not working, as main did, with no write.
- The retry's give-up is wall time since the episode's first refused round; only a round that made
  progress ends the episode, and give-up drops loaded reads.
- Drop the unused settleStructuredAgentSessionDeadGeneration wrapper.
… about

What a chat shows and whether a card may be delivered are separate answers. The display reads the
projection's live generation; delivery reads the owner's adjudication, so an unreconciled or
recovering owner holds the queue (and reads busy to orchestration) as on main, while its turn
reads unverifiable and not working. The view key carries that state so subscribers republish when
recovery concludes.
… host's child

Admission, Send-now, steer, Stop, prompt answers and command admission built current work without
this host's child, so an owner no adjudication concluded about read working there and idle on the
display and in the drain. Every host reader now builds it in one place. The queue hold and the
orchestration idle gate read only that answer, as on main; whether a send may acquire stays with
start, which reconciles and resolves recovery first.
Conflict: journal-subagent-liveness.ts. Main (#27228) added `lostAt`, the
time a live host saw the session end; this branch added `lost`, which
narrows settlement to the entries the ended generation ran. Both now pass
as one options object, and each caller names what it supplies.

Merge-caused fixes:
- roster-provenance test: the Claude group row helpers moved with the
  shared subagent tracker (#27228).
- journal partition receipts (#27559): regenerated with the previous
  partitioner on this branch's row shape (each item row states its owner
  generation), which moves three chunk boundaries.
- line caps after main's additions: main's hasLoadedProviders (#26473)
  lives on the conversations map and the host delegates to it; one wire
  type and two navigation requests written on one line.
Main moved again during the sync (#26988: queued-message actions and
prompt answers accept through their own command receipt).

Conflicts:
- journal-queued-messages.ts: one options object carries main's receipt,
  the edit lease's `adopted`, and this branch's background write flag.
- turns-prompt.ts: the answer row's turn scope stays the host's current
  work projection; it now also commits main's operation receipt.
- agent-session-store-transactions.ts: main's commitReceipt (a person's
  write, normal wait) beside this branch's background-capable commit.

Merge-caused fixes: main's prompt-receipt test rebuilds the prompt with
the generation that raised it; record-store stays within its line cap.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review summary

Verdict: ready to merge. Eight review rounds, two independent architecture challenges, and live QA against main, all on the final head. Nothing is open.

What review changed in the design

  • Retries. The first build had three retry loops: per chat, per startup check and per queued card. Reviews kept finding bugs between them.
    • They are now one retry coordinator per database connection, with one timer, one backoff (1 s, then 2 s) and one budget of about 3 minutes.
    • When the budget runs out, the owed work is kept, and the next trigger starts a fresh budget.
  • Background writes no longer freeze the app. Cleanup writes made in the background fail at once against another program's lock, instead of waiting 5 s on the main thread. A person's own writes keep the normal wait.
  • Death is recorded first. An exit is recorded and published before any cleanup is written, so no update shows a stopped agent as working.
  • One view of current work. Two places built it differently: the send path didn't know whether this process still holds a live agent, and the display and queue did.
    • So a dead agent's leftover turn read as working when you sent, but idle on screen.
    • An attempt to patch this with a lease check on the queue was rejected. It held a person's own send as a card that nothing would ever send.
    • Now every reader builds the view from one constructor. Whether a send may take over the agent stays where main has it: start reconciles the owner, resolves recovery, then runs the ownership check.
  • Merge with fix(native-chat): settle a reply cut off by a server restart #26460 (replaced-server detection). The detector and its verdicts are kept, and folded into the one cleanup path. Main's settles at open and at start are removed; the restart heal runs at startup.

Verified

  • Live QA (BEFORE main at fff0bb0d065 vs AFTER), with a real OMP agent and another process holding the database lock:

    Scenario BEFORE (main) AFTER (this PR)
    S1: stale Working after a crash Never cleared on its own Cleared 0.22 s after the lock released
    S2 and S2b: queued card behind a dead agent Never sent Sent 1.5–2.1 s after release
    Worst stall during startup under the lock 9.5 s 11 ms
    • 1 s frames across the release moment never showed Working, and never flashed "Done" during the lock.
    • A fresh send after a relaunch, the cut-off reply after a restart, and the history rows all match main.
  • Automated tests:

    • real-SQLite tests for each failure path;
    • main-parity tests for the one-view fix, each failing on the commit before it;
    • cross-version wire tests;
    • CI green on the merged tree at 3b19224a296 (synced with main at be4cea1584f).
  • Final main sync. Three conflicts, each resolved by keeping both sides (main's subagent end time with this PR's per-agent narrowing; main's command receipts with this PR's background writes and current-work turn scope). Nothing main added settles turns, holds the queue or decides ownership.

  • First-hand checks of main. The queue hold never read the lease. Opening a chat wrote the leftover turn as "can't verify". A send in that state went to start.

Not verified

  • A send to a chat whose agent truly survived the restart. On this rig the startup restore stopped the survivor first, on both builds.
  • S4: a hidden-tab survivor at startup.
  • Other hosts: SSH, WSL and Windows weren't run live. The execution host owns all of this, and losing contact writes nothing.

Pre-existing, seen in QA on both builds

  • An agent that dies while another program holds the database froze the app for 15 s or more, from the agent's own output writes waiting out the lock.
  • "Worked for" ends at the last time the agent was proven alive.
  • History labels OMP chats "Pi".
  • Orchestration mail shows "Run orca-dev orchestration check".

brennanb2025 added a commit that referenced this pull request Oct 14, 2026
…uild of #26867) (#28092)

* feat(native-chat): record which agent run wrote each journal item

Each journal item row, subagent roster entry and background-task entry now
records ownerFence: the lease fence of the agent run whose output produced it.
Optional, persisted, no row version bump and no migration. The journal's
itemFence() returns it, so the turn-verdict rules and per-run provider activity
read the producing run rather than the writer's fence.

* test(native-chat): fewer provenance tests: fold reopen and unstated-owner checks into the main case

Drops the epoch-replacement case (Part 2 rewind test reads the same values through the same rebuild) and the corrupt-value case (no version writes one).

* test(native-chat): an unstamped roster entry from an older build reads as its row provenance

Moved here from Part 4 so it sits beside stampJournalEntryProvenance.

* test(native-chat): build the older-build roster row inline, after main removed its body helper

Main #27947 writes one row per subagent and deleted journal-subagent-group-body; a roster row from an older build is still what this case reads.

* refactor(native-chat): provenance is per item only; drop per-entry stamping

Main's #27947 writes one saved row per subagent, and each background task already has its own row,
so an item's own ownerFence names the run of every entry a producer still writes. Per-entry stamps
inside a row mattered only for the shared roster rows saved before #27947, and no run writes into
those any more, so the row's own provenance settles them correctly. Removes the entry stamping,
the optional ownerFence on roster entries and background tasks, and their tests.

* fix(native-chat): an item's provenance is set when it is created; revisions keep it

A newer run's provider can revise an item an older run created: Pi's start and an ACP
session/load both report context usage onto the newest saved turn. Restamping that turn with
the newer run let the newer run's exit settle the older run's unverifiable turn as interrupted.
Only creation states an owner now, as main's itemFences rule did.

* test(native-chat): keep the provenance test below the production lines it covers
AmethystLiang added a commit that referenced this pull request Oct 14, 2026
* fix(worktrees): never delete a folder git no longer tracks (#25075)

* fix(worktrees): a retried or resumed delete only removes the folder it started deleting

A failed worktree delete stays listed for a retry, and an interrupted one is
finished at the next start. Both later deletes force-deleted whatever was at
the recorded path, proven only by "git does not list it and it has no .git",
so an ordinary folder the user put at that path since was deleted with its
files, with no click needed in the startup case (STA-9338).

An accepted removal now records the checkout directory's identity (device,
inode, creation time) in its durable record. A retry, a startup finish, and
the in-slot check before the force-delete refuse any folder at the path that
is not that directory. Startup no longer rebuilds a missing .git for a
registered checkout unless the folder is the recorded one. Records without an
identity (older builds, or no creation time) are only finished through Git's
own checks and never force-deleted.

* fix(worktrees): identify the accepted checkout by inode and a real creation time only

The device number changes when an external volume is attached again, so a
genuine leftover read as a different folder. Windows reports a missing
creation time as a negative number rather than 0, which slipped past the
guard.

* refactor(worktrees): every background removal states the checkout identity it accepted

A new acceptance site that forgot the identity used to compile and silently
write records no retry or resume could ever finish. The resume tests also
assert the identity was read, so their refusals can't pass as unrecorded.

* fix(worktrees): a delete that leaves the user's folder in place also ends the workspace

When Orca decided the folder at a failed or interrupted delete's path was not
the one it started deleting, it dropped the removal record but kept the
workspace's metadata. That metadata still says Orca created a checkout there,
and with no record left, the next Delete of the same workspace (a runtime
Delete from mobile, the CLI or a paired client, or a second desktop Delete on a
row not yet refreshed) went to the cleanup that deletes an Orca-created folder
Git no longer lists, and removed the user's folder after all.

Now, when a removal ends without deleting while Git does not list the path (a
listing ends a failed delete, or a retry, resume or first delete fails with no
leftover to show), the host runs a finished delete's bookkeeping: metadata,
terminal history, caches and change events. The folder and the branch are left
alone, and nothing is ended while Git still lists the path.

* test(worktrees): cover the in-slot folder check when Git cannot remove a registered checkout

Reverting that check left every test green: only the unregistered branch's
check had a test where the folder changes during the delete-slot wait.

* fix(worktrees): a resumed or retried Git delete checks the folder inside the delete slot

The check that the folder at the path is still the one Orca accepted ran
before the watcher gate and the delete-slot wait, which can last minutes behind
other large deletes. A folder restored there meanwhile with a copy of the
checkout's .git file passes Git's own validation, so `git worktree remove
--force` deleted it. The resume and retry now repeat the check inside the slot,
right before Git deletes, as the non-Git branch already did; the refusal skips
the Windows recovery that could otherwise finish the delete itself. A normal
first delete is unchanged.

* test(worktrees): assert the second desktop Delete refuses the user's folder

The handler result is untyped, so the previous catch-all did not typecheck; the
assertion now names the refusal the Delete gets once the workspace has ended.

* test(worktrees): the desktop Delete test's stand-in host ends the workspace without a cast

* fix(worktrees): a listing asks Git before dropping a failed delete, and ends its workspace in the same step

* fix(worktrees): a failed delete Git cannot be asked about stays failed for the next listing to decide

* test(worktrees): the failed-delete record test states that Git still registers the checkout

* fix(worktrees): a restart keeps a failed delete whose checkout is gone, so the first listing ends its workspace

* fix(worktrees): a folder Orca cannot read keeps its failed delete and is never deleted

* fix(worktrees): a failed delete leaves the disk only after its workspace's end is saved

* fix(worktrees): a runtime Delete of a failed delete's row is told when Orca left the folder in place

* test(worktrees): the desktop Delete test's stand-in host returns nothing

* fix(worktrees): a Delete of a failed delete's leftover whose .git Orca cannot read says so

* Revert "fix(worktrees): a runtime Delete of a failed delete's row is told when Orca left the folder in place"

This reverts commit 68d65989def954d1831bfcb4fad673e3b9896f73.

The shortcut reaches no real client: the CLI and mobile list the workspace before deleting it, which ends the failed delete first, so they still answer not found (the folder is kept either way).

* fix(worktrees): a failed delete Git could not be asked about is dropped once Git says it still registers the checkout

* revert to main before the standard-model rework

* fix(worktrees): stop deleting Orca-created folders that have no .git and that Git no longer tracks

Deleting an Orca-created workspace whose folder Git no longer tracked and that had no `.git` force-
deleted the whole folder once the user confirmed force. "Orca made a workspace here once" and "there
is no .git" do not prove the folder still holds that checkout: an ordinary folder the user put at
the path was deleted.

Such a folder now gets the existing "Refusing to delete unregistered worktree path" answer, forced or
not. Once the user removes the folder, Delete takes the existing missing-path branch and drops the
workspace. An orphaned worktree whose `.git` file points back at this repo is still deleted after
the user confirms force, as before.

* fix(worktrees): delete a failed or interrupted workspace only through Git

A delete that failed partway (Git dropped the registration, files left) stays listed as "Delete
failed", and a delete a quit interrupted is finished at the next launch. Both later deletes removed
the folder with Orca's own file removal, proven only by "Git does not list it and there is no .git".
An ordinary folder the user put at that path was deleted, at startup without any click.

Orca now deletes a checkout only through Git, plus the existing cleanup right after a Git delete that
succeeded in the same operation:

- Delete on a failed row: if Git registers a checkout at the path, the normal delete runs. If the
  folder is still there and Git does not register it, Delete refuses with "Git no longer tracks
  <path>, so Orca won't delete it. Remove the folder yourself; Orca removes this workspace once the
  folder is gone." and keeps the row. With the folder gone, Delete prunes Git's stale entry, deletes
  the branch as recorded and drops the workspace.
- Startup finish of an interrupted delete: a checkout Git still registers is removed with
  `git worktree remove` and the user's recorded force choice, no longer always forced. If Git refuses
  or fails, the row shows Git's error. The step that rewrote a missing `.git` so Git could force the
  delete is gone. A folder Git does not register becomes a failed row and is not deleted; with the
  folder gone, the rest of the delete finishes.

Records written by earlier daily builds still load; fields this version does not know are ignored.

* test(worktrees): read Git's listing before the Delete call in the real-Git failed-delete suite

* docs(worktrees): say when a failed delete's record ends under the Git-only delete

* fix(worktrees): keep main's handling of a startup finish Git refuses, and say the listing drops the workspace

A startup finish that Git refuses for a checkout Git still registers now clears its record and
leaves Git's normal row, exactly as an in-session failure does on main; the resumed-only failed
record and the listing that put Git's error on Git's own row are gone, and the listing is main's
again. An unregistered folder that still exists is still a failed row, and nothing is deleted.

The refusal now reads: "Git no longer tracks <path>, so Orca won't delete it. Remove the folder
yourself, and Orca will drop this workspace from the list." The listing drops a failed record once
its folder is gone, as on main.

* fix(worktrees): finish a failed delete's branch and push-target remote when it fails

A delete Git fails partway keeps a "Delete failed" row for the folder Git left. The row's record
also carried the branch delete and the push-target remote cleanup for later, but the listing drops
the record once the user removes the folder, so both were silently left behind. Now, once Git no
longer registers the checkout, the failure runs that Git side right away (merged branch only,
stale admin entry, push-target remote), in the one settle path desktop and runtime share. It
deletes no files, and a failure of this bookkeeping is logged without touching the failed row.

* fix(worktrees): unregister an interrupted delete's checkout whose .git Git already deleted

A quit mid-delete can leave a checkout Git still registers but whose .git link Git already
deleted (Git deletes it first on Windows). No `git worktree remove` can validate it, so the startup
finish failed, the record was cleared, and the workspace came back as a normal row no Delete could
ever remove. The startup finish now has Git prune that registration (refused while locked; every
file kept) and then treats the folder as one Git no longer registers: the "Delete failed" row with
the remove-it-yourself message, ending once the user removes the folder. Adds the non-forced
partial-delete case: Git refuses, the files stay, and the row returns as before.

* fix(worktrees): name a worktree Git registers inside a failed delete's folder before asking the user to remove it

The refusal for a folder Git no longer tracks tells the user to remove the folder. When that folder
holds another worktree Git still registers, doing so would delete that worktree's files too. Delete
on the failed row and the startup finish now run the existing nested-worktree check first, so its
message ("contains another registered worktree: <path>") wins, as it did before this branch.

* fix(worktrees): don't prune other worktrees when a delete fails

The Git side of a failed delete started with a repo-wide `git worktree prune`. It did nothing for
the failed delete, whose admin entry Git had already dropped, but it unregistered any other
worktree whose folder was missing at that moment (an unmounted drive), so Orca dropped that
workspace too. The failure now runs only the branch step; the prune stays where it was on main,
in the folder-gone finish and at startup.

* test(worktrees): cover the push-target cleanup every delete job wires for a failed delete

A failed delete removes the push-target remote Orca added through the hook each job creator passes: desktop Delete, runtime Delete, and the startup finish. Nothing tested that wiring; these tests fail when any creator drops it.

* fix(worktrees): say the leftover folder was left on disk instead of what Orca won't do

* Shorten worker sub-dispatch instructions (#28565)

* Allow workers to dispatch one level of sub-workers by default

The default nested worker depth was 1, so a coordinator's workers were refused on their first dispatch. Raising it to 2 lets one generation of sub-workers run without changing any settings. The depth constant, the global settings default, and the affected tests now share that value, so they stay in step.

- Set NESTED_WORKER_MAX_DEPTH_DEFAULT and the settings default to 2.
- Pin the cap-1 refusal test to an explicit cap of 1, and point the depth-2 test at the default constant.
- Update the resolver and settings pane tests to expect 2 when unset.

* Keep worker depth at 1 and shorten sub-dispatch instructions

* fix(unread): a pane is read when it is on screen; closing a waiting tab clears its dot (#28637)

* test(unread): characterize today's workspace and pane unread transitions

Pins, against the real store, what every unread trigger does today: the workspace
flag per host row, the three tab/pane marker maps, persistence calls and payloads,
lastActivityAt and sortEpoch bumps, the Dock count and the floating launcher dot.
Events are replayed through one driver file so a later rewiring of who writes the
state changes only the driver, never these expectations.

* refactor(unread): one workspace-attention module owns every unread transition

Every write to the workspace unread flag and the tab/pane/completion markers now
goes through src/renderer/src/store/slices/workspace-attention: store operations
named by the triggering event (bell, agent attention, pane input, viewed-agent
auto-ack, manual mark read/unread) and pure transitions folded into other slices'
set() calls (activation, tab activation, close, sleep, hibernate, retire, rekey,
reconcile, mirror removal, purge, acknowledge). Behaviour, storage, readers,
persistence and wire format are unchanged; the characterization suites pass
without edits to their expectations.

* refactor(unread): review fixes for the workspace-attention module

- Ratchets: moved terminal-tab-attention baseline entries to terminal-tab-appearance; split
  the characterization setup/observables into an exempt fixture so the driver holds only events.
- Removed the test-only writer seam; mocked-store tests assert the event they fire.
- The slice owns the experimental pane gate for completions too; groupAttentionEnabled is gone
  from the attention request and write.
- Collapsed marker removals to removeTabsAttention / removePanesAttention /
  removeCompletionAttention / removeTabMarkers / movePaneAttention; tab activation uses
  omitRecordKeys.
- Mark read/unread is passed in like other store actions; readers of the workspace dot go
  through isWorkspaceUnread.

* feat(unread): on screen means read; the workspace flag follows its markers

While Orca's window is visible and focused, the tabs on screen (active tab
of the active workspace, plus an open floating panel) are read: every tab,
pane and completion marker of each. One scan (the auto-ack hook, now
startViewedAttentionScan) replaces the keydown, pointerdown, tab
activation, group focus, workspace activation and auto-ack marker clears.

After a read, close, sleep, hibernate, retire or purge that removed a
marker, a workspace's flag is cleared once no tab or completion marker
remains on a live tab; a marker-less flag (Mark as unread, restart,
another client) is read when its workspace comes on screen. Mark as read
removes every marker in the workspace. Reads and removals dismiss the
affected panes' OS notifications in one IPC call.

* fix(unread): a bell or completion already on screen leaves no marker or flag write

Marking now asks the scan's own on-screen rule (isTabOnScreen: the window is
visible and focused and the tab is a scan target), so an on-screen bell no
longer persists the flag true then false. A completion in any split pane of
the tab on screen is viewed, matching the read. A superseded turn's
completion-marker removal settles the flag and dismisses like other removals.

* fix(unread): read the screen across hosts, groups and non-agent views; mark only for an absent user

- Arriving at a workspace in its own view settles its flag even when it shows an
  editor, browser or nothing; Settings and other views read nothing.
- A bell or completion on screen skips marking only when the user is confirmed
  present under the scan's own presence gate (input, or main reporting the
  desktop active within the shared away threshold); otherwise it marks and the
  gated scan reads it when the user returns.
- The active workspace's host is part of the screen, so switching same-id folder
  rows between hosts is an arrival on the new host.
- Removal settles lower every same-id folder row and persist each host.
- Opening and closing the floating panel both rescan.
- Every visible tab group's active tab is on screen, not only the focused one.
- One pane-key parser, one marker-tab enumeration, one removal wrapper
  (settleAttentionRemovedBy), one remove-and-dismiss; the hook is now
  useReadOnScreenAttention over on-screen-attention-scan.ts, and terminal
  keystrokes reach presence through a capture-phase window keydown.

* fix(unread): presence only from renderer input; host-exact folder flags; subjectless completions follow the screen

- Main's 'not away' answers only the scan that asked; presence is stamped
  only by trusted input (wheel included), so it can't outlive the threshold.
- isWorkspaceViewed uses the on-screen rule (workspace view showing, focused
  window, user present), so a subjectless completion marks under Settings or
  while away.
- Folder flag writes resolve the row's host like updateFolderWorkspace does
  (project-group fallback), so the row flipped and the owner persisted match.
- A runtime host purge dismisses but doesn't settle flags of surviving rows.
- DESKTOP_AWAY_SECONDS is the shared threshold's neutral name.

* test(unread): folder flag persists name the row's host

* test(unread): drop casts from the folder persistence seeds

* fix(unread): point the reliability gate and e2e fixture at the renamed on-screen hook

* refactor(unread): drop reshapes the follow-up deletes; keep the flag functions module-internal

Reverts the reconcile/mirror/activation/focus/group call sites and the isWorkspaceUnread
selector to main, removes removeTabMarkers, removeCompletionAttention and the activation
read helpers, and drives tests through public attention actions.

* test(unread): read the Dock badge flag down by putting its tab on screen

* fix(unread): keep the on-input read action removed after merging main

* fix(serve): restore a remote server's browser tabs after it restarts (#28166)

* feat(serve): keep browser tabs across an orca serve restart

A host with no window now saves the browser tabs it opens in the same shape a
desktop window saves its own, and restores them the same way: listed at once
with their last address, each page started when a client first opens or
drives it. A closed tab is forgotten; a page that ends with the process is not
a close.

* test(e2e): the server's published strip now holds its saved browser tab

* fix(serve): save browser addresses cheaply, open once, restore by page id

Review fixes: a page's address is written onto its saved records without
reloading the layout, and only on committed navigations; reopening a saved
page writes nothing; a command naming only the page finds the workspace that
saved it; a refused save no longer throws from a page event or a close. The
browser-tab map is renamed to say it lists saved tabs too.

* fix(serve): list, switch and close saved browser tabs from commands that name no page or worktree

* fix(serve): a tab list does not start saved pages; only a command acting on a page does

* fix(serve): a pageless command starts the browser tab the layout shows, not the first saved one

A host now records the browser tab a window would show: the one it just
opened, and the one a tab switch picks. With nothing running, a command
that names no page starts that tab; when the layout shows none it starts
nothing and reports no browser tab open.

* fix(serve): report the saved active browser tab as current

Claude-Session: p2-headless

* chore(ratchet): count the serve browser-tab save as a main-process layout writer

Claude-Session: p2-headless

* fix(serve): use the window's active browser tab rule, one scope, one active row

Claude-Session: p2-headless

* fix(browser): pick the active tab among tabs this host can start

A desktop document page or a remote page recorded as active no longer leaves a
pageless command with no tab. Adds a test for the first-saved-worktree scope.

Claude-Session: p2-headless

* refactor(browser): restore saved serve tabs through the page wake point

Saved serve browser tabs now start where a window would mount them: the two
existing wake helpers ask one host hook before messaging a window. The offscreen
backend reports opened and moved pages, so the command layer no longer threads
save, list, select or close hooks. No worktree named and no page running reports
no tab, as a window does.

Claude-Session: p2-headless

* fix(browser): only page creation opens a saved serve tab

A navigation now only updates an existing saved tab, so a late load after a close
cannot re-add it; a restored page sends no open, so its saved title stays.

Claude-Session: p2-headless

* refactor(browser): drop the restore mark the open/navigate split made redundant

Claude-Session: p2-headless

* refactor(browser): save serve tabs from the create command, list unstarted ones as tab rows

The create command saves the tab (it holds the group), so the backend reports only
navigations. Unstarted saved tabs are tab-info rows the existing listings take
as-is, the restore dedupe map goes (a created page registers before createTab
returns), and one lookup gives a page's unified tab id.

Claude-Session: p2-headless

* fix(browser): opening a serve browser tab no longer records it as active

Which tab shows is a view's choice; after a restart the active tab is the one a
window recorded, else the first.

Claude-Session: p2-headless

* fix(browser): give the composed browser command owners the saved-tab host member

Completes the forward merge of main's browser command split (#27576).

Claude-Session: p2-headless

* fix(terminal): store the Terminal shell setting trimmed so agent tabs start like plain tabs (#28635)

* fix(terminal): store the Terminal shell setting trimmed

The Settings field only stripped leading spaces and a hand-edited settings file loaded as-is, so a trailing space reached agent tabs, the CLI and other host-planned launches, while plain terminal tabs trimmed it in their own reader. Trim the setting when the field loses focus and when settings load (whitespace-only becomes unset), and drop the plain-tab reader's now-redundant trim.

* fix(terminal): trim the shell setting at the settings write too

A keystroke write could still store a padded shell, and Escape closes Settings without a blur, so a plain tab could launch the padded value once its own trim was gone. Trim at the settings write boundary (shared with load, like the machine name), and keep the typed text in a local draft while the field is focused.

* fix(settings): drop the shell field's draft when the field unmounts

The draft lived on the whole Terminal pane, so a field removed without a blur (another window switching to System shell, or the settings search hiding it) left a stale draft that showed later instead of the saved shell. Move it into a small input component so it is discarded with the field.

* refactor(pty): one failure cleanup and agent_error for both terminal spawn paths (#28613)

* test(pty): pin a failed provider start on both spawn lanes

Characterizes main before the two execute steps merge: the error is
rethrown, the pre-spawn hidden mark, pending registration, worktree spawn
gate, cached size and pane reservation are all undone, and only the window
lane records agent_error.

* refactor(pty): one failure cleanup and agent_error for both spawn lanes

The window (pty:spawn) and the host (runtime controller) each undid a failed
execute step with their own copy of the same cleanup: provisional execution
context, early-exit fence, pending registration, cached size and provider
state for a minted session id. Both now call failPtySpawnExecute, which also
records agent_error in one place.

recordsAgentError is TEMPORARY: host starts still record none, as on main,
until C5a-2 removes the input. The window's extra hidden-mark rollback in this
catch duplicated its outer catch, which still runs, and is gone.

* chore: re-run CI against current main

* fix(terminal): judge an agent's --shell against the runtime it runs in (#28234)

* fix(terminal): judge an agent's --shell against the runtime it runs in

`orca terminal create --shell` for an agent is now judged only against the runtime that agent
runs in, not also against the project's saved runtime. So --shell wsl.exe for an agent in a
\\wsl$ repo (saved as Windows host, or with no setting) runs instead of being refused.

* chore(ci): re-run checks against current main

* chore(ci): re-run checks against current main

* chore(ci): re-run checks against current main

* chore(ci): re-run checks against current main

* chore(ci): re-run checks against current main

* Keep CI failure excerpts bounded and strip malformed ANSI controls linearly (#28671)

* Bound and sanitize CI failure excerpts with linear ANSI stripping

* Fix excerpt regression checks and reduce bounded marker overhead

* Require signal proof for benchmark timeouts and load consumer fixtures portably

* Validate benchmark timeout framing and run required cases with a pinned CI baseline

* Strip dense generic ANSI escapes with bounded forward scanning

* Use the standard UTF8 encoder for byte-cap test oracles

* Gate CI log performance suites behind a dedicated job

The wall-clock performance suites run about 1k child workloads up to 63 MiB, so they were sharing runners with unit tests and could fail on noise. They now run only in their own `check_log_performance` job, opted in with `ORCA_CHECK_LOG_PERF=1`.

- Remove the pinned-baseline checkout and `ORCA_CHECK_LOG_BASELINE_DIR`. The baseline comparison is now a manual step that reads the pinned ref from local Git history.
- Run the current-implementation checks with `compareBaseline: false`, which skips baseline builds and audits.

* Inline check-log fixture and drop dedicated perf CI job

- Replace the captured failure-log JSON with a synthetic log built by `createCheckLogFixture()`, so no scraped job output or provenance metadata is kept in the repo.
- Remove the `check_log_performance` CI job. The log performance suites now run only when `ORCA_CHECK_LOG_PERF=1` is set, as a manual benchmark.
- Update the benchmark scripts and tests to use the new fixture helper and drop the `fixturePath` parameter.

* Remove Hermes automation support (#28519)

* Remove external cron history from the automation UI

* Simplify the automation editor

* Remove Hermes cron discovery and management

* test(cross-version): pin the ephemeral-key and source-fence downgrade tests to v1.4.224 (#28803)

v1.4.225 ships both capabilities, so the newest release no longer models an
old host. Pin each to the last release without its capability, as the other
downgrade tests in the suite already do.

* fix(terminal): name the fix that applies when --shell is refused (#28235)

A refusal names a \\wsl$ working directory first, since no runtime setting can move it out of
WSL, and names Settings > Project Runtime when the runtime comes from the global default.

* Native chat: record which agent run wrote each journal item (1/5, rebuild of #26867) (#28092)

* feat(native-chat): record which agent run wrote each journal item

Each journal item row, subagent roster entry and background-task entry now
records ownerFence: the lease fence of the agent run whose output produced it.
Optional, persisted, no row version bump and no migration. The journal's
itemFence() returns it, so the turn-verdict rules and per-run provider activity
read the producing run rather than the writer's fence.

* test(native-chat): fewer provenance tests: fold reopen and unstated-owner checks into the main case

Drops the epoch-replacement case (Part 2 rewind test reads the same values through the same rebuild) and the corrupt-value case (no version writes one).

* test(native-chat): an unstamped roster entry from an older build reads as its row provenance

Moved here from Part 4 so it sits beside stampJournalEntryProvenance.

* test(native-chat): build the older-build roster row inline, after main removed its body helper

Main #27947 writes one row per subagent and deleted journal-subagent-group-body; a roster row from an older build is still what this case reads.

* refactor(native-chat): provenance is per item only; drop per-entry stamping

Main's #27947 writes one saved row per subagent, and each background task already has its own row,
so an item's own ownerFence names the run of every entry a producer still writes. Per-entry stamps
inside a row mattered only for the shared roster rows saved before #27947, and no run writes into
those any more, so the row's own provenance settles them correctly. Removes the entry stamping,
the optional ownerFence on roster entries and background tasks, and their tests.

* fix(native-chat): an item's provenance is set when it is created; revisions keep it

A newer run's provider can revise an item an older run created: Pi's start and an ACP
session/load both report context usage onto the newest saved turn. Restamping that turn with
the newer run let the newer run's exit settle the older run's unverifiable turn as interrupted.
Only creation states an owner now, as main's itemFences rule did.

* test(native-chat): keep the provenance test below the production lines it covers

* refactor(native-chat): open a chat visual like any file (#28437)

* fix(files): never write through a dangling symlink

A path that doesn't exist yet was authorized by walking up to the nearest
existing folder. A dangling symlink fails realpath with ENOENT, so the walk
stepped over it and approved the link's own path; the write then followed
the link and created its target outside the allowed folders. The walk now
continues from the link's target, and returns that real destination.

* refactor(native-chat): rename the chat visuals folder to the chat scratch folder

The per-chat folder agents write into is the chat's scratch space, not only
a visuals folder. Its root becomes <state>/chat-scratch/<hash> (the hash is
unchanged) and the agent variable becomes ORCA_CHAT_SCRATCH_DIR. The old
ORCA_CHAT_VISUALS_DIR is never set and is still stripped from what every
agent child inherits, Pi included. The visuals skill names the new variable
and says the folder is temporary.

* test(native-chat): keep the delivery test to the rename

The launch parity snapshot already pins that every agent drops the
pre-rename variable.

* fix(files): refuse any dangling symlink in the missing-path walk

Following a dangling link by hand resolved relative targets against the
lexical parent, not the link's real folder: through a folder link the walk
could loop forever or authorize the wrong file. Refuse instead: realpath
can't say where a dangling link leads, but a write would follow it.

* feat(runtime-files): the host serves a chat's scratch folder as a file root

File commands accept `path:<this host's chat-scratch root>/<32 hex>` and
resolve it only when it names this host's own folder, at the file-commands
seam so the selector never reaches chat placement. They authorize against
the project roots plus the chat-scratch root, refuse files.open/openDiff
for the folder, and agentSession.readVisual's ok results carry the file's
absolute path so a client can build the selector.

* test(runtime-files): name the readVisual helper's parameter type

* test(files): drop the loop case that duplicated the dangling-link refusal

* test(runtime-files): run the readVisual RPC test, which opens a real SQLite store, under Node

* test(runtime-files): put the same-suffix folder inside the authorized root so only the selector refuses it

* refactor(native-chat): open a chat visual like any file

"Open in new tab" on an inline chat visual now opens the visual's file the
way any HTML file of the chat's workspace opens: a file:// browser tab for a
local chat (its overflow menu gains "Open source file"), the document
preview for a paired-host chat (with its existing source action and Share).
Edits save on the chat's host through the exact path: selector the host
serves, and a matching editor save re-reads the inline copy freshly. The
read-only chat-visual tab is removed.

* fix(native-chat): a visual read without a path is a malformed reply

A visual's path is always on the current host's readVisual answer, so the
inline Open needs no branch for a missing one. Also prune the deleted
chat-visual tab action from the layout-writer baseline.

* test(native-chat): give visual read replies their path without longer lines

* fix(native-chat): address a scratch file by its folder only outside every workspace

A workspace that contains the host's state folder keeps its own address, so
explorer drops, folder creation and renames inside it stay on one root.
Document preview Share reads a runtime grant's own selector and root
directly instead of passing the selector off as a workspace id.

* test(runtime-files): wait for the stores to close before removing the state folder

* fix(i18n): drop catalog strings left behind by the automation removal (#28810)

The automation removal deleted the screens but kept their strings in every
locale catalog. With no call site left, the boot-bundle catalog check counts
them as required and fails on main.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(wsl-mover): refuse edits to a project a WSL move is taking (D1b-5c-2) (#28761)

* feat(wsl-mover): refuse edits to a project a WSL move is taking, and drop its background bookkeeping quietly (D1b-5c-2)

* fix(wsl-mover): hide only local rows of a moved project; the host's own row keeps its id (D1b-5c-2)

* fix(wsl-mover): refuse a user's unread toggle, fence branch deletes, host setups and issue commands; settings unfreeze once the host owns a repo (D1b-5c-2)

* test(wsl-mover): the fence e2e refuses edits to moving projects and drops their bookkeeping quietly (D1b-5c-2)

* refactor(wsl-mover): name the update type the fence inspects (D1b-5c-2)

* test(wsl-mover): run the fence tests that open a real store in the Node runtime (D1b-5c-2)

* fix(wsl-mover): a host setup's own repo stays frozen once the host owns it; e2e pins the quiet drop (D1b-5c-2)

* Resume in New Native Chat for Pi (#28080)

* feat(chat): Resume in New Native Chat for Pi terminal conversations

A Pi conversation started in the terminal now offers "Resume in New Native Chat" in its Session
History row menu and its tab's right-click menu, like the other chat agents: a new Pi chat takes
it over, showing its history and continuing it.

Pi joins the shared adoption path. Its import finds the session file Session History lists under
the row id, and reads it with OMP's decoder, since OMP kept Pi's session format. A Pi chat's handle
names its session file, so the import says so and create mints the adopted handle from the found
file; the committed-create replay compares through the registration's row id, and the adopted
link id is kept to the link-id alphabet. A Pi chat forks a conversation recorded in another folder
instead of resuming it, so the workspace rule covers Pi too.

* fix(pi): preserve adopted session identity and active history

* Fix saved Pi adoption history and summary content

* test: keep only the tests that pin user-visible behavior

* feat(relay): measure each host hello's pre-auth time on the cell (#28695)

* feat(relay): measure each host hello's pre-auth time on the cell

Adds preAuthLatencyMs to the per-cell orca_relay_runtime_metrics line: per
admit path (db, reserve) and outcome (admitted, refused), a count plus
p50/p95/p99/max for the window. Each sample runs from the cell accepting the
host control WebSocket to the hello being admitted (proof verified) or
refused. Samples are kept in a bounded reservoir, shared with the control
round-trip metric. No behaviour, wire, or flag change.

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* fix(relay): count abandoned hellos and publish mergeable pre-auth buckets

- Record a third outcome, abandoned, for a host that hangs up before a decision or before
  the cell acts on one, so the slowest hellos no longer drop out of the window.
- Add non-cumulative bucket counts per group (bounds 50..5000 ms and +Inf, 450 exact) so
  the share at or under 450 ms sums exactly across windows and cells.
- Split refusals that end before an admission check answers into a beforeCheck path.
- One refuse() closure per phase records the metric, and the path is passed to settle.
- Drop the half-used LatencyReservoir type; the shared reservoir function stays.
- Replace test casts with a typed accessor or SAFETY comments.

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* docs(relay): note pre-auth path labels for late throws and the combined role

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* fix(relay): end the restart-safe quiet at the drain's pace window, not a window after it (#28677)

* fix(relay): end the restart-safe quiet at the drain's pace window, not a window after it

A paced drain tells its last host when the window ends, so the restart-safe
wait has to see an empty runtime reaching past that point. It counted a full
window of quiet samples from the first empty one instead, and the runtime only
empties as the window ends, so every same-cap cell waited the window twice:
about 25 minutes per Asia cell at 1200 s on 2026-10-13, and 5 minutes per
300 s cell.

The window is now measured from the verifier's own start, which runs after the
cell accepted the drain and so ends no earlier than the cell's own window. A
pass still needs two consecutive restart-safe samples, the last taken at or
after that end, and any non-zero runtime counter or open migration still
restarts the count. Progress lines report paceWindowRemainingMs in place of the
old sample target.

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* fix(relay): drop the same-cap drain timeout's double-wait allowance and stale quiet wording

The drain step's timeout added the window's excess over 300000 only because
restart-safe used to wait a second window after the cell emptied, so it is
now the 15-minute migration lease plus the window for every pace (35 minutes
at 1200000, unchanged at 300000 and below). Docs, workflow comments and the
shadow gate's settledAfterSeconds note now describe the window-end rule. The
always-quiet test starts its clock late, so a window measured from zero
fails it, and the overlapping late-control test is folded away.

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* docs(relay): state the restart-safe window-end rule exactly

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* docs(relay): the slowest restart-safe wait is now 35 minutes

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* ci: run the Electron browser probes serially, out of the unit shards (#28799)

The three popup compatibility probes ran in the parallel unit shards and
timed out at their 14s in-process deadline when other files starved the
runner. Move them into the package job's serial Electron lifecycle step,
and stop the six probes already in that step from also running in the
shards.

Claude-Session: p2-headless

* fix(pty): report agent start failures the same way from every launch path (#28724)

* feat(telemetry): count agent start failures from the host too

The host spawn path (CLI, phone, orchestration workers, headless automations,
worktree startup) now records agent_error when starting an agent fails, as the
window path already did. Removes C5a's TEMPORARY recordsAgentError input; the
host already threads each launch's telemetry, so failures get real kinds.

* fix(telemetry): count a claimed start that several requests joined once

Concurrent resumes of one agent session join one claimed start. When it
fails, every joined request ran the host catch and recorded agent_error, so
one failed start counted once per request. Only the request that ran the
start records it now; the others still clean up.

* fix(telemetry): only skip agent_error for a request that joined another start

The host marked a request as joined before calling ensure, so a claim that
refused the request on its own (conflict, capacity, unreachable owner) recorded
no agent_error. ensure now reports the join itself, right before awaiting the
other request's start.

* chore: re-run CI after main's localization fix (#28810)

* fix(new-tab): Enter on a visited site's name opens the site, not a file (#28804)

* Rank browser history above fuzzy file matches in the omnibox

Scattered-character fuzzy file matches are weak evidence, so a remembered
page should appear above them. Exact and literal file matches and typed
URLs still rank above history. Adds a test for typing a host like
linear.app, which should rank the page above unrelated fuzzy files.

* Anchor omnibox history on the typed URL instead of demoting fuzzy files

The real bug: after visiting https://linear.app/, typing `linear.app`
made Enter open an unrelated file. The history row removes the typed-URL
row it duplicates, but was then placed below every file match, so the
page lost the top slot the URL row had.

History now sits with the typed URL row (in its slot when it replaced
it). Queries with no typed URL keep the old rule: below every file match.

This replaces the previous commit's rule of ranking history above
"fuzzy" files. That label covers every non-exact match for queries with
a slash, a dot suffix or a space, so a code-host page whose title holds
the file path took Enter away from local rows for path queries (or left
nothing selected when pasted). It also left `localhost` broken when a
file name contained it.

* feat(wsl-mover): pause a moving project's terminals through Sleep and prove they exited (D1b-5d) (#28820)

* feat(wsl-mover): pause a moving project's terminals through Sleep and prove they exited (D1b-5d)

* fix(wsl-mover): gate again under the fence, swap journal phases atomically, keep sessions frozen through commit (D1b-5d)

* test(wsl-mover): the fence e2e walks the journal one phase at a time, as a move writes it (D1b-5d)

* feat(native-chat): Share a chat visual from the chat (#28479)

* fix(files): never write through a dangling symlink

A path that doesn't exist yet was authorized by walking up to the nearest
existing folder. A dangling symlink fails realpath with ENOENT, so the walk
stepped over it and approved the link's own path; the write then followed
the link and created its target outside the allowed folders. The walk now
continues from the link's target, and returns that real destination.

* refactor(native-chat): rename the chat visuals folder to the chat scratch folder

The per-chat folder agents write into is the chat's scratch space, not only
a visuals folder. Its root becomes <state>/chat-scratch/<hash> (the hash is
unchanged) and the agent variable becomes ORCA_CHAT_SCRATCH_DIR. The old
ORCA_CHAT_VISUALS_DIR is never set and is still stripped from what every
agent child inherits, Pi included. The visuals skill names the new variable
and says the folder is temporary.

* test(native-chat): keep the delivery test to the rename

The launch parity snapshot already pins that every agent drops the
pre-rename variable.

* fix(files): refuse any dangling symlink in the missing-path walk

Following a dangling link by hand resolved relative targets against the
lexical parent, not the link's real folder: through a folder link the walk
could loop forever or authorize the wrong file. Refuse instead: realpath
can't say where a dangling link leads, but a write would follow it.

* feat(runtime-files): the host serves a chat's scratch folder as a file root

File commands accept `path:<this host's chat-scratch root>/<32 hex>` and
resolve it only when it names this host's own folder, at the file-commands
seam so the selector never reaches chat placement. They authorize against
the project roots plus the chat-scratch root, refuse files.open/openDiff
for the folder, and agentSession.readVisual's ok results carry the file's
absolute path so a client can build the selector.

* test(runtime-files): name the readVisual helper's parameter type

* test(files): drop the loop case that duplicated the dangling-link refusal

* test(runtime-files): run the readVisual RPC test, which opens a real SQLite store, under Node

* test(runtime-files): put the same-suffix folder inside the authorized root so only the selector refuses it

* refactor(native-chat): open a chat visual like any file

"Open in new tab" on an inline chat visual now opens the visual's file the
way any HTML file of the chat's workspace opens: a file:// browser tab for a
local chat (its overflow menu gains "Open source file"), the document
preview for a paired-host chat (with its existing source action and Share).
Edits save on the chat's host through the exact path: selector the host
serves, and a matching editor save re-reads the inline copy freshly. The
read-only chat-visual tab is removed.

* feat(native-chat): share a chat visual from the chat

The inline visual's toolbar gains Share beside Open. It publishes under the
file's own key on the chat's host, the key the opened preview and editor use,
so every surface updates one link. The published text comes from a fresh read
begun after the click; a failed read publishes nothing and says the visual
couldn't be read. The toolbar stays shown while Share's popover is open.

* fix(native-chat): a visual read without a path is a malformed reply

A visual's path is always on the current host's readVisual answer, so the
inline Open needs no branch for a missing one. Also prune the deleted
chat-visual tab action from the layout-writer baseline.

* test(native-chat): give visual read replies their path without longer lines

* fix(native-chat): address a scratch file by its folder only outside every workspace

A workspace that contains the host's state folder keeps its own address, so
explorer drops, folder creation and renames inside it stay on one root.
Document preview Share reads a runtime grant's own selector and root
directly instead of passing the selector off as a workspace id.

* fix(native-chat): show a chat visual's Share whenever it shows

Every read now carries the visual's path, so Share no longer waits on one; its
key comes from the path the click's fresh read returns.

* test(runtime-files): wait for the stores to close before removing the state folder

* fix(opencode): refuse a picked OpenCode model in any \\wsl$ repo (#28236)

OpenCode in a \\wsl$ repo runs in WSL whatever the project's setting, and Orca can't verify a
model there yet, so picking one is refused, as it already is for a project set to WSL, instead
of being checked on Windows.

* fix(mobile): workspace list host badge, "workspaces" wording, and search keyboard on the page (#28824)

* fix(mobile): workspace list host badge, wording, and search keyboard on the page

- Host badge no longer shrinks to "m…"; the branch/path text gives up the space.
- Search placeholder, accessibility label, and empty states say "workspaces".
- The page's workspace list no longer closes the keyboard on each narrowing keystroke:
  react-native-web dismisses on-drag on every scroll event, including the offset clamp.

* fix(mobile): let the row path take only the leftover space instead of pinning the host badge

A non-shrinking badge overflowed narrow, indented rows; a zero-basis path keeps a short host name whole and still lets the badge shrink when the row is genuinely too narrow.

* fix(mobile): reword the row path's layout comment

* refactor(mobile): inline the page's keyboard dismiss choice and use flex: 1 for the row path

Drop the platform split and its react-native-web test: an inline Platform.OS check states the
same choice where it is used. flex: 1 renders identically to flexBasis 0 + flexGrow 1.

* fix(relay): supersede a reserve seat from the feed once a later, newer join shows (#28716)

* test(relay): check invariant 4 (one demotion winner) in the step-5 simulation

Every demotion now names its winner (the newer booking, or the row). The model
flags a director that names a different winner for a divergence another already
named, and a host whose two seats are each demoted for the other. A fault where
directors break level ties by their own cell order shows the check fires.
Violations are capped per invariant so one flood cannot hide another class.

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* test(relay): bound unseen duplicates by the silence close and assert all invariants on contested ties

A reserve seat the booking director's map had not seen (joined, then half-open within a poll)
is never superseded and has no lease to re-check, so it lasts until the cell's control silence
close (75 s + one 15 s ping). Invariant 3 now uses that bound for such seats, and the
level-divergence config asserts every invariant.

Stale maps now judge a divergence another director already demoted, so the config's
"contested" counter (divergences judged by two or more directors) is the case invariant 4
guards. The silence-close constant now matches production (90 s, not 100 s).

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* test(relay): raise the floor on map-judged demotes and count only level contests

A reconcile whose map has not seen another director's demotion still demotes in
production, which raises its epoch floor; the model now does too. The contested
counter counts only same-epoch pairs, the only ones invariant 4 can split. The
keep-this-seat rule is one helper.

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* refactor(relay): name the simulation's fault-kept seat check for the fault

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* fix(relay): supersede a reserve seat from the feed once a later, newer join shows

A half-open seat the booking director's map had not yet seen was never demoted and held its
cell until the 75 s control silence close. Directors now demote it once both joins are in the
map; the simulation holds invariant 3 at the supersede bound for it.

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* fix(relay): outrank only past cell clock skew, reuse demoteSeat, keep invariant 3's loose clock running

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* refactor(relay): share the outrank rule with the simulation, pin the skew boundary

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* fix(relay): count only confirmed level demotions and every second judgment, and bound duplicates by placement records alone

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* fix(relay): a drained seat keeps its drain grace under a demote, and the feed reports each seat once

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* refactor(relay): name the outranked-report bound and the reconcile backstop

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* refactor(tabs): delete unused copy-tab and merge-group store actions (#28836)

* refactor(tabs): delete unused copy-tab and merge-group store actions

copyUnifiedTabToGroup and mergeGroupIntoSibling had no callers outside
the store and its tests. Tests that used the copy action as a setup step
now create the duplicate tab directly, the same call the action made.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(tabs): follow the split-ratio file rename in the layout-writer baseline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* perf(layout): re-project only the written partition in the layout stream (#28845)

The layout stream (layout.subscribe, still unused) re-loaded every session
partition and ran the load's save-and-diff report after each write. A save
now names the partition it wrote, the stream re-loads only that partition
without the report, and the renderer layout client no longer re-subscribes
on a timer. Adds a latency spec variant with a subscriber attached.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(wsl-mover): background writers step aside for a project a WSL move is taking (D1b-5c-3) (#28835)

* feat(wsl-mover): background writers back off a project a WSL move is taking (D1b-5c-3)

* fix(wsl-mover): re-check before renames, quiet owned automations, stable folder ids (D1b-5c-3)

* test(wsl-mover): seed journals one phase at a time and advance existing moves (D1b-5c-3)

* fix(wsl-mover): a branch rename that already ran settles even when the move skips the folder (D1b-5c-3)

* fix(i18n): correct the Japanese label for the Cleaned browser identity (#28526)

The Japanese option read 掃除済み ("housekeeping done"), while the migration notice that points to the same setting already calls it クリーン. Use クリーン in the option and its settings-search keyword.

Also restore the literal CLI command in the reset hint, which translation had re-capitalised in ja, zh, and fr so it could not be copied and run.

Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>

* fix(i18n): use クリーンアップ in the Japanese VM cleanup stop dialog (#28533)

The dialog title and cancel button said 掃除 (household cleaning), while its own description and confirm button already say クリーンアップ. Use クリーンアップ throughout.

Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>

* refactor(terminal): publish new tabs together with their startup command (#28848)

Seven call sites created a terminal tab and then queued its startup command
in a second store write. Pass the command through createTab's existing
pendingStartup option instead, so the tab and its command land in one write.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(daemon): keep every pane in main's layout through a terminal service restart (#28852)

Restarting the terminal service ends each session with a synthetic -1 exit. Main
read those as ordinary deaths and retired every terminal surface from the saved
layout, while the window kept drawing them. Phones and the CLI lost the tabs, and
the next launch restored a split as a single pane.

The restart now labels those exits as replaced, and main records them in its
existing intentional-stop register, the one terminal restarts already use. The
runtime keeps the surface and the window receives the same replaced label.

Claude-Session: p2-headless

* chore(relay): pin staging c4 to image G for E-pre (#28854)

G is main 2de73812 (relay sha256:07b5bf67…), which adds the cell's t_preauth latency metric.

Claude-Session: f2fe8cb5-4467-4a25-8aab-98598b70791f

* test(session): compare what the window shows before and after the shared session loader (#28842)

* test(session): compare what the window shows before and after the shared session loader

Boots the window's real startup hydration on each saved-profile fixture as
stored and as the shared loader rewrites it (load then save), and compares
tabs, groups, active tabs, pane trees, terminal bindings, editor and browser
tabs. Today's eight differences are listed with the loader rule behind each;
the list may only shrink, so any new difference fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(session): let the parity test own its store so the harness reads no host focus

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(session): restore the parity boot's UUID spy even when the boot throws

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(checks): add optional job log outcome

* fix(checks): preserve host capture lifetimes and safe outcomes

* fix(checks): retrieve and retry bounded failed-job logs

* test(checks): cover queued snapshots and captured error safety

* test(checks): verify sanitized host excerpts and paired failures

* test(checks): identify measurements and preserve paired cleanup

* fix(checks): hold check log lifetimes until processes exit

- Nested gh calls now stay registered until their child closes and their
  scope seals, so a check-details request no longer reports terminated
  while its process is still running.
- Failed-job log requests leave the shared in-flight cache only after the
  result is delivered and the process has exited, so a replacement request
  cannot start while the old child is still alive.
- Check-details metadata calls wait for their own termination in a
  `finally`, replacing the chained `previous` promise that serialized calls
  and could skip cleanup on error.
- Abort handling uses `assertCheckDetailsActive` directly, and the test
  fixture moved to a shared config script.

* fix(checks): reuse job logs with pinned credentials across runtimes

---------

Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
Co-authored-by: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
Co-authored-by: Sojiro.O <53679703+sojiro-o@users.noreply.github.com>
brennanb2025 added a commit that referenced this pull request Oct 15, 2026
… recorded first (2/5, rebuild of #26867) (#28103)

* feat(native-chat): record which agent run wrote each journal item

Each journal item row, subagent roster entry and background-task entry now
records ownerFence: the lease fence of the agent run whose output produced it.
Optional, persisted, no row version bump and no migration. The journal's
itemFence() returns it, so the turn-verdict rules and per-run provider activity
read the producing run rather than the writer's fence.

* feat(native-chat): one current-work projection for every host reader; record death first

The host decides what work is current in one place
(structured-agent-session-current-work.ts) from the lease, the exit this host
saw, the runtimes it replaced, its live child and each item's provenance.
Every host reader (queue, Stop, prompt answers, commands, status feed, idle
sweep, teardown snapshot, history pages and frames, orchestration mailbox)
reads it, so a dead agent's leftovers stop reading Working or holding the queue
even when their cleanup write failed. The journal's activeTurnId()/liveTurnScope()
become the raw runningTurn().

On exit the host records the child's end first and signals generationEnded,
which republishes frames, the status feed and settlement waits and wakes the
queue drain with no journal row. Pages and frames carry optional working and
actionablePromptIds fields.

* refactor(native-chat): keep structuredAgentSessionHandsOver file-local until a caller needs it

Nothing outside the projection calls it in this part; Part 5 exports it for the start-failure row.

* test(native-chat): fewer provenance tests: fold reopen and unstated-owner checks into the main case

Drops the epoch-replacement case (Part 2 rewind test reads the same values through the same rebuild) and the corrupt-value case (no version writes one).

* test(native-chat): drop current-work mirrors: the viewKey unit case and the still-live rewind case

The flow cases keep every outcome: dead leftovers read as nothing, Stop has nothing to stop, a waiting card drains, a live owner publishes as before, and a rewind never promotes dead work.

* test(native-chat): an unstamped roster entry from an older build reads as its row provenance

Moved here from Part 4 so it sits beside stampJournalEntryProvenance.

* test(native-chat): build the older-build roster row inline, after main removed its body helper

Main #27947 writes one row per subagent and deleted journal-subagent-group-body; a roster row from an older build is still what this case reads.

* refactor(native-chat): provenance is per item only; drop per-entry stamping

Main's #27947 writes one saved row per subagent, and each background task already has its own row,
so an item's own ownerFence names the run of every entry a producer still writes. Per-entry stamps
inside a row mattered only for the shared roster rows saved before #27947, and no run writes into
those any more, so the row's own provenance settles them correctly. Removes the entry stamping,
the optional ownerFence on roster entries and background tasks, and their tests.

* fix(native-chat): an item's provenance is set when it is created; revisions keep it

A newer run's provider can revise an item an older run created: Pi's start and an ACP
session/load both report context usage onto the newest saved turn. Restamping that turn with
the newer run let the newer run's exit settle the older run's unverifiable turn as interrupted.
Only creation states an owner now, as main's itemFences rule did.

* test(native-chat): keep the provenance test below the production lines it covers
brennanb2025 added a commit that referenced this pull request Oct 15, 2026
… refusal for a stopped agent's prompt (3/5, rebuild of #26867) (#28104)

* feat(native-chat): record which agent run wrote each journal item

Each journal item row, subagent roster entry and background-task entry now
records ownerFence: the lease fence of the agent run whose output produced it.
Optional, persisted, no row version bump and no migration. The journal's
itemFence() returns it, so the turn-verdict rules and per-run provider activity
read the producing run rather than the writer's fence.

* feat(native-chat): one current-work projection for every host reader; record death first

The host decides what work is current in one place
(structured-agent-session-current-work.ts) from the lease, the exit this host
saw, the runtimes it replaced, its live child and each item's provenance.
Every host reader (queue, Stop, prompt answers, commands, status feed, idle
sweep, teardown snapshot, history pages and frames, orchestration mailbox)
reads it, so a dead agent's leftovers stop reading Working or holding the queue
even when their cleanup write failed. The journal's activeTurnId()/liveTurnScope()
become the raw runningTurn().

On exit the host records the child's end first and signals generationEnded,
which republishes frames, the status feed and settlement waits and wakes the
queue drain with no journal row. Pages and frames carry optional working and
actionablePromptIds fields.

* feat(native-chat): clients read the host's working answer; refuse answers to a stopped agent plainly

Desktop and mobile prefer the host's working and actionablePromptIds fields
when present (merged across batches like latestTurn) and fall back to today's
row derivation against an older host. A prompt an ended agent raised stops
looking active; answering it is refused before any provider sees it, with
"<Agent> has stopped, so your answer was not sent. Send a message to continue."
Cancelling it only dismisses it in the journal: it no longer triggers the
chat's Stop, pauses the queue or withdraws queued cards.

* refactor(native-chat): keep structuredAgentSessionHandsOver file-local until a caller needs it

Nothing outside the projection calls it in this part; Part 5 exports it for the start-failure row.

* test(native-chat): fewer provenance tests: fold reopen and unstated-owner checks into the main case

Drops the epoch-replacement case (Part 2 rewind test reads the same values through the same rebuild) and the corrupt-value case (no version writes one).

* test(native-chat): drop current-work mirrors: the viewKey unit case and the still-live rewind case

The flow cases keep every outcome: dead leftovers read as nothing, Stop has nothing to stop, a waiting card drains, a live owner publishes as before, and a rewind never promotes dead work.

* test(native-chat): fewer client tests: one flow per client, one fallback each

Keeps desktop and phone Working from the host (with the older-host fallback), the reducer merge contract, the ended question Cancel that only dismisses, the agent-named refusal and the resolution receipt. Drops per-helper prompt tests, the transcript-placement test, the stop-note client reduction, the Steer cards that match main, and per-reason refusal rows.

* test(native-chat): an unstamped roster entry from an older build reads as its row provenance

Moved here from Part 4 so it sits beside stampJournalEntryProvenance.

* test(native-chat): build the older-build roster row inline, after main removed its body helper

Main #27947 writes one row per subagent and deleted journal-subagent-group-body; a roster row from an older build is still what this case reads.

* refactor(native-chat): provenance is per item only; drop per-entry stamping

Main's #27947 writes one saved row per subagent, and each background task already has its own row,
so an item's own ownerFence names the run of every entry a producer still writes. Per-entry stamps
inside a row mattered only for the shared roster rows saved before #27947, and no run writes into
those any more, so the row's own provenance settles them correctly. Removes the entry stamping,
the optional ownerFence on roster entries and background tasks, and their tests.

* fix(native-chat): an item's provenance is set when it is created; revisions keep it

A newer run's provider can revise an item an older run created: Pi's start and an ACP
session/load both report context usage onto the newest saved turn. Restamping that turn with
the newer run let the newer run's exit settle the older run's unverifiable turn as interrupted.
Only creation states an owner now, as main's itemFences rule did.

* test(native-chat): keep the provenance test below the production lines it covers

* fix(native-chat): an ended agent's card Cancel commits with its receipt, through dismissPrompt

The ended-generation dismissal wrote the cancelled resolution without the Cancel's operation
receipt and without the dismissal's failure handling, so a receipt write failing after it would
answer "outcome unknown" over a card already closed. It now goes through dismissPrompt, which
carries the uncommitted receipt in the same append and answers dismissalNotSaved on failure; a
null `answer` skips the adapter, since no live provider holds an ended generation's card (Pi's
adapter refuses a fence with no live session outright).
brennanb2025 added a commit that referenced this pull request Oct 16, 2026
…eft (4/5, rebuild of #26867) (#28111)

* feat(native-chat): record which agent run wrote each journal item

Each journal item row, subagent roster entry and background-task entry now
records ownerFence: the lease fence of the agent run whose output produced it.
Optional, persisted, no row version bump and no migration. The journal's
itemFence() returns it, so the turn-verdict rules and per-run provider activity
read the producing run rather than the writer's fence.

* feat(native-chat): one current-work projection for every host reader; record death first

The host decides what work is current in one place
(structured-agent-session-current-work.ts) from the lease, the exit this host
saw, the runtimes it replaced, its live child and each item's provenance.
Every host reader (queue, Stop, prompt answers, commands, status feed, idle
sweep, teardown snapshot, history pages and frames, orchestration mailbox)
reads it, so a dead agent's leftovers stop reading Working or holding the queue
even when their cleanup write failed. The journal's activeTurnId()/liveTurnScope()
become the raw runningTurn().

On exit the host records the child's end first and signals generationEnded,
which republishes frames, the status feed and settlement waits and wakes the
queue drain with no journal row. Pages and frames carry optional working and
actionablePromptIds fields.

* feat(native-chat): clients read the host's working answer; refuse answers to a stopped agent plainly

Desktop and mobile prefer the host's working and actionablePromptIds fields
when present (merged across batches like latestTurn) and fall back to today's
row derivation against an older host. A prompt an ended agent raised stops
looking active; answering it is refused before any provider sees it, with
"<Agent> has stopped, so your answer was not sent. Send a message to continue."
Cancelling it only dismisses it in the journal: it no longer triggers the
chat's Stop, pauses the queue or withdraws queued cards.

* feat(native-chat): one settlement transaction for everything an ended run left

An exit now settles, in one lifecycle batch planned at its own turn in the
write queue, everything its run left (turn, calls, prompts, reasoning,
unanswered sends) plus leftovers of earlier ended runs, and only the subagent
roster entries and background tasks those runs observed, by each entry's own
provenance. Main's stale settle moves to stale-state-settlement.ts with fence
scoping; dead-generation-settlement.ts becomes a planner;
leftover-settlement.ts combines them.

Resume eligibility widens in one case: this host saw the root exit at the
lease's fence and the release write failed; the acquisition replaces the
owner only once a probe proves it gone.

* refactor(native-chat): keep structuredAgentSessionHandsOver file-local until a caller needs it

Nothing outside the projection calls it in this part; Part 5 exports it for the start-failure row.

* test(native-chat): fewer provenance tests: fold reopen and unstated-owner checks into the main case

Drops the epoch-replacement case (Part 2 rewind test reads the same values through the same rebuild) and the corrupt-value case (no version writes one).

* test(native-chat): drop current-work mirrors: the viewKey unit case and the still-live rewind case

The flow cases keep every outcome: dead leftovers read as nothing, Stop has nothing to stop, a waiting card drains, a live owner publishes as before, and a rewind never promotes dead work.

* test(native-chat): fewer client tests: one flow per client, one fallback each

Keeps desktop and phone Working from the host (with the older-host fallback), the reducer merge contract, the ended question Cancel that only dismisses, the agent-named refusal and the resolution receipt. Drops per-helper prompt tests, the transcript-placement test, the stop-note client reduction, the Steer cards that match main, and per-reason refusal rows.

* test(native-chat): fewer settlement tests: keep the exit-delivery flows and the per-entry scoping flow

Drops the no-added-delay timing check, the frame-once check, two stamping unit cases and the Codex combined case (the roster flow test covers its outcome).

* test(native-chat): drop the resume-eligibility predicate mirror; move the unstamped-entry case to Part 1

* test(native-chat): an unstamped roster entry from an older build reads as its row provenance

Moved here from Part 4 so it sits beside stampJournalEntryProvenance.

* test(native-chat): build the older-build roster row inline, after main removed its body helper

Main #27947 writes one row per subagent and deleted journal-subagent-group-body; a roster row from an older build is still what this case reads.

* refactor(native-chat): provenance is per item only; drop per-entry stamping

Main's #27947 writes one saved row per subagent, and each background task already has its own row,
so an item's own ownerFence names the run of every entry a producer still writes. Per-entry stamps
inside a row mattered only for the shared roster rows saved before #27947, and no run writes into
those any more, so the row's own provenance settles them correctly. Removes the entry stamping,
the optional ownerFence on roster entries and background tasks, and their tests.

* fix(native-chat): an item's provenance is set when it is created; revisions keep it

A newer run's provider can revise an item an older run created: Pi's start and an ACP
session/load both report context usage onto the newest saved turn. Restamping that turn with
the newer run let the newer run's exit settle the older run's unverifiable turn as interrupted.
Only creation states an owner now, as main's itemFences rule did.

* test(native-chat): keep the provenance test below the production lines it covers

* fix(native-chat): an ended agent's card Cancel commits with its receipt, through dismissPrompt

The ended-generation dismissal wrote the cancelled resolution without the Cancel's operation
receipt and without the dismissal's failure handling, so a receipt write failing after it would
answer "outcome unknown" over a card already closed. It now goes through dismissPrompt, which
carries the uncommitted receipt in the same append and answers dismissalNotSaved on failure; a
null `answer` skips the adapter, since no live provider holds an ended generation's card (Pi's
adapter refuses a fence with no live session outright).

* Native chat: a resumed subagent or Claude background task belongs to the run executing it

A subagent row that run 1 created and run 2 resumed kept run 1's creation
fence, so settling run 1's death marked run 2's live subagent unverifiable.
Claude background tasks reuse their rows the same way (a matching parent tool
use, or a parentless row).

Rows of reusable child execution now also name their execution owner: the
fence of the child process whose report the write copies, captured when that
report arrives, never the lease that is current when a queued write flushes.
- Subagent rows: the host captures the live child's fence when its child-work
  report changes the records, and rewrites a running subagent another child now
  reports even when its text is unchanged.
- Claude background-task rows: written through that child's own event sink,
  which stamps its bound fence.
- Creation provenance (`ownerFence`) is unchanged. Writes that do not state an
  owner (settlement, Pi's start usage, ACP session/load replay, ACP tasks) keep
  it, and a row without one falls back to its creation fence.

`journal.itemFence()` now answers whose execution an item is
(`executionOwner ?? ownerFence`), so every settlement and liveness read, inside
its write transaction, follows the run that resumed the work.

Also drops the event sink's compatibility alias for the identity resolver (the
Codex sink names the resolver itself), keeping the sink under its line limit.

* Native chat: a subagent row is written through the child whose report it copies

Review of c0add67: the subagent row writer read its execution owner from
the host's installed child when a report landed. A child that is still being
acquired reports a resumed subagent before the host installs it, so its row
was written at once under the old owner, then the attach's settlement of what
the previous child left marked it unverifiable, and nothing rewrote it until
the next report.

Each adapter (Claude, Codex, ACP) now hands its child-work report to the host
with that child's own event sink, the write path its rows already take. The
host passes it through the status feed to the subagent row writer, which writes
the rows that report changes through that sink with `executes`. They land in
the child's own order, after the attach's settlement, at the fence the sink is
bound to, and that fence is the row's execution owner. A running subagent a
child has not written yet is written once even when its text is unchanged.
Changes the host makes itself (a Stop's acknowledgement, an end) still write
directly and keep the row's owner. The shared child-work evidence type is
unchanged: the sink travels as a separate argument.

Test: a Claude helper the next child reports again while it is still starting
stays working after that start's settlement, through the shipping adapter and
host. It fails on c0add67 (the row lands `unverifiable`).

* Native chat: the subagent row writer always awaits a promise

CI's type-aware lint flagged the row writer handing `Promise.all` a value
that could be undefined when a sink has no `written()` barrier. A sink without
one now reads as landed.

* Native chat: keep refused subagent writes, and carry both owners through a rewind

Review of b161aa3 / 129f36d:
- `admitChildWork`'s producer is optional again, so the host's own
  turn-started report compiles.
- A subagent row written through the reporting child's sink uses the sink's
  checked admission. A write it refuses under backpressure is queued again
  once what the sink holds has landed; a refusal or a failed write frees that
  child's claim on the row, so a later report retries it.
- A rewind carried `itemFence()` (now whose execution an item is) into the
  rebuilt row's creation `ownerFence`, and dropped `executionOwner`. Retained
  rows now carry both as stored (`journal.itemProvenance`), the rewind record
  keeps `executionOwner` beside `ownerFence`, and both rebuild paths write it
  back: epoch replacement and the context rewind, which builds its rows from
  the same replacement items.

Test: the two-fence test now rebuilds the epoch from the resumed rows and
settles the first run's death again; the resumed rows stay live. It fails if
the epoch replacement drops `executionOwner`.

* test: run the resumed-child owner test in the Node SQLite project

It opens a real journal database, so it belongs on the list the SQLite runtime
boundary test checks.
@brennanb2025

brennanb2025 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Closing without merging, by Brennan's decision: this was split into #28103, #28104, #28111 and #28122. The first three merged and fixed the stale Working bug; #28122 is closed, and its one remaining fix moves to #30405.

@brennanb2025
brennanb2025 deleted the brennanb2025/chat-settle-at-ownership-events branch October 18, 2026 19:35
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