From 2282da2a669d07e1b65cd9df002eb8920f74573e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 04:59:39 +0000 Subject: [PATCH 1/5] CONTRACT: fix(ui-server): let another owner login continue a chat's retained voice history (#3963) Every owner sign-in is its own principal, and a chat's retained dialogue belonged to the exact login that started it, so a second device's login was refused with "Dialogue ownership mismatch". Under the maintainer's ruling (option A) the history now belongs to the account, as its safety history does since #3952/#3962. `dialogueOwner` decides history access with `sameAccount` over the owner row's stored account (089's `principal_account`), so owner/session/alias lookup, opening, binding and adoption, reads, writes and close accept another owner login, also after the starting login is pruned. A typed-first chat's first voice reuses the chat's safety owner from any login of its account; a safety owner of another account, or with unknown or contradictory evidence, is refused rather than forked. The retained-conversation list and live dialogue pages and storage errors reach every login of the account and nobody else. Live-epoch authority stays exact and separate from history ownership. Migration 090 records the opening login on each dialogue conversation (backfilled from its owner, which was always the opener before this change); only that login reopens or closes it. The catalog's active epochs carry their opening principal, and liveness checks compare the owner's attribution and account instead of the caller. Native voice recovery of any login of the account, or of a pruned login, keeps a chat legacy; another login's unclosed epoch still marks it partial. Attribution, records, aliases, generations and deletion's exact-principal rule are unchanged, and nothing enters provider history. Co-Authored-By: Claude Opus 5.5 --- .changeset/3963-dialogue-account-ownership.md | 5 + docs/decisions/governed-writable-workers.md | 2 +- docs/http-api.md | 2 +- docs/integration-contract.md | 10 + docs/integration-contract/http.md | 12 + docs/integration-contract/wire.md | 48 ++- docs/plans/chat-history-deletion.md | 12 +- .../090_dialogue_conversation_principal.sql | 17 + packages/ui-server/src/routes/sessions.ts | 20 +- packages/ui-server/src/ws/clients.ts | 5 +- packages/ui-server/src/ws/dialogue-storage.ts | 81 ++++- packages/ui-server/src/ws/dialogue.ts | 36 +- packages/ui-server/src/ws/host.ts | 14 +- packages/ui-server/src/ws/session-catalog.ts | 19 +- .../tests/dialogue-account-ownership.test.ts | 321 ++++++++++++++++++ 15 files changed, 553 insertions(+), 51 deletions(-) create mode 100644 .changeset/3963-dialogue-account-ownership.md create mode 100644 packages/ui-server/migrations/090_dialogue_conversation_principal.sql create mode 100644 packages/ui-server/tests/dialogue-account-ownership.test.ts diff --git a/.changeset/3963-dialogue-account-ownership.md b/.changeset/3963-dialogue-account-ownership.md new file mode 100644 index 0000000000..f65ff91b0b --- /dev/null +++ b/.changeset/3963-dialogue-account-ownership.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +An owner can continue a chat by voice from another device (#3963). Every owner sign-in is its own principal, and a chat's retained voice history belonged to the exact login that started it, so a second login was refused with "Dialogue ownership mismatch". That history now belongs to the account, as its safety history does: another owner login opens voice on it, reads it, binds it and receives its live pages, also after the starting login has been pruned. A typed-first chat's first voice from either login uses the chat's own history owner. A live conversation and its epochs stay with the login that opened them (migration 090 records it), so sharing the history gives no control over another login's conversation. Agents, ambient, system and unknown principals still match only themselves, a pruned or revoked login regains nothing, corrupt or contradictory ownership is refused, coverage stays honestly `legacy` or `partial`, and exact-principal chat deletion is unchanged. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 7d7b70627e..d0f9ea77de 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -2254,7 +2254,7 @@ The brain's git history stays the durable record of its content. - **The Activity recorder and its rollups** price those events under the [cost-tracking rules](cost-tracking.md). An unknown price is never counted as zero. The session total that counts unknown as zero - (`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:500`) + (`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:507`) must not feed any budget. **Enforcement:** diff --git a/docs/http-api.md b/docs/http-api.md index e0cd5b4f9f..75b01c70a7 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -630,7 +630,7 @@ key or SSE resumption promise exists. All are protected; access is to the shared server record, not solely the calling principal's runs or sessions. -**GET /api/sessions.** Optional `includeRetainedConversations=true` adds principal-owned host-only conversation metadata in `retainedConversations` (`id`, `created_at`), without fabricating backend sessions or tasks. At most 200 metadata rows are returned; `retainedAfter` is the exclusive ID cursor for the next page. Omit it for the first page. Dialogue itself uses the separately negotiated bounded WebSocket history protocol. Returns `{ sessions: ChatSession[], +**GET /api/sessions.** Optional `includeRetainedConversations=true` adds the caller's account's host-only conversation metadata in `retainedConversations` (#3963) (`id`, `created_at`), without fabricating backend sessions or tasks. At most 200 metadata rows are returned; `retainedAfter` is the exclusive ID cursor for the next page. Omit it for the first page. Dialogue itself uses the separately negotiated bounded WebSocket history protocol. Returns `{ sessions: ChatSession[], unavailableBackends?: string[] }`, newest lastActiveAt first. Each session has id, nullable title, createdAt, lastActiveAt, totalCostUsd, numTurns and backendId. Stored nonzero accounting supplements a backend's zero figures. diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 97364992e6..7aee62f22f 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -218,6 +218,16 @@ as a credential, so it cannot enable a provider. `buildSystemPromptAppend` accepts `webTools: true`, which adds the brief's line on what the web tools do not offer. This ships in a minor. +## Retained voice history belongs to its account (additive, 0.45.0, #3963) + +Another owner login continues a chat's retained dialogue by voice, reads it +and receives its live pages; a pruned starting login no longer strands it. A +live conversation and its epochs stay with the login that opened them, and +other accounts are refused as before. No field changes. See +[wire](integration-contract/wire.md#retained-voice-history-belongs-to-its-account-additive-0450-3963) +and [HTTP](integration-contract/http.md#retained-conversations-account-additive-3963). +This ships in a minor; no breaking ruling is required. + ## Retained barge-in and conversation end (additive, 0.45.0, #3729) `DialogueEvidence` gains `voice_interruption`, written when the host forwards diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 2f7e8192bb..439d202431 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -363,6 +363,18 @@ evidence is contradictory, which no released host writes, and attribution, records, verdicts, gaps and generations are not rewritten ([decision](../decisions/session-safety-reviews.md#a-chats-safety-history-outlives-its-login-3962)). + + +### Retained conversations list the account's histories (additive, #3963) + +`GET /api/sessions?includeRetainedConversations=true` lists, in +`retainedConversations`, the host-only histories of the caller's account: its +own, and those another owner login started, including one whose login has +since been pruned. An agent, ambient or system principal still lists only its +own. A history whose stored ownership evidence is corrupt or contradictory is +listed for nobody. The shape, paging and `retainedAfter` cursor are unchanged +([wire](wire.md#retained-voice-history-belongs-to-its-account-additive-0450-3963)). + ### Root server warning (additive, #1638) diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index dc2ceb7f11..283f37f9d6 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -2705,8 +2705,8 @@ Missing session reads use the same known-chat check as opening/resume and return `SESSION_NOT_FOUND` with their request ID; absence is not legacy coverage. A known chat without a journal receives an empty `complete` snapshot, with no spoken-history warning or latest-conversation control. A session ID alone is not -evidence of prior voice use. `legacy` requires principal/session-scoped native -voice recovery evidence without a matching journal conversation. Missing old +evidence of prior voice use. `legacy` requires account/session-scoped native +voice recovery evidence without a matching journal conversation ([#3963](#retained-voice-history-belongs-to-its-account-additive-0450-3963)). Missing old recovery metadata cannot reconstruct speech or prove it existed. No spoken words are invented from task prompts, JSON, drafts or paraphrases. @@ -2773,7 +2773,7 @@ so a prior unclosed epoch is still conservatively qualified before Start. Failure notices latch once per owner/open episode; shutdown still reports the aggregate writer failure. Draining a failed epoch cannot close its replacement. -Before a backend names a session, a principal-owned host history owner retains +Before a backend names a session, an account-owned host history owner retains the evidence without creating a backend turn. `conversation_opened` adds optional `historyOwnerId`/`historyGeneration`. A new `conversation_start.historyOwnerId` reopens such history without using it as a backend session ID. Exact host task @@ -2829,6 +2829,48 @@ answer. Its complete semantic source group remains readable with unknown cross-stream position until the missing history page or evidence is available. + + +### Retained voice history belongs to its account (additive, 0.45.0, #3963) + +A chat's retained dialogue now follows the account that owns it, as its +safety history does ([#3952, #3962](http.md#durable-safety-account-additive-3962)): +another owner login, on another device, continues the chat by voice. The host +reads the same `dialogue_read` page, resolves the same `ownerId`, +`sessionId` and aliases, opens `conversation_start` with `sessionId` or +`historyOwnerId` on the same canonical owner and history, binds and adopts it, +and sends that login's live `dialogue_history` pages and dialogue storage +errors to every connected login of the account. A typed-first chat's first +voice, from either login, reuses the chat's safety history owner. Account +matching is `sameAccount` over the owner's stored account (migration 089), so +the history stays the owner's after the login that started it is pruned. + +What stays exact: + +- A live conversation and its epochs belong to the login that opened them. + Another login of the account starts a new conversation on the history; it + cannot resume, reopen or close another login's conversation or epoch. + Migration `090_dialogue_conversation_principal.sql` records the opening + login on each conversation, and fills it for existing rows from their owner, + which before this change was always the opening login. +- An agent, ambient, system or unknown principal matches only itself. A + pruned, expired or revoked login regains nothing: the caller is still a + current, authorized login. Exact-principal chat deletion is unchanged. +- History whose login was pruned before it stored an account stays unknown + and refused. Corrupt or contradictory stored evidence matches nobody, its + own principal included, and refuses only that chat. +- Coverage never claims more than the evidence: native voice recovery of any + login of the account, or of a login whose row is gone, keeps a chat + `legacy`, and another login's unclosed earlier epoch still marks it + `partial`. + +Nothing previously accepted is refused, with two exceptions no released host +reaches in ordinary use: voice opened on a chat whose typed safety owner is +another account, which formerly forked a second history owner, and a record +whose stored evidence is contradictory. Records, order, aliases, attribution +and generations are not rewritten, no field is added, and no ownership data +reaches a provider. + ### Retained barge-in and conversation end (additive, 0.45.0, #3729) `DialogueEvidence` gains two kinds. Both are display evidence, retained on the diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 650327c382..22e1f389f4 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -146,7 +146,7 @@ consent for a replacement identity. Existing [session principals](../decisions/s and [operational recovery](../inbox-recovery.md) remain binding. There is no general delete operation: `createSessionRoutes` only lists/reads -(`createSessionRoutes`, `packages/ui-server/src/routes/sessions.ts:9-157`). +(`createSessionRoutes`, `packages/ui-server/src/routes/sessions.ts:27-175`). `AgentBackend` exposes native list/read and read-only storage roots, not deletion (`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:826-882`). A storage root is not removal authority. Future supported package/HTTP/wire changes need their @@ -191,7 +191,7 @@ must be tested through their installed runtime, not inferred from directory name Payloads include independent recognition/output evidence and backend range text; hashes/order/identity are not substitutes for erasing the payload. An owner can start unbound, bind to a backend session or merge into an existing owner through - aliases (`bindDialogue`, `packages/ui-server/src/ws/dialogue-storage.ts:176-222`). + aliases (`bindDialogue`, `packages/ui-server/src/ws/dialogue-storage.ts:220-266`). Resolve the complete alias/conversation set transactionally; do not delete only the current session key or confuse a provisional owner ID with a backend ID. - **Task recovery and facts.** `069_conversation_tasks.sql` and @@ -213,7 +213,7 @@ must be tested through their installed runtime, not inferred from directory name readable projections according to the adopted extent. Retained digests can reveal guessed short text; discard unnecessary hashes, not just plaintext. Native history joins several of these owners - (`prepareHistory`, `packages/ui-server/src/ws/host.ts:642-654`). + (`prepareHistory`, `packages/ui-server/src/ws/host.ts:685-697`). - **Independent session ledgers.** `retry_receipts`, `session_work`, `turn_boundaries`, draft send/save/upload receipts and revisions, handoff IDs/lineage, Claude usage deduplication, worker profiles, provider-exposure and born-masked lineage are @@ -256,8 +256,8 @@ must be tested through their installed runtime, not inferred from directory name handoff preparation, classifier callbacks, DialogueJournal routing/pending writes, ConversationHost receipts/results/output and frozen startup envelopes can retain or publish text. Catalog optimistic maps precede worker acknowledgements - (`rowEffects`, `packages/ui-server/src/ws/session-catalog.ts:255-268`; - `activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:298-301`). + (`rowEffects`, `packages/ui-server/src/ws/session-catalog.ts:258-271`; + `activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:301-304`). Both submission and worker commit need a generation check. - **Browser state.** Chat buffers/history chunks, shared timeline, session title/list cache, dialogue pages/cursors, recognition/generated/unsaved tails, @@ -300,7 +300,7 @@ The paired WS dispatcher is `packages/ui-server/src/ws/dispatch.ts`, with one handler per frame under `ws/handlers/`; gating its resume handler alone would leave HTTP, background readers and provider startup open. Existing ordinary history publication checks concurrent turn changes -(`publishHistory`, `packages/ui-server/src/ws/host.ts:568-602`). Future deletion +(`publishHistory`, `packages/ui-server/src/ws/host.ts:629-663`). Future deletion must additionally invalidate it even when no turn starts or ends. Startup reads native history, canonical evidence and completed facts, and freezes a snapshot (`readLiveHistory`, `packages/ui-server/src/ws/live-history.ts:9-74`). Recheck the diff --git a/packages/ui-server/migrations/090_dialogue_conversation_principal.sql b/packages/ui-server/migrations/090_dialogue_conversation_principal.sql new file mode 100644 index 0000000000..9ca7d0af03 --- /dev/null +++ b/packages/ui-server/migrations/090_dialogue_conversation_principal.sql @@ -0,0 +1,17 @@ +-- A chat's retained dialogue belongs to its account (#3963), as its safety +-- history does (#3962): another login of the same owner continues it by voice +-- from another device. A live conversation does not: only the login that +-- opened it reopens or closes its epochs. +-- +-- `principal_id` names that login. The server writes it when the conversation +-- first opens and never rewrites it. The history's ownership stays on +-- dialogue_owners (`principal_id` and 089's `principal_account`); this column +-- is no second ownership record and grants no history access. +-- +-- Before this migration an owner opened only with its own exact principal, +-- and adoption joined only two owners of that same principal, so every +-- existing conversation was opened by its owner's principal. That is the +-- verified evidence the backfill copies. Nothing else changes. +ALTER TABLE dialogue_conversations ADD COLUMN principal_id TEXT; +UPDATE dialogue_conversations SET principal_id= + (SELECT o.principal_id FROM dialogue_owners o WHERE o.id=dialogue_conversations.owner_id); diff --git a/packages/ui-server/src/routes/sessions.ts b/packages/ui-server/src/routes/sessions.ts index 0ad115ce9f..9bec7dec18 100644 --- a/packages/ui-server/src/routes/sessions.ts +++ b/packages/ui-server/src/routes/sessions.ts @@ -5,6 +5,24 @@ import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; import type { BackendRegistry } from "../agent/backend.js"; import { SESSION_NOT_FOUND, type SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; import { ChatRetiredError } from "../ws/chat-lifecycle.js"; +import { principalAccount } from "../middleware/account-partition.js"; + +/** + * The caller's host-only retained histories: its own, and those another login + * of its account started (#3963). This is `sameAccount` over each owner's + * stored evidence, kept in SQL so the page stays one indexed range. Evidence + * is consistent when its account is NULL, or 'owner' with no live row that + * says otherwise; corrupt or contradictory evidence lists for nobody. The + * caller's account comes from its own current row. Comparisons use IS, so no + * NULL term can admit a row. + */ +const RETAINED_CONVERSATIONS = `SELECT d.id,d.created_at FROM dialogue_owners d + WHERE d.session_id IS NULL AND d.id>?3 + AND (d.principal_account IS NULL OR (d.principal_account IS 'owner' + AND NOT EXISTS (SELECT 1 FROM principals p WHERE p.id=d.principal_id AND p.kind IS NOT 'owner'))) + AND (d.principal_id IS ?1 OR (?2 IS 'owner' AND (d.principal_account IS 'owner' + OR EXISTS (SELECT 1 FROM principals p WHERE p.id=d.principal_id AND p.kind IS 'owner')))) + ORDER BY d.id LIMIT 201`; export function createSessionRoutes(deps: { registry: BackendRegistry; @@ -120,7 +138,7 @@ export function createSessionRoutes(deps: { if (after && (after.length > 2048 || !c.req.query("includeRetainedConversations"))) return c.json({error:"Invalid retained conversation cursor"},400); const retainedRows = c.req.query("includeRetainedConversations") === "true" && principal - ? db.query("SELECT id,created_at FROM dialogue_owners WHERE principal_id=? AND session_id IS NULL AND id>? ORDER BY id LIMIT 201").all(principal.id,after ?? "") as {id:string;created_at:number}[] + ? db.query(RETAINED_CONVERSATIONS).all(principal.id,principalAccount(db,principal.id),after ?? "") as {id:string;created_at:number}[] : undefined; const retainedConversations = retainedRows?.slice(0,200).filter(row => !deps.retired?.({ ownerId: row.id })); const retainedAfter = retainedRows && retainedRows.length > 200 ? retainedConversations!.at(-1)!.id : undefined; diff --git a/packages/ui-server/src/ws/clients.ts b/packages/ui-server/src/ws/clients.ts index 3c4033aa22..1372403ec9 100644 --- a/packages/ui-server/src/ws/clients.ts +++ b/packages/ui-server/src/ws/clients.ts @@ -160,12 +160,13 @@ export class ClientSet { onSendError?: (err: unknown) => void, /** Only connections that declared this `client_hello` capability. */ requiredCapability?: string, - principalId?: string + /** Only this principal's connections, or only those of the principals it admits. */ + principalId?: string | ((principalId: string) => boolean) ): void { if (this.clients.size === 0) return; const payload = JSON.stringify(shrinkForReplication(msg)); for (const { ws, capabilities, principalId: owner } of this.clients.values()) { - if (principalId !== undefined && owner !== principalId) continue; + if (typeof principalId === "string" ? owner !== principalId : principalId !== undefined && !principalId(owner)) continue; if (requiredCapability !== undefined && capabilities?.[requiredCapability] !== true) continue; try { // Bun's ServerWebSocket reports a dropped write by RETURNING 0 (closed diff --git a/packages/ui-server/src/ws/dialogue-storage.ts b/packages/ui-server/src/ws/dialogue-storage.ts index cd3a3e453f..7198587220 100644 --- a/packages/ui-server/src/ws/dialogue-storage.ts +++ b/packages/ui-server/src/ws/dialogue-storage.ts @@ -10,11 +10,19 @@ import { dialogueRecordSchema, } from "@schlessera/brain-ui-sdk/schemas"; import { assertLive, isRetired } from "./chat-lifecycle.js"; -import { principalAccount } from "../middleware/account-partition.js"; +import { principalAccount, sameAccount, type AccountRecord } from "../middleware/account-partition.js"; +import { resolvePrincipal } from "../db/principals.js"; +/** + * A chat's retained dialogue owner. `principal_id` is the login that started + * it and is never rewritten; `principal_account` is the durable account the + * server stored beside it (#3962). The history belongs to that account, so + * another login of the same owner continues it (#3963). + */ export interface DialogueOwner { id: string; principal_id: string; + principal_account?: string | null; session_id: string | null; generation: number; coverage: DialoguePage["coverage"]; @@ -36,6 +44,15 @@ export interface DialogueTarget { before?: number; } const MAX_PAGE_BYTES = 128 * 1024; +/** The owner row as stored account evidence for `sameAccount`. */ +export function ownerRecord(owner: Pick): AccountRecord { + return { principalId: owner.principal_id, account: owner.principal_account ?? null }; +} +/** + * The retained history owner `principalId` may use: its own, or one its + * account owns (#3963). This is history access only. It is never authority + * over another login's live conversation or epoch, which stays exact. + */ export function dialogueOwner( db: Database, target: DialogueTarget, @@ -52,21 +69,28 @@ export function dialogueOwner( .get(target.ownerId ?? "", target.ownerId ?? ""); if (!row) return null; const owner = row as DialogueOwner; - if (owner.principal_id !== principalId) + if (!sameAccount(db, ownerRecord(owner), principalId)) throw new Error("Dialogue ownership mismatch"); if (target.generation !== undefined && owner.generation !== target.generation) throw new Error("Dialogue generation changed"); return owner; } -/** Retained native voice recovery is evidence; an ordinary session ID is not. */ +/** + * Retained native voice recovery is evidence; an ordinary session ID is not. + * Any login of the caller's account counts (#3963), and so does a login whose + * row is gone: its account is unknown, and coverage never claims more than + * the evidence proves. Another account's recovery never counts. + */ export function hasUnretainedVoice(db: Database, principalId: string, sessionId: string): boolean { - return !!db.query(`SELECT 1 FROM conversation_epochs e - WHERE e.principal_id=? AND e.session_id=? - AND NOT EXISTS (SELECT 1 FROM dialogue_conversations c WHERE c.id=e.id) LIMIT 1`).get(principalId, sessionId); + const rows = db.query(`SELECT DISTINCT e.principal_id FROM conversation_epochs e + WHERE e.session_id=? AND NOT EXISTS (SELECT 1 FROM dialogue_conversations c WHERE c.id=e.id)`).all(sessionId) as { principal_id: string }[]; + return rows.some(row => sameAccount(db, row.principal_id, principalId) || !resolvePrincipal(db, row.principal_id)); } export interface ActiveDialogueEpoch { owner: DialogueOwner; epoch: number; + /** The login that opened this epoch: its authority, separate from the history owner's attribution. */ + principalId: string; } /** Host-submitted open not yet acknowledged by the worker; never supplied by a wire target. */ export interface PendingDialogueEpoch { @@ -79,7 +103,9 @@ function pendingEpochFor(db:Database, owner:DialogueOwner, row:{id:string;epoch: return pending.some(scope=>{ const input=scope.input; if(input.conversationId!==row.id || input.epoch!==row.epoch || input.providerId!==row.provider_id - || input.epoch <= (scope.previousEpoch ?? 0) || input.principalId!==owner.principal_id || scope.generation!==owner.generation) return false; + || input.epoch <= (scope.previousEpoch ?? 0) || scope.generation!==owner.generation) return false; + // Liveness of a login of the owner's account, never authority over it. + if(!sameAccount(db,ownerRecord(owner),input.principalId)) return false; // A pending submission is liveness only for the exact row its successful // earlier transaction could have opened, under the same durable owner. if(input.sessionId && input.sessionId!==owner.session_id) return false; @@ -90,12 +116,16 @@ function pendingEpochFor(db:Database, owner:DialogueOwner, row:{id:string;epoch: return input.sessionId || input.historyOwnerId ? true : dialogueOwner(db,{ownerId:input.conversationId},input.principalId)?.id===owner.id; }); } -function activeEpochFor(db:Database, owner:DialogueOwner, principalId:string, row:{id:string;epoch:number}, activeEpochs?:ReadonlyMap):ActiveDialogueEpoch|undefined { +function activeEpochFor(db:Database, owner:DialogueOwner, row:{id:string;epoch:number}, activeEpochs?:ReadonlyMap):ActiveDialogueEpoch|undefined { const active=activeEpochs?.get(row.id); - if(!active || active.epoch!==row.epoch || active.owner.principal_id!==principalId || active.owner.generation!==owner.generation) return; + // Liveness only: the exact epoch, owner attribution and generation this + // catalog opened, by a login of the owner's account (#3963). Whoever asks, + // it grants nobody authority over that epoch. + if(!active || active.epoch!==row.epoch || active.owner.principal_id!==owner.principal_id || active.owner.generation!==owner.generation + || !sameAccount(db,ownerRecord(owner),active.principalId)) return; // Adoption may commit before the catalog receives its acknowledgement. // Resolve only the durable alias; never infer a new generation or principal. - return active.owner.id===owner.id || dialogueOwner(db,{ownerId:active.owner.id},principalId)?.id===owner.id ? active : undefined; + return active.owner.id===owner.id || dialogueOwner(db,{ownerId:active.owner.id},active.principalId)?.id===owner.id ? active : undefined; } export function openDialogue(db: Database, input: DialogueOpen, activeEpochs?:ReadonlyMap, pending:readonly PendingDialogueEpoch[]=[]): DialogueOwner { return db @@ -106,10 +136,15 @@ export function openDialogue(db: Database, input: DialogueOpen, activeEpochs?:Re .query("SELECT * FROM dialogue_conversations WHERE id=?") .get(input.conversationId) as { owner_id: string; + principal_id: string | null; epoch: number; provider_id: string; closed: number; } | null; + // A live conversation is its opening login's, even when the history it + // writes belongs to the account (#3963): no other login reopens it. + if (known && known.principal_id !== input.principalId) + throw new Error("Dialogue conversation principal mismatch"); if ( known && (input.epoch <= known.epoch || input.providerId !== known.provider_id) @@ -139,8 +174,12 @@ export function openDialogue(db: Database, input: DialogueOpen, activeEpochs?:Re if (owner) assertLive(db, [["dialogue_owner", owner.id]]); if (!owner) { // A typed first turn already has a once-bound host safety owner. Reuse - // that identity when its first retained dialogue opens later. - const safety=input.sessionId?db.query("SELECT history_owner_id FROM safety_sessions WHERE session_id=? AND principal_id=? AND classification='new'").get(input.sessionId,input.principalId) as {history_owner_id:string}|null:null; + // that identity when its first retained dialogue opens later, from + // any login of its account (#3963). Another account's, or one whose + // evidence is unknown or contradictory, is refused, never forked. + const safety=input.sessionId?db.query("SELECT history_owner_id,principal_id,principal_account FROM safety_sessions WHERE session_id=? AND classification='new'").get(input.sessionId) as {history_owner_id:string;principal_id:string|null;principal_account:string|null}|null:null; + if (safety && !sameAccount(db, { principalId: safety.principal_id, account: safety.principal_account }, input.principalId)) + throw new Error("Dialogue ownership mismatch"); const id = safety?.history_owner_id ?? input.conversationId; db.prepare( "INSERT INTO dialogue_owners(id,principal_id,principal_account,session_id,coverage,created_at) VALUES(?,?,?,?,?,?)" @@ -156,7 +195,7 @@ export function openDialogue(db: Database, input: DialogueOpen, activeEpochs?:Re owner = dialogueOwner(db, { ownerId: id }, input.principalId)!; } const unfinished = (db.query("SELECT id,epoch,provider_id FROM dialogue_conversations WHERE owner_id=? AND closed=0 LIMIT ?").all(owner.id,(activeEpochs?.size ?? 0)+pending.length+1) as Array<{id:string;epoch:number;provider_id:string}>).some(row=>{ - const active=activeEpochFor(db,owner!,input.principalId,row,activeEpochs); + const active=activeEpochFor(db,owner!,row,activeEpochs); // The same native ID must have a real close-before-open boundary. // Other exact healthy live IDs are not evidence of interruption. return row.id===input.conversationId || (active ? active.owner.coverage === "partial" : !pendingEpochFor(db,owner!,row,pending)); @@ -169,9 +208,11 @@ export function openDialogue(db: Database, input: DialogueOpen, activeEpochs?:Re } if (input.sessionId && owner.session_id !== input.sessionId) throw new Error("Dialogue session mismatch"); + // The opening login is the conversation's own attribution and is never + // rewritten; the history owner it writes to may be another login's. db.prepare( - "INSERT INTO dialogue_conversations(id,owner_id,epoch,provider_id) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET epoch=excluded.epoch,closed=0" - ).run(input.conversationId, owner.id, input.epoch, input.providerId); + "INSERT INTO dialogue_conversations(id,owner_id,epoch,provider_id,principal_id) VALUES(?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET epoch=excluded.epoch,closed=0" + ).run(input.conversationId, owner.id, input.epoch, input.providerId, input.principalId); return owner; }) .immediate(); @@ -378,7 +419,7 @@ export function readDialogue( } // One more row than live scopes proves interruption without a lifetime scan. const unclosed = db.query("SELECT id,epoch FROM dialogue_conversations WHERE owner_id=? AND closed=0 LIMIT ?").all(owner.id,(activeEpochs?.size ?? 0)+1) as Array<{id:string;epoch:number}>; - const exactActive = (row:{id:string;epoch:number}) => activeEpochFor(db,owner,principalId,row,activeEpochs); + const exactActive = (row:{id:string;epoch:number}) => activeEpochFor(db,owner,row,activeEpochs); const failedActive=unclosed.some(row=>exactActive(row)?.owner.coverage === "partial"); const more = rows.length > records.length; return { @@ -421,9 +462,13 @@ export function closeDialogue( // Retirement already closed every epoch of the chat. if (isRetired(db, "conversation", conversationId)) return; const c = db - .query("SELECT owner_id FROM dialogue_conversations WHERE id=?") - .get(conversationId) as { owner_id: string } | null; + .query("SELECT owner_id,principal_id FROM dialogue_conversations WHERE id=?") + .get(conversationId) as { owner_id: string; principal_id: string | null } | null; if (!c) return; + // Sharing the history's account is not authority over another login's + // epoch (#3963): only the login that opened the conversation closes it. + if (c.principal_id !== principalId) + throw new Error("Dialogue conversation principal mismatch"); if (!dialogueOwner(db, { ownerId: c.owner_id }, principalId)) throw new Error("Dialogue owner unavailable"); if (partial) diff --git a/packages/ui-server/src/ws/dialogue.ts b/packages/ui-server/src/ws/dialogue.ts index ca77be0c66..65de8f63a7 100644 --- a/packages/ui-server/src/ws/dialogue.ts +++ b/packages/ui-server/src/ws/dialogue.ts @@ -13,6 +13,8 @@ export class DialogueJournal { private readonly sessions = new Map(); private readonly conversations = new Map(); private readonly adopting = new Map(); + /** The login whose typed turn adopts a provisional history, by turn. */ + private readonly adopters = new Map(); private readonly offsets = new Map(); private failure: unknown; private readonly failedOwners = new Set(); @@ -25,7 +27,8 @@ export class DialogueJournal { private readonly refusals = new Map void>>(); constructor( private readonly catalog: SessionCatalog, - private readonly publish: (page: DialoguePage, principalId: string) => void, + /** Delivers a committed page to the owner's audience: every login of its account (#3963). */ + private readonly publish: (page: DialoguePage, owner: DialogueOwner) => void, private readonly failed: (owner: DialogueOwner, cause: "queue_pressure" | "storage_error" | "storage_indeterminate", kind?: DialogueEvidence["kind"]) => void ) {} private transition(conversationId: string, run: () => Promise): Promise { @@ -73,13 +76,24 @@ export class DialogueJournal { if (this.sessions.size > 128) this.sessions.delete(this.sessions.keys().next().value!); } + /** + * Whether `principalId` may use this retained history: the login that + * started it, or another login of its account (#3963). Storage decides + * again inside every write; this only skips work it would refuse. + */ + private historyOwner(owner: DialogueOwner, principalId: string): boolean { + if (owner.principal_id === principalId) return true; + try { return this.catalog.dialogueOwnerForId?.(owner.id, principalId)?.id === owner.id; } + catch { return false; } + } + private ownerForConversation(conversationId: string, principalId: string): DialogueOwner | null | undefined { + return this.conversations.get(conversationId) ?? this.catalog.dialogueOwnerForConversation?.(conversationId, principalId); + } bind(conversationId: string, principalId: string, sessionId: string): void { - const owner = - this.conversations.get(conversationId) ?? - this.catalog.dialogueOwnerForConversation?.(conversationId, principalId); + const owner = this.ownerForConversation(conversationId, principalId); if ( !owner || - owner.principal_id !== principalId || + !this.historyOwner(owner, principalId) || !this.catalog.dialogueBind ) return; @@ -135,9 +149,9 @@ export class DialogueJournal { * conversation's retained routing; storage still checks its scope. */ ended(conversationId: string, principalId: string, evidence: Extract): boolean { - const owner = this.conversations.get(conversationId) ?? this.catalog.dialogueOwnerForConversation?.(conversationId, principalId); + const owner = this.ownerForConversation(conversationId, principalId); // An owner whose writes failed since it opened is not written to again. - if (!owner || owner.principal_id !== principalId || this.failedOwners.has(owner.id)) return false; + if (!owner || !this.historyOwner(owner, principalId) || this.failedOwners.has(owner.id)) return false; this.append(owner, JSON.stringify([conversationId, "ended", evidence.startedAt]), evidence); return true; } @@ -150,6 +164,7 @@ export class DialogueJournal { ) throw new Error("Retained conversation is not provisional"); this.adopting.set(turnId, owner); + this.adopters.set(turnId, principalId); } /** Exact UI-only draft target of an authorized provisional adoption. */ draftSource(turnId: string): string | undefined { @@ -158,6 +173,7 @@ export class DialogueJournal { } retireTurn(turnId: string): void { this.adopting.delete(turnId); + this.adopters.delete(turnId); this.offsets.delete(turnId); } backend(msg: ServerMessage): void { @@ -182,8 +198,10 @@ export class DialogueJournal { const adopting = this.adopting.get(turnId); if (msg.type === "session_info" && adopting) { this.conversations.set(adopting.id, adopting); - this.bind(adopting.id, adopting.principal_id, sessionId); + // The adopting turn's own login binds it, not the history's first one. + this.bind(adopting.id, this.adopters.get(turnId) ?? adopting.principal_id, sessionId); this.adopting.delete(turnId); + this.adopters.delete(turnId); this.conversations.delete(adopting.id); } const owner = @@ -291,7 +309,7 @@ export class DialogueJournal { records: [record], coverage: owner.coverage, }, - owner.principal_id + owner ); after?.(true); }, diff --git a/packages/ui-server/src/ws/host.ts b/packages/ui-server/src/ws/host.ts index 334d72782f..b9fcc6f7c5 100644 --- a/packages/ui-server/src/ws/host.ts +++ b/packages/ui-server/src/ws/host.ts @@ -1,5 +1,6 @@ import { StorageSettlementIndeterminate, withinStorageBudget } from "../db/settlement.js"; import { DialogueJournal } from "./dialogue.js"; +import type { DialogueOwner } from "./dialogue-storage.js"; import { type AskUserFormLimits } from "@schlessera/brain-ui-sdk/tool-contracts"; import { resolveAskUserFormLimits } from "@schlessera/brain-ui-sdk/internal/client"; import { CHAT_DELETION_CAPABILITY, FOLLOW_UP_QUEUE_CAPABILITY, type ServerMessage, type ServerSessionQueue } from "@schlessera/brain-ui-sdk/protocol"; @@ -479,19 +480,24 @@ export class WsHost { this.conversations = live.providers.length > 0 ? new ConversationHost(this, live, saved, options.livePersonas) : null; - this.dialogue = new DialogueJournal(this.catalog, (page, principalId) => { - this.clients.broadcast({ type: "dialogue_history", ...page }, undefined, "sessionDialogue", principalId); + // Retained history reaches every login of its account (#3963), never another account. + const audience = (owner: DialogueOwner) => (principalId: string) => { + if (principalId === owner.principal_id) return true; + try { return this.catalog.dialogueAudience?.(owner, principalId) === true; } catch { return false; } + }; + this.dialogue = new DialogueJournal(this.catalog, (page, owner) => { + this.clients.broadcast({ type: "dialogue_history", ...page }, undefined, "sessionDialogue", audience(owner)); }, (owner, cause, kind) => { const finish=this.conversations?.storageFailing(owner.id); const message=cause === "storage_indeterminate" ? "Conversation text persistence could not be confirmed. Voice stopped; history may be incomplete. Restore storage before restarting voice." : kind === "backend" ? "Original discussion position could not be saved. The complete answer remains in chat history. Check storage before restarting voice." : cause === "queue_pressure" ? "Conversation text is arriving faster than it can be saved. Voice capture stopped at the pending-write limit. The unsaved tail is unavailable after reload. Let pending writes finish and check storage before restarting voice." : "Conversation text could not be saved. The unsaved tail is unavailable after reload. Restore storage before restarting voice."; - this.clients.broadcast({type:"error",code:cause === "storage_indeterminate" ? "DIALOGUE_INDETERMINATE" : cause === "queue_pressure" ? "DIALOGUE_PENDING_PRESSURE" : "DIALOGUE_STORAGE",historyOwnerId:owner.id,...(owner.session_id ? {sessionId:owner.session_id} : {}),message},undefined,"sessionDialogue",owner.principal_id); + this.clients.broadcast({type:"error",code:cause === "storage_indeterminate" ? "DIALOGUE_INDETERMINATE" : cause === "queue_pressure" ? "DIALOGUE_PENDING_PRESSURE" : "DIALOGUE_STORAGE",historyOwnerId:owner.id,...(owner.session_id ? {sessionId:owner.session_id} : {}),message},undefined,"sessionDialogue",audience(owner)); // The write watchdog already withheld unknown observations for this owner. if (cause === "storage_indeterminate") {finish?.(message);return;} // Drain already observed text before closing its epoch, preserving the unsaved tail. void this.dialogue.settleOwner(owner).then(() => finish?.(message), error => { if (!(error instanceof StorageSettlementIndeterminate)) {finish?.(message);return;} const unknown="Conversation text persistence could not be confirmed. Voice stopped; history may be incomplete. Restore storage before restarting voice."; - this.clients.broadcast({type:"error",code:"DIALOGUE_INDETERMINATE",historyOwnerId:owner.id,...(owner.session_id ? {sessionId:owner.session_id} : {}),message:unknown},undefined,"sessionDialogue",owner.principal_id); + this.clients.broadcast({type:"error",code:"DIALOGUE_INDETERMINATE",historyOwnerId:owner.id,...(owner.session_id ? {sessionId:owner.session_id} : {}),message:unknown},undefined,"sessionDialogue",audience(owner)); finish?.(unknown); }); }); diff --git a/packages/ui-server/src/ws/session-catalog.ts b/packages/ui-server/src/ws/session-catalog.ts index 0a03ff53ea..bce25ee56d 100644 --- a/packages/ui-server/src/ws/session-catalog.ts +++ b/packages/ui-server/src/ws/session-catalog.ts @@ -1,4 +1,5 @@ -import { dialogueOwner, readDialogue, hasUnretainedVoice, type PendingDialogueEpoch, type ActiveDialogueEpoch, type DialogueOpen, type DialogueAppend, type DialogueOwner, type DialogueTarget } from "./dialogue-storage.js"; +import { dialogueOwner, ownerRecord, readDialogue, hasUnretainedVoice, type PendingDialogueEpoch, type ActiveDialogueEpoch, type DialogueOpen, type DialogueAppend, type DialogueOwner, type DialogueTarget } from "./dialogue-storage.js"; +import { sameAccount } from "../middleware/account-partition.js"; import { createActivityStore, priceUsage, type ActivityStore, type AwaitableActivityStore, type RollupPricing } from "../activity/store.js"; import type { ActivityPricingConfig } from "../activity/store-writes.js"; import { createModelPricing } from "../pricing/model-pricing.js"; @@ -47,6 +48,8 @@ export interface SessionCatalog { dialogueOwnerForConversation?(conversationId:string,principalId:string): DialogueOwner | null; dialogueOwnerForId?(ownerId:string,principalId:string): DialogueOwner | null; dialogueOwnerForSession?(sessionId: string): DialogueOwner | null; + /** Whether `principalId` may receive this owner's retained history: a login of its account (#3963). */ + dialogueAudience?(owner: DialogueOwner, principalId: string): boolean; dialogueClose?(conversationId:string,principalId:string,epoch:number,partial:boolean): Promise; dialogueOpen?(input: DialogueOpen): Promise; dialogueAppend?(input: DialogueAppend): Promise; @@ -306,6 +309,7 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi const row=db().query("SELECT owner_id FROM dialogue_conversations WHERE id=?").get(conversationId) as {owner_id:string}|null; return row ? live(dialogueOwner(db(),{ownerId:row.owner_id},principalId)) : null; }, + dialogueAudience: (owner,principalId) => sameAccount(db(),ownerRecord(owner),principalId), dialogueOwnerForId: (ownerId,principalId) => isRetired(db(),"dialogue_owner",ownerId) ? null : live(dialogueOwner(db(),{ownerId},principalId)), dialogueOwnerForSession: sessionId => { if(isRetired(db(),"session",sessionId)) return null; @@ -336,7 +340,8 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi dialogueClose: (conversationId,principalId,epoch,partial) => { for(const scope of pendingDialogueEpochs) if(scope.input.conversationId===conversationId && scope.input.principalId===principalId && scope.input.epoch===epoch) scope.closed=true; const active=activeDialogueEpochs.get(conversationId); - if(active?.epoch===epoch && active.owner.principal_id===principalId) activeDialogueEpochs.delete(conversationId); + // The epoch's own login, not the history owner's attribution (#3963). + if(active?.epoch===epoch && active.principalId===principalId) activeDialogueEpochs.delete(conversationId); return submit("dialogueClose",conversationId,principalId,epoch,partial); }, dialogueOpen: async input => { @@ -347,10 +352,10 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi // this one's acknowledgement registers its successful active identity. const pending=[...pendingDialogueEpochs].filter(scope=>!scope.closed).map(scope=>({input:scope.input,generation:scope.generation,ownerId:scope.ownerId,previousEpoch:scope.previousEpoch})); pendingDialogueEpochs.add(scope); - const live=new Map([...activeDialogueEpochs].map(([id,scope])=>[id,{epoch:scope.epoch,owner:{...scope.owner}}])); + const live=new Map([...activeDialogueEpochs].map(([id,scope])=>[id,{epoch:scope.epoch,principalId:scope.principalId,owner:{...scope.owner}}])); try { const owner=await submit("dialogueOpen", input, live, pending); - if(!scope.closed && (activeDialogueEpochs.get(input.conversationId)?.epoch ?? 0)<=input.epoch) activeDialogueEpochs.set(input.conversationId,{owner,epoch:input.epoch}); + if(!scope.closed && (activeDialogueEpochs.get(input.conversationId)?.epoch ?? 0)<=input.epoch) activeDialogueEpochs.set(input.conversationId,{owner,epoch:input.epoch,principalId:input.principalId}); return owner; } finally { pendingDialogueEpochs.delete(scope); } }, @@ -358,11 +363,13 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi dialogueBind: async (conversationId, principalId, sessionId) => { const owner=await submit("dialogueBind", conversationId, principalId, sessionId); const active=activeDialogueEpochs.get(conversationId); - if(owner && active && active.owner.principal_id===principalId) { + if(owner && active && active.principalId===principalId) { // Pending callbacks still hold this object across adoption. Replacing // it would hide their genuine failure behind a fresh healthy owner. + // Every live scope on the adopted owner takes its canonical identity, + // whichever login of the account opened it (#3963). const previousId=active.owner.id; - for(const scope of activeDialogueEpochs.values()) if(scope.owner.id===previousId && scope.owner.principal_id===principalId){ + for(const scope of activeDialogueEpochs.values()) if(scope.owner.id===previousId){ const partial=scope.owner.coverage === "partial"; Object.assign(scope.owner,owner); if(partial) scope.owner.coverage="partial"; diff --git a/packages/ui-server/tests/dialogue-account-ownership.test.ts b/packages/ui-server/tests/dialogue-account-ownership.test.ts new file mode 100644 index 0000000000..d049a6344a --- /dev/null +++ b/packages/ui-server/tests/dialogue-account-ownership.test.ts @@ -0,0 +1,321 @@ +/** + * A chat's retained voice history belongs to the account, as its safety + * history does (#3962): another owner login continues it by voice from another + * device, after the first login is pruned too (#3963). A live conversation and + * its epochs stay with the exact login that opened them. + */ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { DialogueEvidence } from "@schlessera/brain-ui-sdk/protocol"; +import { createUiDb } from "../src/db/client"; +import { createPrincipal, isUsablePrincipal, PRINCIPAL_RETENTION_MS, prunePrincipals, resolveAmbientPrincipal, resolvePrincipal, + resolveSystemPrincipal, revokePrincipal, type Principal } from "../src/db/principals"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createGovernanceWrites } from "../src/governance/event-writes"; +import { safetyCatalogCreated } from "../src/governance/safety-store"; +import { appendDialogue, bindDialogue, closeDialogue, dialogueOwner, hasUnretainedVoice, openDialogue, readDialogue } from "../src/ws/dialogue-storage"; +import { resolveChat } from "../src/ws/chat-lifecycle"; +import { createSessionCatalog } from "../src/ws/session-catalog"; +import { createOffloopActivityStore } from "../src/activity/store-writes"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { WsHost } from "../src/ws/host"; +import { createWsHandlers } from "../src/ws/connection"; +import type { WSContext } from "../src/ws/clients"; +import { Hono } from "hono"; +import type { AppEnv } from "../src/app-env"; +import { createSessionRoutes } from "../src/routes/sessions"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import { fakeLiveProvider } from "./helpers/live-conversation"; + +async function fixture() { + const root = mkdtempSync(join(tmpdir(), "odysseus-dialogue-account-")), path = join(root, "ui.db"); + const db = createUiDb(path), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); + // Every sign-in mints its own owner principal: one on the ship, one at home. + const ship = createPrincipal(db, { authMethod: "password", label: "Odysseus on the ship", ttlSeconds: 3600 }); + const home = createPrincipal(db, { authMethod: "password", label: "Odysseus at Ithaca", ttlSeconds: 7200 }); + const agent = createPrincipal(db, { authMethod: "delegated", label: "Mentor", createdBy: ship.id, ttlSeconds: 7200 }); + const penelope = resolveAmbientPrincipal(db, "proxy", "penelope", "Penelope"); + const system = resolveSystemPrincipal(db, { identity: "harbour-watch", label: "Harbour watch" }); + const foreign = [["agent", agent.id], ["ambient", penelope.id], ["system", system.id], ["unknown", "polyphemus"]] as const; + /** One retained recognition in the given conversation epoch. */ + const speak = (ownerId: string, principalId: string, conversationId: string, sequence: number, text: string, epoch = 1) => { + const evidence: DialogueEvidence = { kind: "voice", conversationId, epoch, providerId: "fake-live", + event: { kind: "unassigned_input_fragment", sequence, text, timing: { kind: "unavailable" }, finalization: "final" } }; + return appendDialogue(db, { ownerId, principalId, generation: 1, identity: `${conversationId}:${epoch}:${sequence}`, evidence }); + }; + const texts = (ownerId: string, principalId: string) => + readDialogue(db, principalId, { ownerId })!.records.map(r => r.evidence.kind === "voice" && "text" in r.evidence.event ? r.evidence.event.text : null); + /** The chat `ithaca`, started by a typed turn on the ship: its safety owner exists before any dialogue. */ + const typed = async (principalId = ship.id) => { + const bindingId = crypto.randomUUID(); + await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId, backendId: "claude", at: 0 }); + db.query("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('ithaca',0,0,'claude')").run(); + db.query("INSERT INTO chat_session_owners VALUES('ithaca',?,0)").run(principalId); + safetyCatalogCreated(db, "ithaca", principalId, "voyage"); await writes.bind("voyage", "ithaca"); + await writes.safetyEnd("voyage"); + return (db.query("SELECT history_owner_id FROM safety_sessions WHERE session_id='ithaca'").get() as { history_owner_id: string }).history_owner_id; + }; + /** The real cleanup path: the ship's login is revoked, or expires, and is pruned once retention has passed. */ + const prune = (how: "revoked" | "expired") => { + if (how === "revoked") { revokePrincipal(db, ship.id, Date.now()); prunePrincipals(db, Date.now() + PRINCIPAL_RETENTION_MS + 1); } + else prunePrincipals(db, ship.expiresAt + PRINCIPAL_RETENTION_MS + 1); + expect(resolvePrincipal(db, ship.id), `DIALOGUE_SHIP_LOGIN_PRUNED: ${how}`).toBeNull(); + expect(resolvePrincipal(db, home.id), "DIALOGUE_HOME_LOGIN_SURVIVES_PRUNING").not.toBeNull(); + }; + const authorized = (principal: Principal) => { const row = resolvePrincipal(db, principal.id); return row !== null && isUsablePrincipal(row, Date.now()); }; + const conversations = () => db.query("SELECT id,owner_id,principal_id,closed FROM dialogue_conversations ORDER BY id").all(); + const owners = () => db.query("SELECT id,principal_id,principal_account,session_id,generation,coverage FROM dialogue_owners ORDER BY id").all(); + return { root, db, writer, writes, ship, home, agent, penelope, system, foreign, speak, texts, typed, prune, authorized, conversations, owners, + async close() { await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } }; +} +const message = (run: () => unknown) => { try { run(); } catch (error) { return (error as Error).message; } return "admitted"; }; + +test("a second owner login continues a voice-first chat's retained history, keyed by owner or alias", async () => { + const f = await fixture(); try { + const owner = openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live" }); + f.speak(owner.id, f.ship.id, "argos-voice", 0, "Set the sail for Ithaca."); + closeDialogue(f.db, "argos-voice", f.ship.id, 1); + // The other device opens a new conversation in the same chat. + const continued = openDialogue(f.db, { conversationId: "ithaca-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", historyOwnerId: owner.id }); + expect(continued.id, "DIALOGUE_SECOND_OWNER_CONTINUES_THE_SAME_HISTORY").toBe(owner.id); + f.speak(continued.id, f.home.id, "ithaca-voice", 0, "Unbar the hall doors."); + expect(f.texts(owner.id, f.home.id), "DIALOGUE_SECOND_OWNER_READS_THE_WHOLE_HISTORY").toEqual(["Set the sail for Ithaca.", "Unbar the hall doors."]); + expect(f.texts(owner.id, f.ship.id), "DIALOGUE_FIRST_OWNER_READS_THE_CONTINUATION").toEqual(["Set the sail for Ithaca.", "Unbar the hall doors."]); + // The adoption that follows a first typed task binds it, from either login. + const bound = bindDialogue(f.db, "ithaca-voice", f.home.id, "ithaca"); + expect(bound?.id, "DIALOGUE_SECOND_OWNER_BINDS_THE_PROVISIONAL_HISTORY").toBe(owner.id); + expect(dialogueOwner(f.db, { sessionId: "ithaca" }, f.ship.id)?.id, "DIALOGUE_SESSION_LOOKUP_FROM_EITHER_LOGIN").toBe(owner.id); + expect(dialogueOwner(f.db, { ownerId: "argos-voice" }, f.home.id)?.id).toBe(owner.id); + // Attribution: the history keeps the login that started it, and each conversation its own. + expect(f.owners(), "DIALOGUE_ATTRIBUTION_IS_NOT_REWRITTEN").toEqual([{ id: owner.id, principal_id: f.ship.id, principal_account: "owner", session_id: "ithaca", generation: 1, coverage: "complete" }]); + expect(f.conversations()).toEqual([ + { id: "argos-voice", owner_id: owner.id, principal_id: f.ship.id, closed: 1 }, + { id: "ithaca-voice", owner_id: owner.id, principal_id: f.home.id, closed: 0 }, + ]); + } finally { await f.close(); } +}); + +test("a typed-first chat's first voice from another owner login uses the chat's canonical safety owner", async () => { + const f = await fixture(); try { + const safetyOwner = await f.typed(); + const owner = openDialogue(f.db, { conversationId: "ithaca-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + expect(owner.id, "DIALOGUE_TYPED_FIRST_REUSES_THE_SAFETY_OWNER").toBe(safetyOwner); + // The owner row is the history's first voice login, under the owner account. + expect(f.owners()).toEqual([{ id: safetyOwner, principal_id: f.home.id, principal_account: "owner", session_id: "ithaca", generation: 1, coverage: "complete" }]); + const again = openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + expect(again.id, "DIALOGUE_TYPED_FIRST_THEN_FIRST_LOGIN").toBe(safetyOwner); + } finally { await f.close(); } +}); + +test("another account's typed chat is refused, never forked into a second voice owner", async () => { + const f = await fixture(); try { + await f.typed(f.agent.id); + expect(message(() => openDialogue(f.db, { conversationId: "ithaca-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" })), + "DIALOGUE_FOREIGN_SAFETY_OWNER_REFUSED").toBe("Dialogue ownership mismatch"); + expect(f.owners()).toEqual([]);expect(f.conversations()).toEqual([]); + } finally { await f.close(); } +}); + +for (const how of ["revoked", "expired"] as const) test(`the history outlives the login that wrote it once it is ${how} and pruned`, async () => { + const f = await fixture(); try { + const owner = openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + f.speak(owner.id, f.ship.id, "argos-voice", 0, "Set the sail for Ithaca."); + closeDialogue(f.db, "argos-voice", f.ship.id, 1); + f.prune(how); + expect(f.authorized(f.ship), "DIALOGUE_PRUNED_LOGIN_STAYS_INVALID").toBe(false); + expect(f.authorized(f.home)).toBe(true); + expect(f.texts(owner.id, f.home.id), "DIALOGUE_PRUNED_ORIGIN_READS").toEqual(["Set the sail for Ithaca."]); + const continued = openDialogue(f.db, { conversationId: "ithaca-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + expect(continued.id, "DIALOGUE_PRUNED_ORIGIN_CONTINUES").toBe(owner.id); + f.speak(continued.id, f.home.id, "ithaca-voice", 0, "Unbar the hall doors."); + expect(f.texts(owner.id, f.home.id)).toEqual(["Set the sail for Ithaca.", "Unbar the hall doors."]); + // Principal retention is unchanged, and the stored account is no credential for anyone else. + for (const [name, principalId] of f.foreign) + expect(message(() => readDialogue(f.db, principalId, { ownerId: owner.id })), `DIALOGUE_FOREIGN_READ_REFUSED_AFTER_PRUNING: ${name}`).toBe("Dialogue ownership mismatch"); + } finally { await f.close(); } +}); + +test("other accounts and unknown identities are refused before any history moves", async () => { + const f = await fixture(); try { + const owner = openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + f.speak(owner.id, f.ship.id, "argos-voice", 0, "Set the sail for Ithaca."); + const before = { owners: f.owners(), conversations: f.conversations() }; + for (const [name, principalId] of f.foreign) { + for (const target of [{ sessionId: "ithaca" }, { historyOwnerId: owner.id }]) + expect(message(() => openDialogue(f.db, { conversationId: `intruder-${name}`, principalId, epoch: 1, providerId: "fake-live", ...target })), + `DIALOGUE_FOREIGN_OPEN_REFUSED: ${name} ${Object.keys(target)[0]}`).toMatch(/^Dialogue (ownership mismatch|provisional owner unavailable)$/); + expect(message(() => readDialogue(f.db, principalId, { sessionId: "ithaca" })), `DIALOGUE_FOREIGN_READ_REFUSED: ${name}`).toBe("Dialogue ownership mismatch"); + expect(message(() => f.speak(owner.id, principalId, "argos-voice", 9, "Bind them to the mast.")), `DIALOGUE_FOREIGN_WRITE_REFUSED: ${name}`).toBe("Dialogue ownership mismatch"); + expect(hasUnretainedVoice(f.db, principalId, "ithaca")).toBe(false); + } + expect({ owners: f.owners(), conversations: f.conversations() }, "DIALOGUE_REFUSALS_MOVE_NOTHING").toEqual(before); + expect(f.texts(owner.id, f.ship.id)).toEqual(["Set the sail for Ithaca."]); + } finally { await f.close(); } +}); + +test("an agent's or an ambient principal's voice history stays only its own", async () => { + const f = await fixture(); try { + for (const starter of [f.agent, f.penelope]) { + const owner = openDialogue(f.db, { conversationId: `${starter.kind}-voice`, principalId: starter.id, epoch: 1, providerId: "fake-live" }); + expect(f.db.query("SELECT principal_account FROM dialogue_owners WHERE id=?").get(owner.id)).toEqual({ principal_account: null }); + for (const other of [f.ship, f.home, starter === f.agent ? f.penelope : f.agent]) + expect(message(() => openDialogue(f.db, { conversationId: `${other.id}-takeover`, principalId: other.id, epoch: 1, providerId: "fake-live", historyOwnerId: owner.id })), + `DIALOGUE_ACCOUNT_STAYS_BOUND: ${starter.kind} ${other.kind}`).toBe("Dialogue ownership mismatch"); + expect(readDialogue(f.db, starter.id, { ownerId: owner.id })!.ownerId, `DIALOGUE_EXACT_PRINCIPAL_CONTINUES: ${starter.kind}`).toBe(owner.id); + } + } finally { await f.close(); } +}); + +test("unknown, corrupt and contradictory ownership evidence refuses within its own chat", async () => { + const f = await fixture(); try { + const legacy = openDialogue(f.db, { conversationId: "legacy-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live" }); + const corrupt = openDialogue(f.db, { conversationId: "corrupt-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live" }); + const contradicted = openDialogue(f.db, { conversationId: "contradicted-voice", principalId: f.agent.id, epoch: 1, providerId: "fake-live" }); + const healthy = openDialogue(f.db, { conversationId: "healthy-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live" }); + // A legacy row whose login was already pruned before it stored an account. + f.db.query("UPDATE dialogue_owners SET principal_account=NULL WHERE id=?").run(legacy.id); + f.prune("revoked"); + f.db.query("UPDATE dialogue_owners SET principal_account='admiral' WHERE id=?").run(corrupt.id); + f.db.query("UPDATE dialogue_owners SET principal_account='owner' WHERE id=?").run(contradicted.id); + expect(message(() => openDialogue(f.db, { conversationId: "legacy-continued", principalId: f.home.id, epoch: 1, providerId: "fake-live", historyOwnerId: legacy.id })), + "DIALOGUE_PRUNED_WITHOUT_EVIDENCE_IS_UNKNOWN").toBe("Dialogue ownership mismatch"); + expect(message(() => readDialogue(f.db, f.home.id, { ownerId: corrupt.id })), "DIALOGUE_CORRUPT_EVIDENCE_MATCHES_NOBODY").toBe("Dialogue ownership mismatch"); + expect(message(() => readDialogue(f.db, f.home.id, { ownerId: contradicted.id })), "DIALOGUE_CONTRADICTED_EVIDENCE_REFUSED").toBe("Dialogue ownership mismatch"); + expect(message(() => readDialogue(f.db, f.agent.id, { ownerId: contradicted.id })), "DIALOGUE_CONTRADICTED_EVIDENCE_REFUSES_ITS_OWN_PRINCIPAL").toBe("Dialogue ownership mismatch"); + // The refusal is that chat's; another chat of the account stays usable. + expect(readDialogue(f.db, f.home.id, { ownerId: healthy.id })!.ownerId, "DIALOGUE_UNRELATED_CHAT_USABLE").toBe(healthy.id); + // A stale generation still refuses after cross-login continuation. + const shared = openDialogue(f.db, { conversationId: "shared-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live" }); + f.db.query("UPDATE dialogue_owners SET generation=2 WHERE id=?").run(shared.id); + expect(message(() => readDialogue(f.db, f.home.id, { ownerId: shared.id, generation: 1 })), "DIALOGUE_STALE_GENERATION_REFUSED").toBe("Dialogue generation changed"); + // No evidence was rewritten to make it fit. + expect(f.db.query("SELECT id,principal_account FROM dialogue_owners WHERE id IN (?,?,?) ORDER BY id").all(legacy.id, corrupt.id, contradicted.id)).toEqual( + [{ id: contradicted.id, principal_account: "owner" }, { id: corrupt.id, principal_account: "admiral" }, { id: legacy.id, principal_account: null }].sort((a, b) => a.id < b.id ? -1 : 1)); + } finally { await f.close(); } +}); + +test("unretained or unfinished voice stays honestly legacy or partial after another login continues", async () => { + const f = await fixture(); try { + // The ship's voice recovery before journals existed, then the ship is pruned. + f.db.query("INSERT INTO conversation_epochs(id,principal_id,epoch,session_id,updated_at) VALUES('old-voice',?,1,'ithaca',0)").run(f.ship.id); + expect(hasUnretainedVoice(f.db, f.home.id, "ithaca"), "DIALOGUE_ACCOUNT_LEGACY_EVIDENCE_COUNTS").toBe(true); + f.prune("expired"); + expect(hasUnretainedVoice(f.db, f.home.id, "ithaca"), "DIALOGUE_PRUNED_LOGIN_LEGACY_STAYS_LEGACY").toBe(true); + const owner = openDialogue(f.db, { conversationId: "ithaca-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + expect(owner.coverage, "DIALOGUE_CROSS_LOGIN_LEGACY_NOT_COMPLETE").toBe("legacy"); + // An unclosed earlier epoch of another login is interruption evidence for a new open. + const pylos = openDialogue(f.db, { conversationId: "pylos-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "pylos" }); + const other = createPrincipal(f.db, { authMethod: "password", label: "Odysseus at Pylos", ttlSeconds: 7200 }); + const reopened = openDialogue(f.db, { conversationId: "pylos-again", principalId: other.id, epoch: 1, providerId: "fake-live", sessionId: "pylos" }); + expect([reopened.id, reopened.coverage], "DIALOGUE_OTHER_LOGINS_UNCLOSED_EPOCH_IS_PARTIAL").toEqual([pylos.id, "partial"]); + } finally { await f.close(); } +}); + +test("sharing the history gives no authority over another login's conversation or epoch", async () => { + const f = await fixture(); try { + const owner = openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + expect(message(() => openDialogue(f.db, { conversationId: "argos-voice", principalId: f.home.id, epoch: 2, providerId: "fake-live", sessionId: "ithaca" })), + "DIALOGUE_OTHER_LOGIN_CANNOT_REOPEN_A_CONVERSATION").toBe("Dialogue conversation principal mismatch"); + expect(message(() => closeDialogue(f.db, "argos-voice", f.home.id, 1, true)), "DIALOGUE_OTHER_LOGIN_CANNOT_CLOSE_AN_EPOCH").toBe("Dialogue conversation principal mismatch"); + expect(f.conversations(), "DIALOGUE_REFUSED_CONTROL_CHANGES_NOTHING").toEqual([{ id: "argos-voice", owner_id: owner.id, principal_id: f.ship.id, closed: 0 }]); + expect(f.owners()).toMatchObject([{ coverage: "complete" }]); + closeDialogue(f.db, "argos-voice", f.ship.id, 1); + expect(f.conversations()).toMatchObject([{ closed: 1 }]); + // Deletion keeps its exact-principal rule: the second login is refused as before. + openDialogue(f.db, { conversationId: "ithaca-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + f.db.query("INSERT INTO conversation_epochs(id,principal_id,epoch,session_id,updated_at) VALUES('argos-voice',?,1,'ithaca',0),('ithaca-voice',?,1,'ithaca',0)").run(f.ship.id, f.home.id); + expect(resolveChat(f.db, { sessionId: "ithaca" }), "DIALOGUE_DELETION_STAYS_EXACT").toEqual({ refused: "unavailable" }); + } finally { await f.close(); } +}); + +test("the catalog keeps live-epoch authority with the login that opened it", async () => { + const f = await fixture(); + const catalog = createSessionCatalog(() => f.db, undefined, undefined, { writer: f.writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(f.db, f.writer) }); + try { + const owner = await catalog.dialogueOpen!({ conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + // Two healthy live conversations of the account on one history: neither is interruption. + const continued = await catalog.dialogueOpen!({ conversationId: "ithaca-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + expect(continued.id).toBe(owner.id); + expect(f.owners(), "DIALOGUE_CROSS_LOGIN_SIBLING_IS_NOT_INTERRUPTION").toMatchObject([{ coverage: "complete" }]); + expect((await catalog.dialogueRead!(f.home.id, { sessionId: "ithaca" }))!.coverage, "DIALOGUE_CROSS_LOGIN_READ_COMPLETE").toBe("complete"); + // The second login's close of the first login's epoch is refused and leaves it live. + let refused: unknown; try { await catalog.dialogueClose!("argos-voice", f.home.id, 1, false); } catch (error) { refused = error; } + expect(refused, "DIALOGUE_CATALOG_REFUSES_FOREIGN_EPOCH_CLOSE").toBeInstanceOf(Error); + expect((await catalog.dialogueRead!(f.ship.id, { sessionId: "ithaca" }))!.coverage, "DIALOGUE_FIRST_EPOCH_STILL_LIVE").toBe("complete"); + // Each login closes its own epoch. + await catalog.dialogueClose!("ithaca-voice", f.home.id, 1, false); + await catalog.dialogueClose!("argos-voice", f.ship.id, 1, false); + expect(f.conversations()).toMatchObject([{ id: "argos-voice", closed: 1 }, { id: "ithaca-voice", closed: 1 }]); + expect(catalog.dialogueAudience!(owner, f.home.id), "DIALOGUE_AUDIENCE_IS_THE_ACCOUNT").toBe(true); + for (const [name, principalId] of f.foreign) expect(catalog.dialogueAudience!(owner, principalId), `DIALOGUE_AUDIENCE_EXCLUDES: ${name}`).toBe(false); + } finally { await catalog.settled!(); await f.close(); } +}); + +test("the retained-conversation list shows the account's host-only histories and nobody else's", async () => { + const f = await fixture(); try { + for (const [id, principalId] of [["argos-voice", f.ship.id], ["ithaca-voice", f.home.id], ["mentor-voice", f.agent.id], ["penelope-voice", f.penelope.id]] as const) + openDialogue(f.db, { conversationId: id, principalId, epoch: 1, providerId: "fake-live" }); + f.prune("revoked"); + const list = async (principal: Principal) => { + const app = new Hono(); + app.use("*", async (c, next) => { c.set("principal", principal); await next(); }); + app.route("/", createSessionRoutes({ db: f.db, registry: createStaticBackendRegistry([makeFakeBackend({ id: "fake", sessions: [] })], "fake") })); + const page = await (await app.request("/sessions?includeRetainedConversations=true")).json() as { retainedConversations: { id: string }[] }; + return page.retainedConversations.map(r => r.id); + }; + expect(await list(f.home), "DIALOGUE_LIST_INCLUDES_PRUNED_LOGINS_HISTORY").toEqual(["argos-voice", "ithaca-voice"]); + expect(await list(f.agent), "DIALOGUE_LIST_AGENT_ONLY_ITS_OWN").toEqual(["mentor-voice"]); + expect(await list(f.penelope), "DIALOGUE_LIST_AMBIENT_ONLY_ITS_OWN").toEqual(["penelope-voice"]); + f.db.query("UPDATE dialogue_owners SET principal_account='admiral' WHERE id='ithaca-voice'").run(); + expect(await list(f.home), "DIALOGUE_LIST_DROPS_CORRUPT_EVIDENCE").toEqual(["argos-voice"]); + } finally { await f.close(); } +}); + +test("live start: another owner login opens voice on the retained history; a foreign login reaches no provider", async () => { + const f = await fixture(); + const live = fakeLiveProvider(); + const catalog = createSessionCatalog(() => f.db, undefined, undefined, { writer: f.writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(f.db, f.writer) }); + const host = new WsHost({ registry: createStaticBackendRegistry([makeFakeBackend({ id: "fake" })], "fake"), catalog, conversationProvider: live.provider }); + const until = async (check: () => boolean) => { const limit = Date.now() + 5000; while (!check()) { if (Date.now() > limit) throw Error("Live start checkpoint unavailable"); await Bun.sleep(1); } }; + const device = async (principal: Principal) => { + const frames: any[] = [], ws = { send: (data: string) => frames.push(JSON.parse(data)) } as WSContext; + const handlers = createWsHandlers(host, principal); + await handlers.onOpen(undefined as never, ws); + const send = (frame: Record) => handlers.onMessage({ data: JSON.stringify(frame.type === "conversation_start" ? { ...frame, disclosed: host.conversations!.profile(false) } : frame) } as MessageEvent, ws); + send({ type: "client_hello", protocolRev: 5, capabilities: { sessionDialogue: true } }); + return { frames, send, of: (type: string) => frames.filter(x => x.type === type) }; + }; + try { + const ship = await device(f.ship), home = await device(f.home), mentor = await device(f.agent); + ship.send({ type: "conversation_start", requestId: "ship-start" }); + await until(() => ship.of("conversation_opened").length === 1); + const first = ship.of("conversation_opened")[0]; + const firstSeed = JSON.stringify(live.sessions[0]!.options.history); + live.sessions[0]!.emit({ kind: "unassigned_input_fragment", sequence: 0, text: "Set the sail for Ithaca.", timing: { kind: "unavailable" }, finalization: "final" } as never); + await until(() => home.of("dialogue_history").length === 1); + expect(ship.of("dialogue_history"), "DIALOGUE_LIVE_PAGE_REACHES_THE_WRITER").toHaveLength(1); + expect(mentor.of("dialogue_history"), "DIALOGUE_LIVE_PAGE_NEVER_REACHES_ANOTHER_ACCOUNT").toHaveLength(0); + ship.send({ type: "conversation_stop", conversationId: first.conversationId }); + await until(() => ship.of("conversation_closed").length === 1); + await host.dialogue.settled(); + // The other device continues the same history in a new conversation of its own. + home.send({ type: "conversation_start", requestId: "home-start", historyOwnerId: first.historyOwnerId }); + await until(() => home.of("conversation_opened").length === 1); + const second = home.of("conversation_opened")[0]; + expect([second.historyOwnerId, second.conversationId !== first.conversationId], "DIALOGUE_LIVE_SECOND_LOGIN_CONTINUES").toEqual([first.historyOwnerId, true]); + expect(live.sessions).toHaveLength(2); + const seeded = live.sessions[1]!.options.history!.items.flatMap(i => "text" in i ? [i.text] : []); + expect(seeded, "DIALOGUE_LIVE_SECOND_LOGIN_RECEIVES_RETAINED_HISTORY").toEqual(["Set the sail for Ithaca."]); + // The first session's provider history is untouched by the continuation. + expect(JSON.stringify(live.sessions[0]!.options.history), "DIALOGUE_FIRST_SESSION_PREFIX_UNCHANGED").toBe(firstSeed); + // Another account names the history: refused before any provider effect. + mentor.send({ type: "conversation_start", requestId: "mentor-start", historyOwnerId: first.historyOwnerId }); + await until(() => mentor.frames.some(x => x.type === "error" || x.type === "conversation_closed")); + expect(mentor.of("conversation_opened"), "DIALOGUE_LIVE_FOREIGN_NEVER_OPENS").toHaveLength(0); + expect(live.sessions, "DIALOGUE_LIVE_FOREIGN_HAS_NO_PROVIDER_EFFECT").toHaveLength(2); + // Ownership metadata never enters the provider-facing history. + expect(JSON.stringify(live.sessions[1]!.options), "DIALOGUE_NO_OWNERSHIP_METADATA_TO_PROVIDER").not.toMatch(/principal|owner_account|"owner"/); + } finally { await host.close(); await catalog.settled!(); await f.close(); } +}); From 1bbea540d6ffd3082d577592e3775f066f5a899d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 05:04:38 +0000 Subject: [PATCH 2/5] CONTRACT: fix(ui-server): keep the dialogue journal's publish callback additive (#3963) The owner the host needs to reach every login of the account is now an optional third argument after the unchanged page and principalId, so an existing two-argument callback still fits. The api report and the package component record the three optional additions. Co-Authored-By: Claude Opus 5.5 --- api-report/ui-server.txt | 4 +++- docs/integration-contract.md | 5 +++-- docs/integration-contract/package-api.md | 10 ++++++++++ packages/ui-server/src/ws/dialogue.ts | 8 ++++++-- packages/ui-server/src/ws/host.ts | 4 ++-- 5 files changed, 24 insertions(+), 7 deletions(-) diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 8ce3db8965..538e5259db 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -552,7 +552,7 @@ signatures (every public export and the types it is made of) } DialogueJournal (packages/ui-server/src/ws/dialogue.ts) export class DialogueJournal { - constructor(private readonly catalog: SessionCatalog, private readonly publish: (page: DialoguePage, principalId: string) => void, private readonly failed: (owner: DialogueOwner, cause: "queue_pressure" | "storage_error" | "storage_indeterminate", kind?: DialogueEvidence["kind"]) => void); + constructor(private readonly catalog: SessionCatalog, private readonly publish: (page: DialoguePage, principalId: string, owner?: DialogueOwner) => void, private readonly failed: (owner: DialogueOwner, cause: "queue_pressure" | "storage_error" | "storage_indeterminate", kind?: DialogueEvidence["kind"]) => void); open(input: DialogueOpen): Promise; bind(conversationId: string, principalId: string, sessionId: string): void; voice(conversationId: string, evidence: Extract; dialogueOpen?(input: DialogueOpen): Promise; dialogueAppend?(input: DialogueAppend): Promise; diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 7aee62f22f..d52339bd8f 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -224,8 +224,9 @@ Another owner login continues a chat's retained dialogue by voice, reads it and receives its live pages; a pruned starting login no longer strands it. A live conversation and its epochs stay with the login that opened them, and other accounts are refused as before. No field changes. See -[wire](integration-contract/wire.md#retained-voice-history-belongs-to-its-account-additive-0450-3963) -and [HTTP](integration-contract/http.md#retained-conversations-account-additive-3963). +[wire](integration-contract/wire.md#retained-voice-history-belongs-to-its-account-additive-0450-3963), +[HTTP](integration-contract/http.md#retained-conversations-account-additive-3963) +and [the package API](integration-contract/package-api.md#retained-dialogue-data-3177). This ships in a minor; no breaking ruling is required. ## Retained barge-in and conversation end (additive, 0.45.0, #3729) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index d8abff8ab1..3f81be3299 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5206,6 +5206,16 @@ meaning. No provider history-selection API is delivered by this slice. write path. The [wire amendment](wire.md#retained-barge-in-and-conversation-end-additive-0450-3729) defines when each is written and how the client draws them. +For account-owned retained history (#3963, additive in 0.45.0), +`DialogueOwner` gains optional `principal_account`, the stored account beside +`principal_id`; `SessionCatalog` gains optional `dialogueAudience(owner, +principalId)`, whether that login may receive the owner's pages; and the +`DialogueJournal` publish callback receives the owner as an optional third +argument after the unchanged page and `principalId`. Existing catalogs and +callbacks keep compiling and behave as before. The +[wire amendment](wire.md#retained-voice-history-belongs-to-its-account-additive-0450-3963) +defines who may use the history. + Failed-write live text exposes optional `ServerConversationEvent.retention` and `ServerError.historyOwnerId`, plus the existing client projection's explicit unsaved recognition/output fields (#3177). These are additive evidence and diff --git a/packages/ui-server/src/ws/dialogue.ts b/packages/ui-server/src/ws/dialogue.ts index 65de8f63a7..2830e22c19 100644 --- a/packages/ui-server/src/ws/dialogue.ts +++ b/packages/ui-server/src/ws/dialogue.ts @@ -27,8 +27,11 @@ export class DialogueJournal { private readonly refusals = new Map void>>(); constructor( private readonly catalog: SessionCatalog, - /** Delivers a committed page to the owner's audience: every login of its account (#3963). */ - private readonly publish: (page: DialoguePage, owner: DialogueOwner) => void, + /** + * Delivers a committed page. `principalId` is the owner's attribution; + * `owner` lets the host reach every login of its account (#3963). + */ + private readonly publish: (page: DialoguePage, principalId: string, owner?: DialogueOwner) => void, private readonly failed: (owner: DialogueOwner, cause: "queue_pressure" | "storage_error" | "storage_indeterminate", kind?: DialogueEvidence["kind"]) => void ) {} private transition(conversationId: string, run: () => Promise): Promise { @@ -309,6 +312,7 @@ export class DialogueJournal { records: [record], coverage: owner.coverage, }, + owner.principal_id, owner ); after?.(true); diff --git a/packages/ui-server/src/ws/host.ts b/packages/ui-server/src/ws/host.ts index b9fcc6f7c5..4d17876193 100644 --- a/packages/ui-server/src/ws/host.ts +++ b/packages/ui-server/src/ws/host.ts @@ -485,8 +485,8 @@ export class WsHost { if (principalId === owner.principal_id) return true; try { return this.catalog.dialogueAudience?.(owner, principalId) === true; } catch { return false; } }; - this.dialogue = new DialogueJournal(this.catalog, (page, owner) => { - this.clients.broadcast({ type: "dialogue_history", ...page }, undefined, "sessionDialogue", audience(owner)); + this.dialogue = new DialogueJournal(this.catalog, (page, principalId, owner) => { + this.clients.broadcast({ type: "dialogue_history", ...page }, undefined, "sessionDialogue", owner ? audience(owner) : principalId); }, (owner, cause, kind) => { const finish=this.conversations?.storageFailing(owner.id); const message=cause === "storage_indeterminate" ? "Conversation text persistence could not be confirmed. Voice stopped; history may be incomplete. Restore storage before restarting voice." : kind === "backend" ? "Original discussion position could not be saved. The complete answer remains in chat history. Check storage before restarting voice." : cause === "queue_pressure" ? "Conversation text is arriving faster than it can be saved. Voice capture stopped at the pending-write limit. The unsaved tail is unavailable after reload. Let pending writes finish and check storage before restarting voice." : "Conversation text could not be saved. The unsaved tail is unavailable after reload. Restore storage before restarting voice."; From 2ba7d12fc90725f640dee2e6974544cf6148edd8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 05:13:28 +0000 Subject: [PATCH 3/5] fix(ui-server): refuse voice evidence written into another login's epoch (#3963) appendDialogue checked a voice-sourced record's owner, epoch and provider, but not the login that opened its conversation. With account-wide history access another owner login could append voice, interruption or end evidence to the first login's epoch by naming it. Storage now requires the appending principal to be the conversation's recorded opener, and the journal writes each epoch's evidence as its own scope's login instead of the history owner's attribution. Backend evidence is still written as the history owner. Co-Authored-By: Claude Opus 5.5 --- docs/integration-contract/wire.md | 3 +- packages/ui-server/src/ws/dialogue-storage.ts | 7 ++++- packages/ui-server/src/ws/dialogue.ts | 19 ++++++++---- .../tests/dialogue-account-ownership.test.ts | 30 +++++++++++++++++++ 4 files changed, 52 insertions(+), 7 deletions(-) diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 283f37f9d6..d9dab2f18e 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -2849,7 +2849,8 @@ What stays exact: - A live conversation and its epochs belong to the login that opened them. Another login of the account starts a new conversation on the history; it - cannot resume, reopen or close another login's conversation or epoch. + cannot resume, reopen or close another login's conversation or epoch, or + write voice, interruption or end evidence into it. Migration `090_dialogue_conversation_principal.sql` records the opening login on each conversation, and fills it for existing rows from their owner, which before this change was always the opening login. diff --git a/packages/ui-server/src/ws/dialogue-storage.ts b/packages/ui-server/src/ws/dialogue-storage.ts index 7198587220..ab7ce235e4 100644 --- a/packages/ui-server/src/ws/dialogue-storage.ts +++ b/packages/ui-server/src/ws/dialogue-storage.ts @@ -266,6 +266,7 @@ export function bindDialogue( } export interface DialogueAppend { ownerId: string; + /** The writing login. For voice-sourced evidence, the login that opened its conversation. */ principalId: string; generation: number; identity: string; @@ -300,16 +301,20 @@ export function appendDialogue( if (sourced) { const c = db .query( - "SELECT owner_id,epoch,provider_id FROM dialogue_conversations WHERE id=?" + "SELECT owner_id,principal_id,epoch,provider_id FROM dialogue_conversations WHERE id=?" ) .get(sourced.conversationId) as { owner_id: string; + principal_id: string | null; epoch: number; provider_id: string; } | null; + // The history is the account's, the epoch only its opening login's + // (#3963): another login writes no voice evidence into it. if ( !c || c.owner_id !== owner.id || + c.principal_id !== input.principalId || c.epoch !== sourced.epoch || c.provider_id !== sourced.providerId ) diff --git a/packages/ui-server/src/ws/dialogue.ts b/packages/ui-server/src/ws/dialogue.ts index 2830e22c19..43f3786728 100644 --- a/packages/ui-server/src/ws/dialogue.ts +++ b/packages/ui-server/src/ws/dialogue.ts @@ -132,7 +132,7 @@ export class DialogueJournal { : null, e.sequence, ]); - this.append(owner, identity, evidence, after); + this.append(owner, identity, evidence, after, this.opener(conversationId, owner)); return true; } /** @@ -143,7 +143,7 @@ export class DialogueJournal { interruption(conversationId: string, evidence: Extract, ordinal: number): boolean { const owner = this.conversations.get(conversationId); if (!owner) return false; - this.append(owner, JSON.stringify([conversationId, evidence.epoch, "interrupted", evidence.outputId ?? null, ordinal]), evidence); + this.append(owner, JSON.stringify([conversationId, evidence.epoch, "interrupted", evidence.outputId ?? null, ordinal]), evidence, undefined, this.opener(conversationId, owner)); return true; } /** @@ -155,7 +155,7 @@ export class DialogueJournal { const owner = this.ownerForConversation(conversationId, principalId); // An owner whose writes failed since it opened is not written to again. if (!owner || !this.historyOwner(owner, principalId) || this.failedOwners.has(owner.id)) return false; - this.append(owner, JSON.stringify([conversationId, "ended", evidence.startedAt]), evidence); + this.append(owner, JSON.stringify([conversationId, "ended", evidence.startedAt]), evidence, undefined, principalId); return true; } adoptTurn(turnId: string, ownerId: string, principalId: string): void { @@ -259,11 +259,20 @@ export class DialogueJournal { this.track(done); } + /** + * The login that opened a live conversation: it alone writes that epoch's + * voice evidence, whoever started the shared history (#3963). + */ + private opener(conversationId: string, owner: DialogueOwner): string { + return this.scopes.get(conversationId)?.principalId ?? owner.principal_id; + } private append( owner: DialogueOwner, identity: string, evidence: DialogueEvidence, - after?: (saved: boolean) => void + after?: (saved: boolean) => void, + /** The writing login; backend evidence is written as the history owner. */ + principalId: string = owner.principal_id ): void { if (!this.catalog.dialogueAppend) return; // Adoption mutates the canonical ID; pending callbacks retain this owner. @@ -295,7 +304,7 @@ export class DialogueJournal { const done = this.catalog .dialogueAppend({ ownerId: owner.id, - principalId: owner.principal_id, + principalId, generation: owner.generation, identity, evidence, diff --git a/packages/ui-server/tests/dialogue-account-ownership.test.ts b/packages/ui-server/tests/dialogue-account-ownership.test.ts index d049a6344a..256df1b6d8 100644 --- a/packages/ui-server/tests/dialogue-account-ownership.test.ts +++ b/packages/ui-server/tests/dialogue-account-ownership.test.ts @@ -230,6 +230,31 @@ test("sharing the history gives no authority over another login's conversation o } finally { await f.close(); } }); +test("another login of the account cannot write voice evidence into an epoch it did not open", async () => { + const f = await fixture(); try { + const owner = openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + openDialogue(f.db, { conversationId: "ithaca-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + const into = (conversationId: string, principalId: string, kind: "voice" | "voice_interruption" | "voice_end", n: number) => { + const scope = { conversationId, epoch: 1, providerId: "fake-live" }; + const evidence: DialogueEvidence = kind === "voice" + ? { kind, ...scope, event: { kind: "unassigned_input_fragment", sequence: n, text: "Bind me to the mast.", timing: { kind: "unavailable" }, finalization: "final" } } + : kind === "voice_interruption" ? { kind, ...scope } : { kind, ...scope, startedAt: 0, endedAt: 1 }; + return message(() => appendDialogue(f.db, { ownerId: owner.id, principalId, generation: 1, identity: `${conversationId}:${kind}:${principalId}:${n}`, evidence })); + }; + for (const [n, kind] of (["voice", "voice_interruption", "voice_end"] as const).entries()) { + expect(into("argos-voice", f.home.id, kind, n), `DIALOGUE_OTHER_LOGIN_CANNOT_WRITE_AN_EPOCH: ${kind}`).toBe("Dialogue source scope mismatch"); + expect(into("ithaca-voice", f.ship.id, kind, n), `DIALOGUE_FIRST_LOGIN_CANNOT_WRITE_THE_SECONDS_EPOCH: ${kind}`).toBe("Dialogue source scope mismatch"); + } + expect(f.db.query("SELECT COUNT(*) AS n FROM dialogue_records").get(), "DIALOGUE_REFUSED_WRITES_LEAVE_NO_RECORD").toEqual({ n: 0 }); + // Each login writes its own epoch, into the one shared history. + for (const [n, kind] of (["voice", "voice_interruption", "voice_end"] as const).entries()) { + expect(into("argos-voice", f.ship.id, kind, n), `DIALOGUE_OPENING_LOGIN_WRITES: ${kind}`).toBe("admitted"); + expect(into("ithaca-voice", f.home.id, kind, n)).toBe("admitted"); + } + expect(f.db.query("SELECT COUNT(*) AS n FROM dialogue_records WHERE owner_id=?").get(owner.id)).toEqual({ n: 6 }); + } finally { await f.close(); } +}); + test("the catalog keeps live-epoch authority with the login that opened it", async () => { const f = await fixture(); const catalog = createSessionCatalog(() => f.db, undefined, undefined, { writer: f.writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(f.db, f.writer) }); @@ -308,6 +333,11 @@ test("live start: another owner login opens voice on the retained history; a for expect(live.sessions).toHaveLength(2); const seeded = live.sessions[1]!.options.history!.items.flatMap(i => "text" in i ? [i.text] : []); expect(seeded, "DIALOGUE_LIVE_SECOND_LOGIN_RECEIVES_RETAINED_HISTORY").toEqual(["Set the sail for Ithaca."]); + // The second login's own speech lands in the shared history through the journal. + live.sessions[1]!.emit({ kind: "unassigned_input_fragment", sequence: 0, text: "Unbar the hall doors.", timing: { kind: "unavailable" }, finalization: "final" } as never); + await until(() => ship.of("dialogue_history").length === 2 && home.of("dialogue_history").length === 2); + await host.dialogue.settled(); + expect(f.db.query("SELECT COUNT(*) AS n FROM dialogue_records").get(), "DIALOGUE_LIVE_SECOND_LOGIN_WRITES_ITS_EPOCH").toEqual({ n: 2 }); // The first session's provider history is untouched by the continuation. expect(JSON.stringify(live.sessions[0]!.options.history), "DIALOGUE_FIRST_SESSION_PREFIX_UNCHANGED").toBe(firstSeed); // Another account names the history: refused before any provider effect. From d34c080dba56222ef8afdcb76039c6ea02bb08dc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 05:23:54 +0000 Subject: [PATCH 4/5] fix(ui-server): keep live owner identity when another login adopts a provisional history (#3963) The catalog updated its live scopes' owner identity after a bind only when the binding login had opened the conversation. When login B's typed turn adopted login A's live provisional history into B's session history, A's scope kept the retired owner and its attribution, so activeEpochFor no longer recognised the healthy epoch and reads reported partial, and the journal kept publishing the obsolete owner id. Every live scope of the previous owner now takes the canonical identity in place, whoever bound it; epoch authority stays with each scope's own principal. The journal's adoption path also replaced a live conversation's owner object with a freshly read copy and deleted the mapping until the bind settled, dropping that epoch's voice in the meantime. A live conversation now keeps its own object through adoption. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/ws/dialogue.ts | 8 +++- packages/ui-server/src/ws/session-catalog.ts | 32 +++++++++------- .../tests/dialogue-account-ownership.test.ts | 38 +++++++++++++++++++ 3 files changed, 62 insertions(+), 16 deletions(-) diff --git a/packages/ui-server/src/ws/dialogue.ts b/packages/ui-server/src/ws/dialogue.ts index 43f3786728..7f3621b025 100644 --- a/packages/ui-server/src/ws/dialogue.ts +++ b/packages/ui-server/src/ws/dialogue.ts @@ -200,12 +200,16 @@ export class DialogueJournal { if (!sessionId) return; const adopting = this.adopting.get(turnId); if (msg.type === "session_info" && adopting) { - this.conversations.set(adopting.id, adopting); + // A live conversation keeps its own owner object through adoption: a + // fresh copy would drop its ingress until the bind settled and leave + // its pending callbacks on the old identity (#3963). + const live = this.conversations.get(adopting.id); + if (!live) this.conversations.set(adopting.id, adopting); // The adopting turn's own login binds it, not the history's first one. this.bind(adopting.id, this.adopters.get(turnId) ?? adopting.principal_id, sessionId); this.adopting.delete(turnId); this.adopters.delete(turnId); - this.conversations.delete(adopting.id); + if (!live) this.conversations.delete(adopting.id); } const owner = this.sessions.get(sessionId) ?? diff --git a/packages/ui-server/src/ws/session-catalog.ts b/packages/ui-server/src/ws/session-catalog.ts index bce25ee56d..3f9921dfdd 100644 --- a/packages/ui-server/src/ws/session-catalog.ts +++ b/packages/ui-server/src/ws/session-catalog.ts @@ -361,22 +361,26 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi }, dialogueAppend: input => submit("dialogueAppend", input), dialogueBind: async (conversationId, principalId, sessionId) => { + // The owner the conversation names before adoption. Read it before the + // bind, which retires that owner's id behind an alias. + const previousId=activeDialogueEpochs.get(conversationId)?.owner.id + ?? (db().query("SELECT owner_id FROM dialogue_conversations WHERE id=?").get(conversationId) as {owner_id:string}|null)?.owner_id; const owner=await submit("dialogueBind", conversationId, principalId, sessionId); - const active=activeDialogueEpochs.get(conversationId); - if(owner && active && active.principalId===principalId) { - // Pending callbacks still hold this object across adoption. Replacing - // it would hide their genuine failure behind a fresh healthy owner. - // Every live scope on the adopted owner takes its canonical identity, - // whichever login of the account opened it (#3963). - const previousId=active.owner.id; - for(const scope of activeDialogueEpochs.values()) if(scope.owner.id===previousId){ - const partial=scope.owner.coverage === "partial"; - Object.assign(scope.owner,owner); - if(partial) scope.owner.coverage="partial"; - } - return active.owner; + if(!owner || previousId===undefined) return owner; + // Pending callbacks still hold these objects across adoption. Replacing + // them would hide their genuine failure behind a fresh healthy owner. + // The adoption already moved every live scope of the previous owner, so + // each takes the canonical identity in place, whichever login opened it + // and whichever login bound it (#3963): its liveness is the durable + // owner's, and its epoch authority stays its own principal. + let shared:DialogueOwner|undefined; + for(const scope of activeDialogueEpochs.values()) if(scope.owner.id===previousId){ + const partial=scope.owner.coverage === "partial"; + Object.assign(scope.owner,owner); + if(partial) scope.owner.coverage="partial"; + shared ??= scope.owner; } - return owner; + return activeDialogueEpochs.get(conversationId)?.owner ?? shared ?? owner; }, async dialogueRead(principalId, target) { await tail; diff --git a/packages/ui-server/tests/dialogue-account-ownership.test.ts b/packages/ui-server/tests/dialogue-account-ownership.test.ts index 256df1b6d8..8fb6bff9db 100644 --- a/packages/ui-server/tests/dialogue-account-ownership.test.ts +++ b/packages/ui-server/tests/dialogue-account-ownership.test.ts @@ -255,6 +255,44 @@ test("another login of the account cannot write voice evidence into an epoch it } finally { await f.close(); } }); +test("another login's adoption of a live provisional history keeps its live identity and healthy coverage", async () => { + const f = await fixture(); + const { DialogueJournal } = await import("../src/ws/dialogue"); + const catalog = createSessionCatalog(() => f.db, undefined, undefined, { writer: f.writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(f.db, f.writer) }); + const pages: { ownerId: string; coverage: string }[] = []; + const journal = new DialogueJournal(catalog, page => pages.push({ ownerId: page.ownerId, coverage: page.coverage }), () => {}); + try { + // The home login already has this chat's session history. + const home = await catalog.dialogueOpen!({ conversationId: "ithaca-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + await catalog.dialogueClose!("ithaca-voice", f.home.id, 1, false); + // The ship login is live in a host-only history. + const ship = await journal.open({ conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live" }); + expect(ship!.id).toBe("argos-voice"); + // The home login's typed turn adopts it into the session. + journal.adoptTurn("homecoming", ship!.id, f.home.id); + journal.backend({ type: "session_info", sessionId: "ithaca", turnId: "homecoming", isNew: false } as never); + // The live epoch keeps speaking while the adoption is in flight. + const during = { kind: "voice" as const, conversationId: "argos-voice", epoch: 1, providerId: "fake-live", + event: { kind: "unassigned_input_fragment" as const, sequence: 1, text: "Hold the course.", timing: { kind: "unavailable" as const }, finalization: "final" as const } }; + expect(journal.voice("argos-voice", during, () => {}), "DIALOGUE_ADOPTION_KEEPS_LIVE_INGRESS").toBe(true); + await journal.settled(); + expect(f.db.query("SELECT owner_id FROM dialogue_aliases WHERE id='argos-voice'").get(), "DIALOGUE_CROSS_LOGIN_ADOPTION_MERGED").toEqual({ owner_id: home.id }); + expect((await catalog.dialogueRead!(f.home.id, { sessionId: "ithaca" }))!.coverage, "DIALOGUE_CROSS_LOGIN_ADOPTION_STAYS_HEALTHY").toBe("complete"); + expect(f.owners(), "DIALOGUE_CROSS_LOGIN_ADOPTION_DB_COMPLETE").toMatchObject([{ id: home.id, coverage: "complete" }]); + // The live epoch's journal references now name the canonical owner. + expect(ship!.id, "DIALOGUE_CROSS_LOGIN_ADOPTION_UPDATES_LIVE_OWNER").toBe(home.id); + const e = { kind: "voice" as const, conversationId: "argos-voice", epoch: 1, providerId: "fake-live", + event: { kind: "unassigned_input_fragment" as const, sequence: 0, text: "Steer for the hall.", timing: { kind: "unavailable" as const }, finalization: "final" as const } }; + expect(journal.voice("argos-voice", e, () => {})).toBe(true); + await journal.settled(); + expect(pages.at(-1), "DIALOGUE_CROSS_LOGIN_ADOPTION_PUBLISHES_CANONICAL_OWNER").toEqual({ ownerId: home.id, coverage: "complete" }); + expect(f.db.query("SELECT COUNT(*) AS n FROM dialogue_records WHERE owner_id=? AND payload LIKE '%argos-voice%'").get(home.id), "DIALOGUE_ADOPTION_RETAINS_BOTH_UTTERANCES").toEqual({ n: 2 }); + journal.close("argos-voice", f.ship.id, 1); + await journal.settled(); + expect((await catalog.dialogueRead!(f.ship.id, { sessionId: "ithaca" }))!.coverage).toBe("complete"); + } finally { await journal.settled().catch(() => {}); await catalog.settled!(); await f.close(); } +}); + test("the catalog keeps live-epoch authority with the login that opened it", async () => { const f = await fixture(); const catalog = createSessionCatalog(() => f.db, undefined, undefined, { writer: f.writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(f.db, f.writer) }); From 2274f53bf89fa43e5f367f7265128f3c991780b5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 05:27:42 +0000 Subject: [PATCH 5/5] docs: follow the session catalog citation the adoption fix moved (#3963) Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 0900ae893c..261cdcb646 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -2254,7 +2254,7 @@ The brain's git history stays the durable record of its content. - **The Activity recorder and its rollups** price those events under the [cost-tracking rules](cost-tracking.md). An unknown price is never counted as zero. The session total that counts unknown as zero - (`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:507`) + (`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:511`) must not feed any budget. **Enforcement:**