From 08c3d18cf3241126d9627e38eaec6b982d759704 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 09:46:23 +0000 Subject: [PATCH 1/3] CONTRACT: feat(ui-server): same-account chat deletion for owner logins (#4138) A chat two owner logins used by voice refused deletion to both of them: resolveChat aggregated exact principal IDs across the dialogue owner, voice epochs and typed-creation binding and refused more than one. Under the maintainer's option B ruling, any currently authorized owner login may delete a chat whose every deletion-relevant ownership record proves that same owner account. - resolveChat returns every ownership record with its stored durable account; chatOwnedBy requires each one to be the caller's account via sameAccount, at the catalog preflight and again in the commit transaction. Missing, corrupt, contradictory or mixed-account evidence refuses that chat alone. - Migration 091 adds principal_account to conversation_epochs and chat_session_owners, written from the principal's own row and backfilled only where a principal row still proves it, so evidence outlives pruning. - The lifecycle, receipt and retry key stay with the initiating login; no record's attribution is rewritten. Provisional chats accept one safety collection per login of one generation. A stale provisional target is reported to the owner account rather than the exact principal. - Decision record amended, HTTP admission semantics and contract index updated, minor changeset added; existing tests that used a second owner login as a foreign caller now use a different account. Co-Authored-By: Claude Opus 5.5 --- .changeset/3963-dialogue-account-ownership.md | 2 +- .changeset/4138-same-account-chat-deletion.md | 5 + docs/decisions/chat-history-deletion.md | 66 +++++- docs/http-api.md | 22 +- docs/integration-contract.md | 14 ++ docs/integration-contract/wire.md | 3 +- docs/plans/chat-history-deletion.md | 15 +- .../migrations/091_chat_ownership_account.sql | 26 +++ packages/ui-server/src/app.ts | 5 +- packages/ui-server/src/ws/chat-lifecycle.ts | 85 ++++--- .../ui-server/src/ws/conversation-storage.ts | 7 +- .../src/ws/session-catalog-writes.ts | 4 +- packages/ui-server/src/ws/session-catalog.ts | 4 +- .../ui-server/tests/chat-deletion.test.ts | 52 ++++- .../ui-server/tests/chat-lifecycle.test.ts | 54 ++++- .../tests/chat-session-owner.test.ts | 33 +-- .../tests/dialogue-account-ownership.test.ts | 214 +++++++++++++++++- .../tests/helpers/safety-history-fixture.ts | 2 +- .../tests/host-publication-safety.test.ts | 2 +- .../tests/live-safety-admission.test.ts | 2 +- .../tests/safety-account-partition.test.ts | 2 +- .../tests/safety-containment.test.ts | 6 +- .../ui-server/tests/safety-ledger.test.ts | 6 +- .../tests/safety-loss-recovery.test.ts | 2 +- .../tests/safety-native-delivery.test.ts | 2 +- .../tests/safety-pi-delivery.test.ts | 2 +- .../tests/safety-result-exits.test.ts | 2 +- .../tests/safety-result-retention.test.ts | 4 +- .../ui-server/tests/safety-reviews.test.ts | 2 +- .../tests/session-safety-boundaries.test.ts | 2 +- .../ui-server/tests/web-pi-delivery.test.ts | 2 +- 31 files changed, 536 insertions(+), 113 deletions(-) create mode 100644 .changeset/4138-same-account-chat-deletion.md create mode 100644 packages/ui-server/migrations/091_chat_ownership_account.sql diff --git a/.changeset/3963-dialogue-account-ownership.md b/.changeset/3963-dialogue-account-ownership.md index f65ff91b0b..fe7b80b83c 100644 --- a/.changeset/3963-dialogue-account-ownership.md +++ b/.changeset/3963-dialogue-account-ownership.md @@ -2,4 +2,4 @@ "@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. +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 chat deletion keeps its own admission rule (#4138). diff --git a/.changeset/4138-same-account-chat-deletion.md b/.changeset/4138-same-account-chat-deletion.md new file mode 100644 index 0000000000..e3e707beda --- /dev/null +++ b/.changeset/4138-same-account-chat-deletion.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +A chat two owner logins used can be deleted by either of them (#4138). Every owner sign-in is its own principal, and explicit chat deletion compared exact principals across the chat's ownership records, so a chat continued by voice from a second device was refused to both logins as `unavailable`. `POST /api/chat-deletions` now admits any usable owner login when every recorded owner (the dialogue owner, each voice epoch, the typed-creation binding, a provisional chat's safety collections) proves that same owner account, also after another login has been pruned. Migration 091 stores the durable account beside each voice epoch and typed-creation binding, from the principal's own row, and backfills legacy rows only where a principal row still proves it. A record of another account, a pruned login with no stored account, or corrupt or contradictory evidence still refuses that chat alone. The caller is checked from its own current row at admission and at commit; revoked, expired, agent, ambient and system callers stay `unauthorized`. The operation, its receipt and its retry key stay with the login that started it, original attribution is never rewritten, and live conversation and epoch control, busy refusal, stale review, permanent fences and per-store outcomes are unchanged. No request, receipt or refusal shape changes. diff --git a/docs/decisions/chat-history-deletion.md b/docs/decisions/chat-history-deletion.md index 1df5cb0ffe..cdafc7f562 100644 --- a/docs/decisions/chat-history-deletion.md +++ b/docs/decisions/chat-history-deletion.md @@ -12,7 +12,10 @@ open implementation scope lives in the tracker. Only an authenticated owner may delete its own chat. Preserve exact principal ownership and recheck current authorization, including revocation, at admission and across asynchronous boundaries. No cross-principal power, reassignment, -agent authority or arbitrary filesystem authority follows. +agent authority or arbitrary filesystem authority follows. The +[same-account amendment](#same-account-deletion--2026-11-17-4138) narrows the +exact-principal rule for one case: another current login of the same owner +account may delete a chat whose every ownership record proves that account. Ambient authentication requires an explicit owner mapping; otherwise deletion is unavailable. Read access, labels, voice recognition and conversation content are not authorization. Existing [principal boundaries](session-principals.md) @@ -91,10 +94,10 @@ prompt, title, label or transcript text. The bridge offers the creator only on a new turn that is not host work and whose authorization is current (`const creator`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:143`). The write worker binds it only in the transaction that first creates the session's row -(`upsertSession(row: SessionRow)`, `packages/ui-server/src/ws/session-catalog-writes.ts:169-178`). +(`upsertSession(row: SessionRow)`, `packages/ui-server/src/ws/session-catalog-writes.ts:170-182`). `resolveChat` counts the row as one more ownership record beside dialogue -owners and voice epochs, so records that disagree still refuse as ambiguous -(`const creator`, `packages/ui-server/src/ws/chat-lifecycle.ts:91-92`). Like the +owners and voice epochs, so records of different accounts still refuse as +ambiguous (`const creator`, `packages/ui-server/src/ws/chat-lifecycle.ts:102-103`). Like the permanent fences, the row is identity data and stays after a deletion cleans the chat's stores. @@ -126,6 +129,61 @@ the endpoint and store cleanup this record feeds. This adds no wire shape: the `POST /api/chat-deletions` request, receipt and refusal shapes are unchanged, and the row is internal storage. +## Same-account deletion — 2026-11-17 (#4138) + +**Decided by the maintainer on 2026-11-17**: +[#4138 ruling](https://github.com/schlessera/brain-kit/issues/4138#issuecomment-6943093310), +option B. Every owner sign-in mints its own principal +([session principals](session-principals.md)), and a chat's retained history +belongs to the account, so a second login of the same owner continues it by +voice ([#3963](https://github.com/schlessera/brain-kit/issues/3963)). Deletion +still compared exact principal IDs across the chat's ownership records, so a +chat two logins had used was refused to both of them as ambiguous ownership. + +**The amendment.** Any currently authorized owner login may explicitly delete a +chat when every deletion-relevant ownership record is verified as belonging to +that same owner account. This narrowly amends the exact-principal deletion +rule under [Authority and extent](#authority-and-extent). Shared read access +alone never grants deletion authority. + +- **Which records.** Every record `resolveChat` consults: the canonical + dialogue owner, each recorded voice conversation epoch, the typed-creation + binding and, for a provisional chat, each safety collection of its history + owner (`resolveChat`, `packages/ui-server/src/ws/chat-lifecycle.ts:87-141`). + Each must prove the caller's account; one that does not refuses the whole chat + (`chatOwnedBy`, `packages/ui-server/src/ws/chat-lifecycle.ts:153-155`). +- **What proves an account.** The record principal's current row, or the + durable account the server stored beside the record when it wrote it + (`principal_account`, migrations 089 and 091). Migration 091 adds that + column to `conversation_epochs` and `chat_session_owners`, and the writers + fill it from the principal's own row. A pruned historical login is + recognized only through that stored evidence. Missing, corrupt or + contradictory evidence, a stored account that a live row disagrees with, or + records of mixed accounts refuse as `unavailable`, within that chat only. + Legacy rows are backfilled only where a principal row still proved the + account at upgrade; the others stay unknown and keep refusing. +- **What authorizes the caller.** Only its own current principal row, re-read + at admission and again in the commit transaction. A revoked, expired or + pruned caller gains nothing from any record's stored account. Agent, + ambient and system principals have no account that holds across auth modes, + so their records match only themselves and they never gain an account-wide + exception. +- **What stays exact.** The operation, its receipt and its retry key belong to + the login that started it: another login of the account reads + `not_admitted` and cannot retry it. The lifecycle records that initiating + login; no record's original principal is rewritten or reassigned. Live + conversation and epoch controls stay with the exact login that opened them. + Busy refusal, stale generation and backend review, the permanent fences and + per-store outcomes are unchanged. The `chat_retired` frame still goes to the + initiating login's capable connections; every other reader, another login's + devices included, already refuses the retired chat. + +Exact-principal-only deletion was rejected because it strands shared chats. +Creator-only deletion was rejected because a missing first login still strands +them and it needs another durable creator model. No request, receipt or +refusal shape changes; the admission semantics in +[the HTTP reference](../http-api.md#explicit-chat-deletion-additive-3230) do. + ## Compatibility and rejected alternatives This decision approves the explicit retention exception, not a shipped machine diff --git a/docs/http-api.md b/docs/http-api.md index 75b01c70a7..1d964b0e38 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -1362,12 +1362,20 @@ recorded owner; the same answer whichever), 409 `stale` (the backend or generation differs from `expected`), 409 `unsupported` (the chat's backend does not advertise and implement native removal) or 409 `busy` (a running or starting turn, queued follow-ups or unsettled live-conversation work; stop or finish it -first). A chat's recorded owner is its dialogue owner, its voice conversation's -principal or, since #3337 (additive), the authenticated principal whose typed -request created its backend session. A typed chat whose session already existed -before that binding (or that the host first saw on a resume) has no recorded -owner and stays `unavailable`; none is backfilled. Otherwise the chat is -retired and the answer is 200 with the SDK's +first). A chat's recorded owners are its dialogue owner, each voice +conversation's principal and, since #3337 (additive), the authenticated +principal whose typed request created its backend session. A typed chat whose +session already existed before that binding (or that the host first saw on a +resume) has no recorded owner and stays `unavailable`; none is backfilled. +Since #4138, any usable owner login is admitted when **every** recorded owner +is the same owner account: the caller's own login, or another owner login +proven by its current principal row or by the durable account the server stored +beside that record when it wrote it, which outlives the login's pruning. A +record of another account (an agent, an ambient or a system principal), a +pruned login with no stored account, or corrupt or contradictory evidence is +`unavailable`, for that chat only. Stored evidence never authorizes the caller, +which is still checked from its own current row at admission and again at +commit. Otherwise the chat is retired and the answer is 200 with the SDK's `ChatDeletionReceipt`: `operationId`, the terminal `generation`, the overall `status`, each selected store's outcome (`native` for a backend session, `dialogue`, `tasks`, `projections`, `drafts`) and `retained`, which always lists @@ -1375,6 +1383,8 @@ retired and the answer is 200 with the SDK's `offline_devices`. `status` is `removed` only when every selected store confirmed removal; `pending`, `partial` and `unknown` say cleanup is not confirmed, and repeating the same `operationId` retries it. A host restart also resumes it. +The operation stays the initiating login's: another login of the same account +that sends its `operationId` gets 404 `unavailable` and retries nothing. The handler re-checks the principal after its asynchronous steps and answers a revoked one with the guard's 401, disclosing nothing. A storage failure before a receipt exists is 500 `{ error: "CHAT_DELETION_FAILED", message }`, never a diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 059ade0a8f..a42312786c 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -872,6 +872,20 @@ answer as for a chat that does not exist. The session catalog's No request, receipt, frame or field shape changes, and paging and retention of undeleted chats are unchanged. This ships in a minor. +## Same-account chat deletion (additive, #4138) + +`POST /api/chat-deletions` ([HTTP](http-api.md#explicit-chat-deletion-additive-3230)) +now admits any usable owner login when every recorded owner of the chat proves +that same owner account, so a chat two owner logins used, by voice or by typing, +is deleted by either of them, also after the other login is pruned. A chat with +a record of another account, or with missing, corrupt or contradictory account +evidence, still refuses as `unavailable`. The operation, its receipt and its +retry key stay with the login that started it. Agent, ambient, system, revoked +and expired callers are still `unauthorized`. No request, receipt, refusal or +frame shape changes, and live conversation and epoch control is unchanged +([decision](decisions/chat-history-deletion.md#same-account-deletion--2026-11-17-4138)). +This ships in a minor. + ## Native history removal (additive, #3229) `BackendCapabilities.historyRemoval?` and the optional diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index d9dab2f18e..ea601fc80f 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -2856,7 +2856,8 @@ What stays exact: 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. + current, authorized login. Chat deletion by another login of the account + follows its own rule ([#4138](../integration-contract.md#same-account-chat-deletion-additive-4138)). - 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. diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 22e1f389f4..196fc59eb3 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -8,7 +8,7 @@ Approval supplies no automatic expiry, routine live cutoff or implementation release commitment. **Built (#3228):** the internal, content-free retirement ledger and gate -(`retireChat`, `packages/ui-server/src/ws/chat-lifecycle.ts:169-202`; +(`retireChat`, `packages/ui-server/src/ws/chat-lifecycle.ts:195-234`; migration `073_chat_lifecycle.sql`). It re-reads owner authority in the serialized writer, resolves the exact identity set from recorded dialogue owners, aliases and voice epochs, refuses unknown/foreign/stale/unsupported/busy @@ -60,10 +60,10 @@ The bridge offers the creator only on a new, non-host-work turn whose authorization is current (`const creator`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:143`). The write worker binds the creator only in the transaction that creates the session's row -(`upsertSession(row: SessionRow)`, `packages/ui-server/src/ws/session-catalog-writes.ts:169-178`). +(`upsertSession(row: SessionRow)`, `packages/ui-server/src/ws/session-catalog-writes.ts:170-182`). `resolveChat` counts the binding as one more ownership record beside dialogue owners and voice epochs, so a disagreement among them still refuses as ambiguous -(`const creator`, `packages/ui-server/src/ws/chat-lifecycle.ts:91-92`). A typed +(`const creator`, `packages/ui-server/src/ws/chat-lifecycle.ts:102-103`). A typed chat's owner can now delete it through `POST /api/chat-deletions`. A chat whose session existed before the binding still refuses as `unavailable`, and so does a native-only session the host first sees on a resume. A foreign principal gets @@ -94,7 +94,10 @@ for native layout and removal; browser clients invalidate their projections. There is no generic storage plugin, second dialogue store or replacement timeline. Only an authenticated owner may delete its own chat, with exact principal -ownership and current authorization at admission and asynchronous boundaries. +ownership and current authorization at admission and asynchronous boundaries +(narrowed by the [same-account amendment](../decisions/chat-history-deletion.md#same-account-deletion--2026-11-17-4138): +another login of the same owner account deletes a chat whose every ownership +record proves that account). Agent principals cannot delete history. Ambient authentication requires an explicit owner mapping; without one deletion is unavailable. Neither labels, history-read access nor speech grants authority. No cross-principal deletion @@ -198,9 +201,9 @@ must be tested through their installed runtime, not inferred from directory name `070_conversation_result_facts.sql` retain epochs, detailed JSON receipts (including submitted context), bounded result facts and independently consumed native/task/request identities. Content retention and identity retention differ - (`saveConversationTask`, `packages/ui-server/src/ws/conversation-storage.ts:37-77`). + (`saveConversationTask`, `packages/ui-server/src/ws/conversation-storage.ts:40-80`). Loading may return receipts/results even without a current provider session - (`loadConversation`, `packages/ui-server/src/ws/conversation-storage.ts:78-105`). + (`loadConversation`, `packages/ui-server/src/ws/conversation-storage.ts:81-108`). Clear receipt/result content while preserving replay refusal under a new lifecycle fence; do not cascade away consumed identities and then allow their reuse. - **Session projections.** `sessions` title and `034_session_labels.sql` label/source; diff --git a/packages/ui-server/migrations/091_chat_ownership_account.sql b/packages/ui-server/migrations/091_chat_ownership_account.sql new file mode 100644 index 0000000000..65cf059da5 --- /dev/null +++ b/packages/ui-server/migrations/091_chat_ownership_account.sql @@ -0,0 +1,26 @@ +-- A chat's deletion ownership keeps the account that owned it after the login +-- that wrote a record is pruned (#4138), as 089 did for its safety history +-- and dialogue owner. Explicit deletion admits any current owner login when +-- every ownership record of the chat proves that same account; a voice epoch +-- or a typed-creation binding whose login was pruned proved nothing, so a +-- chat two logins used became undeletable once either aged out. +-- +-- `principal_account` sits beside each record's `principal_id`. The server +-- writes it from the principal row when the record is written: 'owner' for an +-- owner login, NULL for a principal whose account is only itself (an agent, +-- an ambient identity, a system principal). `principal_id` stays the +-- attribution and is never rewritten. The account is evidence, not a +-- credential: the caller still has to be a current, authorized owner login, +-- and live epoch control stays with the exact login that opened it. +-- +-- Legacy rows gain an account only from verified evidence: a principal row +-- that still exists and is an owner login. A row whose principal is already +-- gone keeps NULL and stays unknown, so its chat keeps refusing deletion. +-- Nothing is owner by default. IN over a NULL principal_id is not true, so a +-- record without a principal stays NULL as well. +ALTER TABLE conversation_epochs ADD COLUMN principal_account TEXT; +ALTER TABLE chat_session_owners ADD COLUMN principal_account TEXT; +UPDATE conversation_epochs SET principal_account='owner' + WHERE principal_id IN (SELECT id FROM principals WHERE kind='owner'); +UPDATE chat_session_owners SET principal_account='owner' + WHERE principal_id IN (SELECT id FROM principals WHERE kind='owner'); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 2a2a4ce018..27d8b1b345 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -47,9 +47,8 @@ import { createApifyRoutes } from "./routes/apify.js"; import { createApifyHost } from "./apify/host.js"; import { createGithubToolsHost } from "./github/host.js"; import { createGithubDetails } from "./github/details.js"; -import { resolveChat } from "./ws/chat-lifecycle.js"; +import { chatOwnedBy, resolveChat } from "./ws/chat-lifecycle.js"; import { createGithubDetailRoutes } from "./routes/github-details.js"; -import { sameAccount } from "./middleware/account-partition.js"; import { createApifyPolicyEdits } from "./apify/settings.js"; import { apifyBudgetSource } from "./apify/budget-liability.js"; import { declaredContentRenderers } from "./brain/content-renderers.js"; @@ -1187,7 +1186,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.isPrincipalValid(principal), - owns: (principal, sessionId) => { const chat = resolveChat(db, { sessionId }); return !("refused" in chat) && sameAccount(db, chat.principalId, principal.id); }, + owns: (principal, sessionId) => { const chat = resolveChat(db, { sessionId }); return !("refused" in chat) && chatOwnedBy(db, chat, principal.id); }, retired: sessionId => host.catalog.chatRetired?.({ sessionId }) === true, history: async sessionId => { const stored = db.query("SELECT backend_id AS backendId FROM sessions WHERE id = ?").get(sessionId) as { backendId: string | null } | null; diff --git a/packages/ui-server/src/ws/chat-lifecycle.ts b/packages/ui-server/src/ws/chat-lifecycle.ts index dc8b306d65..5c2c63c3e0 100644 --- a/packages/ui-server/src/ws/chat-lifecycle.ts +++ b/packages/ui-server/src/ws/chat-lifecycle.ts @@ -7,6 +7,7 @@ */ import type { Database } from "bun:sqlite"; import { isUsablePrincipal, resolvePrincipal } from "../db/principals.js"; +import { sameAccount, type AccountRecord } from "../middleware/account-partition.js"; type RetiredKind = "session" | "dialogue_owner" | "conversation" | "task" | "request" | "native_task"; export const CHAT_STORES = ["native", "dialogue", "tasks", "projections", "drafts"] as const; @@ -65,47 +66,58 @@ export function nativeTaskRetired(db: Database, conversationId: string, epoch: n } interface Resolved { - id: string; kind: "session" | "provisional"; principalId: string; backendId: string | null; generation: number; + id: string; kind: "session" | "provisional"; backendId: string | null; generation: number; + /** + * Every deletion-relevant ownership record, each with the durable account + * the server stored beside its principal (#3962): never empty. Attribution + * only; a record never authorizes anyone (`chatOwnedBy` decides). + */ + owners: AccountRecord[]; identities: RetiredChatIdentities; } +type OwnerRow = { principal_id: string | null; principal_account: string | null }; /** * The exact current identity set of a chat, from verified ownership records * only: canonical dialogue owners (with every alias an earlier adoption * joined), recorded voice conversation epochs and the typed session-creation - * binding (#3337). A chat with no such record, or with records naming - * different principals, has unknown ownership. + * binding (#3337). A chat with no such record has unknown ownership. Records + * naming different logins are returned as they are; whether they are one + * account is `chatOwnedBy`'s question (#4138). */ export function resolveChat(db: Database, target: ChatTarget): Resolved | { refused: "unavailable" | "stale" } { - const owners = new Set(), conversations = new Set(), principals = new Set(); + const owners = new Set(), conversations = new Set(), records = new Map(); + // A record without a principal is unknown ownership, kept so it refuses. + const record = (row: OwnerRow) => { records.set(JSON.stringify([row.principal_id, row.principal_account]), { principalId: row.principal_id, account: row.principal_account }); }; let id: string, kind: Resolved["kind"], generation = 1, sessionId: string | null = null; if ("sessionId" in target) { if (!target.sessionId || target.sessionId.length > MAX_ID) return { refused: "unavailable" }; id = sessionId = target.sessionId; kind = "session"; - const owner = db.query("SELECT id,principal_id,generation FROM dialogue_owners WHERE session_id=?").get(sessionId) as { id: string; principal_id: string; generation: number } | null; - if (owner) { owners.add(owner.id); principals.add(owner.principal_id); generation = owner.generation; } - for (const row of db.query("SELECT id,principal_id FROM conversation_epochs WHERE session_id=?").all(sessionId) as { id: string; principal_id: string }[]) { - conversations.add(row.id); principals.add(row.principal_id); + const owner = db.query("SELECT id,principal_id,principal_account,generation FROM dialogue_owners WHERE session_id=?").get(sessionId) as OwnerRow & { id: string; generation: number } | null; + if (owner) { owners.add(owner.id); record(owner); generation = owner.generation; } + for (const row of db.query("SELECT id,principal_id,principal_account FROM conversation_epochs WHERE session_id=?").all(sessionId) as (OwnerRow & { id: string })[]) { + conversations.add(row.id); record(row); } // The principal whose typed request created the session (#3337). It joins - // the other records: a disagreement is still ambiguous ownership. - const creator = db.query("SELECT principal_id FROM chat_session_owners WHERE session_id=?").get(sessionId) as { principal_id: string } | null; - if (creator) principals.add(creator.principal_id); + // the other records: every one of them must be the caller's account. + const creator = db.query("SELECT principal_id,principal_account FROM chat_session_owners WHERE session_id=?").get(sessionId) as OwnerRow | null; + if (creator) record(creator); } else { if (!target.ownerId || target.ownerId.length > MAX_ID) return { refused: "unavailable" }; - const owner = db.query("SELECT id,principal_id,session_id,generation FROM dialogue_owners WHERE id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=?),?)") - .get(target.ownerId, target.ownerId) as { id: string; principal_id: string; session_id: string | null; generation: number } | null; + const owner = db.query("SELECT id,principal_id,principal_account,session_id,generation FROM dialogue_owners WHERE id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=?),?)") + .get(target.ownerId, target.ownerId) as OwnerRow & { id: string; session_id: string | null; generation: number } | null; if (!owner) { // A typed first turn has a host-minted safety/history owner before a - // native session exists. No dialogue or agent turn is fabricated. - const retained=db.query("SELECT DISTINCT principal_id,generation FROM safety_collections WHERE history_owner_id=? AND session_id IS NULL").all(target.ownerId) as {principal_id:string|null;generation:string}[]; - if(retained.length!==1||!retained[0]!.principal_id)return {refused:"unavailable"}; + // native session exists. No dialogue or agent turn is fabricated. Each + // collection is one ownership record; they must share one generation. + const retained=db.query("SELECT DISTINCT principal_id,principal_account,generation FROM safety_collections WHERE history_owner_id=? AND session_id IS NULL").all(target.ownerId) as (OwnerRow&{generation:string})[]; + if(!retained.length||new Set(retained.map(row=>row.generation)).size!==1)return {refused:"unavailable"}; id=target.ownerId;kind="provisional";generation=Number(retained[0]!.generation); - owners.add(target.ownerId);principals.add(retained[0]!.principal_id!); + owners.add(target.ownerId);for(const row of retained)record(row); } else { // Adoption made this a backend session's chat: the reviewed target changed. if (owner.session_id || owner.id !== target.ownerId) return { refused: "stale" }; id = owner.id; kind = "provisional"; generation = owner.generation; - owners.add(owner.id); principals.add(owner.principal_id); + owners.add(owner.id); record(owner); } } for (const owner of [...owners]) { @@ -113,10 +125,10 @@ export function resolveChat(db: Database, target: ChatTarget): Resolved | { refu for (const row of db.query("SELECT id FROM dialogue_conversations WHERE owner_id=?").all(owner) as { id: string }[]) conversations.add(row.id); } for (const conversation of conversations) { - const row = db.query("SELECT principal_id FROM conversation_epochs WHERE id=?").get(conversation) as { principal_id: string } | null; - if (row) principals.add(row.principal_id); + const row = db.query("SELECT principal_id,principal_account FROM conversation_epochs WHERE id=?").get(conversation) as OwnerRow | null; + if (row) record(row); } - if (principals.size !== 1) return { refused: "unavailable" }; + if (!records.size) return { refused: "unavailable" }; const tasks: string[] = [], requests: string[] = [], nativeTasks: string[] = []; for (const conversation of conversations) { for (const row of db.query("SELECT epoch,native_handle,task_id,request_id FROM conversation_tasks WHERE conversation_id=? ORDER BY rowid").all(conversation) as { epoch: number; native_handle: string; task_id: string; request_id: string }[]) { @@ -124,10 +136,24 @@ export function resolveChat(db: Database, target: ChatTarget): Resolved | { refu } } const backend = sessionId ? db.query("SELECT backend_id FROM sessions WHERE id=?").get(sessionId) as { backend_id: string | null } | null : null; - return { id, kind, principalId: [...principals][0]!, backendId: backend?.backend_id ?? null, generation, identities: { + return { id, kind, owners: [...records.values()], backendId: backend?.backend_id ?? null, generation, identities: { sessions: sessionId ? [sessionId] : [], dialogueOwners: [...owners].sort(), conversations: [...conversations].sort(), tasks, requests, nativeTasks } }; } +/** + * Whether every ownership record of a resolved chat is the caller's account + * (#4138): the caller's own login, or another login of the same durable + * account, proven by that record's current principal row or by the account + * stored beside it. Missing, corrupt, contradictory or mixed-account evidence + * refuses. The caller proves its account only by its own current row, so a + * stored account is never a credential; whether the caller may act at all is + * `authorizedOwner`'s question, asked separately. Today only owner logins + * share an account: agent, ambient and system records match only themselves. + */ +export function chatOwnedBy(db: Database, chat: Pick, principalId: string): boolean { + return chat.owners.length > 0 && chat.owners.every(owner => sameAccount(db, owner, principalId)); +} + /** The caller alone: a usable owner principal. Ambient callers have no owner mapping, agents never delete. */ export function authorizedOwner(db: Database, principalId: string, at: number): boolean { const principal = resolvePrincipal(db, principalId); @@ -173,7 +199,8 @@ export function retireChat(db: Database, input: RetireChatInput): RetireChatResu const previous = db.query("SELECT id,principal_id,operation_id,generation,backend_id FROM chat_lifecycles WHERE operation_id=?") .get(input.operationId) as { id: string; principal_id: string; operation_id: string; generation: number; backend_id: string | null } | null; if (previous) { - // The same key for the same owner and target is the same operation. + // The same key for the same initiating login and target is the same + // operation; another login of the account never adopts its handle. return previous.principal_id === input.principalId && previous.id === targetId(input.target) ? receipt(db, previous) : { status: "refused", reason: "unavailable" }; } @@ -181,12 +208,12 @@ export function retireChat(db: Database, input: RetireChatInput): RetireChatResu return { status: "refused", reason: "unavailable" }; const chat = resolveChat(db, input.target); if ("refused" in chat) return { status: "refused", reason: chat.refused === "stale" && ownsAlias(db, input) ? "stale" : "unavailable" }; - if (chat.principalId !== input.principalId) return { status: "refused", reason: "unavailable" }; + if (!chatOwnedBy(db, chat, input.principalId)) return { status: "refused", reason: "unavailable" }; if (chat.backendId !== input.expected.backendId || chat.generation !== input.expected.generation) return { status: "refused", reason: "stale" }; if (chat.backendId !== null && !input.removableBackends.includes(chat.backendId)) return { status: "refused", reason: "unsupported" }; const generation = chat.generation + 1; db.prepare("INSERT INTO chat_lifecycles(id,kind,principal_id,backend_id,generation,operation_id,retired_at) VALUES(?,?,?,?,?,?,?)") - .run(chat.id, chat.kind, chat.principalId, chat.backendId, generation, input.operationId, input.at); + .run(chat.id, chat.kind, input.principalId, chat.backendId, generation, input.operationId, input.at); const fence = db.prepare("INSERT OR IGNORE INTO chat_retired_identities(kind,id,lifecycle_id) VALUES(?,?,?)"); const kinds: [RetiredKind, string[]][] = [["session", chat.identities.sessions], ["dialogue_owner", chat.identities.dialogueOwners], ["conversation", chat.identities.conversations], ["task", chat.identities.tasks], ["request", chat.identities.requests], ["native_task", chat.identities.nativeTasks]]; @@ -205,12 +232,12 @@ export function retireChat(db: Database, input: RetireChatInput): RetireChatResu return receipt(db, { id: chat.id, operation_id: input.operationId, generation, backend_id: chat.backendId }); }).immediate(); } -/** Whether a stale provisional target is the caller's own; otherwise staleness would reveal it. */ +/** Whether a stale provisional target is the caller's account's own; otherwise staleness would reveal it. */ function ownsAlias(db: Database, input: RetireChatInput): boolean { if (!("ownerId" in input.target)) return false; - const row = db.query("SELECT principal_id FROM dialogue_owners WHERE id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=?),?)") - .get(input.target.ownerId, input.target.ownerId) as { principal_id: string } | null; - return row?.principal_id === input.principalId; + const row = db.query("SELECT principal_id,principal_account FROM dialogue_owners WHERE id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=?),?)") + .get(input.target.ownerId, input.target.ownerId) as OwnerRow | null; + return !!row && chatOwnedBy(db, { owners: [{ principalId: row.principal_id, account: row.principal_account }] }, input.principalId); } /** The retirement's current non-content outcome for its owner, or null. */ diff --git a/packages/ui-server/src/ws/conversation-storage.ts b/packages/ui-server/src/ws/conversation-storage.ts index a061ead00f..5a846dfba7 100644 --- a/packages/ui-server/src/ws/conversation-storage.ts +++ b/packages/ui-server/src/ws/conversation-storage.ts @@ -2,6 +2,7 @@ import type { Database } from "bun:sqlite"; import { CONVERSATION_LIMITS, type ConversationWorkReceipt } from "@schlessera/brain-ui-sdk/protocol"; import { conversationWorkReceiptSchema } from "@schlessera/brain-ui-sdk/schemas"; +import { principalAccount } from "../middleware/account-partition.js"; import { assertLive, isRetired, nativeTaskRetired, ChatRetiredError } from "./chat-lifecycle.js"; /** UTF-16 characters of completed result context per conversation; oldest admitted goes first. */ @@ -24,9 +25,11 @@ export function saveConversationEpoch(db: Database, state: StoredConversationEpo assertLive(db, [["conversation", state.id], ["session", state.sessionId]]); const old = db.query("SELECT principal_id FROM conversation_epochs WHERE id=?").get(state.id) as { principal_id: string } | null; if (old && old.principal_id !== state.principalId) throw new Error("Conversation ownership mismatch"); - db.prepare(`INSERT INTO conversation_epochs(id,principal_id,epoch,session_id,agent_provider_id,updated_at) VALUES(?,?,?,?,?,?) + // The durable account is read from the principal's own row, once (#4138): + // deletion evidence after the login is pruned. A later save never rewrites it. + db.prepare(`INSERT INTO conversation_epochs(id,principal_id,principal_account,epoch,session_id,agent_provider_id,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET epoch=MAX(epoch,excluded.epoch),session_id=COALESCE(excluded.session_id,session_id),updated_at=excluded.updated_at`) - .run(state.id, state.principalId, state.epoch, state.sessionId ?? null, state.agentProviderId ?? null, Date.now()); + .run(state.id, state.principalId, principalAccount(db, state.principalId), state.epoch, state.sessionId ?? null, state.agentProviderId ?? null, Date.now()); db.exec(`DELETE FROM conversation_epochs WHERE id IN (SELECT id FROM conversation_epochs ORDER BY updated_at DESC LIMIT -1 OFFSET 64) AND id NOT IN (SELECT conversation_id FROM conversation_tasks WHERE receipt IS NOT NULL AND (json_extract(receipt,'$.state') IN ('queued','running') OR json_extract(receipt,'$.delivery')='pending'))`); diff --git a/packages/ui-server/src/ws/session-catalog-writes.ts b/packages/ui-server/src/ws/session-catalog-writes.ts index 1905d609c1..d155e567d5 100644 --- a/packages/ui-server/src/ws/session-catalog-writes.ts +++ b/packages/ui-server/src/ws/session-catalog-writes.ts @@ -30,6 +30,7 @@ import { saveTurnFailure, type RecordedTurnFailure } from "./turn-failures.js"; import { saveConversationEpoch, saveConversationTask } from "./conversation-storage.js"; import { assertLive, recordChatCleanup, retireChat, type ChatStore, type ChatStoreOutcome, type RetireChatInput } from "./chat-lifecycle.js"; import { cleanChatStore, type HostChatStore } from "./chat-store-cleanup.js"; +import { principalAccount } from "../middleware/account-partition.js"; export const url = import.meta.url; export const UPSERT_SESSION_SQL = `INSERT INTO sessions (id, title, created_at, last_active_at, total_cost_usd, num_turns, provider_id, backend_id) @@ -174,7 +175,8 @@ export function setup(db: Database, options: SessionCatalogWriteOptions = {}): W const created = !db.query("SELECT 1 FROM sessions WHERE id=?").get(row.id); db.prepare(UPSERT_SESSION_SQL).run(row.id, row.title, row.at, row.at, row.costUsd, row.turns, row.providerId, row.backendId); if (created) { - db.prepare("INSERT OR IGNORE INTO chat_session_owners(session_id,principal_id,created_at) VALUES(?,?,?)").run(row.id, owner, row.at); + // Its durable account from the creator's own row (#4138), deletion evidence once the login is pruned. + db.prepare("INSERT OR IGNORE INTO chat_session_owners(session_id,principal_id,principal_account,created_at) VALUES(?,?,?,?)").run(row.id, owner, principalAccount(db, owner), row.at); safetyCatalogCreated(db,row.id,owner,row.creatorTurnId); } })(); diff --git a/packages/ui-server/src/ws/session-catalog.ts b/packages/ui-server/src/ws/session-catalog.ts index 3f9921dfdd..d3fc0e3f61 100644 --- a/packages/ui-server/src/ws/session-catalog.ts +++ b/packages/ui-server/src/ws/session-catalog.ts @@ -29,7 +29,7 @@ import { import { loadConversation } from "./conversation-storage.js"; import type { HostChatStore } from "./chat-store-cleanup.js"; -import { authorizedOwner, chatRetirement, isRetired, resolveChat, unfinishedChatRetirements, type ChatRetirementStatus, type ChatStore, type ChatStoreOutcome, type ChatTarget, type RetireChatInput, type RetireChatResult, type RetiredChatIdentities } from "./chat-lifecycle.js"; +import { authorizedOwner, chatOwnedBy, chatRetirement, isRetired, resolveChat, unfinishedChatRetirements, type ChatRetirementStatus, type ChatStore, type ChatStoreOutcome, type ChatTarget, type RetireChatInput, type RetireChatResult, type RetiredChatIdentities } from "./chat-lifecycle.js"; import * as retries from "./retry-requests.js"; import * as work from "./session-work.js"; import { attachTurnFailures, type RecordedTurnFailure } from "./turn-failures.js"; @@ -322,7 +322,7 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi await tail; if (!authorizedOwner(db(), input.principalId, input.at)) return { status: "refused", reason: "unauthorized" }; const preview = resolveChat(db(), input.target); - if ("refused" in preview || preview.principalId !== input.principalId) return submit("retireChat", input); + if ("refused" in preview || !chatOwnedBy(db(), preview, input.principalId)) return submit("retireChat", input); if (busy(preview.identities)) return { status: "refused", reason: "busy" }; const result = await submit("retireChat", input); if (result.status === "retired") { diff --git a/packages/ui-server/tests/chat-deletion.test.ts b/packages/ui-server/tests/chat-deletion.test.ts index b5c02dd585..32bc16c4f3 100644 --- a/packages/ui-server/tests/chat-deletion.test.ts +++ b/packages/ui-server/tests/chat-deletion.test.ts @@ -107,12 +107,14 @@ async function fixture() { const path = join(root, "ui.db"); const host = open(path); const owner = createPrincipal(host.db, { authMethod: "password", label: "Odysseus phone", ttlSeconds: 86_400 }).id; - const other = createPrincipal(host.db, { authMethod: "passkey", label: "Penelope tablet", ttlSeconds: 86_400 }).id; + // Every owner sign-in is the one owner account (#4138); another person is another account. + const second = createPrincipal(host.db, { authMethod: "passkey", label: "Odysseus tablet", ttlSeconds: 86_400 }).id; + const other = resolveAmbientPrincipal(host.db, "proxy", "penelope", "Penelope").id; const agent = createPrincipal(host.db, { authMethod: "delegated", label: "Mentor agent", createdBy: owner, ttlSeconds: 86_400 }).id; await seedChat(host, owner, "voyage", "ithaca", MARKER); await seedChat(host, other, "aeaea", "circe", CONTROL); createDraftStore(host.db).save(owner, "unbound-draft", { ifMatch: 0, idempotencyKey: "unbound", sessionId: null, text: UNBOUND, attachmentIds: [] }); - return { root, path, host, owner, other, agent }; + return { root, path, host, owner, second, other, agent }; } function deletionFor(catalog: SessionCatalog, native: AgentBackend, overrides: Partial = {}) { @@ -177,7 +179,8 @@ test("unsupported backends, busy work and other principals refuse before anythin expect(await busy.deletion.delete(voyage(f.owner)), "BUSY_REFUSES").toEqual({ status: "refused", reason: "busy" }); const { deletion, retired } = deletionFor(catalog, backend([])); expect(await deletion.delete(voyage(f.agent)), "AGENT_REFUSES").toEqual({ status: "refused", reason: "unauthorized" }); - expect(await deletion.delete(voyage(f.other)), "FOREIGN_REFUSES_AS_ABSENT").toEqual({ status: "refused", reason: "unavailable" }); + expect(await deletion.delete({ ...voyage(f.owner, "delete-aeaea"), target: { sessionId: "aeaea" } }), "FOREIGN_REFUSES_AS_ABSENT").toEqual({ status: "refused", reason: "unavailable" }); + expect(await deletion.delete(voyage(f.other)), "ANOTHER_ACCOUNT_IS_UNAUTHORIZED").toEqual({ status: "refused", reason: "unauthorized" }); expect(retired, "NOTHING_RETIRED_LIVE").toEqual([]); expect(db.query("SELECT COUNT(*) AS n FROM chat_lifecycles").get()).toEqual({ n: 0 }); expect(holding(db, MARKER).length).toBeGreaterThanOrEqual(15); @@ -218,6 +221,36 @@ test("a failed store stays partial or unknown, and restart reconciliation comple } finally { await (reopened ?? f.host).close(); } }); +test("another owner login deletes a chat it continued: honest partial outcomes, retries and reconciliation stay under its operation", async () => { + const f = await fixture(); + let reopened: ReturnType | undefined; + try { + const { db, catalog } = f.host; + // The tablet continued the phone's chat by voice: two logins of one account own its records. + await catalog.saveConversationEpoch!({ id: "telemachus", principalId: f.second, epoch: 1, sessionId: "voyage" }); + await catalog.settled!(); + db.exec("CREATE TRIGGER hold_dialogue BEFORE DELETE ON dialogue_records BEGIN SELECT RAISE(ABORT,'Ithaca dialogue cleanup interrupted'); END"); + const { deletion, retired } = deletionFor(catalog, backend(["partial"])); + const first = await deletion.delete(voyage(f.second)); + expect(first, "SECOND_LOGIN_PARTIAL_IS_HONEST").toEqual({ status: "retired", receipt: { operationId: "delete-voyage", generation: 2, status: "partial", + stores: { dialogue: "partial", drafts: "removed", native: "partial", projections: "removed", tasks: "removed" }, retained: RETAINED } }); + expect(retired.map(r => r.principalId), "SECOND_LOGIN_RETIRES_LIVE_HOLDERS").toEqual([f.second]); + expect(holding(db, MARKER), "ONLY_THE_FAILED_STORES_HOLD_TEXT").toEqual(["dialogue_records.payload"]); + // The operation is the tablet's: the phone neither reads nor retries it. + expect(await deletion.read("delete-voyage", f.owner), "RECEIPT_STAYS_ITS_INITIATORS").toBeNull(); + expect(await deletion.delete(voyage(f.owner)), "HANDLE_STAYS_ITS_INITIATORS").toEqual({ status: "refused", reason: "unavailable" }); + db.exec("DROP TRIGGER hold_dialogue"); + await f.host.close(); + reopened = open(f.path); + const resumed = deletionFor(reopened.catalog, backend(["removed"])); + await resumed.deletion.reconcile(); + expect(resumed.retired.map(r => r.principalId), "RECONCILED_UNDER_THE_INITIATOR").toEqual([f.second]); + expect(await resumed.deletion.read("delete-voyage", f.second), "SECOND_LOGIN_READS_COMPLETION").toMatchObject({ status: "removed" }); + expect(holding(reopened.db, MARKER), "RECONCILED_NOTHING_REMAINS").toEqual([]); + expect(holding(reopened.db, CONTROL).length, "CONTROL_CHAT_INTACT").toBeGreaterThanOrEqual(15); + } finally { await (reopened ?? f.host).close(); } +}); + function routesApp(db: Database, ...routes: Hono[]) { const app = new Hono(); app.use("*", async (c, next) => { const id = c.req.header("x-odysseus-principal"); const p = id ? resolvePrincipal(db, id) : null; if (p) c.set("principal", p); await next(); }); @@ -242,7 +275,9 @@ test("the endpoint admits only the authenticated owner and answers with content- const response = await post(app, principal, requestBody(`by-${principal}`)); refusals.push([response.status, (await response.json()).reason]); } - expect(refusals, "AGENT_AMBIENT_FOREIGN_REFUSED").toEqual([[403, "unauthorized"], [403, "unauthorized"], [404, "unavailable"]]); + const foreign = await post(app, f.owner, { ...requestBody("by-owner-for-aeaea"), target: { sessionId: "aeaea" } }); + refusals.push([foreign.status, (await foreign.json()).reason]); + expect(refusals, "AGENT_AMBIENT_FOREIGN_REFUSED").toEqual([[403, "unauthorized"], [403, "unauthorized"], [403, "unauthorized"], [404, "unavailable"]]); const stale = await post(app, f.owner, { ...requestBody(), expected: { backendId: "claude", generation: 5 } }); expect([stale.status, (await stale.json()).reason]).toEqual([409, "stale"]); expect(db.query("SELECT COUNT(*) AS n FROM chat_lifecycles").get()).toEqual({ n: 0 }); @@ -358,15 +393,16 @@ test("the read answers the caller's receipt, and one byte-identical not_admitted expect([MARKER, '"voyage"', "ithaca", "claude", "sessionId"].filter(s => ownText.includes(s)), "RECEIPT_READ_IS_CONTENT_FREE").toEqual([]); // A refused attempt records nothing to read. - expect((await post(app, f.other, requestBody("penelope-attempt"))).status).toBe(404); + expect((await post(app, f.owner, { ...requestBody("penelope-attempt"), target: { sessionId: "aeaea" } })).status).toBe(404); const answers: Record = {}; - for (const [label, principal, operation] of [["foreign", f.other, "delete-voyage"], ["agent", f.agent, "delete-voyage"], - ["ambient", ambient, "delete-voyage"], ["refused", f.other, "penelope-attempt"], ["unknown", f.owner, "never-sent"]] as const) { + // The account's other login does not read this login's operation (#4138). + for (const [label, principal, operation] of [["second login", f.second, "delete-voyage"], ["foreign", f.other, "delete-voyage"], ["agent", f.agent, "delete-voyage"], + ["ambient", ambient, "delete-voyage"], ["refused", f.owner, "penelope-attempt"], ["unknown", f.owner, "never-sent"]] as const) { const response = await read(app, principal, operation); answers[label] = `${response.status} ${response.headers.get("cache-control")} ${await response.text()}`; } const miss = `404 no-store ${missBytes}`; - expect(answers, "EVERY_MISS_IS_BYTE_IDENTICAL").toEqual({ foreign: miss, agent: miss, ambient: miss, refused: miss, unknown: miss }); + expect(answers, "EVERY_MISS_IS_BYTE_IDENTICAL").toEqual({ "second login": miss, foreign: miss, agent: miss, ambient: miss, refused: miss, unknown: miss }); expect({ retireChat: calls.retireChat, cleanChatStore: calls.cleanChatStore, removals: removals.length }, "READS_STARTED_NO_CLEANUP") .toEqual({ retireChat: 2, cleanChatStore: 4, removals: 1 }); } finally { await f.host.close(); } diff --git a/packages/ui-server/tests/chat-lifecycle.test.ts b/packages/ui-server/tests/chat-lifecycle.test.ts index 1e9c7b542b..5739789e12 100644 --- a/packages/ui-server/tests/chat-lifecycle.test.ts +++ b/packages/ui-server/tests/chat-lifecycle.test.ts @@ -9,7 +9,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import type { ConversationWorkReceipt, DialogueEvidence } from "@schlessera/brain-ui-sdk/protocol"; import { createUiDb } from "../src/db/client.js"; -import { createPrincipal, revokePrincipal } from "../src/db/principals.js"; +import { createPrincipal, resolveAmbientPrincipal, revokePrincipal } from "../src/db/principals.js"; import { openSqliteWriter } from "../src/db/write-worker.js"; import { createOffloopActivityStore } from "../src/activity/store-writes.js"; import { createSessionCatalog, type SessionCatalog } from "../src/ws/session-catalog.js"; @@ -79,11 +79,13 @@ async function fixture() { const path = join(root, "ui.db"); const host = open(path); const owner = createPrincipal(host.db, { authMethod: "password", label: "Odysseus phone", ttlSeconds: 86_400 }).id; - const other = createPrincipal(host.db, { authMethod: "passkey", label: "Penelope tablet", ttlSeconds: 86_400 }).id; + // Every owner sign-in is the one owner account (#4138); another person is another account. + const second = createPrincipal(host.db, { authMethod: "passkey", label: "Odysseus tablet", ttlSeconds: 86_400 }).id; + const other = resolveAmbientPrincipal(host.db, "proxy", "penelope", "Penelope").id; const agent = createPrincipal(host.db, { authMethod: "delegated", label: "Mentor agent", createdBy: owner, ttlSeconds: 86_400 }).id; await seedChat(host.catalog, owner, "voyage", "ithaca", MARKER); await seedChat(host.catalog, other, "aeaea", "circe", CONTROL); - return { root, path, host, owner, other, agent }; + return { root, path, host, owner, second, other, agent }; } async function seedChat(catalog: SessionCatalog, principalId: string, sessionId: string, conversationId: string, text: string) { catalog.persistSessionStub(sessionId, "Plan the voyage home", null, "claude"); @@ -113,11 +115,12 @@ test("unauthorized, foreign, unknown, stale, unsupported and busy chats refuse b let consulted = 0; const busyProbe = (identities: RetiredChatIdentities) => { consulted++; return identities.conversations.includes("ithaca"); }; expect(await catalog.retireChat!(request(f.agent), idle), "AGENT_CANNOT_RETIRE").toEqual({ status: "refused", reason: "unauthorized" }); - // A foreign owner and a target that does not exist receive the same answer. - const foreign = await catalog.retireChat!(request(f.other), busyProbe); - const missing = await catalog.retireChat!(request(f.other, { target: { sessionId: "nowhere" } }), busyProbe); + // Another account's chat and a target that does not exist receive the same answer. + const foreign = await catalog.retireChat!(request(f.owner, { target: { sessionId: "aeaea" } }), busyProbe); + const missing = await catalog.retireChat!(request(f.owner, { target: { sessionId: "nowhere" } }), busyProbe); expect(foreign, "FOREIGN_REFUSAL_LEAKS_NOTHING").toEqual({ status: "refused", reason: "unavailable" }); expect(missing).toEqual(foreign); + expect(await catalog.retireChat!(request(f.other), busyProbe), "ANOTHER_ACCOUNT_CANNOT_RETIRE").toEqual({ status: "refused", reason: "unauthorized" }); expect(consulted, "BUSY_NOT_ASKED_FOR_FOREIGN_CHAT").toBe(0); // A typed native-only chat with no recorded owner: ownership is never guessed. catalog.persistSessionStub("scheria", "Ask the Phaeacians for a ship", null, "claude"); @@ -153,6 +156,32 @@ test("revocation while admission waits on the writer refuses at commit", async ( } finally { await f.host.close(); } }); +for (const change of ["revocation", "foreign epoch", "corrupt evidence"] as const) test(`another owner login's admission rechecks ${change} at commit`, async () => { + const f = await fixture(); + try { + const { catalog } = f.host; + // The second login continued the chat by voice: two logins of one account own its records (#4138). + await catalog.saveConversationEpoch!({ id: "telemachus", principalId: f.second, epoch: 1, sessionId: "voyage" }); + await catalog.settled!(); + expect(await catalog.retireChat!(request(f.second), () => true), "SECOND_LOGIN_BUSY_REFUSES").toEqual({ status: "refused", reason: "busy" }); + await f.host.hold(); + const submitted = posted("retireChat"); + const pending = catalog.retireChat!(request(f.second), idle); + // The preflight admitted it; the change lands before the writer takes its turn. + await submitted; + const other = new Database(f.path); other.exec("PRAGMA busy_timeout = 5000"); + try { + if (change === "revocation") revokePrincipal(other, f.second, Date.now()); + else if (change === "foreign epoch") other.query("INSERT INTO conversation_epochs(id,principal_id,principal_account,epoch,session_id,updated_at) VALUES('mentor',?,NULL,1,'voyage',0)").run(f.agent); + else other.query("UPDATE conversation_epochs SET principal_account='admiral' WHERE id='telemachus'").run(); + } finally { other.close(); } + f.host.release(); + expect(await pending, `COMMIT_RECHECKS_${change.toUpperCase().replace(" ", "_")}`).toEqual({ status: "refused", reason: change === "revocation" ? "unauthorized" : "unavailable" }); + expect(fences(f.host.db)).toBe(0); + expect(await readable(catalog, f.owner, "voyage")).toEqual([MARKER]); + } finally { await f.host.close(); } +}); + test("retirement fences every identity, refuses late writes and keeps unrelated chats and accounting", async () => { const f = await fixture(); try { @@ -198,10 +227,11 @@ test("retirement fences every identity, refuses late writes and keeps unrelated expect(db.query("SELECT id,total_cost_usd,num_turns FROM sessions ORDER BY id").all(), "ACCOUNTING_UNCHANGED").toEqual(cost); // Retirement is not deletion: content stays for its owners to remove, and nothing claims completion. expect(db.query("SELECT COUNT(*) AS n FROM dialogue_records WHERE payload LIKE ?").get(`%${MARKER}%`)).toEqual({ n: 1 }); - // The same key is the same operation; a new key or another principal learns nothing. + // The same key is the same operation; a new key or another login of the account learns nothing. expect(await catalog.retireChat!(request(f.owner), idle)).toEqual(result); expect(await catalog.retireChat!(request(f.owner, { operationId: "retire-again" }), idle)).toEqual({ status: "refused", reason: "unavailable" }); - expect(await catalog.retireChat!(request(f.other), idle)).toEqual({ status: "refused", reason: "unavailable" }); + expect(await catalog.retireChat!(request(f.second), idle), "OPERATION_STAYS_ITS_INITIATORS").toEqual({ status: "refused", reason: "unavailable" }); + expect(await catalog.chatRetirement!("retire-voyage", f.second)).toBeNull(); expect(await catalog.chatRetirement!("retire-voyage", f.other)).toBeNull(); // Cleanup outcomes are durable and honest: only every store confirming removal completes. expect(await catalog.recordChatCleanup!("voyage", "native", "partial")).toBe("partial"); @@ -299,12 +329,16 @@ test("a provisional chat retires by its owner identity without a native store", expect(await settle(catalog.recordChatCleanup!("ogygia", "native", "removed"))).toContain("not selected"); expect(await settle(catalog.dialogueBind!("ogygia", f.owner, "voyage"))).toContain("retired"); expect(await catalog.dialogueRead!(f.owner, { ownerId: "ogygia" })).toBeNull(); - // An adopted provisional ID is now the session's chat: the reviewed target is stale, for its owner only. + // An adopted provisional ID is now the session's chat: the reviewed target is stale, for its owner account only. await catalog.dialogueOpen!({ conversationId: "calypso", principalId: f.owner, epoch: 1, providerId: "gemini-live" }); await catalog.dialogueBind!("calypso", f.owner, "voyage"); const adopted = request(f.owner, { operationId: "retire-calypso", target: { ownerId: "calypso" }, expected: { backendId: null, generation: 1 } }); expect(await catalog.retireChat!(adopted, idle)).toEqual({ status: "refused", reason: "stale" }); - expect(await catalog.retireChat!({ ...adopted, principalId: f.other }, idle)).toEqual({ status: "refused", reason: "unavailable" }); + expect(await catalog.retireChat!({ ...adopted, principalId: f.second }, idle), "STALE_FOR_THE_ACCOUNTS_OTHER_LOGIN").toEqual({ status: "refused", reason: "stale" }); + // A provisional owner of another account is unavailable to an owner login, never stale. + await catalog.dialogueOpen!({ conversationId: "scylla", principalId: f.other, epoch: 1, providerId: "gemini-live" }); + await catalog.dialogueBind!("scylla", f.other, "aeaea"); + expect(await catalog.retireChat!({ ...adopted, operationId: "retire-scylla", target: { ownerId: "scylla" } }, idle), "STALE_NEVER_REVEALS_ANOTHER_ACCOUNT").toEqual({ status: "refused", reason: "unavailable" }); } finally { await f.host.close(); } }); diff --git a/packages/ui-server/tests/chat-session-owner.test.ts b/packages/ui-server/tests/chat-session-owner.test.ts index bbb717b834..1421ce3832 100644 --- a/packages/ui-server/tests/chat-session-owner.test.ts +++ b/packages/ui-server/tests/chat-session-owner.test.ts @@ -18,7 +18,7 @@ import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; import type { AppEnv } from "../src/app-env.js"; import { createStaticBackendRegistry } from "../src/agent/backend.js"; import { createUiDb } from "../src/db/client.js"; -import { createPrincipal, isUsablePrincipal, resolvePrincipal } from "../src/db/principals.js"; +import { createPrincipal, isUsablePrincipal, resolveAmbientPrincipal, resolvePrincipal } from "../src/db/principals.js"; import { openSqliteWriter } from "../src/db/write-worker.js"; import { createOffloopActivityStore } from "../src/activity/store-writes.js"; import type { WSContext } from "../src/ws/clients.js"; @@ -62,7 +62,9 @@ function world() { const host = new WsHost({ registry: createStaticBackendRegistry([backend], backend.id), catalog, isPrincipalValid: () => true, isPrincipalAuthorized: id => { const current = resolvePrincipal(db, id); return !!current && isUsablePrincipal(current, Date.now()); } }); const owner = resolvePrincipal(db, createPrincipal(db, { authMethod: "password", label: "Odysseus phone", ttlSeconds: 86_400 }).id)!; - const other = createPrincipal(db, { authMethod: "passkey", label: "Penelope tablet", ttlSeconds: 86_400 }).id; + // Every owner sign-in is the one owner account (#4138); another person is another account. + const second = createPrincipal(db, { authMethod: "passkey", label: "Odysseus tablet", ttlSeconds: 86_400 }).id; + const other = resolveAmbientPrincipal(db, "proxy", "penelope", "Penelope").id; const agent = createPrincipal(db, { authMethod: "delegated", label: "Mentor agent", createdBy: owner.id, ttlSeconds: 86_400 }).id; host.chatDeletion = createChatDeletion({ catalog, backends: async () => [backend], busy: identities => host.chatBusy(identities), retired: (principalId, retirement) => host.chatRetired(principalId, retirement) }); @@ -74,7 +76,7 @@ function world() { app.route("/api", createChatDeletionRoutes({ deletion: host.chatDeletion, principalValid: p => { const current = resolvePrincipal(db, p.id); return !!current && isUsablePrincipal(current, Date.now()); } })); cleanups.push(async () => { await host.close(); await catalog.settled!(); await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); }); return { - db, catalog, owner, other, agent, + db, catalog, owner, second, other, agent, /** One typed request, through dispatch and the run loop, settled on the writer. */ async type(text: string, sessionId?: string) { const before = finished; @@ -125,30 +127,33 @@ test("a typed chat created now is deletable by its owner; one created before the expect(w.db.query("SELECT id FROM chat_lifecycles").all(), "LEGACY_CHATS_NOT_RETIRED").toEqual([{ id: "voyage" }]); }); -test("other principals refuse a bound typed chat exactly as they refuse one that does not exist", async () => { +test("other accounts refuse a bound typed chat, and a chat they share refuses exactly as one that does not exist", async () => { const w = world(); await w.type(`Plan the voyage home. ${MARKER}`); await w.type("Steer between Scylla and Charybdis"); expect(bindings(w.db)).toEqual([{ sessionId: "scylla", principalId: w.owner.id }, { sessionId: "voyage", principalId: w.owner.id }]); + // Another person is another account, with no owner authority at all. const foreign = await w.remove(w.other, "voyage"); - const missing = await w.remove(w.other, "nowhere"); - const foreignBody = await foreign.json(), missingBody = await missing.json(); - expect(foreign.status, "FOREIGN_OWNER_UNAVAILABLE").toBe(404); - expect(foreignBody, "FOREIGN_REFUSAL_LEAKS_NOTHING").toEqual(missingBody); - expect([missing.status, missingBody.reason]).toEqual([404, "unavailable"]); + expect([foreign.status, (await foreign.json()).reason], "ANOTHER_ACCOUNT_CANNOT_DELETE").toEqual([403, "unauthorized"]); // An agent the owner created holds no owner authority over its chats. const agent = await w.remove(w.agent, "voyage"); expect([agent.status, (await agent.json()).reason], "AGENT_CANNOT_DELETE").toEqual([403, "unauthorized"]); expect(w.db.query("SELECT COUNT(*) AS n FROM chat_lifecycles").get(), "NOTHING_RETIRED_BY_OTHERS").toEqual({ n: 0 }); - // A binding naming a different principal than a recorded voice owner is ambiguous, never resolved for either. + // A binding beside a voice owner of another account is unknown ownership for every owner login. await w.catalog.saveConversationEpoch!({ id: "sirens", principalId: w.other, epoch: 1, sessionId: "scylla" }); await w.catalog.settled!(); - for (const principal of [w.owner.id, w.other]) { - const conflict = await w.remove(principal, "scylla"); - expect([conflict.status, (await conflict.json()).reason], "CONFLICTING_OWNERS_UNAVAILABLE").toEqual([404, "unavailable"]); + const missing = await w.remove(w.owner.id, "nowhere"), missingBody = await missing.json(); + expect([missing.status, missingBody.reason]).toEqual([404, "unavailable"]); + for (const principal of [w.owner.id, w.second]) { + const conflict = await w.remove(principal, "scylla"), body = await conflict.json(); + expect([conflict.status, body.reason], "CONFLICTING_ACCOUNTS_UNAVAILABLE").toEqual([404, "unavailable"]); + expect(body, "FOREIGN_REFUSAL_LEAKS_NOTHING").toEqual(missingBody); } - expect((await w.remove(w.owner.id, "voyage")).status, "OWNER_STILL_DELETES").toBe(200); + // Another login of the owner account deletes the owner's typed chat; the record keeps its creator. + expect((await w.remove(w.second, "voyage")).status, "ACCOUNTS_OTHER_LOGIN_DELETES").toBe(200); + expect(bindings(w.db), "CREATOR_ATTRIBUTION_KEPT").toEqual([{ sessionId: "scylla", principalId: w.owner.id }, { sessionId: "voyage", principalId: w.owner.id }]); + expect(w.db.query("SELECT principal_id AS principalId FROM chat_lifecycles WHERE id='voyage'").get(), "OPERATION_IS_THE_DELETERS").toEqual({ principalId: w.second }); }); diff --git a/packages/ui-server/tests/dialogue-account-ownership.test.ts b/packages/ui-server/tests/dialogue-account-ownership.test.ts index 8fb6bff9db..60fd9ce27d 100644 --- a/packages/ui-server/tests/dialogue-account-ownership.test.ts +++ b/packages/ui-server/tests/dialogue-account-ownership.test.ts @@ -16,8 +16,9 @@ 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 { resolveChat, type RetireChatResult } from "../src/ws/chat-lifecycle"; +import { principalAccount } from "../src/middleware/account-partition"; +import { createSessionCatalog, type SessionCatalog } from "../src/ws/session-catalog"; import { createOffloopActivityStore } from "../src/activity/store-writes"; import { createStaticBackendRegistry } from "../src/agent/backend"; import { WsHost } from "../src/ws/host"; @@ -52,7 +53,8 @@ async function fixture() { 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); + // As the write worker binds it: the creator's durable account from its own row. + db.query("INSERT INTO chat_session_owners(session_id,principal_id,principal_account,created_at) VALUES('ithaca',?,?,0)").run(principalId, principalAccount(db, 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; @@ -223,13 +225,135 @@ test("sharing the history gives no authority over another login's conversation o 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(); } }); +/** The real deletion path (#4138): admission on the catalog, commit on the fixture's write worker. */ +const catalogOf = (f: Awaited>) => + createSessionCatalog(() => f.db, undefined, undefined, { writer: f.writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(f.db, f.writer) }); +const retire = (catalog: SessionCatalog, principalId: string, operationId: string, sessionId = "ithaca"): Promise => + catalog.retireChat!({ operationId, principalId, target: { sessionId }, expected: { backendId: "claude", generation: 1 }, removableBackends: ["claude"], at: Date.now() }, () => false); +const retireProvisional = (catalog: SessionCatalog, principalId: string, operationId: string, ownerId: string): Promise => + catalog.retireChat!({ operationId, principalId, target: { ownerId }, expected: { backendId: null, generation: 1 }, removableBackends: [], at: Date.now() }, () => false); +const UNAVAILABLE = { status: "refused", reason: "unavailable" }, UNAUTHORIZED = { status: "refused", reason: "unauthorized" }; +const settle = (p: Promise) => p.then(() => "written", (e: Error) => e.message); +/** + * The chat `ithaca`, typed on the ship, then continued by voice from the ship + * and from home: every ownership record a deletion consults, written by the + * real catalog writers. Two logins of one account, and no other. + */ +async function sharedChat(f: Awaited>, catalog: SessionCatalog) { + await f.typed(); + for (const [conversationId, principal] of [["argos-voice", f.ship], ["ithaca-voice", f.home]] as const) { + await catalog.dialogueOpen!({ conversationId, principalId: principal.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" }); + await catalog.saveConversationEpoch!({ id: conversationId, principalId: principal.id, epoch: 1, sessionId: "ithaca" }); + await catalog.dialogueClose!(conversationId, principal.id, 1, false); + } + await catalog.settled!(); +} +/** Another chat of the account, from the home login alone: a refusal elsewhere must not reach it. */ +async function unrelatedChat(f: Awaited>, catalog: SessionCatalog) { + catalog.persistSessionStub("pylos", "Ask Nestor for news", null, "claude", f.home.id); + await catalog.dialogueOpen!({ conversationId: "pylos-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "pylos" }); + await catalog.saveConversationEpoch!({ id: "pylos-voice", principalId: f.home.id, epoch: 1, sessionId: "pylos" }); + await catalog.settled!(); +} +const evidence = (db: Awaited>["db"]) => ({ + owners: db.query("SELECT id,principal_id,principal_account FROM dialogue_owners ORDER BY id").all(), + epochs: db.query("SELECT id,principal_id,principal_account FROM conversation_epochs ORDER BY id").all(), + creators: db.query("SELECT session_id,principal_id,principal_account FROM chat_session_owners ORDER BY session_id").all(), +}); +const lifecycles = (db: Awaited>["db"]) => db.query("SELECT id,principal_id,operation_id FROM chat_lifecycles ORDER BY id").all(); + +for (const deleter of ["ship", "home", "a third login"] as const) test(`a chat two owner logins used by voice is deleted by ${deleter}, under its own operation`, async () => { + const f = await fixture(); const catalog = catalogOf(f); try { + await sharedChat(f, catalog); + // The real writers stored each record's durable account beside its login. + expect(evidence(f.db), "DELETION_RECORDS_CARRY_DURABLE_ACCOUNTS").toEqual({ + owners: [{ id: expect.any(String), principal_id: f.ship.id, principal_account: "owner" }], + epochs: [{ id: "argos-voice", principal_id: f.ship.id, principal_account: "owner" }, { id: "ithaca-voice", principal_id: f.home.id, principal_account: "owner" }], + creators: [{ session_id: "ithaca", principal_id: f.ship.id, principal_account: "owner" }] }); + const before = evidence(f.db); + const third = createPrincipal(f.db, { authMethod: "passkey", label: "Odysseus in the hall", ttlSeconds: 7200 }); + const caller = deleter === "ship" ? f.ship : deleter === "home" ? f.home : third; + const bystander = caller === f.home ? f.ship : f.home; + const result = await retire(catalog, caller.id, "retire-ithaca"); + expect(result, `DELETION_ADMITS_THE_ACCOUNTS_LOGIN: ${deleter}`).toMatchObject({ status: "retired", lifecycleId: "ithaca", operationId: "retire-ithaca", generation: 2, + identities: { sessions: ["ithaca"], conversations: ["argos-voice", "ithaca-voice"] } }); + // The operation belongs to the login that asked; no record is reassigned. + expect(lifecycles(f.db), "DELETION_OPERATION_IS_THE_CALLERS").toEqual([{ id: "ithaca", principal_id: caller.id, operation_id: "retire-ithaca" }]); + expect(evidence(f.db), "DELETION_KEEPS_ORIGINAL_ATTRIBUTION").toEqual(before); + expect(await catalog.chatRetirement!("retire-ithaca", caller.id), "DELETION_RECEIPT_READS_FOR_ITS_INITIATOR").toMatchObject({ status: "retired" }); + expect(await catalog.chatRetirement!("retire-ithaca", bystander.id), "DELETION_RECEIPT_IS_NOT_ANOTHER_LOGINS").toBeNull(); + expect(await retire(catalog, bystander.id, "retire-ithaca"), "DELETION_HANDLE_IS_NOT_ANOTHER_LOGINS").toEqual(UNAVAILABLE); + // The fences hold for every login of the account. + expect(await retire(catalog, bystander.id, "retire-ithaca-again"), "DELETION_RETIRED_CHAT_STAYS_RETIRED").toEqual(UNAVAILABLE); + expect(await settle(catalog.dialogueOpen!({ conversationId: "late-voice", principalId: bystander.id, epoch: 1, providerId: "fake-live", sessionId: "ithaca" })), + "DELETION_FENCE_REFUSES_THE_OTHER_LOGIN").toContain("retired"); + expect(await settle(catalog.saveConversationEpoch!({ id: "ithaca-voice", principalId: f.home.id, epoch: 2, sessionId: "ithaca" })), "DELETION_EPOCH_NEVER_REOPENS").toContain("retired"); + expect(lifecycles(f.db)).toHaveLength(1); + } finally { await catalog.settled!(); await f.close(); } +}); + +for (const how of ["revoked", "expired"] as const) test(`the remaining login deletes the shared chat once the other is ${how} and pruned`, async () => { + const f = await fixture(); const catalog = catalogOf(f); try { + await sharedChat(f, catalog); + f.prune(how); + // The pruned login proves its records' account only through what was stored. + expect(await retire(catalog, f.ship.id, "retire-by-the-pruned"), "DELETION_PRUNED_CALLER_GAINS_NOTHING").toEqual(UNAUTHORIZED); + expect(await retire(catalog, f.home.id, "retire-ithaca"), "DELETION_DURABLE_EVIDENCE_OUTLIVES_PRUNING").toMatchObject({ status: "retired", generation: 2 }); + expect(lifecycles(f.db)).toEqual([{ id: "ithaca", principal_id: f.home.id, operation_id: "retire-ithaca" }]); + } finally { await catalog.settled!(); await f.close(); } +}); + +test("a caller that is not a current owner login is refused, whatever the chat's records say", async () => { + const f = await fixture(); const catalog = catalogOf(f); try { + await sharedChat(f, catalog); + for (const [name, principalId] of f.foreign) + expect(await retire(catalog, principalId, `retire-by-${name}`), `DELETION_REFUSES_CALLER: ${name}`).toEqual(UNAUTHORIZED); + revokePrincipal(f.db, f.home.id, Date.now()); + expect(await retire(catalog, f.home.id, "retire-by-revoked"), "DELETION_REFUSES_CALLER: revoked").toEqual(UNAUTHORIZED); + // Its login lapsed, but retention has not pruned its row yet. + f.db.query("UPDATE principals SET expires_at=? WHERE id=?").run(Date.now() - 1, f.ship.id); + expect([f.authorized(f.ship), resolvePrincipal(f.db, f.ship.id) !== null]).toEqual([false, true]); + expect(await retire(catalog, f.ship.id, "retire-by-expired"), "DELETION_REFUSES_CALLER: expired").toEqual(UNAUTHORIZED); + expect(lifecycles(f.db), "DELETION_NOTHING_RETIRED").toEqual([]); + } finally { await catalog.settled!(); await f.close(); } +}); + +/** + * Each case leaves one ownership record of the shared chat unproven. The + * caller is a current owner login every time; only the evidence differs. + */ +const UNPROVEN: [string, (f: Awaited>) => void][] = [ + ["a pruned voice epoch with no stored account", f => { f.db.query("UPDATE conversation_epochs SET principal_account=NULL WHERE id='argos-voice'").run(); f.prune("revoked"); }], + ["a pruned creation binding with no stored account", f => { f.db.query("UPDATE chat_session_owners SET principal_account=NULL WHERE session_id='ithaca'").run(); f.prune("revoked"); }], + ["a pruned dialogue owner with no stored account", f => { f.db.query("UPDATE dialogue_owners SET principal_account=NULL WHERE session_id='ithaca'").run(); f.prune("expired"); }], + ["a corrupt voice epoch account", f => { f.db.query("UPDATE conversation_epochs SET principal_account='admiral' WHERE id='ithaca-voice'").run(); }], + ["a corrupt creation binding account", f => { f.db.query("UPDATE chat_session_owners SET principal_account='admiral' WHERE session_id='ithaca'").run(); }], + ["a corrupt dialogue owner account", f => { f.db.query("UPDATE dialogue_owners SET principal_account='admiral' WHERE session_id='ithaca'").run(); }], + ["an agent epoch claiming the owner account", f => { f.db.query("INSERT INTO conversation_epochs(id,principal_id,principal_account,epoch,session_id,updated_at) VALUES('mentor-voice',?,'owner',1,'ithaca',0)").run(f.agent.id); }], + ["an agent's voice epoch", f => { f.db.query("INSERT INTO conversation_epochs(id,principal_id,principal_account,epoch,session_id,updated_at) VALUES('mentor-voice',?,NULL,1,'ithaca',0)").run(f.agent.id); }], + ["an ambient principal's voice epoch", f => { f.db.query("INSERT INTO conversation_epochs(id,principal_id,principal_account,epoch,session_id,updated_at) VALUES('penelope-voice',?,NULL,1,'ithaca',0)").run(f.penelope.id); }], + ["a system principal's voice epoch", f => { f.db.query("INSERT INTO conversation_epochs(id,principal_id,principal_account,epoch,session_id,updated_at) VALUES('watch-voice',?,NULL,1,'ithaca',0)").run(f.system.id); }], + ["an unknown principal's voice epoch", f => { f.db.query("INSERT INTO conversation_epochs(id,principal_id,principal_account,epoch,session_id,updated_at) VALUES('cyclops-voice','polyphemus',NULL,1,'ithaca',0)").run(); }], + ["an unknown principal claiming the owner account", f => { f.db.query("INSERT INTO conversation_epochs(id,principal_id,principal_account,epoch,session_id,updated_at) VALUES('cyclops-voice','polyphemus','admiral',1,'ithaca',0)").run(); }], +]; +for (const [name, unprove] of UNPROVEN) test(`deletion refuses within the chat for ${name}, and moves nothing`, async () => { + const f = await fixture(); const catalog = catalogOf(f); try { + await sharedChat(f, catalog); + await unrelatedChat(f, catalog); + unprove(f); + const before = evidence(f.db); + for (const caller of [f.home, f.ship].filter(f.authorized)) + expect(await retire(catalog, caller.id, `retire-ithaca-${caller.id}`), `DELETION_UNPROVEN_OWNERSHIP_REFUSES: ${name}`).toEqual(UNAVAILABLE); + expect(lifecycles(f.db), `DELETION_UNPROVEN_RETIRES_NOTHING: ${name}`).toEqual([]); + expect(evidence(f.db), `DELETION_UNPROVEN_REWRITES_NOTHING: ${name}`).toEqual(before); + // The refusal is that chat's: the account's other chat is still deleted. + expect(await retire(catalog, f.home.id, "retire-pylos", "pylos"), `DELETION_UNRELATED_CHAT_USABLE: ${name}`).toMatchObject({ status: "retired", lifecycleId: "pylos" }); + } finally { await catalog.settled!(); 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" }); @@ -387,3 +511,79 @@ test("live start: another owner login opens voice on the retained history; a for 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(); } }); + +for (const third of ["the account's", "an agent's", "an ambient principal's"] as const) test(`a provisional chat both logins typed into, with ${third} turn beside them`, async () => { + const f = await fixture(); const catalog = catalogOf(f); try { + // Typed turns before any backend session exists: the history owner is the first turn's binding. + const first = crypto.randomUUID(); + const turn = async (turnId: string, bindingId: string, principalId: string) => { + await f.writes.safetyBegin({ turnId, bindingId, sessionId: null, principalId, historyOwnerId: first, backendId: "claude", at: 0 }); + await f.writes.safetyEnd(turnId); + }; + await turn("voyage", first, f.ship.id); + await turn("return", crypto.randomUUID(), f.home.id); + const extra = third === "the account's" ? null : third === "an agent's" ? f.agent.id : f.penelope.id; + if (extra) await turn("stowaway", crypto.randomUUID(), extra); + const chat = resolveChat(f.db, { ownerId: first }); + expect("refused" in chat ? chat : chat.owners.length, "PROVISIONAL_RECORDS_EACH_LOGIN").toBe(extra ? 3 : 2); + const result = await retireProvisional(catalog, f.home.id, "retire-provisional", first); + if (extra) { + expect(result, `PROVISIONAL_MIXED_ACCOUNT_REFUSES: ${third}`).toEqual(UNAVAILABLE); + expect(await retireProvisional(catalog, f.ship.id, "retire-provisional-ship", first)).toEqual(UNAVAILABLE); + expect(lifecycles(f.db)).toEqual([]); + } else { + expect(result, "PROVISIONAL_SHARED_BY_THE_ACCOUNT_RETIRES").toMatchObject({ status: "retired", lifecycleId: first, generation: 2, backendId: null }); + expect(lifecycles(f.db)).toEqual([{ id: first, principal_id: f.home.id, operation_id: "retire-provisional" }]); + } + } finally { await catalog.settled!(); await f.close(); } +}); + +test("the write worker's typed-creation binding keeps its account, so the chat outlives its creator's login", async () => { + const f = await fixture(); const catalog = catalogOf(f); try { + // The ship's typed request creates the session; home continues it by voice. + catalog.persistSessionStub("pylos", "Ask Nestor for news", null, "claude", f.ship.id); + catalog.persistSessionStub("mentor", "Carry the message", null, "claude", f.agent.id); + await catalog.dialogueOpen!({ conversationId: "pylos-voice", principalId: f.home.id, epoch: 1, providerId: "fake-live", sessionId: "pylos" }); + await catalog.saveConversationEpoch!({ id: "pylos-voice", principalId: f.home.id, epoch: 1, sessionId: "pylos" }); + await catalog.settled!(); + expect(f.db.query("SELECT session_id,principal_id,principal_account FROM chat_session_owners ORDER BY session_id").all(), "CREATION_BINDING_STORES_ITS_ACCOUNT").toEqual([ + { session_id: "mentor", principal_id: f.agent.id, principal_account: null }, { session_id: "pylos", principal_id: f.ship.id, principal_account: "owner" }]); + f.prune("revoked"); + expect(await retire(catalog, f.home.id, "retire-pylos", "pylos"), "CREATION_BINDING_OUTLIVES_PRUNING").toMatchObject({ status: "retired", lifecycleId: "pylos" }); + // An agent's typed chat is the agent's alone: no owner login deletes it. + expect(await retire(catalog, f.home.id, "retire-mentor", "mentor"), "AGENT_CREATION_BINDING_STAYS_THE_AGENTS").toEqual(UNAVAILABLE); + } finally { await catalog.settled!(); await f.close(); } +}); + +test("upgrading gives legacy epochs and creation bindings an account only where a principal row still proves it", async () => { + const f = await fixture(); const catalog = catalogOf(f); + let db = f.db, writer = f.writer; + try { + await sharedChat(f, catalog); + await unrelatedChat(f, catalog); + f.db.query("INSERT INTO conversation_epochs(id,principal_id,epoch,session_id,updated_at) VALUES('mentor-voice',?,1,'mentor',0)").run(f.agent.id); + await catalog.settled!(); + // The tables as they stood before 091, with the ship's login pruned before the upgrade. + f.db.exec(`ALTER TABLE conversation_epochs DROP COLUMN principal_account; ALTER TABLE chat_session_owners DROP COLUMN principal_account; + DELETE FROM _migrations WHERE filename='091_chat_ownership_account.sql'`); + f.prune("revoked"); + await f.writer.close(); f.db.close(); + db = createUiDb(join(f.root, "ui.db")); writer = openSqliteWriter(db); + expect(db.query("SELECT id,principal_id,principal_account FROM conversation_epochs ORDER BY id").all(), "UPGRADE_EPOCH_ACCOUNTS").toEqual([ + { id: "argos-voice", principal_id: f.ship.id, principal_account: null }, + { id: "ithaca-voice", principal_id: f.home.id, principal_account: "owner" }, + { id: "mentor-voice", principal_id: f.agent.id, principal_account: null }, + { id: "pylos-voice", principal_id: f.home.id, principal_account: "owner" }, + ]); + expect(db.query("SELECT session_id,principal_id,principal_account FROM chat_session_owners ORDER BY session_id").all(), "UPGRADE_CREATION_ACCOUNTS").toEqual([ + { session_id: "ithaca", principal_id: f.ship.id, principal_account: null }, + { session_id: "pylos", principal_id: f.home.id, principal_account: "owner" }, + ]); + // The lost proof stays unknown: the shared chat refuses, the home login's own chat does not. + const upgraded = createSessionCatalog(() => db, undefined, undefined, { writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(db, writer) }); + try { + expect(await retire(upgraded, f.home.id, "retire-ithaca"), "UPGRADE_UNPROVEN_LEGACY_REFUSES").toEqual(UNAVAILABLE); + expect(await retire(upgraded, f.home.id, "retire-pylos", "pylos"), "UPGRADE_PROVEN_LEGACY_DELETES").toMatchObject({ status: "retired", lifecycleId: "pylos" }); + } finally { await upgraded.settled!(); } + } finally { await writer.close(); db.close(); rmSync(f.root, { recursive: true, force: true }); } +}); diff --git a/packages/ui-server/tests/helpers/safety-history-fixture.ts b/packages/ui-server/tests/helpers/safety-history-fixture.ts index 45176671e1..aff64315ac 100644 --- a/packages/ui-server/tests/helpers/safety-history-fixture.ts +++ b/packages/ui-server/tests/helpers/safety-history-fixture.ts @@ -41,7 +41,7 @@ export async function safetyHistoryFixture(bound=true,review=false,mode:AuthMode const bindingId=crypto.randomUUID(); await writes.safetyBegin({turnId:"voyage",bindingId,sessionId:null,principalId:principal.id,backendId:"claude",at:0});await writes.safetyReady("voyage","claude",1); const bind=async()=>{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(principal.id);safetyCatalogCreated(db,"ithaca",principal.id,"voyage");await writes.bind("voyage","ithaca");}; + db.query("INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca',?,0)").run(principal.id);safetyCatalogCreated(db,"ithaca",principal.id,"voyage");await writes.bind("voyage","ithaca");}; if(bound)await bind(); const secret="odysseus-safety-history-loopback-secret"; const auth={host:"127.0.0.1",mode,passwordHash:"unused",cookieSecret:secret,trustProxy:mode==="proxy"||mode==="tailscale",trustProxyHops:1,proxyAuthHeader:"x-user"} as AuthRuntime; diff --git a/packages/ui-server/tests/host-publication-safety.test.ts b/packages/ui-server/tests/host-publication-safety.test.ts index 7af645946c..4086b2303e 100644 --- a/packages/ui-server/tests/host-publication-safety.test.ts +++ b/packages/ui-server/tests/host-publication-safety.test.ts @@ -36,7 +36,7 @@ async function fixture(backendId: "claude" | "pi" = "claude") { const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: principal.id, backendId, at: 0 }); db.query("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('ithaca',0,0,?)").run(backendId); - db.query("INSERT INTO chat_session_owners VALUES('ithaca',?,0)").run(principal.id); + db.query("INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca',?,0)").run(principal.id); safetyCatalogCreated(db, "ithaca", principal.id, "voyage"); await writes.bind("voyage", "ithaca"); const controller = new AbortController(); const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, sessionId: () => "ithaca", backendId, diff --git a/packages/ui-server/tests/live-safety-admission.test.ts b/packages/ui-server/tests/live-safety-admission.test.ts index f37d7e28db..4c61373884 100644 --- a/packages/ui-server/tests/live-safety-admission.test.ts +++ b/packages/ui-server/tests/live-safety-admission.test.ts @@ -50,7 +50,7 @@ async function fixture() { const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: principal.id, 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(principal.id); + db.query("INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca',?,0)").run(principal.id); safetyCatalogCreated(db, "ithaca", principal.id, "voyage"); await writes.bind("voyage", "ithaca"); const controller = new AbortController(); const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, sessionId: () => "ithaca", backendId: "claude", diff --git a/packages/ui-server/tests/safety-account-partition.test.ts b/packages/ui-server/tests/safety-account-partition.test.ts index af6577047d..1681f87a9c 100644 --- a/packages/ui-server/tests/safety-account-partition.test.ts +++ b/packages/ui-server/tests/safety-account-partition.test.ts @@ -42,7 +42,7 @@ async function fixture() { 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); + db.query("INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca',?,0)").run(principalId); safetyCatalogCreated(db, "ithaca", principalId, "voyage"); await writes.bind("voyage", "ithaca"); const first = await taint("voyage", bindingId, "A"); await writes.safetyEnd("voyage"); diff --git a/packages/ui-server/tests/safety-containment.test.ts b/packages/ui-server/tests/safety-containment.test.ts index caf92bc3ef..a0462b4d81 100644 --- a/packages/ui-server/tests/safety-containment.test.ts +++ b/packages/ui-server/tests/safety-containment.test.ts @@ -32,7 +32,7 @@ async function chat(f: F, turnId: string, sessionId: string) { const bindingId = crypto.randomUUID(); await f.writes.safetyBegin({ turnId, bindingId, sessionId: null, principalId: "odysseus", backendId: "pi", at: 0 }); f.db.query("INSERT INTO sessions(id,created_at,last_active_at) VALUES(?,0,0)").run(sessionId); - f.db.query("INSERT INTO chat_session_owners VALUES(?,'odysseus',0)").run(sessionId); + f.db.query("INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES(?,'odysseus',0)").run(sessionId); safetyCatalogCreated(f.db, sessionId, "odysseus", turnId); await f.writes.bind(turnId, sessionId); const controller = new AbortController(); const collector = createSafetyCollector(f.db, f.writes, { turnId, bindingId, sessionId: () => sessionId, backendId: "pi", @@ -477,7 +477,7 @@ test("room for turns not yet in a chat is spent for good only when nothing can f expect(waiting, "SAFETY_UNBOUND_CEILING_REFUSES").toBeInstanceOf(SafetyRecordingUnavailable); expect(waiting, "SAFETY_UNBOUND_ROOM_A_RUNNING_TURN_FREES_IS_RETRYABLE").toMatchObject({ capacity: true, full: null }); // That turn joins its chat; the same retry now starts, with no limit raised. - f.db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + f.db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca','odysseus',0)"); safetyCatalogCreated(f.db, "ithaca", "odysseus", "landfall"); await f.writes.bind("landfall", "ithaca"); expect(await begin("waiting"), "SAFETY_UNBOUND_RETRY_STARTS_ONCE_ROOM_FREES").toBeNull(); // Once only ended unbound collections remain, retrying can never help. @@ -501,7 +501,7 @@ test("unbound byte room a running first turn holds is retryable; ballast that en const begin = (turnId: string) => f.writes.safetyBegin({ turnId, bindingId: crypto.randomUUID(), sessionId: null, principalId: "odysseus", backendId: "pi", at: 1 }) .then(() => null, error => error as SafetyRecordingUnavailable); expect(await begin("waiting"), "SAFETY_UNBOUND_BYTES_A_RUNNING_TURN_HOLDS_ARE_RETRYABLE").toMatchObject({ capacity: true, full: null }); - f.db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + f.db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca','odysseus',0)"); safetyCatalogCreated(f.db, "ithaca", "odysseus", "landfall"); await f.writes.bind("landfall", "ithaca"); expect(await begin("waiting"), "SAFETY_UNBOUND_BYTE_RETRY_STARTS_ONCE_ROOM_FREES").toBeNull(); // Ended ballast alone leaves no room: retrying can never help. diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 8ffb2e26b3..bcf2099f70 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -19,7 +19,7 @@ function fixture(){const root=mkdtempSync(join(tmpdir(),"odysseus-safety-ledger- async function fresh(f:ReturnType,turnId="voyage",sessionId="ithaca"){ const bindingId=crypto.randomUUID();await f.writes.safetyBegin({turnId,bindingId,sessionId:null,principalId:"odysseus",backendId:"claude",at:0}); f.db.query("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES(?,0,0,'claude')").run(sessionId); - f.db.query("INSERT INTO chat_session_owners VALUES(?,'odysseus',0)").run(sessionId); + f.db.query("INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES(?,'odysseus',0)").run(sessionId); safetyCatalogCreated(f.db,sessionId,"odysseus",turnId); await f.writes.bind(turnId,sessionId); const collector=createSafetyCollector(f.db,f.writes,{turnId,bindingId,sessionId:()=>sessionId,backendId:"claude",signal:new AbortController().signal,shellProxied:()=>true,brainPath:"/srv/ithaca"}); @@ -348,7 +348,7 @@ test("an imported provisional alias binds its actual owner and generation withou const f=fixture();try{ f.db.exec("INSERT INTO dialogue_owners(id,principal_id,session_id,generation,coverage,created_at) VALUES('canonical-owner','odysseus',NULL,9,'complete',0); INSERT INTO dialogue_aliases VALUES('native-alias','canonical-owner')"); const bindingId=crypto.randomUUID();await f.writes.safetyBegin({turnId:"adopt-import",bindingId,historyOwnerId:"native-alias",principalId:"odysseus",sessionId:null,backendId:"claude",at:1}); - f.db.exec("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('adopted',0,0,'claude'); INSERT INTO chat_session_owners VALUES('adopted','odysseus',0); UPDATE dialogue_owners SET session_id='adopted' WHERE id='canonical-owner'"); + f.db.exec("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('adopted',0,0,'claude'); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('adopted','odysseus',0); UPDATE dialogue_owners SET session_id='adopted' WHERE id='canonical-owner'"); safetyCatalogCreated(f.db,"adopted","odysseus","adopt-import");await f.writes.bind("adopt-import","adopted");await f.writes.safetyReady("adopt-import","claude",1); const state=f.writes.safety(null,"adopted"); expect(state.session,"SAFETY_BINDING_USES_CANONICAL_HISTORY_OWNER_AND_GENERATION").toEqual({sessionId:"adopted",historyOwnerId:"canonical-owner",historyGeneration:"9"}); @@ -429,7 +429,7 @@ for(const boundary of ["count","bytes"] as const)for(const race of [false,true]) const row=governanceEventRow({kind:"taint",turnId,sessionId:null,actor:"interactive",model:null,profile:null,payload:{source:"web_fetch",tool:"WebFetch",detail:null}}); for(let i=0;i"ithaca",backendId:"pi",shellProxied:()=>false,signal:controller.signal,stop:()=>{controller.abort();if(stopThrows)throw new Error("Producer stop failed");}});await collector.ready("pi",1); // This real deferred FK fails at COMMIT after the loss flag was written, diff --git a/packages/ui-server/tests/safety-native-delivery.test.ts b/packages/ui-server/tests/safety-native-delivery.test.ts index 2909d452d4..4e88b85ddb 100644 --- a/packages/ui-server/tests/safety-native-delivery.test.ts +++ b/packages/ui-server/tests/safety-native-delivery.test.ts @@ -47,7 +47,7 @@ for(const mode of ["complete","writer-loss"] as const)test(`installed Claude ${m }}); try{ await writes.safetyBegin({turnId:"voyage",bindingId,sessionId:null,principalId:"odysseus",backendId:"claude",at:0}); - db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca','odysseus',0)"); safetyCatalogCreated(db,"ithaca","odysseus","voyage");await writes.bind("voyage","ithaca"); const collector=createSafetyCollector(db,writes,{turnId:"voyage",bindingId,backendId:"claude",sessionId:()=>"ithaca",brainPath:brain,shellProxied:()=>false,signal:controller.signal,stop:error=>controller.abort(error)}); await collector.ready("claude",1); diff --git a/packages/ui-server/tests/safety-pi-delivery.test.ts b/packages/ui-server/tests/safety-pi-delivery.test.ts index 1508f0e092..de501e0b9c 100644 --- a/packages/ui-server/tests/safety-pi-delivery.test.ts +++ b/packages/ui-server/tests/safety-pi-delivery.test.ts @@ -44,7 +44,7 @@ async function fixture(mode:Mode="normal",acknowledge=true,durable=false) { }}); const bindingId=crypto.randomUUID(),sessionId=crypto.randomUUID(); await writes.safetyBegin({turnId:"voyage",bindingId,sessionId:null,principalId:"odysseus",backendId:"pi",at:0}); - db.exec("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('ithaca',0,0,'pi'); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + db.exec("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('ithaca',0,0,'pi'); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca','odysseus',0)"); safetyCatalogCreated(db,"ithaca","odysseus","voyage");await writes.bind("voyage","ithaca"); const collector=createSafetyCollector(db,writes,{turnId:"voyage",bindingId,sessionId:()=>"ithaca",backendId:"pi",brainPath:root,shellProxied:()=>false,signal:controller.signal,stop:()=>controller.abort()}); if(acknowledge)await collector.ready("pi",1); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index d6c00dc180..8fbb0e49f3 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -45,7 +45,7 @@ async function voyage() { holdSafetyRecovery(db); const bindingId = crypto.randomUUID(), controller = new AbortController(); await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: "odysseus", backendId: "pi", at: 0 }); - db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca','odysseus',0)"); safetyCatalogCreated(db, "ithaca", "odysseus", "voyage"); await writes.bind("voyage", "ithaca"); const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, backendId: "pi", sessionId: () => "ithaca", brainPath: brain, shellProxied: () => false, signal: controller.signal, stop: error => controller.abort(error) }); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index a4118d3d04..22dd8a410f 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -93,7 +93,7 @@ esac const controller=new AbortController(),bindingId=crypto.randomUUID(); await writes.safetyBegin({turnId,bindingId,sessionId,principalId:"odysseus",backendId:"claude",at:turn}); if(!sessionId){ - db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca','odysseus',0)"); safetyCatalogCreated(db,"ithaca","odysseus",turnId);await writes.bind(turnId,"ithaca"); } const collector=createSafetyCollector(db,writes,{turnId,bindingId,backendId:"claude",sessionId:()=>"ithaca",brainPath:brain,shellProxied:()=>false,signal:controller.signal,stop:error=>controller.abort(error)}); @@ -293,7 +293,7 @@ for(const late of [false,true])test(`a denied shell call reusing a search's id c holdSafetyRecovery(db); const controller=new AbortController(),bindingId=crypto.randomUUID(); await writes.safetyBegin({turnId:"voyage",bindingId,sessionId:null,principalId:"odysseus",backendId:"claude",at:0}); - db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca','odysseus',0)"); safetyCatalogCreated(db,"ithaca","odysseus","voyage");await writes.bind("voyage","ithaca"); const collector=createSafetyCollector(db,writes,{turnId:"voyage",bindingId,backendId:"claude",sessionId:()=>"ithaca",brainPath:brain,shellProxied:()=>false,signal:controller.signal}); await collector.ready("claude",1); diff --git a/packages/ui-server/tests/safety-reviews.test.ts b/packages/ui-server/tests/safety-reviews.test.ts index 5fdb973a2b..358f57657d 100644 --- a/packages/ui-server/tests/safety-reviews.test.ts +++ b/packages/ui-server/tests/safety-reviews.test.ts @@ -30,7 +30,7 @@ async function fixture() { const bindingId = crypto.randomUUID(); await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: principal.id, 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(principal.id); + db.query("INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca',?,0)").run(principal.id); safetyCatalogCreated(db, "ithaca", principal.id, "voyage"); await writes.bind("voyage", "ithaca"); const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, sessionId: () => "ithaca", backendId: "claude", signal: new AbortController().signal, shellProxied: () => true, brainPath: root }); diff --git a/packages/ui-server/tests/session-safety-boundaries.test.ts b/packages/ui-server/tests/session-safety-boundaries.test.ts index bed9e1059c..95372f952d 100644 --- a/packages/ui-server/tests/session-safety-boundaries.test.ts +++ b/packages/ui-server/tests/session-safety-boundaries.test.ts @@ -137,7 +137,7 @@ test("queued handoff turns retain the original inherited evidence without copyin try { await f.writes.safetyBegin({ turnId: "source-turn", bindingId, sessionId: null, principalId: principal.id, backendId: "claude", at: 0 }); f.db.query("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('source',0,0,'claude')").run(); - f.db.query("INSERT INTO chat_session_owners VALUES('source',?,0)").run(principal.id); + f.db.query("INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('source',?,0)").run(principal.id); safetyCatalogCreated(f.db, "source", principal.id, "source-turn"); await f.writes.bind("source-turn", "source"); await source.ready("claude", 1); diff --git a/packages/ui-server/tests/web-pi-delivery.test.ts b/packages/ui-server/tests/web-pi-delivery.test.ts index d8393a3949..348fab2109 100644 --- a/packages/ui-server/tests/web-pi-delivery.test.ts +++ b/packages/ui-server/tests/web-pi-delivery.test.ts @@ -56,7 +56,7 @@ test("installed Pi records a forwarded web result before the next provider reque try { const bindingId = crypto.randomUUID(); await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: "odysseus", backendId: "pi", at: 0 }); - db.exec("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('ithaca',0,0,'pi'); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + db.exec("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('ithaca',0,0,'pi'); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca','odysseus',0)"); safetyCatalogCreated(db, "ithaca", "odysseus", "voyage"); await writes.bind("voyage", "ithaca"); const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, sessionId: () => "ithaca", backendId: "pi", brainPath: root, shellProxied: () => false, signal: controller.signal, stop: () => controller.abort() }); From d2a53cd63bb03723c6a2adac09fc8d2a5d9a0ab8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 09:55:07 +0000 Subject: [PATCH 2/3] fix(ui-server): count unbound safety collections and check expiry by the current clock (#4138) Review of 08c3d18cf found two holes in same-account deletion admission: - resolveChat consulted a history owner's unbound safety collections only when no dialogue owner existed. With a provisional dialogue owner, or under a session chat's history owner, a collection with corrupt or another account's evidence did not stop retirement. Every branch now records each unbound collection under every history owner and alias. - The catalog preflight and the commit transaction checked the caller's expiry against input.at, stamped before the catalog and writer waits, so a login that expired in between still retired the chat. Both now check the current clock; input.at stays only as the recorded retirement time. Co-Authored-By: Claude Opus 5.5 --- .changeset/4138-same-account-chat-deletion.md | 2 +- docs/decisions/chat-history-deletion.md | 11 +++--- docs/decisions/governed-writable-workers.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- packages/ui-server/src/ws/chat-lifecycle.ts | 14 ++++++-- packages/ui-server/src/ws/session-catalog.ts | 3 +- .../ui-server/tests/chat-lifecycle.test.ts | 32 +++++++++++++++++ .../tests/dialogue-account-ownership.test.ts | 35 +++++++++++++++++++ 8 files changed, 91 insertions(+), 10 deletions(-) diff --git a/.changeset/4138-same-account-chat-deletion.md b/.changeset/4138-same-account-chat-deletion.md index e3e707beda..89dbd8202c 100644 --- a/.changeset/4138-same-account-chat-deletion.md +++ b/.changeset/4138-same-account-chat-deletion.md @@ -2,4 +2,4 @@ "@schlessera/brain-ui-server": minor --- -A chat two owner logins used can be deleted by either of them (#4138). Every owner sign-in is its own principal, and explicit chat deletion compared exact principals across the chat's ownership records, so a chat continued by voice from a second device was refused to both logins as `unavailable`. `POST /api/chat-deletions` now admits any usable owner login when every recorded owner (the dialogue owner, each voice epoch, the typed-creation binding, a provisional chat's safety collections) proves that same owner account, also after another login has been pruned. Migration 091 stores the durable account beside each voice epoch and typed-creation binding, from the principal's own row, and backfills legacy rows only where a principal row still proves it. A record of another account, a pruned login with no stored account, or corrupt or contradictory evidence still refuses that chat alone. The caller is checked from its own current row at admission and at commit; revoked, expired, agent, ambient and system callers stay `unauthorized`. The operation, its receipt and its retry key stay with the login that started it, original attribution is never rewritten, and live conversation and epoch control, busy refusal, stale review, permanent fences and per-store outcomes are unchanged. No request, receipt or refusal shape changes. +A chat two owner logins used can be deleted by either of them (#4138). Every owner sign-in is its own principal, and explicit chat deletion compared exact principals across the chat's ownership records, so a chat continued by voice from a second device was refused to both logins as `unavailable`. `POST /api/chat-deletions` now admits any usable owner login when every recorded owner (the dialogue owner, each voice epoch, the typed-creation binding, a provisional chat's safety collections) proves that same owner account, also after another login has been pruned. A typed turn's safety collection that no session has bound yet counts as one more record, under a provisional or a session chat's history owner. Migration 091 stores the durable account beside each voice epoch and typed-creation binding, from the principal's own row, and backfills legacy rows only where a principal row still proves it. A record of another account, a pruned login with no stored account, or corrupt or contradictory evidence still refuses that chat alone. The caller is checked from its own current row against the current clock at admission and at commit, so a login that expires while the request waits is refused; revoked, expired, agent, ambient and system callers stay `unauthorized`. The operation, its receipt and its retry key stay with the login that started it, original attribution is never rewritten, and live conversation and epoch control, busy refusal, stale review, permanent fences and per-store outcomes are unchanged. No request, receipt or refusal shape changes. diff --git a/docs/decisions/chat-history-deletion.md b/docs/decisions/chat-history-deletion.md index cdafc7f562..9699eb0e22 100644 --- a/docs/decisions/chat-history-deletion.md +++ b/docs/decisions/chat-history-deletion.md @@ -148,10 +148,11 @@ alone never grants deletion authority. - **Which records.** Every record `resolveChat` consults: the canonical dialogue owner, each recorded voice conversation epoch, the typed-creation - binding and, for a provisional chat, each safety collection of its history - owner (`resolveChat`, `packages/ui-server/src/ws/chat-lifecycle.ts:87-141`). + binding and every safety collection a typed turn left under any of the + chat's history owners before a session bound it, for a provisional chat and + a backend session's chat alike (`resolveChat`, `packages/ui-server/src/ws/chat-lifecycle.ts:87-146`). Each must prove the caller's account; one that does not refuses the whole chat - (`chatOwnedBy`, `packages/ui-server/src/ws/chat-lifecycle.ts:153-155`). + (`chatOwnedBy`, `packages/ui-server/src/ws/chat-lifecycle.ts:158-160`). - **What proves an account.** The record principal's current row, or the durable account the server stored beside the record when it wrote it (`principal_account`, migrations 089 and 091). Migration 091 adds that @@ -163,7 +164,9 @@ alone never grants deletion authority. Legacy rows are backfilled only where a principal row still proved the account at upgrade; the others stay unknown and keep refusing. - **What authorizes the caller.** Only its own current principal row, re-read - at admission and again in the commit transaction. A revoked, expired or + at admission and again in the commit transaction, each time against the + current clock rather than the time the request was stamped, so a login that + expires while the request waits on the catalog or the writer is refused. A revoked, expired or pruned caller gains nothing from any record's stored account. Agent, ambient and system principals have no account that holds across auth modes, so their records match only themselves and they never gain an account-wide diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 7373e6cdc9..cdc36d0e3e 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:511`) + (`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:512`) must not feed any budget. **Enforcement:** diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 196fc59eb3..336530dcdd 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -8,7 +8,7 @@ Approval supplies no automatic expiry, routine live cutoff or implementation release commitment. **Built (#3228):** the internal, content-free retirement ledger and gate -(`retireChat`, `packages/ui-server/src/ws/chat-lifecycle.ts:195-234`; +(`retireChat`, `packages/ui-server/src/ws/chat-lifecycle.ts:204-244`; migration `073_chat_lifecycle.sql`). It re-reads owner authority in the serialized writer, resolves the exact identity set from recorded dialogue owners, aliases and voice epochs, refuses unknown/foreign/stale/unsupported/busy diff --git a/packages/ui-server/src/ws/chat-lifecycle.ts b/packages/ui-server/src/ws/chat-lifecycle.ts index 5c2c63c3e0..35309f8d85 100644 --- a/packages/ui-server/src/ws/chat-lifecycle.ts +++ b/packages/ui-server/src/ws/chat-lifecycle.ts @@ -124,6 +124,11 @@ export function resolveChat(db: Database, target: ChatTarget): Resolved | { refu for (const row of db.query("SELECT id FROM dialogue_aliases WHERE owner_id=?").all(owner) as { id: string }[]) owners.add(row.id); for (const row of db.query("SELECT id FROM dialogue_conversations WHERE owner_id=?").all(owner) as { id: string }[]) conversations.add(row.id); } + // A typed turn not yet bound to a session keeps its safety collection under + // the history owner. Whichever branch resolved the chat, each one is an + // ownership record: retirement fences and scrubs them as the chat's. + for (const owner of owners) + for (const row of db.query("SELECT DISTINCT principal_id,principal_account FROM safety_collections WHERE history_owner_id=? AND session_id IS NULL").all(owner) as OwnerRow[]) record(row); for (const conversation of conversations) { const row = db.query("SELECT principal_id,principal_account FROM conversation_epochs WHERE id=?").get(conversation) as OwnerRow | null; if (row) record(row); @@ -154,7 +159,11 @@ export function chatOwnedBy(db: Database, chat: Pick, princi return chat.owners.length > 0 && chat.owners.every(owner => sameAccount(db, owner, principalId)); } -/** The caller alone: a usable owner principal. Ambient callers have no owner mapping, agents never delete. */ +/** + * The caller alone: a usable owner principal. Ambient callers have no owner + * mapping, agents never delete. `at` is the moment of the check, never a + * time stamped before an asynchronous wait: callers pass the current clock. + */ export function authorizedOwner(db: Database, principalId: string, at: number): boolean { const principal = resolvePrincipal(db, principalId); return !!principal && principal.kind === "owner" && isUsablePrincipal(principal, at); @@ -195,7 +204,8 @@ const targetId = (target: ChatTarget) => "sessionId" in target ? target.sessionI export function retireChat(db: Database, input: RetireChatInput): RetireChatResult { if (!input.operationId || input.operationId.length > MAX_ID) return { status: "refused", reason: "unavailable" }; return db.transaction((): RetireChatResult => { - if (!authorizedOwner(db, input.principalId, input.at)) return { status: "refused", reason: "unauthorized" }; + // Authority is the caller's now, at commit: `input.at` was stamped before the queue waits. + if (!authorizedOwner(db, input.principalId, Date.now())) return { status: "refused", reason: "unauthorized" }; const previous = db.query("SELECT id,principal_id,operation_id,generation,backend_id FROM chat_lifecycles WHERE operation_id=?") .get(input.operationId) as { id: string; principal_id: string; operation_id: string; generation: number; backend_id: string | null } | null; if (previous) { diff --git a/packages/ui-server/src/ws/session-catalog.ts b/packages/ui-server/src/ws/session-catalog.ts index d3fc0e3f61..f63ea390cd 100644 --- a/packages/ui-server/src/ws/session-catalog.ts +++ b/packages/ui-server/src/ws/session-catalog.ts @@ -320,7 +320,8 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi // Settle every earlier submission first, so this preflight judges the // set the writer will see; the writer still decides atomically. await tail; - if (!authorizedOwner(db(), input.principalId, input.at)) return { status: "refused", reason: "unauthorized" }; + // The current clock, after the wait above: never the request's stamp. + if (!authorizedOwner(db(), input.principalId, Date.now())) return { status: "refused", reason: "unauthorized" }; const preview = resolveChat(db(), input.target); if ("refused" in preview || !chatOwnedBy(db(), preview, input.principalId)) return submit("retireChat", input); if (busy(preview.identities)) return { status: "refused", reason: "busy" }; diff --git a/packages/ui-server/tests/chat-lifecycle.test.ts b/packages/ui-server/tests/chat-lifecycle.test.ts index 5739789e12..1a3f5c2a5f 100644 --- a/packages/ui-server/tests/chat-lifecycle.test.ts +++ b/packages/ui-server/tests/chat-lifecycle.test.ts @@ -182,6 +182,38 @@ for (const change of ["revocation", "foreign epoch", "corrupt evidence"] as cons } finally { await f.host.close(); } }); +for (const stage of ["preflight", "commit"] as const) test(`a login that expires after the request was stamped is refused at the ${stage} by the current time`, async () => { + const f = await fixture(); + try { + const { catalog } = f.host; + const input = request(f.second, { at: Date.now() }); + await catalog.saveConversationEpoch!({ id: "telemachus", principalId: f.second, epoch: 1, sessionId: "voyage" }); + await catalog.settled!(); + let consulted = 0; + const busy = () => { consulted++; return false; }; + // Usable at the request's stamp, expired by the time authority is checked. + const expire = (db: Database) => db.query("UPDATE principals SET expires_at=? WHERE id=?").run(input.at + 1, f.second); + let pending: Promise; + if (stage === "preflight") { + expire(f.host.db); await Bun.sleep(5); + pending = catalog.retireChat!(input, busy); + } else { + await f.host.hold(); + const submitted = posted("retireChat"); + pending = catalog.retireChat!(input, busy); + await submitted; + expect(consulted, "PREFLIGHT_PASSED_BEFORE_EXPIRY").toBe(1); + const other = new Database(f.path); other.exec("PRAGMA busy_timeout = 5000"); + try { expire(other); } finally { other.close(); } + await Bun.sleep(5); + f.host.release(); + } + expect(await pending, `EXPIRY_CHECKED_AT_${stage.toUpperCase()}_BY_CURRENT_TIME`).toEqual({ status: "refused", reason: "unauthorized" }); + if (stage === "preflight") expect(consulted, "EXPIRED_CALLER_NEVER_REACHES_BUSY").toBe(0); + expect(fences(f.host.db)).toBe(0); + } finally { await f.host.close(); } +}); + test("retirement fences every identity, refuses late writes and keeps unrelated chats and accounting", async () => { const f = await fixture(); try { diff --git a/packages/ui-server/tests/dialogue-account-ownership.test.ts b/packages/ui-server/tests/dialogue-account-ownership.test.ts index 60fd9ce27d..3a1aa05e41 100644 --- a/packages/ui-server/tests/dialogue-account-ownership.test.ts +++ b/packages/ui-server/tests/dialogue-account-ownership.test.ts @@ -587,3 +587,38 @@ test("upgrading gives legacy epochs and creation bindings an account only where } finally { await upgraded.settled!(); } } finally { await writer.close(); db.close(); rmSync(f.root, { recursive: true, force: true }); } }); + +/** + * A typed turn's unbound safety collection under a chat's history owner is an + * ownership record whichever branch resolves the chat (#4138 review): a + * provisional dialogue owner, or a backend session's history owner. + */ +for (const shape of ["provisional dialogue owner", "session history owner"] as const) + for (const evidence of ["the account's", "corrupt", "another account's"] as const) test(`an unbound safety collection under a ${shape} is one more record: ${evidence}`, async () => { + const f = await fixture(); const catalog = catalogOf(f); try { + let historyOwnerId: string; + if (shape === "provisional dialogue owner") { + historyOwnerId = (await catalog.dialogueOpen!({ conversationId: "ogygia-voice", principalId: f.ship.id, epoch: 1, providerId: "fake-live" })).id; + await catalog.dialogueClose!("ogygia-voice", f.ship.id, 1, false); + } else { + await sharedChat(f, catalog); + historyOwnerId = (f.db.query("SELECT id FROM dialogue_owners WHERE session_id='ithaca'").get() as { id: string }).id; + } + // The home login types into that history before any session binds the turn. + const bindingId = crypto.randomUUID(); + await f.writes.safetyBegin({ turnId: "calypso", bindingId, sessionId: null, principalId: f.home.id, historyOwnerId, backendId: "claude", at: 0 }); + await f.writes.safetyEnd("calypso"); + await catalog.settled!(); + expect(f.db.query("SELECT principal_id,principal_account,session_id FROM safety_collections WHERE id=?").get(bindingId)).toEqual({ principal_id: f.home.id, principal_account: "owner", session_id: null }); + if (evidence === "corrupt") f.db.query("UPDATE safety_collections SET principal_account='admiral' WHERE id=?").run(bindingId); + if (evidence === "another account's") f.db.query("UPDATE safety_collections SET principal_id=?,principal_account=NULL WHERE id=?").run(f.agent.id, bindingId); + const result = shape === "provisional dialogue owner" + ? await retireProvisional(catalog, f.home.id, "retire-calypso", historyOwnerId) + : await retire(catalog, f.home.id, "retire-calypso"); + if (evidence === "the account's") expect(result, `UNBOUND_COLLECTION_OF_THE_ACCOUNT_RETIRES: ${shape}`).toMatchObject({ status: "retired", generation: 2 }); + else { + expect(result, `UNBOUND_COLLECTION_EVIDENCE_REFUSES: ${shape} ${evidence}`).toEqual(UNAVAILABLE); + expect(lifecycles(f.db)).toEqual([]); + } + } finally { await catalog.settled!(); await f.close(); } + }); From 26fbb985596e7df6f57c4ab3bc181469059e9e1d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 09:58:59 +0000 Subject: [PATCH 3/3] test(ui-server): keep the deletion refusal fixtures literal for the typechecker (#4138) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/dialogue-account-ownership.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/dialogue-account-ownership.test.ts b/packages/ui-server/tests/dialogue-account-ownership.test.ts index 3a1aa05e41..97788915e3 100644 --- a/packages/ui-server/tests/dialogue-account-ownership.test.ts +++ b/packages/ui-server/tests/dialogue-account-ownership.test.ts @@ -235,7 +235,7 @@ const retire = (catalog: SessionCatalog, principalId: string, operationId: strin catalog.retireChat!({ operationId, principalId, target: { sessionId }, expected: { backendId: "claude", generation: 1 }, removableBackends: ["claude"], at: Date.now() }, () => false); const retireProvisional = (catalog: SessionCatalog, principalId: string, operationId: string, ownerId: string): Promise => catalog.retireChat!({ operationId, principalId, target: { ownerId }, expected: { backendId: null, generation: 1 }, removableBackends: [], at: Date.now() }, () => false); -const UNAVAILABLE = { status: "refused", reason: "unavailable" }, UNAUTHORIZED = { status: "refused", reason: "unauthorized" }; +const UNAVAILABLE = { status: "refused", reason: "unavailable" } as const, UNAUTHORIZED = { status: "refused", reason: "unauthorized" } as const; const settle = (p: Promise) => p.then(() => "written", (e: Error) => e.message); /** * The chat `ithaca`, typed on the ship, then continued by voice from the ship