Skip to content

agentHost: remove archived and deleted worktrees in the background - #341721

Merged
Sandeep Somavarapu (sandy081) merged 19 commits into
mainfrom
agents/deferred-worktree-cleanup-fix6
Oct 15, 2026
Merged

Sandeep Somavarapu (sandy081) merged 19 commits into
mainfrom
agents/deferred-worktree-cleanup-fix6

Conversation

@sandy081

@sandy081 Sandeep Somavarapu (sandy081) commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Fixes #341747

Builds on Block 3a (#341626, merged): the in-use check reads 3a's central session state.

What

Archiving or deleting an Agent Host session no longer runs Git on its worktree. Archive and delete only record that the worktree should be removed. One background clean-up service then removes the folder a few seconds later. This applies to both session worktrees and detached (Dev Container) worktrees, and the clean-up never removes a worktree another live session or chat still uses.

Before, manual archive committed and removed the worktree inline, and delete awaited the removal. Neither checked whether another session or chat still worked in that folder.

How

  • Recording intent. A pending removal row goes into agent-host.db (new table pending_worktree_removals, migration 18). The row holds the worktree path, repository root, branch, owner, kind (session or detached), mode, whether the owner was deleted, attempts and timestamps.
    • Modes: commit (manual archive: commit uncommitted changes, then remove), synced (automatic archive and lifecycle deletion: remove only while the branch is synced with its upstream), and delete (manual deletion: force-remove). Branches are always kept.
    • Archive writes the row under the worktree's lock. Delete writes it in the same transaction as the tombstone, so it is crash-safe even though the session's data is deleted right after.
  • One clean-up service (IAgentHostWorktreeCleanupService).
    • When it runs: a pass runs about 3 s after any archive or delete; at startup only once startup has settled (after the first listing); and periodically while rows remain.
    • Per row, under that worktree's lock, a pass:
      • drops the row if the owner was unarchived since;
      • keeps the folder if a non-archived, non-deleted other session or chat still has a folder at or inside the worktree;
      • otherwise runs the mode's Git work, removes the folder, and deletes the row.
    • Failures retry with exponential backoff and are logged as a warning after 5 attempts.
    • Startup reconciliation of unclaimed detached worktrees now runs as part of this deferred start.
  • In-use check. One SQL query over central working directories only, with no session.db opens. It reads the session list entry (sessions_v2.payload), agentHost.sessionWorkingDirectories, chats_v2.working_directories, and the session_chat_state working and launch folders.
    • A session counts as archived when its list entry or its central state says so.
    • A peer chat's backing provider session is not counted, because the chat itself is.
    • Each JSON column is prefiltered with instr, and case is folded in SQLite.
  • Unarchive drops the pending row and recreates the folder if it is missing, as before.
  • Lifecycle auto-delete keeps today's guarantee: it deletes only when each worktree is gone, or exists with its branch synced. It then records synced removals.
  • No AHP or UI change. AGENTS.md documents the clean-up.

Decisions

  • The session list entry is an in-use source. A session's own folders are not in 3a's central state unless its workspace changed, so the query also reads sessions_v2.payload. This is still one query with no session.db opens.
  • Deleting a session reads its worktrees under their lock, so a worktree still being created is recorded. Only a deletion falls back to a worktree whose metadata never persisted, because unarchive could not recreate it.

Migration number

pending_worktree_removals uses agent-host.db migration 18. Block 3b (#341714) merged first with migration 17, and Insiders profiles already run it, so this table comes after it rather than reusing 16: every database upgrades strictly in order (15, then 17, then 18). The table is also created idempotently on open as a safety net. Block 4a takes 19.

Real-data dry run (read-only)

On a copy of a daily Insiders agent-host.db and the session.db of all 743 sessions (read with mode=ro, nothing written or removed):

  • The upgrade from schema 14 (to 16 at the time; now 18) records 0 pending removals. Upgrading removes nothing.
  • There are 431 recorded worktrees: 375 session worktrees (268 with archived owners) and 56 detached worktrees in 12 sessions. 139 are still on disk.
  • The in-use query was checked on all 431 against independent ground truth (list-entry folders, chats_v2 folders and session.db-only folders of every non-archived, non-backing session). It agreed on 431/431, with 0 false negatives and 0 false positives. Median 2.3 ms, max 25 ms.
  • Safety: 0 records equal a repository root, 0 lie outside a .worktrees/ folder, and 0 point at a primary checkout. One path recorded by two sessions (one archived, one live) is kept, as designed.

Performance

Measured with real Git on a 3,000-file worktree, median of 5:

Before After
Archive path 555 ms 4.4 ms
Delete, end to end 213 ms 6.3 ms

The Git work moves to the background pass, about 584 ms per archived worktree. The in-use query at 10k sessions / 20k chats on a file-backed agent-host.db takes about 10 ms in the worst case (no match) and about 3.4 ms on a match. These were measured at low load; under machine load around 24 the numbers were about 2× higher.

Validation

All runs with COPILOT_*, AGENT_HOST_* and GITHUB_TOKEN unset.

Command Result
npm run typecheck-client Passed (0 errors)
eslint --max-warnings 0 on every changed .ts Passed
npm run valid-layers-check Passed
./scripts/test.sh --runGlob "vs/platform/agentHost/test/node/**/*.test.js" (head 98005bd710c) 11054 passing, 0 failing, 75 pending
./scripts/test.sh --grep "AgentHost|Chat" (head ab4f4a15e7d) 12850 passing, 0 failing, 70 pending
npm run test-agent-host-e2e -- --jobs 2 (strict replay, head 98005bd710c) All 6 suites passed, 950 passing, 0 failing: Conformance 368, Claude 124, Codex 153, Copilot 268, Copilot OTel 22, Copilot managed settings 15
npm run smoketest -- -g "Agents Window" (pre-rebase head) 5 passing, 4 pending
Mutation checks (31: one per rule, including dropping the list-entry source, an unlocked deletion read, archive using the unpersisted fallback, lifecycle deleting unsynced work, the clean-up opening session.db, and one for each review fix below) 31/31 killed

Live (Agents window, Copilot, scratch repo, pre-rebase head):

Scenario Result
Archive a worktree session with an uncommitted file Shown as archived at once; folder removed 3.7 s later; the file was committed on the kept branch
Unarchive Folder recreated in 2.3 s with the file
A second session working in that worktree Folder kept while that session was live; removed 4.0 s after it was archived
Delete Folder removed 4.1 s later; branch kept
Kill the app right after archiving, then relaunch The pending row survived; folder removed 5.0 s after relaunch

An independent code review found three issues, all fixed with tests:

  • a peer chat's backing session kept the parent's worktree in use;
  • a deletion during worktree creation could leak the worktree;
  • the unpersisted fallback had also applied to archive.

The PR review raised seven more, all fixed with tests:

  • reconciliation of detached worktrees no longer removes a folder that is pending clean-up or that another session or chat uses;
  • an archive request is dropped when the session's persisted state says it was unarchived (a crash between unarchive and its cancellation);
  • the removal asks the in-use check again right before git worktree remove, after the commit that precedes it. A path-scoped reservation shared by every folder-acquisition path is left as a follow-up;
  • the central archived flag takes precedence over a stale list entry;
  • owner deletion is tracked apart from the Git mode, so a lifecycle (synced) deletion also deletes the detached record;
  • a skipped removal (unsynced, branch missing, unknown Git state) is kept and retried with backoff;
  • a folder that is already gone is pruned from Git in every mode.

#341747 (Windows EBUSY in the session storage identity tests): the suite's teardown disposed its agent-host.db instances, which only starts an asynchronous close, and then deleted the temp folder while SQLite still held agent-host.db-journal open. The teardown now awaits each database's close before deleting the folder, and the test that #341749 skipped is enabled again.

Not run:

  • Dev Container live scenarios (Docker was not available). The detached path is covered by unit tests and the E2E detached-worktree suite.
  • Azure pipeline 111 cross-platform validation for the updated E2E tests.
  • The Agents window smoke tests and live scenarios on the final rebased head. They ran on the pre-rebase head, and the rebase onto main had no conflicts.

@sandy081 Sandeep Somavarapu (sandy081) added this to the 1.143.0 milestone Oct 15, 2026
Copilot AI balanced review requested due to automatic review settings October 15, 2026 08:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved concurrency and lifecycle-state issues can remove live worktrees, while incomplete cleanup handling can leave orphaned resources.

7 open findings
What changed in this PR

Moves Agent Host worktree cleanup out of archive and delete operations into a durable background service, building on centralized session state.

Changes:

  • Adds persistent removal requests, deferred processing, and retry backoff.
  • Routes session and detached-worktree lifecycle operations through cleanup.
  • Updates documentation and tests for deferred removal and shared-folder protection.
File Description
src/​vs/​platform/​agentHost/​test/​node/​shared/​worktreeIsolation.test.ts Tests deferred removal and preservation rules.
src/​vs/​platform/​agentHost/​test/​node/​e2e/​suites/​workingDirectoriesSuite.ts Waits for background deletion.
src/​vs/​platform/​agentHost/​test/​node/​e2e/​suites/​detachedWorktreeSuite.ts Polls for detached-worktree cleanup.
src/​vs/​platform/​agentHost/​test/​node/​copilotAgent.test.ts Uses the cleanup service in restoration tests.
src/​vs/​platform/​agentHost/​test/​node/​chatMetadataTestHelpers.ts Adds cleanup fixtures and database forwarding.
src/​vs/​platform/​agentHost/​test/​node/​chatContributions.test.ts Updates lifecycle service mocks.
src/​vs/​platform/​agentHost/​test/​node/​agentSideEffects.test.ts Registers cleanup dependencies.
src/​vs/​platform/​agentHost/​test/​node/​agentServiceTestUtils.ts Exposes cleanup service access for tests.
src/​vs/​platform/​agentHost/​test/​node/​agentService.test.ts Tests deferred lifecycle cleanup integration.
src/​vs/​platform/​agentHost/​test/​node/​agentHostWorktreeRemovalDatabase.test.ts Tests persistence and in-use queries.
src/​vs/​platform/​agentHost/​test/​node/​agentHostWorktreeCleanupService.test.ts Tests scheduling, cancellation, and retries.
src/​vs/​platform/​agentHost/​test/​node/​agentHostTurnTelemetry.test.ts Updates telemetry test dependencies.
src/​vs/​platform/​agentHost/​test/​node/​agentHostTurnHangTelemetry.test.ts Updates hang-telemetry test dependencies.
src/​vs/​platform/​agentHost/​test/​node/​agentHostToolCallTelemetry.test.ts Updates tool-telemetry test dependencies.
src/​vs/​platform/​agentHost/​test/​node/​agentHostSessionStateDatabase.test.ts Updates migration expectations.
src/​vs/​platform/​agentHost/​test/​node/​agentHostSessionLifecycle.test.ts Tests revised automatic-deletion behavior.
src/​vs/​platform/​agentHost/​test/​node/​agentHostSavedChatContinuation.test.ts Updates worktree lifecycle mocks.
src/​vs/​platform/​agentHost/​test/​node/​agentHostDatabase.test.ts Expects schema version 16 and removal table.
src/​vs/​platform/​agentHost/​node/​shared/​worktreeIsolation.ts Separates metadata recording from Git removal.
src/​vs/​platform/​agentHost/​node/​compatibleAgentHostDatabase.ts Forwards cleanup operations with identity mapping.
src/​vs/​platform/​agentHost/​node/​chatContributions/​additionalWorktreeLifecycle/​additionalWorktreeLifecycleService.ts Delegates additional-worktree cleanup.
src/​vs/​platform/​agentHost/​node/​agentSideEffects.ts Requests cleanup on archive and cancellation on unarchive.
src/​vs/​platform/​agentHost/​node/​agentSessionRegistry.ts Includes removal requests with tombstones.
src/​vs/​platform/​agentHost/​node/​agentServiceComposition.ts Removes inline cleanup from lifecycle accessors.
src/​vs/​platform/​agentHost/​node/​agentService.ts Integrates deferred cleanup into session operations.
src/​vs/​platform/​agentHost/​node/​agentHostWorktreeRemovalDatabase.ts Defines removal persistence and in-use queries.
src/​vs/​platform/​agentHost/​node/​agentHostWorktreeCleanupService.ts Implements background cleanup processing.
src/​vs/​platform/​agentHost/​node/​agentHostSessionLifecycle.ts Checks deletion eligibility without inline removal.
src/​vs/​platform/​agentHost/​node/​agentHostServices.ts Registers the cleanup service.
src/​vs/​platform/​agentHost/​node/​agentHostDatabase.ts Adds migration and transactional removal storage.
src/​vs/​platform/​agentHost/​AGENTS.md Documents deferred cleanup behavior.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@sandy081
Sandeep Somavarapu (sandy081) marked this pull request as ready for review October 15, 2026 09:38
Sandeep Somavarapu (sandy081) added a commit that referenced this pull request Oct 15, 2026
The deferred worktree clean-up change (#341721) lands first with version 16
(its pending worktree removals table), so the chat origin migration follows it.

Co-authored-by: Copilot <[email protected]>
@github-actions

github-actions Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Base: e941aa12 Current: 1a4b3932

No screenshot changes.

Sandeep Somavarapu (sandy081) added a commit that referenced this pull request Oct 15, 2026
* agentHost: sync Agent Host Protocol (chat-level config)

Sync the generated protocol from 13277064 to agent-host-protocol dbbd1217
(microsoft/agent-host-protocol#527), which adds per-chat config:
`chatMutable` on session config schema properties, the `ChatState.config`
overlay and the client-dispatchable `chat/configChanged` action (introduced
in 1.1.0; PROTOCOL_VERSION unchanged). The range also brings the optional
`SessionModelInfo.vendor` field (#505).

Re-export `ChatConfigState` and `ChatConfigChangedAction` from the wrappers.

Co-authored-by: Copilot <[email protected]>

* agentHost: add per-chat config helpers (Block 3b)

A property with `chatMutable` in the session's config schema can be set per
chat; a chat's effective config is the session's config with its own values
applied over it. Add the shared helpers the host and clients use to tell the
two apart, split a patch between chat and session, compute the effective
config, and validate a chat write.

Co-authored-by: Copilot <[email protected]>

* agentHost: keep a chat's own config on its registration (Block 3b)

`ChatState.config` holds the values a chat sets for itself. The state
manager keeps them on the chat's registration so they exist before a
restored chat's state is resolved: a `chat/configChanged` for such a chat
updates them, and resolution carries them into its state. Restore, restored
peers and new chats accept initial values; hydration contributions can
return them through `IRestoredChat.config`.

Co-authored-by: Copilot <[email protected]>

* agentHost: resolve config per chat in the configuration service (Block 3b)

A chat's effective config is its own values, then those of the chats that
spawned it (by the recorded spawn edge), then the session's and the host's.
Own values only count for properties a chat may set (`chatMutable`).

Add chat reads, `updateChatConfig` (settable properties change the chat, a
subagent's go to the chat it inherits from, the rest change the session),
`onDidChatConfigChange` (fired for a changed chat and its subagents, and for
chats that inherit a changed session key), and seeds that give a chat being
created its values before it is registered.

The session chain no longer derives a parent from the shape of a subagent
session URI; inheritance follows recorded spawn edges only.

Co-authored-by: Copilot <[email protected]>

* agentHost: validate client changes of a chat's own config (Block 3b)

A client may set only properties that the session's schema lets a chat set
(`chatMutable`), never host-written or read-only ones, and only with values
the session's write rules accept. A subagent has no config of its own: it
inherits from the chat that spawned it. A replacement keeps the chat's
host-written values.

Co-authored-by: Copilot <[email protected]>

* agentHost: persist a chat's own config in its own database (Block 3b)

The values a chat sets for itself are stored under
`agentHost.chatConfigValues` in the chat's own database (the session
database for the default chat, separate from the session's `configValues`).
Nothing is mirrored: older builds never read them. The value records the
chat it belongs to, so a copied database (a fork's `VACUUM INTO`) is never
read as another chat's values.

The new `chatConfig` contribution persists every accepted change, from
clients, the host and providers alike, and restores the values with the
chat. Subagents have none.

A fork or side chat starts with its source chat's own values: a seed makes
them visible to the provider while it creates the chat, and they are
registered and persisted with the new chat. Other chats start with none and
inherit the session's.

Co-authored-by: Copilot <[email protected]>

* agentHost: apply approvals and tool permissions per chat (Block 3b)

The host's approval decisions read the effective config of the chat a tool
call belongs to: its approval level (including a host-reported effective
mode) and its tool permissions. "Allow in this Session" adds the tool to
that chat's own permissions; from a subagent, to the chat it inherits its
config from.

Co-authored-by: Copilot <[email protected]>

* agentHost: resolve sandbox enablement per chat (Block 3b)

A chat's sandbox selection is its own value over the session's, within the
session's policy floor. The sandbox APIs take the chat and its session:

- The applied enablement is recorded per chat in the session's
  `vscode.sandboxState` metadata (`chats[chat]`), read through a typed,
  validating reader. The session-level fields keep describing the default
  chat for older clients.
- A policy that requires sandboxing turns a chat's own `off` back on, like
  the session's.
- A rejected change rolls back where the selection was set (the chat's own
  values or the session's), unless a newer selection superseded it.
- Copilot's SDK sandbox, its terminal sandbox engine and its browser tool
  restrictions apply the chat's selection; a session opt-out from a
  permission request changes that chat only.

`getChatConfigValues` returns the same object while its inputs are unchanged,
which keeps the superseded-request check based on identity.

Co-authored-by: Copilot <[email protected]>

* agentHost: elevate Agent Merge's autonomous config per owning chat (Block 3b)

Agent Merge elevates the chat that owns each enabled folder, not the whole
session. Properties a chat may set (mode, approvals, tool permissions) are
elevated in that chat's own values and restored once it owns no enabled
folder; the per-chat bookkeeping (`agentMerge.chatInjectedConfiguration`,
host-owned) records the chat's own values before elevation. Narrowing never
waits for an active turn.

Properties no chat may set keep the session-wide elevation and its
bookkeeping, which also rolls back session-wide elevation an older build
applied. Folder enablement and lifecycle stay per (session, folder).

A fork or side chat copies its source chat's own values without the
elevation.

Co-authored-by: Copilot <[email protected]>

* agentHost: read and write Copilot's approvals and mode per chat (Block 3b)

Each Copilot chat runtime reads its own chat's effective approvals and mode
(permission mode, autopilot, the SDK mode sent with a turn) and reacts to
that chat's config changes. Write-backs change that chat only: an SDK mode
switch (e.g. leaving plan mode), a direct approval toggle and the
effective approval mode it applied. The policy's available approval modes
stay session-level and are reported by the session-backed chat.

Slash-command completion state stays session-level: completions are
addressed to the session, not a chat.

Co-authored-by: Copilot <[email protected]>

* agentHost: tell chats about config keys a replacement removed (Block 3b)

A replacing `session/configChanged` or `chat/configChanged` removes keys it
does not list. The chat change events now carry the keys the action set and
the keys whose value the reduction changed, so a runtime also hears about a
removed key. The state manager reports a chat's previous and new own config
for this, like it does for a session's.

Co-authored-by: Copilot <[email protected]>

* agentHost: read and write Claude's permission mode per chat (Block 3b)

A Claude chat runtime reads its own chat's effective permission mode (at
materialize, before each send and on its chat's config changes) and records
it in the chat's overlay snapshot. Approving `ExitPlanMode` switches that
chat to `acceptEdits`; other chats of the session keep their mode.

Co-authored-by: Copilot <[email protected]>

* agentHost: read Codex's session settings per chat (Block 3b)

A Codex chat runtime reads its own chat's effective permissions preset,
approval policy, sandbox mode, writable directories, network access,
reasoning effort, personality and summary at thread and turn start (the
session's while it is not bound to a chat yet). A fork starts from its own
effective values, which Agent Host seeds with its source chat's.

Co-authored-by: Copilot <[email protected]>

* agentHost: let chats set their own approvals, mode and permissions (Block 3b)

Marks the settings a chat may set for itself `chatMutable` in each session
schema: approvals, mode, tool permissions and sandbox on the host schema;
Copilot's effective approval mode; Claude's permission mode; and Codex's
permissions preset and its (hidden) native permission keys. Workspace and
other settings stay with the session.

Agent Merge now elevates these in the own values of the chat that owns each
enabled folder; the session-wide path remains for anything a chat may not set.

Co-authored-by: Copilot <[email protected]>

* agentHost: use a chat's own approvals and mode for telemetry, trust and Mission Control (Block 3b)

- Turn telemetry reports the chat's effective approvals and mode, also for
  subagent turns (through their spawning chats), and a chat's own mode change
  reports agentHost.executionModeChanged with its initiator.
- Changing a chat's workspace requests workspace trust unless that chat's
  effective approvals allow everything.
- The Mission Control adapter translates a chat's own values in chat
  snapshots and chat/configChanged in both directions.

Adds IAgentConfigurationService.getChatConfigState (the session's schema with
the chat's effective values).

Co-authored-by: Copilot <[email protected]>

* agentHost: record the session each chat is created in (Block 3b)

Adds `chats_v2.origin_session_uri` (agent-host.db migration 16), written
once when a chat row is inserted and exposed as `originSession` on the
host's chat records. Rows written before it, or by an older build, read as
created in their owner, which holds until chats can move (Block 4).

Rebase check: #6 also adds a migration 16; this one takes the next free
version.

Co-authored-by: Copilot <[email protected]>

* sessions: read and set agent host settings per chat in the Agents window (Block 3b)

Session config reads and writes now name their chat (a required parameter):
- `getSessionConfig(session, chat)` applies the chat's own values, from its
  `ChatState.config`, over the session's. Only properties the session's schema
  lets a chat set (`chatMutable`) apply, so a host without them reads exactly
  as before. The chat's state subscription is kept while it is read and
  released when idle, as for session state.
- `setSessionConfigValue(session, chat, ...)` sends a property the chat may set
  as `chat/configChanged` to that chat; anything else stays a session write.
- `getSessionSandboxEnabled(session, chat)` reads the chat's sandbox state,
  else the session's.
- `getSessionOwnConfig(session)` is the session's own config, which the
  session settings file shows and edits.

Pickers, completions and config slash commands use the chat they act on:
the active chat, the submitting chat, or a draft's main chat.

Co-authored-by: Copilot <[email protected]>

* chat: read and set agent host settings per chat in the editor (Block 3b)

An editor chat backed by an agent host reads its chat's effective config
(its session's, with the chat's own values from `ChatState.config` applied
for the properties a chat may set) and sends a change to the chat
(`chat/configChanged`) or its session (`session/configChanged`) by property.
The backend chat comes from the session's chat catalog: its default chat, or
the peer chat the resource's fragment names.

- The chat input picker follows its chat's state alongside its session's.
- Config completions and submit-time config use the same helpers.
- The sandbox notice reads the chat's sandbox selection and applied state,
  turns off that chat's sandboxing, and reports a failed change of any chat
  this client made (`readChatSandboxStates`).
- The Agents window refreshes its pickers when a chat's applied sandbox state
  changes.

Co-authored-by: Copilot <[email protected]>

* agentHost: document per-chat config (Block 3b)

Describes where a chat's own config is stored and how it resolves (own,
spawning chats, session, host), the client rule for chat/configChanged, the
per-chat sandbox selection and state, Agent Merge's elevation per owning
chat, the chats_v2 origin column, and the chatConfig contribution's order
and hooks.

Co-authored-by: Copilot <[email protected]>

* agentHost: expect /goal to set its chat's mode in the Copilot E2E suite (Block 3b)

Mode is a chat's own setting, so the config slash command changes the
chat's mode and leaves its session's.

Co-authored-by: Copilot <[email protected]>

* agentHost: persist a fork's copied config before creating it (Block 3b review L1)

A fork or side chat's copy of its source chat's own config values was
written in the background after the chat was announced, so a crash or a
failed write left it with its session's values. It is now written before the
chat is registered, and a failed write fails and rolls back the creation like
the chat's other initial records.

Co-authored-by: Copilot <[email protected]>

* agentHost: pin that a restored summary never rolls back a resolved chat's config (Block 3b review L2)

registerRestoredChatSummary replaces a chat's own config only while the chat has no resolved state; once resolved, the chat's live values (and its state's config) are authoritative and a later restore of its summary leaves them. Adds the test that pins this.

Co-authored-by: Copilot <[email protected]>

* agentHost: define writes to a gone chat and the chat config layers (Block 3b review L3, L4)

- L3: a write for a chat that is neither registered nor being created (it
  was disposed while a provider event was in flight) applies its session
  part and drops its chat part with a warning. Documented and tested; the
  host never resurrects a chat's values for it.
- L4: `getChatConfigValues` is to `getChatEffectiveValue` what
  `getSessionConfigValues` is to `getEffectiveValue`: the same chain (own,
  recorded spawning chats, session), with the host's layer only in the
  effective value. Documented and pinned by a test.

Co-authored-by: Copilot <[email protected]>

* agentHost: explain the unbound Codex runtime and the per-chat effective approval mode (Block 3b review L5, pass 3)

Comments only: a Codex runtime reads its session's values only before Agent Host binds it to its chat, before any thread or turn; Copilot's effectiveApprovalMode is chatMutable because the host writes it per chat, and stays readOnly to clients.

Co-authored-by: Copilot <[email protected]>

* agentHost: elevate a chat for any of its Agent Merge folders (Block 3b review M3)

Agent Merge elevated the chat owning an enabled folder only when the folder
was the chat's first working directory, so a multi-root chat lost elevation
for its other folders (the session-wide elevation it had before 3b).

The elevated chat for a folder is now its repair owner, else the first chat
with the folder among any of its working directories (recorded chat, default
chat, then catalog order; never a tool chat). A folder that no chat has keeps
the session-wide elevation of every property. Repairs still run in the chat
whose checkout is the folder.

Co-authored-by: Copilot <[email protected]>

* agentHost: test per-chat config end to end on the real schema (Block 3b review L6, L7)

With `platformSessionSchema`, a client's `chat/configChanged` for a chat's
approvals and mode is validated (isolation stays a session setting),
persisted in the chat's own storage and read through its chain by its
subagents. Also pins the accepted downgrade behaviour (Q1): an older client's
`session/configChanged` changes the session's value, which the default chat
follows only for properties it has not set for itself.

Co-authored-by: Copilot <[email protected]>

* sessions: show a chat's settings as resolving until its own values arrive (Block 3b review M4, L8, L9)

- M4: until a chat's state (with its own values) has arrived, its config is
  the session's and `isSessionConfigResolving(session, chat)` is true, so a
  picker renders as resolving instead of briefly showing the session's
  value. A chat whose state cannot be read stops resolving. Hosts without
  per-chat properties open no chat subscription and never resolve.
- L8: the config subscription of each visible session's active chat is held
  while it is shown, instead of re-arming an idle timer on every read; it is
  released after the idle period once it is no longer shown.
- L9: a value chosen in a peer chat is that chat's own and is no longer
  remembered as the default for new sessions; a choice in the default chat
  still is.

Co-authored-by: Copilot <[email protected]>

* sessions: subscribe a chat's own config only while it is shown (Block 3b review L8, M4, L10)

- L8: reading a chat's config (getSessionConfig, isSessionConfigResolving)
  never subscribes. The chat-state subscription supplying a chat's own
  values is acquired for the active chat of each visible session, and briefly
  by an explicit write, and released after the idle period once neither
  applies.
- M4: a chat that is not subscribed yet, or whose state has not arrived,
  reports resolving and reads as its session; readers are notified once its
  values are known, including when it is subscribed again after a release.
  Tested for the first read and the read after the idle release.
- L10: documented why splitting a mixed patch into the chat's and the
  session's actions (in that order) is safe.

Co-authored-by: Copilot <[email protected]>

* chat: show a chat's settings as resolving in the editor until its own values arrive (Block 3b review M4)

The editor's chat input picker showed the session's value for a property the
chat may set for itself until the chat's state arrived, then flipped to the
chat's own value. Until the chat's state is known, such a picker is now
dimmed and marked busy, and it cannot be opened or written; properties that
stay with the session are unaffected.

Co-authored-by: Copilot <[email protected]>

* agentHost: filter Copilot slash-command toggles by the completing chat's config

The completions service now tells providers the completing chat, resolved from
recorded state (the requested chat, else the named session's default chat), and
the Copilot provider reads that chat's effective mode and approvals instead of
the session's.

Co-authored-by: Copilot <[email protected]>

* sessions: keep a held chat config resolving observable in step with its subscription

isSessionConfigResolving returned the subscription entry's observable, which
went stale once the subscription was released (idle or reconnect) and was
never updated for an observable taken before the subscription. It now returns
an observable that follows the chat's subscription as it is acquired and
released.

Co-authored-by: Copilot <[email protected]>

* agentHost: document older clients' session config edits and mixed client writes

Co-authored-by: Copilot <[email protected]>

* sessions: show a subagent the config of the chats that spawned it

A subagent has no config of its own; the host applies the values of the chats
that spawned it (recorded Tool origins), but the Agents window showed the
session's. Reads, the sandbox state, the resolving state and the active-chat
subscriptions now follow the same recorded chain, and a subagent's writes
change its nearest spawning chat that is not one, as the host does. Only chats
the session's catalog lists are subscribed.

Co-authored-by: Copilot <[email protected]>

* chat: show a subagent the config of the chats that spawned it in the editor

The editor's pickers, sandbox notification and config helpers read only a
chat's own values, so a subagent showed the session's. They now follow the
recorded spawning chain like the host, the picker follows those chats' states
(resolving until all arrive), and a subagent's writes go to its nearest
spawning chat that is not one.

Co-authored-by: Copilot <[email protected]>

* agentHost: keep the session's effective approval mode the one a chat taking the session's approvals gets

A chat without its own effective approval mode shows the session's, but since
each chat reports its own, nothing kept the session's current, so a new chat
showed a mode its runtime would not apply. A Copilot chat runtime now also
reports the mode a chat taking the session's approvals runs with under the same
policy, and records its own mode only when what the chat would otherwise show
(its own value, else the session's) differs.

Co-authored-by: Copilot <[email protected]>

* agentHost: test that a new chat shows the approval mode and sandbox its runtime applies

Pins the live scenarios: a chat taking the session's approvals is shown the
mode its runtime policy resolves (not the one resolved when the session was
created with global auto-approval), and a new chat is shown and runs with the
session's sandbox selection rather than the default chat's own.

Co-authored-by: Copilot <[email protected]>

* sessions: retry a chat's config subscription once its session's catalog changes

A chat's config subscription that failed (e.g. a chat the host could not serve
yet after a restart) stayed held, failed, while the chat was shown, so it never
got its own values. It is now released, the chat shows its session's values,
and it is subscribed again once the session's chat catalog changes; the active
chats' subscriptions also follow catalog changes, so a chat the catalog lists
later is subscribed then.

Co-authored-by: Copilot <[email protected]>

* agentHost: show a chat's chosen approvals right away rather than a mode reported for others

After choosing approvals for a chat, its picker kept showing the reported
effective approval mode (the session's, or the chat's earlier one) until a turn
ran. A reported mode now only applies to the approvals it was resolved for: a
client choosing other approvals for a chat drops the chat's reported mode, a
chat that chose its own approvals without a reported mode of its own is shown
them rather than the session's mode, and a Copilot runtime records the mode it
applies whenever it differs from what the chat shows.

Co-authored-by: Copilot <[email protected]>

* sessions: follow a subagent's spawning chats for its sandbox change error and rejected selection

The Agents window's sandbox change-error and rejected-selection reads (from
main's managed sandbox bypass handling) now read the chat's applied sandbox
state through the same recorded spawning chain as its enablement.

Co-authored-by: Copilot <[email protected]>

* sessions: pass the chat to the per-chat config APIs in the branch picker test from main

Co-authored-by: Copilot <[email protected]>

* agentHost: never elevate a subagent that owns an Agent Merge folder's repairs

A subagent working in the folder could own its repairs and be chosen for
elevation; its writes go to its spawning chat, which may work elsewhere. The
elevated chat now falls through to the first normal chat working in the folder.

Co-authored-by: Copilot <[email protected]>

* agentHost: don't apply the session's reported approval mode to a chat that chose its own approvals

A chat choosing Manual in an Allow All session still inherited the session's
reported effective approval mode, so the host auto-approved its tool calls. A
reported mode now applies only to the approvals of its own layer and the
layers outside it (one rule for the host's chat values and both clients), and
the host's approval level falls back to a chat's chosen approvals until its
runtime reports the mode it applies.

Co-authored-by: Copilot <[email protected]>

* agentHost: let a chat set a chatMutable property whose session value is fixed

chatMutable is independent of sessionMutable in AHP, but a chat write was also
validated against the session's mutability, so a chat-only property was
rejected. Chat writes now check chat mutability (read-only properties stay
host-written), and the client write gates treat a chatMutable property as
writable from its chat.

Co-authored-by: Copilot <[email protected]>

* sessions: give the new chat widget and mode picker fixtures the chats the pickers read

The pickers now read a session's main and active chat for its per-chat config;
the fixtures' sessions lacked them, so the new chat widget fixtures failed to
render.

Co-authored-by: Copilot <[email protected]>

* agentHost: make the chat origin migration agent-host.db version 17

The deferred worktree clean-up change (#341721) lands first with version 16
(its pending worktree removals table), so the chat origin migration follows it.

Co-authored-by: Copilot <[email protected]>

* agentHost: start a new chat from the default chat's current config (D1)

A new chat that is not a fork, side chat or subagent now starts with the
default chat's current effective values for the properties a chat may set
(its own, else the session's) as its own, so Cmd+T begins where the default
chat is, as when chats shared the session's values. Read-only values and Agent
Merge's elevation are not copied; forks and side chats still copy their
source chat's own values.

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>
…d worktree clean-up)

Adds the pending_worktree_removals table (migration 16) that archive and
delete use to record a worktree removal instead of running Git inline,
the central in-use query over the session and chat working directories,
and lets a session's tombstone record its removals in the same
transaction.

Co-authored-by: Copilot <[email protected]>
…eferred worktree clean-up)

Archive and delete now only record the worktree removal: archive in its
worktree's lock, delete in the same transaction as the tombstone, and
neither runs Git. A single clean-up service removes session and detached
(Dev Container) worktrees after a short debounce, once startup settled,
and periodically while removals remain. Under the worktree's lock it
drops a removal whose owner was unarchived, keeps a folder that another
non-archived session or chat still uses, and otherwise runs the mode's
Git work (commit, synced or delete), retrying failures with backoff.

Unarchive drops the pending removal and recreates a missing folder.
Automatic deletion keeps its guarantee by checking that each worktree is
gone or synced, then records synced removals. Startup reconciliation of
unclaimed detached worktrees moves into the deferred clean-up start.

Co-authored-by: Copilot <[email protected]>
…ee clean-up)

Covers the removal modes, the deletion row written with the tombstone,
unarchive dropping a removal (also while a pass runs), the in-use rule
for non-archived, non-deleted sessions and chats, retries with backoff,
startup deferral and detached worktrees pending deletion. Periodic
passes are only armed once the clean-up started.

Co-authored-by: Copilot <[email protected]>
…worktree clean-up)

A session's own folders are only in its central session list entry
unless its workspace changed, so the in-use query also reads the
folders of sessions_v2 payloads, and treats a session as archived when
its list entry or its session state says so. Still one query and no
session database opens.

Adds end-to-end tests that archive and delete run no Git and the
clean-up opens no session database, that a session created in, and a
chat of another session working in, a worktree keep it while not
archived, that clean-up waits for startup to settle, and that automatic
deletion only checks that worktrees are gone or synced.

Co-authored-by: Copilot <[email protected]>
…tree clean-up)

The end-to-end in-use test now gives the session created in a worktree
and the chat working in another worktree one worktree each, so dropping
either central source fails it.

Co-authored-by: Copilot <[email protected]>
…ed worktree clean-up)

Archive and delete now record the removal and the host removes the
checkout once its startup settled, so the detached-worktree and
workspace-delegation tests serve a listing and poll the exact disk and
Git state instead of expecting the folder gone when the call returns.

Co-authored-by: Copilot <[email protected]>
…e query (deferred worktree clean-up)

The in-use query now skips a JSON column unless it contains the worktree
folder, which brings its worst case at 10k sessions and 20k chats from
about 59 ms to about 10 ms, and folds the case of both sides in SQLite
so a folder with non-ASCII letters cannot be missed.

Co-authored-by: Copilot <[email protected]>
- A peer chat's backing provider session has its own session list entry
  with the parent's folders; it no longer keeps the parent's worktree in
  use (its chat counts instead), so a multi-chat session's worktree is
  removed once the session is archived.
- Deleting a session reads its worktrees under their lock, so a worktree
  still being created is recorded for removal, and falls back to the
  worktree this process created when its metadata was never persisted.

Co-authored-by: Copilot <[email protected]>
…never persisted (deferred worktree clean-up)

Co-authored-by: Copilot <[email protected]>
…rsisted (deferred worktree clean-up)

Unarchive recreates a worktree from its persisted metadata, so an archive
must not remove one that only this process knows about; only a deletion
falls back to it.

Co-authored-by: Copilot <[email protected]>
…-up (deferred worktree clean-up)

A session without a worktree of its own may keep another session's
worktree in use; archiving or deleting it now schedules the debounced
pass, so that worktree is removed a few seconds later rather than at
the next periodic re-check.

Co-authored-by: Copilot <[email protected]>
…e (deferred worktree clean-up)

Co-authored-by: Copilot <[email protected]>
- Startup and client reconciliation of detached worktrees no longer remove a
  folder that is pending clean-up or that another session or chat uses.
- A session archive request is dropped when the session's persisted state
  says it was unarchived, so a crash between unarchive and its cancellation
  cannot remove a live checkout.
- The removal asks its in-use guard again right before Git removes the
  folder, after the commit that precedes it.
- The archive check prefers the central archived flag over a possibly stale
  session list entry.
- Removals of a deleted owner are tracked separately from the Git mode, so a
  lifecycle deletion (synced) also deletes the detached worktree record.
- Removals report removed, skipped or in use; a skipped removal is kept and
  retried with backoff instead of being dropped.
- A folder that is already gone is pruned from Git in every mode.

Co-authored-by: Copilot <[email protected]>
…ws still holds its database open

Co-authored-by: Copilot <[email protected]>
…heir folder

Disposing only starts closing an agent host database, so the teardown removed
the folder while SQLite still held agent-host.db-journal open, which Windows
reports as EBUSY. Await each raw database's close first.

Co-authored-by: Copilot <[email protected]>
…in the in-use tests

The tests waited for the removal call and then read the pending rows, which a
slow runner reads before the pass deletes the acknowledged row. Wait for the
row to disappear instead.

Co-authored-by: Copilot <[email protected]>
@sandy081
Sandeep Somavarapu (sandy081) merged commit 811e884 into main Oct 15, 2026
35 checks passed
@sandy081
Sandeep Somavarapu (sandy081) deleted the agents/deferred-worktree-cleanup-fix6 branch October 15, 2026 14:06
Sandeep Somavarapu (sandy081) added a commit that referenced this pull request Oct 16, 2026
…and convert every session (Block 4a) (#341904)

* agentHost: publish the older-build copy of normalized chat catalogs (Block 4a C1)

Normalized (chats_v2) sessions now publish what older builds read, like
legacy-catalog sessions: the session database's `peerChats` (visible peers
only, never private chats), each listed peer's read/provider/origin/
inherited-turn keys in its own database, and the acknowledgement
(`legacy_mirrored_revision` and payload) that is the next import's merge base.

- Published only for membership, read, archive, provider, origin,
  inherited-turn and folder changes (not titles, summaries or changes),
  coalesced to one flush per session per burst like the Block 3a mirror, and
  flushed by `whenIdle`; an unchanged list is only acknowledged.
- Per-chat keys are written only for entries that differ from the
  acknowledged payload and only for peers stored at their own URI.
- `isListedInOlderBuildCopy` is the single hook for the pending decisions on
  session-moved chats and promoted sessions; every visible peer is listed today.
- AGENTS.md §3b documents the new rule.

Co-authored-by: Copilot <[email protected]>

* agentHost: publish normalized catalogs' older-build copy off the hot path (Block 4a C1b)

Perf follow-up to C1, which published on every isolated edit and had
`whenIdle` force-flush pending publishes on hot paths.

- `whenIdle` awaits only writes in flight again. Pending copies publish
  after the session is idle for `COMPATIBILITY_PUBLISH_IDLE_DELAY` (5 s,
  bounded by 30 s), or through `flushCompatibilityPublishes`, called only at
  shutdown and on session release while its database is held.
- A publish reads its source in one transaction
  (`readOlderBuildCopySource`), writes the session database, then
  acknowledges in one short transaction: six agent-host.db statements.
  `markSessionChatCatalogLegacyMirrored` drops its re-read.
- Invariant: the acknowledged payload always equals `peerChats`. The ack is
  never written with a catalog write, so a host stopped before its publish
  leaves an older but matching pair that 1.141 republishes from central.
- A peer's own database is opened only when one of its keys changed, behind
  `isPeerKeyReadByOlderBuilds`.
- Tests: bursts of ten creates and ten deletes each publish once in six
  statements; nothing publishes inline; release and shutdown publish; the
  stopped-host downgrade to 1.141 keeps the normalized write.

Co-authored-by: Copilot <[email protected]>

* agentHost: import older-build chat list edits into normalized catalogs (Block 4a C2)

Builds without normalized authority can still edit a normalized session's
chat list after a downgrade. Those edits are now imported on upgrade instead
of being lost.

- Detection: 1.141 writes `session_chats` and then re-acknowledges its own
  `peerChats`, so its edits show as `session_chats` differing from the
  projection of `chats_v2` (`readOlderBuildChatCatalogEdits`, one batched
  query sharing the projection SQL); that projection is the merge base.
  A build writing only `peerChats` shows as it differing from the
  acknowledged payload, the merge base.
- Merge is entry-wise like legacy reconciliation, applied through
  `replaceSessionChatCatalog` / `_replaceNormalizedPeers`, then published.
  Chats recorded under another session or deleted keep their normalized
  record: an import never transfers ownership.
- `_replaceNormalizedPeers` records a peer's storage once when it enters
  (its own URI, the creation-time rule); updates never re-derive it.
- Runs where legacy import runs: open/restore (which also drops live peers
  the import removed), the startup conversion batch, before the first
  normalized write per session in a process, and
  `reconcileOlderBuildCopy`, the hook Block 4 calls before a move or
  promotion validates.
- A session that lists no peer and never published a copy needs none.
- Tests: an old-build chat list writer fixture (1.141 central catalog and
  peerChats-only), round trips for create/delete/archive/read/reorder with
  private, moved-in and session-moved chats, a chat recorded elsewhere, a
  conflict on the same peer, the conversion batch and restore wiring.

Co-authored-by: Copilot <[email protected]>

* agentHost: convert every session to normalized chat authority again (Block 4a C4)

Older-build chat list edits are now imported back into normalized catalogs
(C2) and published for older builds (C1), so compatibility-backed and
historical provider-scheme sessions no longer need to keep legacy chat
authority (#340980). Conversion is always on, with no setting.

- The catalog gate `requiresLegacyChatCatalog` is removed with every branch
  it guarded: new sessions register a normalized catalog at creation, the
  conversion batch and restore convert legacy catalogs lazily as before,
  restored subagents persist as private normalized chats, and the
  compatibility wrapper forwards `ensureChatCatalogV2` and
  `registerChatCatalogV2`.
- Storage addressing is unchanged: `prepareSessionStorage`, the
  provider-scheme disk address, translation, and recording a restored
  subagent's storage spelling never depended on the catalog gate.
- Tests: converting a legacy compatibility session (1.143 and 2b) keeps an
  old build's pending edits and its provider-scheme address; a new
  compatibility-backed session registers normalized authority under its
  provider-scheme address; historical identities keep their address.
  Restoring an identity-based gate at the compatibility call sites fails
  five of them.

Perf: conversion stays lazy and bounded per tick; no new statements.

Co-authored-by: Copilot <[email protected]>

* agentHost: document normalized chat authority for every session and older-build reconciliation (Block 4a C5)

- AGENT_HOST_SESSIONS_PROVIDER.md: all sessions convert to normalized chat
  authority; older builds edit its legacy-readable copy and upgrading
  imports those edits back; disk addresses are unchanged.
- AGENTS.md I5: when and how older-build edits are imported, and that an
  import never transfers ownership.
- agentHostChatCatalogV2.md: the `session_chats` projection and the
  published copy are what older builds read and write; how their edits are
  detected (projection diff, `peerChats` against its acknowledgement),
  merged and applied; what is still not imported.

Co-authored-by: Copilot <[email protected]>

* agentHost: one projection for older builds; import their edits only when real (Block 4a C2a)

1. One projection. `normalizedPeerProjectionSql` is the only definition of
   what builds without normalized authority see. It writes `session_chats`
   (`_projectNormalizedPeersToLegacy`), is the merge base and diff of the
   older-build edit check (`hasOlderBuildChatCatalogEditsSql`, also used by
   the batch selector), and is what `peerChats` publishes
   (`readOlderBuildCopySource`). Which peers older builds see moves into it
   (`OLDER_BUILD_LISTED_PEER_SQL`, the Q-A/Q-B hook), replacing the separate
   TypeScript predicate.
2. Ordering across restarts. The first normalized write of a session in a
   process checks for older-build edits with one statement
   (`readOlderBuildCopyState`) and imports before it re-projects; a released
   session is re-checked on its next write.
3. False positives. A difference between `session_chats` and the projection
   is imported only when it is a completed older-build write: an older build
   wrote the acknowledgement (this build records the revisions it
   acknowledged, and older builds always advance the revision before
   acknowledging) and its payload lists exactly the `session_chats` rows.
   Anything else (an older build stopped mid-write, a normalized write whose
   projection never ran, a projection this build changed) is re-projected
   from `chats_v2` and logged, never imported. Rows naming chats `chats_v2`
   records but the projection does not list (private, deleted, default,
   owned elsewhere) are never imported. `peerChats` is read back only when
   the acknowledged copy is outdated: just acknowledged when it is this
   build's projection, merged otherwise.

Listing no longer triggers an import (`_readCentral`). The old-build writer
fixture runs through the database's transaction sequencer.

Tests: write/diff/copy agree after every kind of normalized write; after a
restart an archive or rename imports first; the startup batch racing a
write in both orders; a stale projection and a changed projection are
re-projected without dropping, duplicating or resurrecting chats; a private
chat listed by an old build is not imported. Mutations caught: diff or
write using its own projection, no import before the first write, trusting
every difference, importing known-unlisted rows.

Perf budgets: listing identical to main (no import from listing); no
dbInit work; hot writes add no statements beyond the first-write check;
first write on a clean session 1 statement, no session.db; publish
coalesced; conversion batch unchanged. Known misses, fixed in C2b with the
approved `projected_revision` (migration 18): the startup divergence check
compares all peer rows (35-80 ms at 10k), and the `peerChats`-only path
still reads session.db for an outdated copy.

Co-authored-by: Copilot <[email protected]>

* agentHost: test when a peerless normalized session starts and keeps an older-build copy (Block 4a C2c)

A normalized session that lists no peer and never published `peerChats`
needs no copy (older builds rebuild one from `session_chats`). Two
conditions bound that exemption, now covered by tests:

(i) Its first peer, from any source, ends it: a write of the peer store
    schedules the publish, and a peer another writer added (such as a move)
    is published from the next open.
(ii) A converted session whose legacy `peerChats` copy was acknowledged
    counts as published, so the copy stays current, down to `[]` once its
    last peer is removed.

Mutations caught: never publishing a session without an acknowledged copy
(5 failing); skipping every peerless session even when published
(1 failing).

Perf budgets: tests only; no production change.

Co-authored-by: Copilot <[email protected]>

* agentHost: guard every re-projection and track the projection with projected_revision (Block 4a C2b)

Review pass 1 (M1 and the LOWs) and perf budgets 3 and 5.

Detection. `session_chat_catalogs.projected_revision` (migration 19,
additive; idempotent ADD COLUMN, repaired on every open from 14, so a
database at 15 migrates straight to 19) holds the revision at which this
build last wrote the `session_chats` projection, set in the same
transaction. Writes that leave the projection alone (titles, private chats)
keep a current marker current. 1.140/1.141 rewrite `session_chats` and
advance only `revision` (the old-build writer fixture pins this, against a
version 19 database); their schema checks return early for versions >= 12
and only inspect `session_chats` columns, so the extra column is invisible
to them. Rows are compared with the projection (the shared
`hasOlderBuildChatCatalogEditsSql`) only when the marker is behind: a
difference is a committed older-build edit and is imported; none (1.142
re-projects itself) records the projection as current. This replaces C2a's
published-revision metadata key and its "completed write" rule: with the
marker in the projection's own transaction, a crash between a chats_v2
write and its projection cannot happen, and a changed projection
definition never looks like an edit.

M1, every caller of `_projectNormalizedPeersToLegacy`:
- `_replaceNormalizedPeers` (`replaceSessionChatCatalog`, the
  `replacePeers` mutation of `ensureChatCatalogV2`): 'guarded' refuses with
  `{ status: 'olderBuildEdits' }` before writing;
  `replaceSessionChatCatalogImportingOlderBuildEdits` is the import's
  unguarded mode and keeps peers older builds are not shown.
- `_updateChatV2` (`updateChatV2Metadata`, the patch mutation): refuses
  when the patch would re-project.
- `_insertChatV2Catalog` (activation, registration): the catalog was not
  normalized before, so no normalized projection can carry an edit.
- `reprojectOlderBuildChatList`: only after an import found nothing.
Peer store callers import and retry once (`_importRefusedOlderBuildEdits`).

peerChats-only edits leave the hot path: read on open with a held session
database, before a move or promotion (`reconcileOlderBuildCopy`), and by
the publisher, which compares `peerChats` with the acknowledgement before
overwriting it and imports first. A `peerChats` equal to the current
projection is this build's own unacknowledged write: just acknowledged.

LOWs: the per-process flag stays as a fast path (correctness is M1);
`readOlderBuildCopySource` is one statement; working directories travel
with each entry instead of being paired by index.

Probe checks: an old-build-created peer's recorded storage resolves to the
folder that build created (`<chatId>-<b64 session>`); importing an
old-build delete tombstones the chat and never reopens its deleted folder.

Perf budgets:
- listing: unchanged from C2a (no import from listing).
- dbInit: one ADD COLUMN at most, inside the existing open-time repair.
- startup divergence check (3): one scan of headers whose marker is behind,
  LIMIT 400, no IN lists, no session.db, in the background batch after
  startup settles; 0.5-0.6 ms at 10,000 clean sessions (load 8). After the
  upgrade every normalized catalog is a candidate once (NULL marker).
- hot writes: no added statement while the marker is current (the guard
  reads `projected_revision` from header rows already selected).
- first write per session (5): 1 statement, no session.db.
- first open of a clean session: 1 statement (header and peers together),
  no session.db read.
- publish: 5 agent-host.db statements (was 6); coalesced as before.

Tests: refusal on every projecting entry point, own writes keep the marker
current, the candidate scan, 15 -> 19, the 1.141 writer on 19; a process
that already imported refuses, imports and retries a create, an archive
and a metadata archive; first write costs one statement and no database;
peerChats-only edit then a write then the publish; own unacknowledged copy
just acknowledged. Mutations caught: no DB guard (5 failing), an own write
leaving the marker behind (1), the publisher overwriting peerChats (1), the
scan never recording unchanged catalogs (2), an own unacknowledged copy
merged instead of acknowledged (1).

Co-authored-by: Copilot <[email protected]>

* agentHost: publish and import normalized peers' titles and drafts for older builds (Block 4a C3)

1.140 and 1.141 do not know normalized (v2) authority: they rename a peer in
session.db `customChatTitle:<chat>` / `customChatTitleSource:<chat>` and in the
peer's own `customTitle` / `customTitleSource`, and write a peer's draft into
session.db `chat_drafts` alone (probe 4a). Today's build neither published
those titles nor noticed those edits, so peer renames and drafts made after a
downgrade were reverted on upgrade.

Titles
- The deferred older-build copy now also publishes the listed peers' titles
  (session.db keys, and the own-db keys where the peer is stored at its own
  URI, behind isPeerKeyReadByOlderBuilds), writing only titles that changed,
  and records them as published (`sessionChatCatalogOlderBuildChatState:`,
  cleared with the catalog) after writing them. A listed peer's title change
  schedules the coalesced publish; nothing is written inline.
- Import is three-way against the published titles, like the 3a mirror: a
  title other than the published one was written by an older build and wins,
  read from the peer's own database first (where it differs from the
  published one), else from session.db. Nothing is imported before a first
  publication. A crash between writing titles and recording them leaves this
  build's own titles, whose import is a no-op. A peer an older build created
  is imported with its title.
- Read on open/restore with the session database held (with `peerChats`, in
  one statement), and by the publisher before it overwrites them.
- isRead needs nothing new: every build persisting a peer's read state
  writes `session_chats` too, which C2 imports.

Drafts
- A peer draft that differs from its mirror base was edited by an older
  build. The load already reads the turn watermark from session.db; that read
  becomes `getRowsWatermark` (watermark and drafts, one statement), and the
  draft mirror bases ride along in the session state markers statement.
  An edit then runs the existing 3a row import.

Perf budgets
- listing, dbInit, startup check, conversion batch: unchanged.
- hot v2 writes: unchanged (a title change only schedules the publish).
- first write per session: unchanged (1 statement, no session.db).
- first clean open: unchanged statement counts (peerChats + titles in one
  getMetadataObject, now batched for compatibility sessions too; the
  watermark read replaces getMaxTurnRowid; the bases join the markers
  statement).
- publish: at most 6 agent-host.db statements; titles add a session.db write
  only when one changed, and the record statement only when titles changed or
  on a session's first publish.

Tests: 1.140/1.141 rename round trip (own db first, wins over this build's
unpublished rename), old-build-created peer with title, crash before the
record, never-published rename kept, draft-only edit imported, the rows
watermark. Mutations caught: no title import, no own-db first, no three-way
base, no draft signal, titles not published. Full agentHost node suite:
9562 passing.

Follow-up (out of scope): the old-build junk folders (UUID folders holding
only peerChatBacking, empty sanitized-name folders).

Co-authored-by: Copilot <[email protected]>

* agentHost: 4a review pass-2 fixes (Block 4a)

- Bounded loops: an import or publish of a normalized catalog's older-build
  copy re-reads its source at most three times while another writer keeps
  moving the catalog on. The import then logs and returns 'superseded'
  (nothing imported from the last read); callers that would write after it
  (open/restore, reconcileOlderBuildCopy, the retry-once of a refused write,
  _replaceCentral, the unmirrored path) map it to their thrown error. The
  first-write check only stays unmarked, since the database guard still
  refuses re-projections. A publish logs and leaves the revision
  unacknowledged, so the next open or write republishes.
- A publish whose acknowledgement finds the catalog moved on (another writer
  between its read and its acknowledgement) republishes the newer revision
  before returning, instead of leaving the copy behind until a later write.
  The acknowledged payload is still recorded in that case, intentionally: it
  is what peerChats holds (commented).
- guardOlderBuildEdits(database, session): the one exported guard for every
  write that re-projects session_chats, usable inside a write transaction.
  The caller contract (each re-projected session, refuse with
  { status: 'olderBuildEdits' }, reconcileOlderBuildCopy, retry once) is in
  agentHostChatCatalogV2.md, for Block 4's move/promote/reorder writes.
- The burst statement-count test no longer counts its own drain query.
- Rebased onto origin/main (3b's migration 17, #341721's 18, 3c, #341762):
  migrations run 15 -> 17 -> 18 -> 19 (projected_revision stays 19), and the
  open-time repairs of 17, 18 and 19 run on every open. Tested: a database at
  15, 17 and 18 each ends at 19 with every repair applied. The older-build
  copy and title import now use main's mirrorsAtChatUri for the "no copies for
  chats stored elsewhere" rule and open a peer's database at its recorded
  storage.

Perf: no change on any budgeted path. Each loop bound only stops work, and
the guard is the same statement as before.

Tests: a writer superseding every import attempt (3 reads, the caller fails,
nothing written), a publish that never settles (3 reads, unacknowledged), a
writer between a publish's read and its acknowledgement (republished,
acknowledged current). Mutations caught: no import cap, 'superseded' not a
failure, guard always passes, no republish. Full agentHost node suite: 9565
passing.

Co-authored-by: Copilot <[email protected]>

* agentHost: per-session paths wait for their own sessions' peer-store writes (Block 4a)

Opening a session while a background conversion pass ran waited for the
whole pass (perf: subscribe of an authority-1 session during a 2k pass,
12-24 ms on main -> 458-1311 ms). The peer store's whenIdle() awaited every
session's writes, and the pass, which C4 turns back on, keeps up to four
sessions' writes in flight continuously. Main has the same barrier; its
passes just never wrote the peer store.

- AgentHostPeerChatStore tracks metadata writes by session (they were one
  global set) and gains whenSessionsIdle(sessions): it awaits the queued and
  metadata writes of exactly those sessions, including any they queue
  meanwhile, and never another session's. whenIdle() stays global for
  shutdown and tests.
- Caller audit (agentService.ts):
  - _persistListVisibleSessionStateNow (every open via restore, and every
    session-level list-visible write: title, read, archive, working
    directories, changes, artifacts): builds its request from this session's
    catalog alone -> [session].
  - _synchronizePassiveSessionMetadata: this session's catalog alone ->
    [session].
  - disposeChat: the chat's writes are queued under its session, and under
    its recorded owner when ownership records another session ->
    [session] or [session, recorded owner] (recorded ownership, never the
    URI). Block 4's moved chats follow the same rule.
  - completeSavedChatContinuation: changes the source session and checks the
    destination's catalog -> [request.session, request.destination].
  - whenCatalogReconciliationIdle (shutdown only): keeps the global barrier.
- The conversion pass is not given an explicit yield: each session's work
  awaits database and file I/O, so it never holds the event loop; the wait
  was the barrier.

Perf: removes the cross-session wait; no statement or database-open change.

Tests: a session-level write on Y and a restore of Y complete while a
peer-store write of X is held; a write on X still waits for X's held write;
whenSessionsIdle awaits a session's metadata writes and ignores other
sessions'. Mutations caught: callers back on the global barrier,
whenSessionsIdle global, metadata writes ignored. Full agentHost node suite:
9696 passing.

Co-authored-by: Copilot <[email protected]>

* agentHost: 4a review pass-3 fixes (Block 4a)

- L1, title crash window: the published titles of a normalized catalog's
  older-build copy are recorded in two steps, as pending before they are
  written and as published after (the pending part cleared). The import never
  takes a title equal to either for an older build's edit. Before, a publish
  that wrote T2 and stopped before recording it, while the user renamed to
  T3, imported T2 over T3 on restart. A publish after an interrupted one
  rewrites every title key, whose contents are then unknown. Cost: +1
  statement per publish, only when a title changed.
- L2: a peer's own database without either title key is no information,
  never "cleared": the session database's title (customChatTitle:<chat>)
  stands. Before, it cleared a real session-database rename.
- L3: the attempt cap counts only writes another writer superseded (a
  conflicting import, a re-projection or an acknowledgement whose revision
  moved on). Progress (importing another build's copy first, a re-projection
  that went through) no longer uses it up. It still fails safe.
- L4, accepted: a crash between mirroring a peer draft and recording its base
  reads the build's own draft as an older build's edit; the import then
  writes the value the own database already holds. Commented.

Perf: no budgeted path changed; the pending title record adds one statement
to a publish only when a title changed.

Tests: the exact L1 sequence (T2 written, rename to T3, stop before the
record, restart: T3 stays); an own database without title keys and an old
build's session-database rename (imported); a publish that first imports
another build's copy and then survives two superseded acknowledgements.
Mutations caught: pending titles not treated as own, no pending record
before the write, absent own keys read as cleared, progress counted toward
the cap. Full agentHost node suite: 9699 passing.

Co-authored-by: Copilot <[email protected]>

* agentHost: document two-session writes for the peer-store barrier and the older-build guard (Block 4a)

Review delta L1: a write that touches two sessions (Block 4's moves and
promotions, a saved-chat continuation) must pass BOTH sessions to
whenSessionsIdle([source, destination]), never the global whenIdle(), and
guard BOTH with guardOlderBuildEdits (each session it re-projects). Documented in the guard contract
(agentHostChatCatalogV2.md), on whenSessionsIdle, and in AGENTS.md. No code
change.

Co-authored-by: Copilot <[email protected]>

* agentHost: convert authority-1 sessions whose legacy catalog orders peers unlike their aggregate (Block 4a)

Live bug: an authority-1 compatibility session with peers never converted to
normalized authority (copilotcli:/851edd39: two user peers, one archived,
one unread). Reproduced on a copy of the live pre-4a snapshot:
migrateChatCatalogV2 returned notReady from ensureChatCatalogV2, which
required the legacy session_chats to list the aggregate's visible peers in
the same ORDER. The aggregate follows the order this build shows (its live
chat list); the legacy catalog had the archived peer first. Nothing
reconciles the two orders, and notReady only marks the payload dirty, which
re-projects the same order again: the session was deferred on every pass,
logged at trace only. Main never reached this for compatibility sessions,
whose conversion was off until C4. (The empty-string chatInheritedTurnId and
the runtime/storage spellings were ruled out on the snapshot.)

- Normalization requires the legacy catalog to list exactly the aggregate's
  visible peers as a set (its membership is current) and takes the
  aggregate's order. On the snapshot the session now converts: payload
  order, archive and read states and titles kept, each peer stored at its
  own URI.
- notReady results carry a required reason (an unverified or dirty
  aggregate; a peer's own database disagreeing until legacy reconciliation;
  a legacy catalog listing other peers).
- AgentService logs a migration that ends without converting a session at
  warn, with its reason, once per session and reason in a process (trace
  after; reset once it converts), so a non-conversion is never silent.

Perf: no change; the set check runs on rows the normalization already reads.

Tests: a 2b compatibility session (one peer archived, one unread, an empty
own-db chatInheritedTurnId) whose legacy catalog orders its peers unlike the
aggregate converts, in the aggregate's order; the deferral warning is logged
once per reason and again after a conversion resets it. Mutations caught:
the order requirement restored, deferrals logged at trace. Full agentHost
node suite: 9701 passing.

Co-authored-by: Copilot <[email protected]>

* agentHost: what older builds drop by merely opening a session is no edit (Block 4a)

Live run: just opening a session in an older build rewrites its legacy
catalog with no user action. 1.141 drops a peer's archived flag (1 -> 0),
1.140 drops it and nulls both peers' is_read, 1.142 changes neither. The v2
import read those as older-build edits ("unarchive", "read state cleared")
and reverted the user's state.

A normalized catalog's import (session_chats and peerChats alike) now merges
through _mergeOlderBuildChanges, which first drops these open artifacts
against the merge base, then merges as before:
- a missing read state, provider data, origin or inherited turn keeps the
  base's: no build clears them, so their absence is no information;
- an archived chat stays archived: archive is sticky against older builds.
  A genuine unarchive made in an old build does not stick (the same
  trade-off as deletes); archiving a chat (0 -> 1, which 1.140 can do)
  still imports;
- an empty working-directory list keeps the base's (1.140 writes it empty);
- the order stays the normalized one: no build can reorder chats (the
  probe found reordering is not client-dispatchable), and chats an older
  build added follow it;
- entries compare in one key order, so another build's JSON spelling is no
  edit either.
Authority-1 reconciliation (main's) is unchanged.

Perf: no change; the rule runs on entries the import already reads.

Tests: 1.141 opening the session (archived flag dropped: kept); 1.140
opening it through session_chats and through peerChats only (archived flags
and read states dropped: kept); 1.140 archiving a chat while dropping the
rest (imported). The C2 import test now expects the normalized order.
Mutations caught: a NULL is_read imported, archive not sticky, a genuine
archive ignored, the older build's order taken. Full agentHost node suite:
9705 passing.

Co-authored-by: Copilot <[email protected]>

* agentHost: show chats Block 4 moved to older builds and neutralize their edits (Block 4a)

Decision Q-A/Q-B (user): show + neutralize. Older builds keep listing chats
Block 4 moved or promoted (OLDER_BUILD_LISTED_PEER_SQL lists every live
visible peer); on upgrade this build neutralizes what they do with them
(probe 4a, section 2):

(a) Older builds route a moved chat's renames (1.140/1.141:
    customChatTitle:<chat> and its source) and drafts (chat_drafts, keyed by
    chat) to the session its address names, its source X. X's older-build
    record now keeps a `left` entry for every chat that left its list: the
    title it last published there and X's draft-mirror base for it, read in
    the publisher's single source read (readOlderBuildCopySource now returns
    the draft bases of the chats a session does not list). Importing X's
    copy reads those title keys in the same single statement, and X's drafts
    in one more read only when chats left it. A title or draft that differs
    from the left entry is an older build's edit: it goes to the chat under
    its CURRENT owner as chats_v2 records it (recorded ownership, never the
    address, never X), with C3's rules, and the left entry takes the value,
    so nothing is imported twice. A deleted chat, or one recorded under X,
    takes nothing.
(b) A moved-in chat (origin_session_uri set to another session) missing from
    an older build's copy of its destination (1.141 drops it) is never
    imported as a delete. Accepted trade-off: an old-build delete of a moved
    chat does not stick. readOlderBuildCopySource marks moved-in peers.
(c) A stale copy listing a moved chat under its source never resurrects or
    duplicates it: session_chats rows through knownUnlisted, peerChats
    entries through the owned-elsewhere rule (pinned by a test).

Perf: (b) and the draft bases are columns of the publisher's and import's
existing single source read. A publish where chats left the list writes the
record once more (a burst of ten deletes: 6 agent-host.db statements, within
the 6 budget). Opening a session that chats left reads its drafts once more;
no other open changes.

Tests (Block 4 rows simulated with moveChatAsBlock4: owner changed,
origin_session_uri kept, both sessions re-projected): a 1.141 rename and
draft of a moved chat routed to its source are imported for it under its new
owner; 1.141 dropping it from its destination's list does not delete it, and
stale source copies (session_chats and peerChats) listing it neither
resurrect nor duplicate it. Mutations caught: no left-chat import, left
chats not tracked, a moved-in chat's absence read as a delete, chats owned
elsewhere imported. Full agentHost node suite: 9707 passing.

Docs: agentHostChatCatalogV2.md, AGENTS.md, the projection hook's comment;
the design's Q-A/Q-B section is rewritten to show + neutralize.

Co-authored-by: Copilot <[email protected]>

* agentHost: 4a final fixes from live L2-L5 and perf

- LIVE HIGH: a 1.140 peer rename was reverted. _importSessionCopyEdits
  returned right after a peer-list import (1.140's open had also
  rewritten every peer), so the title and left-chat diffs never ran and
  the publisher kept NEW's title. Titles and left chats now import in the
  same visit as the list.
- Leftover per-chat keys: when a peer is deleted or stops being listed,
  the deferred publish deletes its customChatTitle(Source) keys in
  session.db (and a deleted chat's own-db title keys) and drops it from
  the published-titles record. Moved chats keep a left entry (neutralize).
- Missing cct keys = no information (old builds 1.140-1.142 never delete
  them: they write '' on chat deletion and values on rename). Only a
  present value that differs from published and pending is an edit; the
  publisher rewrites missing keys.
- 1.140 open-only (every peer rewritten, revision bump,
  customChatTitle:default = session title) imports nothing; the default
  chat's cct key is never a peer key.
- Older-build imports per background pass are capped at the batch size;
  the rest carries to the next pass.
- A sessions_v2 CAS conflict against a moved-on chat catalog (an import
  or a conversion) logs at trace; callers still warn when it doesn't
  settle.
- Docs: 1.141 writes chats_v2 for some sessions (1.141.2 in the live
  run) and the legacy stores for others; only 1.140 is legacy-only
  everywhere. The import is store-based and handles both.

Perf: a burst of peer deletes publishes in 5 statements; other publish
and listing counts unchanged.

Mutations caught: leftover keys kept, deleted own keys kept, imports
uncapped, titles skipped after a list import, missing keys read as
cleared, missing keys not rewritten.

Co-authored-by: Copilot <[email protected]>

* agentHost: 4a conversion retry, subagent storage and record parsing

- F3b: a chat catalog conversion that is notReady only because the
  session's aggregate awaits its re-projection (normal on the first start
  after an upgrade) records the session with the reconciliation, which
  converts it right after the pass that re-projects it instead of at the
  next 5-minute batch. notReady carries awaitsReprojection. That reason
  logs at trace and warns only after 5 attempts in a row; provisional
  sessions never warn; other reasons still warn once per reason.
- F6 (introduced by 4a): on main 3fb15cb a compat (authority-1)
  session recorded a subagent's storage in session_chat_state, and the
  session delete removed it. 4a converts those sessions to v2, where the
  subagent is a private chats_v2 row tombstoned with its peer, which the
  session delete then never finds. A peer delete now removes its private
  descendants' storage with its own.
- F9: the published-titles record is parsed field by field: a missing
  `left` is empty, a missing `pending` null; a structurally wrong field
  is dropped (logged), the others kept.

Mutations caught: no retry after the re-projection (service and the
agent service hook), transient reason warning at once, provisional
warning, descendants' storage kept, record ignored without `left`, a
malformed field dropping the whole record.

Co-authored-by: Copilot <[email protected]>

* agentHost: 4a review last-delta fixes

- L1: a moved chat's older-build rename whose write to its owner's
  catalog conflicts (a lost CAS, or the chat moved or was deleted after
  its owner was read) keeps its left-chat base, so it is retried on a
  later visit instead of dropped.
- L2: left-chat drafts get the titles' two-step: the drafts about to be
  imported are recorded as pendingDraft first. A draft is imported only
  over the draft the chat had when it left (three-way), so a newer one,
  this build's or the import's own before a crash, is never overwritten.
  One chat's failed import is logged and leaves its base for the next
  visit without aborting the others.
- L3: prompt conversion retries after a re-projection are capped at 5 per
  session and process; past that the conversion batches' cadence
  applies.

Mutations caught: base advanced on conflict, newer draft overwritten,
per-chat errors not isolated, retries uncapped.

Co-authored-by: Copilot <[email protected]>

* agentHost: apply imported older-build edits to loaded sessions

F10 (live): after an older-build title import (a 1.140 peer rename) the
running host kept showing the old title until a restart: the import
updated chats_v2 but not live state, and restoring a loaded session skips
chats it already holds.

The peer store now announces what each import changed
(onDidImportOlderBuildEdits: membership, archived/read, title, draft,
with the imported values), collected per visit and fired when it ends,
also after a conflict or error (its writes are committed). The agent
service applies it to a loaded session through the actions a local
change dispatches: updateChatTitle (SessionChatUpdated, marking a
user-sourced title renamed), ChatIsArchivedChanged/ChatIsReadChanged for
opened chats and SessionChatUpdated status for unopened ones,
ChatDraftChanged for opened chats (unopened ones read the draft when
opened), removeChat (SessionChatRemoved), and the restore path's
registration plus SessionChatAdded for peers an older build added. An
unloaded session reads them on restore. No new actions.

Mutations caught: event never applied, no title dispatch, list edits not
noted.

Co-authored-by: Copilot <[email protected]>

* agentHost: 4a docs, 1.141 writes only the legacy stores

F4 settled on genuine builds: 1.141.2 (16507d9) writes only the
legacy stores (session_chats and peerChats, customChatTitle:* and
customTitle in the session and peer databases, chat_drafts); its
agentHostMain.js has no chats_v2 reference, 1.142.0 has 31. The earlier
"1.141 writes chats_v2 for some sessions" came from a ShipIt-updated
1.142 bundle. Corrected in agentHostChatCatalogV2.md and the peer store's
import doc comment: 1.140 and 1.141 write only the legacy stores, 1.142+
write chats_v2. No code or test depends on 1.141 writing chats_v2 (the
fixtures model 1.141 from release/1.141 as legacy-only).

Co-authored-by: Copilot <[email protected]>

* agentHost: test an old build's archive and rename round trip in 4a

Real-data suspect: after a genuine 1.140 round trip, 4a imported a peer
rename but the peer's archive read 0. Reproduced through the agent
service's real paths (the background import while the session is loaded,
and restore after eviction), for 1.140 (open rewrite dropping archived
and read state for every peer, the session title as the default chat's
customChatTitle) and 1.141 (dropping archived), each followed by a second
old-build write archiving one peer, plus a rename of another peer.

It does not reproduce: the archive and the rename import into chats_v2,
live state, and the session_chats/peerChats copy republished for older
builds; the open rewrite unarchives and unreads nothing.

Mutations caught (all 4 variants): the open rewrite unarchiving
(archived: entry.archived), an archive never importing
(archived: previous.archived).

Co-authored-by: Copilot <[email protected]>

* agentHost: 4a review fixes for older-build import edge cases

- The older-build edit check uses CASE instead of AND: SQLite evaluates
  both AND operands, so clean catalogs paid for the session_chats row
  diff on every readOlderBuildCopyState/readOlderBuildCopySource.
- findOlderBuildChatCatalogEdits filters to listed registrations
  (registered, not tombstoned, not excluded) before LIMIT: an excluded
  catalog the batch cannot reach no longer holds a slot on every pass and
  starves live sessions' imports.
- Imported read changes dispatch ChatIsReadChanged for chats not opened
  yet too, so the session's read aggregate follows (the state manager
  applies it to unresolved registered chats).
- An imported draft change, including a clear, replaces an unopened
  chat's cached draft (new AgentHostStateManager.setUnresolvedChatDraft),
  so opening it does not bring the old draft back.

Mutations caught: the filter after LIMIT, read dispatched only for
resolved chats, unresolved draft not replaced.

Co-authored-by: Copilot <[email protected]>

* agentHost: restore waits for its session's in-flight metadata writes

Windows / Electron E2E "session metadata history and provider context
survive a host restart" failed twice on 4a: after `/rename Persisted
Session`, the restored title was the first agent-bound message.

The rename persists its title keys fire-and-forget through the peer
store. Before each such write, 4a's metadata migration hook attempted a
chat catalog conversion, which for a new session is not ready (aggregate
unverified or awaiting re-projection): a reconcile, an exclusive
migration and a dirty mark per write. That delayed the rename's write
past the release and restore, which then read the session metadata
without it, took the provider's title (the SDK titles the session from
the first message) and persisted it.

- Restoring a session awaits that session's in-flight peer-store writes
  (whenSessionsIdle) before reading its metadata.
- The migration hook skips the conversion attempt while the aggregate is
  not ready (one read) and asks for the conversion after its
  re-projection instead.

Shutdown already awaited these writes (whenCatalogReconciliationIdle).
Reproduced locally by delaying the hook 400 ms: the E2E fails without
this change and passes with it. Unit test: a restore while the rename's
write is held resolves with the renamed title; mutation (no wait)
caught.

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>
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.

Flaky test: restoring a compatibility session registers its subagent chat in memory with its origin, without a catalog admission

3 participants