Skip to content

agentHost: reconcile older-build edits into normalized chat catalogs and convert every session (Block 4a) - #341904

Merged
Sandeep Somavarapu (sandy081) merged 24 commits into
mainfrom
agents/block4a-reconcile-v2-chat-catalogs
Oct 16, 2026
Merged

Sandeep Somavarapu (sandy081) merged 24 commits into
mainfrom
agents/block4a-reconcile-v2-chat-catalogs

Conversation

@sandy081

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

Copy link
Copy Markdown
Member

Problem

Since #340980 and #341086, Copilot CLI, Claude and Codex sessions keep a legacy chat catalog (authority 1), and conversion to the normalized catalog (authority 2, chats_v2) is disabled for them. That's because a stable build without normalized-catalog code (1.140 and 1.141) writes only the legacy stores, and on a normalized session those edits were lost on the next upgrade:

  • created chats dropped from the list;
  • deleted chats came back;
  • archive, read and order changes reverted.

Moving chats between sessions (Block 4) only works on normalized catalogs, so this blocks it.

Change

The normalized catalog stays the only authority. Older-build edits are imported back into it instead of being kept in a second store.

  • Publish an older-build copy for normalized sessions: session_chats/peerChats, each listed peer's own keys (titles, drafts), and the acknowledgement. It's coalesced off the hot path, and the ack always equals what was published.
  • Detect divergence cheaply: migration 19 adds session_chat_catalogs.projected_revision. Divergence is revision ≠ projected_revision, followed by a single-SQL row diff. Every re-projection goes through one in-transaction guard, guardOlderBuildEdits(database, session), which imports first and retries once.
  • Import only real edits:
    • added and removed chats, order, and archive/read changes;
    • titles, imported three-way (a peer's own database first), and drafts;
    • what an older build drops merely by opening a session isn't an edit: archived 1→0 and NULL/missing values carry no information;
    • imports are capped at 50 per pass.
  • Chats moved by Block 4: they are shown to older builds and their edits are neutralized through left entries (decision: show + neutralize). An old-build rename or draft of a moved chat is routed to its current owner.
  • Convert every session to normalized authority again in the background: bounded batches, a retry after re-projection (capped at 5 per session per process), and per-session whenSessionsIdle instead of a global barrier.
  • Loaded sessions see imports live: onDidImportOlderBuildEdits applies imported titles, archive/read, drafts and membership changes through the existing state-manager paths.
  • A peer delete removes its private descendants' storage.
  • The published-titles record is parsed field by field.
  • Docs: agentHostChatCatalogV2.md and AGENTS.md describe the contract. 1.140 and 1.141 write only the legacy stores; 1.142+ write chats_v2.

No protocol change, no change to the on-disk addresses of existing sessions, and no URI-derived ownership.

Validation

All at load < 20, with COPILOT_* unset.

  • ./scripts/test.sh --runGlob "**/agentHost/test/node/**/*.test.js": passed, 9810 passing / 75 pending / 0 failing, on head fbbe9df: after the rebase onto main, plus the Copilot review fixes and the restore fix below, each with a test and a caught mutation.
  • Restore fix (found by Windows CI): a session restored right after /rename could miss the rename, because a 4a hook delayed the fire-and-forget title write. Restore now waits for its session's in-flight metadata writes, and the hook skips its conversion attempt while the aggregate isn't ready. With a 400 ms injected delay the host-restart E2E fails without the fix and passes with it (5/5 × 2).
  • npm run typecheck-client: passed. npm run eslint on all 30 changed files: passed. Hygiene: passed.
  • Mutation checks on each fix: all killed.
  • Code review: three passes plus the last delta; ship, and the low findings are fixed.
  • Live, with genuine and commit-verified stable builds (1.140.0 07f806f, 1.141.2 16507d9, 1.142.0 6d62b1d):
    • open-only round trips keep archive and unread state;
    • edit round trips import a peer rename (shown live, without a restart), a draft, a new peer, a session rename and a delete;
    • 1.142 edits survive;
    • log scan clean.
  • Perf, an ABBA comparison against main at 2k and 10k sessions:
    • listing, dbInit, the divergence check, hot writes, first writes and first opens are within budget, with the same agent-host.db statements as main;
    • background conversion converts 10k sessions in 200 passes;
    • an open that lands inside a conversion pass costs +80 ms (2k) / +170 ms (10k) while conversion runs. That's accepted, with a follow-up to give interactive work priority.
  • Real user data (a copy):
    • main and Insiders identical; 4a's open sample identical to main;
    • about 20 sessions don't convert because their provider store is missing in the real data. Not converting is correct for them, and nothing user-visible changes.
    • Old-build round trips on real data (genuine 1.140.0 / 1.141.2 vs main): no regression against main.
      • An archive plus rename made in 1.140, and a rename alone, survive in 4a; main loses them.
      • Turn counts are identical to main.
      • Known gap, the same as main (follow-up): a rename made in genuine 1.141 isn't imported. 1.141 re-mirrors session_chats unchanged at quit (and reverts its own archive), so the row diff sees no edit and its customChatTitle change isn't read.

Follow-ups

  • Import genuine 1.141 renames: also detect older-build title changes when the rows are unchanged, and model 1.141's re-mirror at quit in the tests.
  • A clearer log message (and lower level) for sessions whose provider can't vouch.
  • An open during a conversion pass: interactive priority.
  • Cleanup after a delete imported from an older build.
  • A session rename made in 1.142 on a legacy session.

…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]>
…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]>
…s (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]>
…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]>
…lder-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]>
…hen 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]>
…n 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]>
…ojected_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]>
… 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]>
- 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]>
…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]>
- 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]>
… 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]>
…eers 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]>
…dit (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]>
…eir 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]>
- 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]>
- 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]>
- 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]>
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]>
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]>
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]>
Copilot AI balanced review requested due to automatic review settings October 16, 2026 00:15
@sandy081 Sandeep Somavarapu (sandy081) added this to the 1.143.0 milestone Oct 16, 2026
@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Screenshot Changes

