Skip to content

agentHost: preserve writable session downgrade compatibility - #340980

Merged
roblourens merged 6 commits into
mainfrom
roblou/agents/native-session-storage-compat
Oct 12, 2026
Merged

roblourens merged 6 commits into
mainfrom
roblou/agents/native-session-storage-compat

Conversation

@roblourens

@roblourens roblourens commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

Summary

Release backport: #341086, targeting release/1.142.

Preserve writable stable downgrade compatibility when new local Agent Host sessions use native ahp-session identities. Older stable clients infer provider routing from persisted URI schemes, so native-only storage can make sessions appear missing or unopenable after downgrade.

  • Keep native runtime/protocol identities while writing newly allocated Copilot CLI, Claude, and Codex sessions through a stable-readable persistence boundary.
  • Read both native and compatibility representations. Historical legacy sessions retain their identities, and existing native data is not migrated.
  • Apply the boundary consistently to registry/catalog keys, tombstones, peer-chat directories, identity-bearing metadata, drafts, and catalog checksums. Provider data and conversation content remain opaque.
  • Keep legacy-readable chat authority during the compatibility window so older-build membership edits survive re-upgrade. Existing normalized catalogs are not demoted.
  • Separate local and per-address remote frontend summary-cache generations from stable's cache to prevent cached legacy addresses from colliding with native host identities.
  • Preserve archived peer state during legacy hydration.

The allocation writer can later switch to native storage without removing the compatibility reader or changing established storage addresses.

Review notes

  • Compatibility is for downgrading the application and local host together, not wire aliases for an older client connected to a newer host.
  • Legacy chat authority and separate frontend cache generations are necessary parts of the round-trip contract, not just URI rewriting.
  • Existing native Insiders data and existing normalized catalogs are intentionally not migrated.
  • Added 54 regression cases. Both independent subagent reviews used Opus 5.5.
  • The first Opus review found a native-tombstone bypass; the follow-up preserves native and legacy tombstones.
  • Copilot's registration-path comment is addressed by moving storage selection out of runtime/importer registration. Explicit allocation and genuinely first-seen discovery select storage; pre-existing native registrations, tombstones, exclusions, and session data retain their representation.
  • The second Opus review identified duplicate-discovery risk if first-seen SDK backings were excluded from compatibility. Discovery round trips now cover all three providers while separately checking existing native drafts.
  • Central receipt checksum pairs are persisted atomically with the catalog write, allowing cold receipt scans without reading payloads or depending on the bounded LRU. Tests cover more than 256 receipts, restart/exclusion compare-and-set, cancelled/stale writes, and synchronization settling after older-writer changes.
  • Copilot's allocation/deletion race is addressed by serializing both tombstone entry points against identity allocation, with deterministic interleaving tests.
  • Discovery selects compatibility storage only when the native directory stat returns FILE_NOT_FOUND; permission and I/O failures preserve existing identity and are logged. Six provider regressions reproduced the issue before the fix.
  • The specification documents the provider-neutral URI rationale, downgrade failure mechanism, and retirement contract for the compatibility writer.

Validation

Merged freshly fetched origin/main (c0f2e898b16593abb270bf06ac9f4256acf3c650) without rewriting pushed history. Resolved the conflict by preserving upstream's non-destructive providerAbsent handling and retaining the compatibility checksum bridge across exclusion and revival. Reran validation on both main and the separate release/1.142 backport.

  • npm run build-fast -- --client-only — passed.
  • npm run typecheck-client — passed.
  • npm run valid-layers-check — passed.
  • npm run eslint -- src/vs/platform/agentHost/node/{sessionStorageIdentity,compatibleAgentHostDatabase,compatibleSessionDatabase,agentHostDatabase,agentHostBootstrap,agentService,sessionDataService,agentHostPeerChatStore}.ts src/vs/platform/agentHost/test/node/sessionStorageIdentity.test.ts src/vs/sessions/contrib/providers/agentHost/browser/localAgentHostSessionsProvider.ts src/vs/sessions/contrib/providers/agentHost/test/browser/localAgentHostSessionsProvider.test.ts src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHostSessionsProvider.ts src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostSessionsProvider.test.ts — passed without warnings.
  • git diff --check — passed.
  • Commit-time hygiene — passed.

