Skip to content

agentHost: restore identity-mapped sessions under the runtime spelling - #341762

Merged
Sandeep Somavarapu (sandy081) merged 1 commit into
mainfrom
agents/fix-compat-session-spelling
Oct 15, 2026
Merged

Sandeep Somavarapu (sandy081) merged 1 commit into
mainfrom
agents/fix-compat-session-spelling

Conversation

@sandy081

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

Copy link
Copy Markdown
Member

Summary

Defensive fix. Restoring an identity-mapped (compat-backed) session by its storage spelling (copilotcli:/<id>) registered a second session state under that spelling, next to the runtime one (ahp-session:/<id>). The default chat's storage resource then became copilotcli:/…, which can surface as "recorded outside …" peer-chat warnings and Chat context resource must be the configuration resource or addressed chat.

No product caller is known to do this today: registry-keyed paths (Agent Merge restore, lifecycle cleanup, listings) already translate to the runtime spelling through CompatibleAgentHostDatabase. It was seen when a client subscribed with the storage URI (a probe). There is no confirmed user impact.

Fix

AgentService.restoreSession canonicalises its input through the new, required IAgentHostDatabase.toRuntimeSession (identity for AgentHostDatabase, SessionStorageIdentity.toRuntime for CompatibleAgentHostDatabase) and re-enters with the runtime spelling. No owner is derived from a chat URI. agentHostPeerChatStore.ts is untouched.

Testing

  • New agentService.test.ts test: restoring an identity-mapped session by its storage spelling restores the runtime session once.
  • Mutation proof: with the redirect disabled the test fails ({ runtime: false, storage: true, defaultChatStorage: undefined }); with the fix it passes.
  • New sessionStorageIdentity.test.ts unit test for the mapping.
  • agentService, sessionStorageIdentity, agentSessionRegistry and agentHostSessionStateStore suites: 1084 passing; eslint and typecheck-client clean.

The test does not reproduce the exact warning/throw text, only the second state registered under the storage spelling.

cc roblourens

Restoring a compat-backed session by its storage spelling (copilotcli:/id)
registered a second session state, so chat ownership and storage were
recorded under a different spelling than the catalog and peers. Canonicalize
to the runtime spelling at the restoreSession entry point.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 15, 2026 12:58
@sandy081 Sandeep Somavarapu (sandy081) added this to the 1.143.0 milestone Oct 15, 2026

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.

🟢 Approval recommended

The narrow redirect preserves existing restore coordination, has focused regression coverage, and leaves no identified blocking issues.

0 open findings

What changed in this PR

Prevents duplicate Agent Host session state by resolving compatibility storage URIs to runtime identities before restoration.

Changes:

  • Adds runtime-session mapping to the database contract and implementations.
  • Redirects restores before existing restore coordination.
  • Adds focused regression coverage and updates test doubles.
File Description
src/​vs/​platform/​agentHost/​test/​node/​sessionStorageIdentity.test.ts Tests mapped and unchanged session identities.
src/​vs/​platform/​agentHost/​test/​node/​mockAgent.ts Adds session seeding for tests.
src/​vs/​platform/​agentHost/​test/​node/​agentSessionRegistry.test.ts Updates the database test double.
src/​vs/​platform/​agentHost/​test/​node/​agentService.test.ts Tests restoration without duplicate state.
src/​vs/​platform/​agentHost/​node/​compatibleAgentHostDatabase.ts Exposes compatibility identity mapping.
src/​vs/​platform/​agentHost/​node/​agentService.ts Redirects storage-addressed restores to runtime identities.
src/​vs/​platform/​agentHost/​node/​agentHostDatabase.ts Defines mapping with an identity default.

🧠 Review effort: Balanced


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

@sandy081
Sandeep Somavarapu (sandy081) merged commit 1022cbc into main Oct 15, 2026
57 of 58 checks passed
@sandy081
Sandeep Somavarapu (sandy081) deleted the agents/fix-compat-session-spelling branch October 15, 2026 14:03

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.

🟢 Approval recommended

The narrow redirect preserves restore coordination, has focused regression coverage, and leaves no identified blocking issues.

0 open findings

🧠 Review effort: Balanced

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.

3 participants