Base: ce2bc857 Current: 9146404e

Changed (1)

sessions/chatCompositeBar/OverflowingTabs/Light
Before After
before after

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 reconciliation and cached-state defects can prevent older-build edits from being reflected correctly.

4 open findings
What changed in this PR

Re-enables normalized Agent Host chat catalogs while preserving edits made after downgrading to older builds, building on the storage compatibility work in #340980 and #341086.

Changes:

  • Adds guarded import and publication of older-build chat state.
  • Enables background conversion with bounded retries and per-session synchronization.
  • Expands compatibility tests and documents the persistence contract.
File Description
src/​vs/​sessions/​contrib/​providers/​agentHost/​AGENT_HOST_SESSIONS_PROVIDER.md Updates normalization and downgrade contracts.
src/​vs/​platform/​agentHost/​test/​node/​sessionStorageIdentity.test.ts Tests normalization without changing storage addresses.
src/​vs/​platform/​agentHost/​test/​node/​sessionStateCompatibilityFixtures.ts Adds older-build editing and move fixtures.
src/​vs/​platform/​agentHost/​test/​node/​sessionDatabase.test.ts Tests combined turn and draft watermarks.
src/​vs/​platform/​agentHost/​test/​node/​agentSessionRegistry.test.ts Updates database mocks.
src/​vs/​platform/​agentHost/​test/​node/​agentService.test.ts Tests live imports, synchronization and cleanup.
src/​vs/​platform/​agentHost/​test/​node/​agentHostSessionStateOwnershipGuard.test.ts Updates compatibility-access allowances.
src/​vs/​platform/​agentHost/​test/​node/​agentHostSessionStateDatabase.test.ts Updates schema-version expectations.
src/​vs/​platform/​agentHost/​test/​node/​agentHostPeerChatStore.test.ts Tests deferred publication and conflict handling.
src/​vs/​platform/​agentHost/​test/​node/​agentHostDatabase.test.ts Tests migration markers and guarded writes.
src/​vs/​platform/​agentHost/​test/​node/​agentHostChatCatalogMigration.test.ts Checks detailed conversion deferrals.
src/​vs/​platform/​agentHost/​test/​node/​agentHostCatalogReconciliationService.test.ts Tests import batches and conversion retries.
src/​vs/​platform/​agentHost/​test/​common/​sessionTestHelpers.ts Adds watermark support to test databases.
src/​vs/​platform/​agentHost/​node/​sessionDatabase.ts Reads turn and draft watermarks together.
src/​vs/​platform/​agentHost/​node/​compatibleSessionDatabase.ts Maps watermarks and batches metadata reads.
src/​vs/​platform/​agentHost/​node/​compatibleAgentHostDatabase.ts Removes conversion gates and maps compatibility APIs.
src/​vs/​platform/​agentHost/​node/​agentServiceComposition.ts Registers peer-store disposal ownership.
src/​vs/​platform/​agentHost/​node/​agentService.ts Applies imports live and coordinates conversion and cleanup.
src/​vs/​platform/​agentHost/​node/​agentHostSessionStateStore.ts Passes draft merge bases into row reconciliation.
src/​vs/​platform/​agentHost/​node/​agentHostSessionStateDatabase.ts Loads persisted draft merge bases.
src/​vs/​platform/​agentHost/​node/​agentHostDatabase.ts Adds projection tracking and guarded reconciliation APIs.
src/​vs/​platform/​agentHost/​node/​agentHostChatRowStore.ts Detects older-build draft edits.
src/​vs/​platform/​agentHost/​node/​agentHostChatCatalogV2.md Documents normalized compatibility behavior.
src/​vs/​platform/​agentHost/​node/​agentHostChatCatalogMigration.ts Reports actionable conversion deferrals.
src/​vs/​platform/​agentHost/​node/​agentHostCatalogSyncService.ts Lowers logging for retried catalog conflicts.
src/​vs/​platform/​agentHost/​node/​agentHostCatalogReconciliationService.ts Schedules import batches and conversion retries.
src/​vs/​platform/​agentHost/​common/​sessionDataService.ts Defines the combined watermark API.
src/​vs/​platform/​agentHost/​AGENTS.md Updates persistence and synchronization guidance.