Affected test selection — passed independently on both branches, 4,040 tests, 28 existing skips:

env -u COPILOT_HOME ./scripts/test.sh --reporter dot \
  --run src/vs/platform/agentHost/test/node/sessionStorageIdentity.test.ts \
  --run src/vs/platform/agentHost/test/node/agentHostPeerChatStore.test.ts \
  --run src/vs/platform/agentHost/test/node/agentHostDatabase.test.ts \
  --run src/vs/platform/agentHost/test/node/sessionDatabase.test.ts \
  --run src/vs/platform/agentHost/test/node/sessionDataService.test.ts \
  --run src/vs/platform/agentHost/test/node/agentHostCatalogSyncService.test.ts \
  --run src/vs/platform/agentHost/test/node/agentHostCatalogReconciliationService.test.ts \
  --run src/vs/platform/agentHost/test/node/agentHostCatalogListReader.test.ts \
  --run src/vs/platform/agentHost/test/node/agentHostCatalogSourceResolver.test.ts \
  --run src/vs/platform/agentHost/test/node/agentSessionRegistry.test.ts \
  --run src/vs/platform/agentHost/test/node/agentService.test.ts \
  --run src/vs/platform/agentHost/test/node/agentHostBootstrap.test.ts \
  --run src/vs/platform/agentHost/test/node/copilotAgent.test.ts \
  --run src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts \
  --run src/vs/platform/agentHost/test/node/claudeAgent.test.ts \
  --run src/vs/platform/agentHost/test/node/codex/codexAgent.test.ts \
  --run src/vs/sessions/contrib/providers/agentHost/test/browser/localAgentHostSessionsProvider.test.ts \
  --run src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostSessionsProvider.test.ts

Unchanged stable round trip

Built tag 1.141.0 (2a59476c9bfcb90b3ddc372c36762471b7dfad1c) in an isolated worktree with independently installed dependencies and no production-source changes. Ran current → stable → current host/service graphs against isolated storage for all three providers. Stable listed/restored new sessions; turn records, titles, unsent drafts, peer additions/archive state, and deletion survived re-upgrade. Sessions created by stable retained their historical identities and legacy authority.

This used mock SDK providers and Electron in Node mode. Authenticated real-provider SDKs, GUI downgrade/re-upgrade, and older stable versions were not exercised. Personal Insiders-build testing is planned.

(Written by Copilot)

Keep native runtime identities while writing stable-readable session and chat storage. Retain dual readers, legacy chat authority during the downgrade window, and separate frontend cache generations.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 12, 2026 02:35
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Some pipeline(s) encountered errors during trigger evaluation.

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

Import paths currently create new storage identities, and compact catalog hashes are not translated correctly after restart.

2 open findings
What changed in this PR

Adds downgrade-compatible persistence for local Agent Host sessions while preserving native runtime identities.

Changes:

  • Introduces runtime-to-storage identity translation across catalogs, metadata, drafts, and peer chats.
  • Separates current and stable frontend cache generations.
  • Adds compatibility documentation and regression coverage.
File Description
remoteAgentHostSessionsProvider.test.ts Tests remote cache isolation.
remoteAgentHostSessionsProvider.ts Advances remote cache generation.
localAgentHostSessionsProvider.test.ts Tests local cache isolation.
localAgentHostSessionsProvider.ts Advances local cache generation.
AGENT_HOST_SESSIONS_PROVIDER.md Documents downgrade persistence.
sessionStorageIdentity.test.ts Covers identity translation and round trips.
sessionStorageIdentity.ts Implements persistence identity mapping.
sessionDataService.ts Applies mapping to session databases.
serviceBootstrapping.md Documents codec initialization.
compatibleSessionDatabase.ts Translates per-session persistence operations.
compatibleAgentHostDatabase.ts Translates orchestrator database operations.
agentService.ts Prepares allocation storage and legacy catalogs.
agentHostPeerChatStore.ts Preserves archived peer state.
agentHostDatabase.ts Adds storage identity metadata support.
agentHostBootstrap.ts Initializes compatibility-aware services.