🧠 Review effort: Balanced


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

- 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]>
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]>
@sandy081
Sandeep Somavarapu (sandy081) marked this pull request as ready for review October 16, 2026 02:38
@sandy081
Sandeep Somavarapu (sandy081) merged commit 38f4504 into main Oct 16, 2026
36 checks passed
@sandy081
Sandeep Somavarapu (sandy081) deleted the agents/block4a-reconcile-v2-chat-catalogs branch October 16, 2026 02:51
Sandeep Somavarapu (sandy081) added a commit that referenced this pull request Oct 16, 2026
…possible re-projection (#342077)

Block 4a (#341904) made every legacy chat catalog convert, including older
provider-scheme sessions whose provider cannot vouch for them (registered
but with an unreadable catalog, or no longer knowing the session). Their
aggregate never becomes verified, so every conversion attempt ended
`notReady` and fed a loop:

- `_migrateChatCatalog` opened the session database (`runMigrationExclusive`)
  and ran legacy reconciliation before the readiness check, then marked the
  payload dirty, which superseded in-flight re-projections and woke parked
  sessions so the reconciliation re-opened them on the next pass.
- The conversion batch re-attempted every legacy session each cursor cycle,
  and `_convertReprojected` treated parked or unverified sessions as ready
  because `_listDirtySessions` omits parked rows, so the retry limit of five
  never bounded them. Each attempt also scheduled a follow-up pass.

Production (one Insiders profile, ~717 sessions, ~110 affected): ~920
migration operations in two ~5 minute windows, passes every 20-30 s.

Conversion now decides readiness from central state first: an unverified or
dirty aggregate returns `notReady` without opening session.db, writing or
waking anything (its re-projection is already owed). A waiting session is
skipped by the conversion batches and owes no follow-up pass; it converts
right after a pass re-projects it (`succeeded` or an already-current
`skipped`) or once its receipt is verified and clean. The check under the
session lock stays authoritative.

With 110 unvouchable sessions over twelve 30 s passes: 150 migration
operations, 350 session database opens and 100 dirty marks per pass before;
50/50/10 operations in the first three passes (re-projections parking each
session once, no conversion opens or writes) and nothing after.

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.

3 participants