🧠 Review effort: Balanced


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

Keep native and legacy tombstones authoritative when preparing compatibility storage. Add discovery, importer, restart, and explicit-create regressions for the Opus review finding.

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

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Base: 85e195f2 Current: 3967bc62

No screenshot changes.

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

Identity allocation has a tombstone race, and compact catalog receipts expose incorrect hashes after cold restart.

3 open findings

🧠 Review effort: Balanced

Preserve existing native storage during discovery and import while preparing genuinely first-seen SDK admissions for stable downgrade. Persist central catalog checksum bridges atomically, translate cold exclusion expectations, and serialize deletion against identity allocation.

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

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

A transient filesystem error during discovery can incorrectly select legacy storage and make existing native session data unreachable.

1 open finding
3 resolved since last review

🧠 Review effort: Balanced

roblourens and others added 2 commits October 12, 2026 09:19
Select compatibility storage for discovered sessions only when their native data directory is genuinely absent. Permission and I/O errors reach the existing discovery warning path without registering or readdressing the session. Add six provider regressions and expand the session-identity rationale and compatibility retirement documentation.

Co-authored-by: Copilot <[email protected]>
Preserve upstream providerAbsent catalog retention and keep compatibility checksum receipts across exclusion and revival.

Co-authored-by: Copilot <[email protected]>
roblourens added a commit that referenced this pull request Oct 12, 2026
…341086)

agentHost: backport storage compatibility (Written by Copilot)

Backport the complete writable session downgrade fix from #340980 to release/1.142, including review fixes, filesystem-error guards, and documentation. Preserve providerAbsent catalog data and its checksum bridge across revival.

Co-authored-by: Copilot <[email protected]>
Adapt session compatibility guards and tests to upstream's always-enabled central catalog, preserving legacy chat authority for stable-readable sessions.

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

@connor4312 Connor Peet (connor4312) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed for security and correctness; no actionable P1/P2 findings.

Written by Connor's agent running GPT-6.1 Sol

@roblourens
roblourens merged commit 72b3e15 into main Oct 12, 2026
35 checks passed
@roblourens
roblourens deleted the roblou/agents/native-session-storage-compat branch October 12, 2026 17:45
@vs-code-engineering vs-code-engineering Bot added this to the 1.143.0 milestone Oct 12, 2026
Sandeep Somavarapu (sandy081) added a commit that referenced this pull request Oct 13, 2026
…#341191)

* agentHost: resolve chat owners from recorded ownership, not chat URIs

Core of Block 1 (m1). The host no longer derives a chat's owning session,
storage location or parent from the session encoded in its URI:

- AgentHostStateManager records owner, storage resource and parent chat
  at registration (getChatOwner/requireChatOwner/getChatStorageResource/
  getChatParent, findRetainedChatOwner for evicted/announced sessions).
- AgentHostDatabase.findChatOwner reads the owner from the containing
  record (chats_v2 incl. tombstones, then session_chats, then the
  sessions_v2 payload); catalog chats expose ownerSession. Read-only, no
  schema change.
- AgentService resolves cold chats via registry -> retained -> central DB
  -> registered-session default chats -> in-flight restores -> spawn edges
  in loaded chats; no URI fallback. Unknown-owner dispatch keeps today's
  IsRead/IsArchived rejections, otherwise a traced no-op.
- Teardown uses owners captured at subscribe/request/registration time
  (subscriptions, GC, residency, input-request timing, workspace
  preparation, side-effect signals for removed chats).
- Provider listings carry their session (IAgentListedChat).

Behavior note: a canonical subagent chat whose parent is neither loaded,
restoring, nor recorded in the catalog is now not found instead of
restoring the parent decoded from its URI (agreed case C / D6). Clients
restore the parent first; a subscribe joins an in-flight parent restore.

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

* agentHost: register chats with their recorded storage resource

Chat registration paths now accept an explicit storage resource. Restoring
a session passes chats_v2.storage_resource from the normalized catalog for
the default chat, peers and restored subagents, and threads it into
hydration, provider chat contexts, history reads and workspace transitions.
The owner+URI-shape rule is kept only as the creation-time rule
(creationTimeChatStorageResource) for brand-new chats and legacy sources
that record no storage. A recorded storage resource is never overwritten
by re-registration or summary refresh.

No behavior change for existing data: for unmoved chats the stored
storage_resource equals what the creation-time rule computes.

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

* agentHost: resolve chat owners in node services and chat contributions

Node services and chat contributions take a chat's owning session from the
in-memory registry, host-passed hook payloads, or owners captured at
registration, instead of decoding the chat URI:

- Telemetry reports, turn/tool-call trackers and session-open telemetry
  carry the recorded owner for attribution.
- Chat contributions record the owner passed with every hook payload;
  `_owningSession` URI parsing is removed.
- Turn service, chat input, automation, customization enablement, git
  state, completion provider, review, PR status, changeset services,
  session title, workspace context and input-needed use registry owners.
- Teardown paths use captured owners: the changeset file monitor records
  each watch's session when tracking starts, workspace context records chat
  owners before release.
- Persisted turn usage, turn delegation and the chat context use the
  recorded storage resource (hydration passes it explicitly).

Legacy per-session peerChats entries now belong to the session whose
database contains them. An entry is skipped when the live registry or the
central catalog (chats_v2 incl. tombstones, then session_chats, then
catalog payloads) records the chat under another session or as deleted.
Behavior change: an entry whose URI encodes another session but has no
central record is now accepted for its containing session instead of
being skipped. No writer produces such entries, so the case is believed
unreachable; unmoved chats behave as before.

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

* agentHost: take chat owners and storage explicitly in providers and shared code

Providers and shared host code receive a chat's owning session and storage
from the host instead of decoding the chat URI:

- Copilot uses the session's recorded owner for server tools, MCP, edit
  tracking, discovery logging and history mapping (mapSessionEvents takes
  the routing session).
- Claude sessions, pipelines and routers carry the owning configuration
  scope; subagent edit chats and retained terminal output use it.
- Codex records each binding's storage resource from the host context and
  uses it, with the recorded configuration scope, for turn-id persistence
  and retained command output.
- Subagent spawn events take the spawning chat's owner from a lookup
  (registry, Claude chat scope, Copilot recorded chat scope).
- Server tools resolve the executing chat's owner from the registry;
  session server tools use an accessor owner lookup.
- Local commands and Mission Control use registry owners.
- Edit attribution, survival and arc telemetry take the owning session
  explicitly; storage-keyed tracking is unchanged.
- MCP controllers take their owning session; channel parsing no longer
  checks the provider via the URI, since providers reject chats they do not
  host.
- Changeset URIs report a session only for session- and folder-owned
  changesets; chat-owned changesets resolve their session through the
  recorded owner (changesetSession). Cold changeset subscriptions resolve
  and restore the owner through the host's cold owner resolution; session
  teardown disposes changesets of the chats registered to it.
- Chat attachment links and plan links are built from the recorded owner.

Unknown owners on non-teardown paths keep today's no-op outcomes. Existing
chats keep today's behavior: their recorded owners and storage equal what
the URI encoded.

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

* agentHost: resolve chat owners on the client from session records

Client code takes a chat's owning session from session state, session
catalogs or host session records instead of decoding the chat URI:

- Sessions provider: a completed chat turn keeps alive the session whose
  catalog lists the chat; context-reference links use the session's backend
  resource.
- Subagent opener: the owner is the session of the spawning chat
  (parentSessionResource) or the session whose chat maps to the backend
  subagent chat; legacy subagent-session parents are still supported.
- Remote session source, inspector and router: a chat listed in the backend
  session's own catalog belongs to that session.
- Session handler: tool confirmation metadata reads the chat from the
  subscribed session state that lists it; restored subagent chats use the
  catalog resource or the canonical chat minted under the parent.
- Usage sidecar: the owner of a default chat comes from the emitting host's
  session records (recorded default chat, else the forward default chat).
- Chat reference chips resolve the owner when clicked: held session state,
  then the local host's and each connected remote host's session records.
  buildOpenSessionLinkForChatResource is removed.

Behavior changes, all for chats whose URI does not encode the session that
lists them (none exist for VS Code hosts today): remote inspection and
messaging use such a chat instead of rejecting it; host-assigned opaque chat
URIs now resolve through session state, so tool confirmations keep the tool
call metadata like VS Code-shaped chats; a chat reference to a chat no host
lists does nothing instead of opening the session decoded from its URI.

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

* agentHost: stop exposing the session encoded in chat URIs

Removes parseRequiredSessionUriFromChatUri, parseDefaultChatUri,
chatStorageUri and resolveChatUri, and narrows parseChatUri to the chat
id: the session a chat URI was minted for is no longer readable, so a
chat's owner and storage can only come from the records that contain it.
Chat URIs are still minted from their session.

Tests:
- A mismatch oracle restores and creates chats whose URIs encode a session
  of an unregistered provider under another owner with recorded storage;
  ownership, configuration owner, cold owner resolution, provider routing,
  provider contexts and storage all follow the records, and the encoded
  session is never touched.
- Cold subscribe restores the session whose normalized or legacy record
  contains the chat; a chat of a deleted session and an unknown chat are not
  found, and the encoded session is never restored.
- Test fakes that emulate hosts use a shared test-only helper for the
  session they minted a chat URI for.

Also restores import formatting that earlier milestone commits collapsed
and documents chat ownership in the agent host AGENTS.md.

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

* agentHost: batch the central owner lookup for legacy peer chats

Legacy per-session peerChats entries are owned by the session whose
database holds them unless the live registry or the central catalog records
the chat under another owner or as deleted. The central check now uses one
batched read-only lookup (findChatOwners) for all entries of a catalog,
bounded by the existing import limit, instead of one query per entry.
findChatOwner delegates to it.

The peer store test now covers: an entry recorded centrally under another
owner (skipped), an entry tombstoned centrally (skipped), an entry live
elsewhere (skipped), and an entry whose URI encodes another session with no
central record (accepted for the reading session). The last case is the
behavior change already noted in the m2 commit (no known writer produces
such entries). The database test checks batched and single lookups agree.

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

* agentHost: harden client chat owner lookups

Usage sidecar:
- An owner lookup returns the matching session directly instead of
  caching every listed session and reading the target back, so a target
  listed among more sessions than the cache holds is no longer evicted.
  Only resolved owners are cached.
- Records are queued per host, and the cache is re-checked when a queued
  step runs, so a burst during the first lookup lists the sessions once
  and a slow host no longer blocks the others.
- Each step catches and traces its failure, so a failing listing no longer
  stops later records.
- Held session state is checked before listing the host's sessions.

Chat reference owner resolution:
- Hosts' session records are queried in parallel with a per-host timeout
  (traced), keeping a deterministic preference: held state, then local,
  then remotes in connection order. A failing host is traced and skipped.
- A reference whose value is a bare session URI (not a chat channel) opens
  that session, as before.

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

* agentHost: fix host review findings for unmoved chats

Fixes regressions for unmoved chats found in host review of the
chat-owner work:

- Sandbox temp dir: a ShellManager keeps the owner session for
  configuration and terminal ownership but keys its sandbox temp dir
  by the chat's recorded storage resource (the session for the default
  chat, the chat URI for peers, as before). Disposing a peer chat's
  ShellManager no longer deletes the directory the default chat uses.
- Session-open telemetry: a cold chat subscribe hands its resolved
  owner to the telemetry scope, so the attempt is measured again.
- Local commands capture the chat owner when they start and pass it
  through, so removing the chat mid-command no longer rejects and the
  turn still ends.
- A chat subscribed before it registers gets its owner when it
  registers, so it counts for residency and last-unsubscribe GC.
- Owner lookups: findChatOwners decodes only catalog payloads that
  contain a pending chat's JSON literal (an instr prefilter, batched).
  Chat-backing checks read the marker owner only for legacy markers
  without a recorded provider, and share one default-chat inventory
  read per discovery, migration or filter pass.
- A cancelled turn is tracked only when its owner is known, and its
  checkpoint discard uses the recorded owner of a chat that already
  left the registry.
- Restored subagents read their transcript from their recorded
  storage resource (registry, then the catalog row), and fall back to
  the creation-time rule only when nothing is recorded.
- Removed the unused IChatOwnerResolution.deleted field. Tombstone
  handling is unchanged.

No schema, protocol or persisted-data change.

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

* agentHost: resolve batched payload owners per batch

findChatOwners resolves a chat from a catalog payload only in the query
batch that searched for it. Before, a payload matched for one batch also
resolved pending chats of later batches, so a chat listed by two payloads
could take the higher session instead of the lowest one that
findChatOwner returns. Tests cover that shape with the lower owner live
and deleted, a chat URI that needs JSON escaping, and a legacy peer-chat
entry skipped because it is recorded under the reading session but
tombstoned.

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

* agentHost: make chat owner resolution a required API

IAgentService.resolveChatOwner and the AgentSideEffects resolveChatOwner
option are required instead of optional, so callers no longer skip the
recorded-owner lookup when an implementation omits it. The chat-backing
owner lookup passed to _readSessionRegistrationFacts is required too.

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

* agentHost: make every Block 1 chat ownership API parameter required

Optional members, optional parameters and default-value parameters that the
chat ownership work added are now required. Where absent is a real state the
caller decides, the type is `T | undefined`. A registration, chat context or
hydration now receives the chat's storage resource explicitly. A caller that
creates a new chat, or restores from a source that records no storage,
applies the creation-time rule itself instead of relying on a hidden default
in the API.

- AgentHostStateManager:
  - addChat takes a required storageResource.
  - registerRestoredChatSummary requires options.storageResource.
  - restoreSession takes a required chatStorageResource(session, chat)
    function instead of an optional storage map.
  - _ensureDefaultChat requires its storage.
  - IChatEntry.parentChat is a required `string | undefined`.
- createAgentChatContext and AgentService._chatContext require
  storageResource.
- AgentService._getChatMessages and _loadWorkspaceTransitions require
  storage.
- IHydrationContext.storageResource and restoreChatIsolation's
  storageResource are required, so contributions no longer fall back.
- AgentService:
  - _isChatBacking and _findRecordedChatOwner require their lookups.
  - IChatOwnerResolution.spawnedBy and its title are required
    `| undefined`.
- Session-open telemetry _start/_classify take a required
  `URI | undefined` owner.
- AgentHostPeerChatStore requires its live-owner lookup.
- getRenameChatArgs takes a required `ProtocolURI | undefined`
  currentChannel and `URI | undefined` currentSession.
- Client:
  - findChatOwnerInSessionRecords requires defaultChatOnly.
  - resolveAgentHostChatOwner requires timeoutMs
    (AGENT_HOST_CHAT_OWNER_TIMEOUT_MS).
  - The subagent opener target reuses the existing
    IOpenSubagentChatContext shape.

No behavior change: every caller passes the value the removed default
produced.

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

* agentHost: keep restore storage fallbacks neutral

Review follow-ups to the required-parameter change, with no behavior change
for unmoved chats.

- A legacy subagent-session restore reads from the subagent's recorded
  storage when it is registered. An unregistered one follows the
  creation-time rule and still skips workspace transitions.
- Peer and subagent restore fall back from recorded storage directly to
  the creation-time rule, without inheriting a live entry of another
  session.
- Default-chat adoption uses the storage the loaded catalog records before
  the creation-time rule, matching restore.
- A normalized catalog row without recorded storage logs a trace when it
  falls back to the creation-time rule.
- getRenameChatSession takes a required `ProtocolURI | undefined`
  currentChannel, like getRenameChatArgs.

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

* agentHost: index subscribed resources by chat

The subscription service indexes subscribed chat and chat-scoped canvas
resources by their chat, so recording the owner of a newly registered chat
and forgetting it after the chat's last subscription no longer scan every
subscription. Owner semantics are unchanged: a registered owner is recorded
only while the chat or one of its canvases is subscribed, and is forgotten
when its last subscribed resource leaves.

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

* agentHost: hand restored chat resolvers their recorded storage

The state manager passes a restored chat's resolver the storage resource
recorded on its entry when resolution starts, while the entry is valid.
The restored peer and subagent resolvers use it for the provider chat
context and the history read, so nothing looks up storage after
registration. Resolution behaves as before: unmoved chats resolve with the
same storage, and a chat invalidated mid-resolve still rejects with
"Restored chat was invalidated while resolving" after its resolver
completes.

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

* agentHost: add a chat ownership service

Chat ownership resolution moves out of AgentService into
IAgentHostChatOwnershipService, a core node service that consumers inject.
It delegates live lookups (owner, required owner, storage, parent, retained
owner) to the state manager registry rather than duplicating it.

It owns the cold resolution chain: registry and retained summaries, the
central catalog, the registered default-chat inventory, tracked in-flight
restores, then spawn edges. It also provides createRecordedOwnerLookup, a
lookup that reads the inventory once per pass.

Registration events now come from the service. onDidRegisterChat and the
new onDidUnregisterChat carry the owner and storage captured from the
registry entry; unregistration fires from the entry's invalidation.

AgentService reports each session and subagent restore with trackRestore,
so the service depends only on the state manager and the database, never
on AgentService.

Callbacks replaced by injection:
- IAgentService.resolveChatOwner and the side-effects resolveChatOwner
  option are removed. ProtocolServerHandler and AgentSideEffects inject the
  service.
- AgentHostPeerChatStore takes the service instead of a live-owner
  callback.
- The subscription service back-fills owners for chats subscribed before
  they register by listening to onDidRegisterChat itself, using the chat
  index. recordChatOwner leaves its interface.

No protocol, persisted-data or schema change; behavior is unchanged.

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

* agentHost: read chat ownership through the ownership service

Every DI-created consumer of chat ownership now injects
IAgentHostChatOwnershipService instead of reading the state manager
registry directly. This covers:
- changeset coordinator, file monitor, operation and changeset services
- chat input, customization enablement, Git state, pull request status,
  review, turn, utility model and session-open telemetry services
- session residency and session permissions
- local commands, Mission Control host and SDK event source
- queue drain, turn delegation, persisted turn usage and workspace
  conversion contributions
- AgentService, AgentSideEffects and ProtocolServerHandler
- the server tool accessor wiring

Contributions and telemetry that no longer need the state manager drop it.
Non-DI helpers keep the state manager: chat context and turn-starter
functions, branch changeset scope, the configuration service built before
DI, the server tool host and the completion provider.

Mechanical; behavior is unchanged.

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

* agentHost: keep catalog payload scans off the owner lookup hot paths

Reading or reconciling a session's legacy peer chats checked each entry
against every cached catalog payload. Those entries are rarely in the
central catalogs, so they all fell through to sessions_v2 table scans: one
per 100 chats, about 10 for a full list of 999 peers. Cold owner lookups
also scanned payloads before the registered session inventory.

IAgentHostDatabase.findChatOwner/findChatOwners are split into:
- findCentralChatOwners: chats_v2 (tombstones included), then
  session_chats; two indexed IN queries and no payload pass.
- findCatalogPayloadChatOwners: the prefiltered sessions_v2 payload scan.

The legacy peer-chat filter consults only findCentralChatOwners and the
live registry. Per the agreed rule, an entry is skipped only when the
central catalog or the live registry records it under another session or
as tombstoned. A chat listed only in another session's cached payload is
not a central record, so its entry now stays with the session whose
database holds it.

The cold owner chain is now:
1. live registry and retained summaries
2. central catalogs
3. registered default-chat inventory
4. catalog payloads
5. in-flight restores
6. spawn edges

A legacy default chat resolves from the inventory without a payload scan.
Tombstone dominance is unchanged because chats_v2 is still checked first.

No schema change.

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

* agentHost: name the payload owner lookup findPayloadChatOwners

Renames IAgentHostDatabase.findCatalogPayloadChatOwners to
findPayloadChatOwners, the name the review asked for. Adds a real-database
test that a chat listed only in a cached catalog payload still resolves
through the ownership service, as the last recorded source.

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

* agentHost: keep the findCatalogPayloadChatOwners name

Restores the IAgentHostDatabase.findCatalogPayloadChatOwners name that was
accepted in review. The only change left relative to the perf fix is the
real-database test that a chat listed only in a cached catalog payload
still resolves through the ownership service.

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

* agentHost: cache the registered default-chat index

A cold owner lookup that misses the live registry and the central catalogs
rebuilt the registered default-chat inventory on every call. It listed both
registration tables and minted up to three default-chat URIs per session,
which costs tens of milliseconds of JavaScript at 10000 sessions on each
cold subscribe of a legacy default chat or an unknown chat.

The ownership service now keeps the index (default chat to registered
session identity) and rebuilds it only when the registrations change. The
database counts registration changes with connection-scoped TEMP triggers
on sessions, sessions_v2 and the tombstone/exclusion metadata keys:
- getRegistrationGeneration reads the count.
- readSessionRegistrations returns both listings together with the count
  they reflect, read in one sequenced task.

The count catches every writer of those tables, including discovery and
migration, because this host's connection is the only writer of
agent-host.db. TEMP objects never change the database file, so there is no
schema change.

A newly registered session's default chat resolves immediately, and an
unregistered, tombstoned or excluded session stops resolving.
createRecordedOwnerLookup uses the same index. The index mints standard
default chats and checks each hit against the state manager's recorded
default chat, so it answers exactly as the per-call inventory did.

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

* agentHost: count default-chat index reads with spies

The default-chat index test counted registration listings from sqlite trace
events, which can arrive after the awaited lookup resolves. It now counts
calls to the listing methods, which is deterministic.

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

* agentHost: build the default-chat index once per recorded-owner pass

createRecordedOwnerLookup holds the first default-chat index of its pass,
so a pass builds it at most once, as before the index was cached, even
when registrations change while the pass runs.

Two fixes to the shared build:
- A caller retries the shared build only when that build is older than
  the registration generation the caller read.
- A finished build clears the shared slot only if the slot still holds
  that build.

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

* agentHost: adapt main's new call sites to chat ownership

Adapts main's #340980 (preserve writable session downgrade compatibility)
to Block 1.

- SessionStorageIdentity translated a chat URI between the runtime and
  storage spellings of its session by reading the session from
  parseChatUri, which Block 1 no longer exposes. That address translation
  now lives in a private function inside sessionStorageIdentity.ts. It
  decodes the URI's encoded session, maps it through the identity records,
  and re-encodes it, keeping the chat id, the subagent tool-call form and
  any ?/# suffix. It never returns the decoded session and is never used
  to determine a chat's owner.
- CompatibleAgentHostDatabase implements the Block 1 database members:
  - findCentralChatOwners and findCatalogPayloadChatOwners look up storage
    chats and return owners keyed by the caller's runtime chat.
  - getRegistrationGeneration passes the generation through.
  - readSessionRegistrations returns translated listings.
- Main's new tests pass the arguments Block 1 made required: ownerSessionUri
  for edit attribution, and the ownership service for the peer chat store.

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

* agentHost: read recorded chat storage once per restore

Restoring a session read the catalog snapshot twice more than main to look
up recorded chat storage: once for its peer chats and once for its restored
subagents.

Both now use storage from a snapshot the restore already reads:
- Peer chats use the snapshot `_restorePeerChats` reads first.
- Subagent admission and its retry receive the map the restore built from
  its own catalog snapshot.

The map is a required parameter. A restore therefore reads the snapshot as
often as on main.

Storage values are unchanged. A restore never records storage other than
the creation-time rule (a legacy migration records only that), so a chat
without recorded storage in the snapshot falls back to the same value as
before.

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

* agentHost: count chat-owned changeset subscriptions for their chat's owner

A `<chat>/changeset/...` subscription was not associated with its chat, so
no owner was recorded for it and hasSessionSubscribers/residency missed an
active peer-chat changeset. Map a chat-owned changeset to its chat via the
parsed changeset owner (no session decoding), so the registration back-fill
and setSubscriptionOwner record its owner like the chat and its canvases.

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

* agentHost: register the peer chat in the Claude MCP artifact tools test

The node-runner-only test (skipped in the Electron runner, which lacks
SharedArrayBuffer) used a peer chat URI that was never registered. The
artifact tools resolve the chat's owner from recorded ownership rather than
the chat URI, so register the chat under its session as the other tool
tests do.

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

---------

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

4 participants