From 2844fe30ee428a0b181668b113f5f572f9c586c6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 12:53:56 +0000 Subject: [PATCH 1/4] feat(ui-server): retire chat identities with permanent replay and restore fences Add the internal, content-free chat lifecycle ledger (migration 073) and the gate later removal owners share (#3228). One immediate transaction on the serialized writer re-reads the caller's owner authority, resolves the exact identity set from recorded dialogue owners, aliases and voice epochs, compares backend and generation with what was reviewed, and persists the terminal generation, every consumed identity and per-store pending intent. Unknown, foreign, stale, unsupported and busy targets refuse first, with one answer for absent and foreign chats. Dialogue open/bind/append/read/close and conversation epoch/task/load refuse retired identities, so a later adoption refuses while an earlier one expands the set, and consumed task/request identities never record again after their rows are evicted or scrubbed. Triggers keep the fences permanent. Nothing is deleted and no completed deletion is reported. Co-Authored-By: Claude Opus 5.5 --- .../migrations/073_chat_lifecycle.sql | 47 +++ packages/ui-server/src/ws/chat-lifecycle.ts | 214 ++++++++++++ .../ui-server/src/ws/conversation-storage.ts | 7 + packages/ui-server/src/ws/dialogue-storage.ts | 17 +- .../src/ws/session-catalog-writes.ts | 3 + packages/ui-server/src/ws/session-catalog.ts | 46 ++- .../ui-server/tests/chat-lifecycle.test.ts | 311 ++++++++++++++++++ 7 files changed, 640 insertions(+), 5 deletions(-) create mode 100644 packages/ui-server/migrations/073_chat_lifecycle.sql create mode 100644 packages/ui-server/src/ws/chat-lifecycle.ts create mode 100644 packages/ui-server/tests/chat-lifecycle.test.ts diff --git a/packages/ui-server/migrations/073_chat_lifecycle.sql b/packages/ui-server/migrations/073_chat_lifecycle.sql new file mode 100644 index 0000000000..71490ebdc8 --- /dev/null +++ b/packages/ui-server/migrations/073_chat_lifecycle.sql @@ -0,0 +1,47 @@ +-- Retired chat identities (#3228). Content-free and permanent within the +-- installation: no prompt, result, title, recognition, attachment, hash of +-- short text or free-form error is stored here. Nothing references a content +-- table, so no content cascade or retention eviction can remove a fence. +-- One row per retired chat: its canonical identity (a backend session ID, or +-- a provisional dialogue owner ID), exact owner and terminal generation. +CREATE TABLE chat_lifecycles ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('session', 'provisional')), + principal_id TEXT NOT NULL, + backend_id TEXT, + generation INTEGER NOT NULL CHECK (generation > 1), + operation_id TEXT NOT NULL UNIQUE, + retired_at INTEGER NOT NULL +); +-- Every identity the retirement consumed: negative lookups that refuse +-- adoption, admission, writes and replay under any of them. +CREATE TABLE chat_retired_identities ( + kind TEXT NOT NULL CHECK (kind IN ('session', 'dialogue_owner', 'conversation', 'task', 'request', 'native_task')), + id TEXT NOT NULL, + lifecycle_id TEXT NOT NULL REFERENCES chat_lifecycles(id), + PRIMARY KEY (kind, id) +); +CREATE INDEX chat_retired_identities_lifecycle ON chat_retired_identities(lifecycle_id); +-- Per-store cleanup under the retirement's intent. Only store categories and +-- outcomes; completion needs every selected store to confirm removal. +CREATE TABLE chat_retirement_stores ( + lifecycle_id TEXT NOT NULL REFERENCES chat_lifecycles(id), + store TEXT NOT NULL CHECK (store IN ('native', 'dialogue', 'tasks', 'projections', 'drafts')), + outcome TEXT NOT NULL CHECK (outcome IN ('pending', 'partial', 'unknown', 'removed')), + updated_at INTEGER NOT NULL, + PRIMARY KEY (lifecycle_id, store) +); +CREATE TRIGGER chat_lifecycles_permanent BEFORE DELETE ON chat_lifecycles +BEGIN SELECT RAISE(ABORT, 'chat lifecycle fences are permanent'); END; +CREATE TRIGGER chat_lifecycles_terminal BEFORE UPDATE ON chat_lifecycles +BEGIN SELECT RAISE(ABORT, 'chat lifecycle fences are permanent'); END; +CREATE TRIGGER chat_retired_identities_permanent BEFORE DELETE ON chat_retired_identities +BEGIN SELECT RAISE(ABORT, 'chat lifecycle fences are permanent'); END; +CREATE TRIGGER chat_retired_identities_fixed BEFORE UPDATE ON chat_retired_identities +BEGIN SELECT RAISE(ABORT, 'chat lifecycle fences are permanent'); END; +CREATE TRIGGER chat_retirement_stores_permanent BEFORE DELETE ON chat_retirement_stores +BEGIN SELECT RAISE(ABORT, 'chat lifecycle fences are permanent'); END; +-- A confirmed removal is never reopened; other outcomes may only move forward. +CREATE TRIGGER chat_retirement_stores_removed BEFORE UPDATE ON chat_retirement_stores +WHEN OLD.outcome = 'removed' AND NEW.outcome != 'removed' +BEGIN SELECT RAISE(ABORT, 'a confirmed store removal cannot be reopened'); END; diff --git a/packages/ui-server/src/ws/chat-lifecycle.ts b/packages/ui-server/src/ws/chat-lifecycle.ts new file mode 100644 index 0000000000..973b542363 --- /dev/null +++ b/packages/ui-server/src/ws/chat-lifecycle.ts @@ -0,0 +1,214 @@ +/** + * Chat identity retirement (#3228): the serialized, content-free ledger and + * gate that every later removal owner shares. Retiring a chat fences its + * identities permanently; it removes no content and never acknowledges a + * completed deletion by itself. Each selected store reports its own cleanup. + * Policy: docs/decisions/chat-history-deletion.md. + */ +import type { Database } from "bun:sqlite"; +import { isUsablePrincipal, resolvePrincipal } from "../db/principals.js"; + +export type RetiredKind = "session" | "dialogue_owner" | "conversation" | "task" | "request" | "native_task"; +export const CHAT_STORES = ["native", "dialogue", "tasks", "projections", "drafts"] as const; +export type ChatStore = (typeof CHAT_STORES)[number]; +export type ChatStoreOutcome = "pending" | "partial" | "unknown" | "removed"; + +/** A write or admission under a retired identity. Content-free by construction. */ +export class ChatRetiredError extends Error { + readonly code = "chat_retired"; + constructor() { super("This chat has been retired and cannot be used again."); this.name = "ChatRetiredError"; } +} + +/** A chat is named by its backend session, or by a provisional dialogue owner never bound to one. */ +export type ChatTarget = { sessionId: string } | { ownerId: string }; +export interface RetireChatInput { + /** Client-minted idempotency key. A repeat returns the same result; it never re-authorizes a replacement. */ + operationId: string; + /** The authenticated caller. Authority is re-read at commit, never inferred from history or titles. */ + principalId: string; + target: ChatTarget; + /** What the caller reviewed. Any difference is stale and refuses. */ + expected: { backendId: string | null; generation: number }; + /** Backends whose native removal is supported. Anything else refuses before retirement. */ + removableBackends: readonly string[]; + at: number; +} +/** + * `unavailable` covers absent, foreign, ambiguous and already-retired targets + * alike, so a refusal never tells a caller whether someone else's chat exists. + * `unauthorized` describes the caller alone. + */ +export type RetireRefusal = "unauthorized" | "unavailable" | "stale" | "unsupported" | "busy"; +export interface RetiredChatIdentities { + sessions: string[]; dialogueOwners: string[]; conversations: string[]; tasks: string[]; requests: string[]; nativeTasks: string[]; +} +export type ChatRetirementStatus = "pending" | "partial" | "unknown" | "removed"; +export type RetireChatResult = + | { status: "refused"; reason: RetireRefusal } + | { status: "retired"; lifecycleId: string; operationId: string; generation: number; identities: RetiredChatIdentities; + cleanup: ChatRetirementStatus; stores: Partial> }; + +const MAX_ID = 2048; +const nativeTaskKey = (conversationId: string, epoch: number, nativeHandle: string) => JSON.stringify([conversationId, epoch, nativeHandle]); + +export function isRetired(db: Database, kind: RetiredKind, id: string): boolean { + return !!db.query("SELECT 1 FROM chat_retired_identities WHERE kind=? AND id=?").get(kind, id); +} +/** Throws `ChatRetiredError` if any named identity is retired. Absent values are ignored. */ +export function assertLive(db: Database, identities: ReadonlyArray): void { + for (const [kind, id] of identities) if (id && isRetired(db, kind, id)) throw new ChatRetiredError(); +} +export function nativeTaskRetired(db: Database, conversationId: string, epoch: number, nativeHandle: string): boolean { + return isRetired(db, "native_task", nativeTaskKey(conversationId, epoch, nativeHandle)); +} + +interface Resolved { + id: string; kind: "session" | "provisional"; principalId: string; backendId: string | null; generation: number; + identities: RetiredChatIdentities; +} +/** + * The exact current identity set of a chat, from verified ownership records + * only: canonical dialogue owners (with every alias an earlier adoption + * joined) and recorded voice conversation epochs. A chat with no such record, + * or with records naming different principals, has unknown ownership. + */ +export function resolveChat(db: Database, target: ChatTarget): Resolved | { refused: "unavailable" | "stale" } { + const owners = new Set(), conversations = new Set(), principals = new Set(); + 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); + } + } 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; + if (!owner) return { refused: "unavailable" }; + // 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); + } + for (const owner of [...owners]) { + 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); + } + 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); + } + if (principals.size !== 1) 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 }[]) { + tasks.push(row.task_id); requests.push(row.request_id); nativeTasks.push(nativeTaskKey(conversation, row.epoch, row.native_handle)); + } + } + 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: { + sessions: sessionId ? [sessionId] : [], dialogueOwners: [...owners].sort(), conversations: [...conversations].sort(), tasks, requests, nativeTasks } }; +} + +/** 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); + return !!principal && principal.kind === "owner" && isUsablePrincipal(principal, at); +} + +function stored(db: Database, lifecycleId: string): Partial> { + return Object.fromEntries((db.query("SELECT store,outcome FROM chat_retirement_stores WHERE lifecycle_id=? ORDER BY store").all(lifecycleId) as { store: ChatStore; outcome: ChatStoreOutcome }[]) + .map(row => [row.store, row.outcome])); +} +/** Completed only when every selected store confirmed removal; unknown dominates partial, partial dominates pending. */ +export function cleanupStatus(stores: Partial>): ChatRetirementStatus { + const outcomes = Object.values(stores); + if (!outcomes.length) return "pending"; + if (outcomes.includes("unknown")) return "unknown"; + if (outcomes.includes("partial")) return "partial"; + return outcomes.every(outcome => outcome === "removed") ? "removed" : "pending"; +} +function identitiesOf(db: Database, lifecycleId: string): RetiredChatIdentities { + const rows = db.query("SELECT kind,id FROM chat_retired_identities WHERE lifecycle_id=? ORDER BY kind,id").all(lifecycleId) as { kind: RetiredKind; id: string }[]; + const of = (kind: RetiredKind) => rows.filter(row => row.kind === kind).map(row => row.id); + return { sessions: of("session"), dialogueOwners: of("dialogue_owner"), conversations: of("conversation"), tasks: of("task"), requests: of("request"), nativeTasks: of("native_task") }; +} +function receipt(db: Database, row: { id: string; operation_id: string; generation: number }): RetireChatResult { + const stores = stored(db, row.id); + return { status: "retired", lifecycleId: row.id, operationId: row.operation_id, generation: row.generation, identities: identitiesOf(db, row.id), cleanup: cleanupStatus(stores), stores }; +} +const targetId = (target: ChatTarget) => "sessionId" in target ? target.sessionId : target.ownerId; + +/** + * One immediate transaction on the serialized writer: re-check the caller's + * authority, resolve the exact identity set (an adoption committed earlier is + * included), compare it with what was reviewed, then persist the content-free + * intent, terminal generation and every fence before any cleanup is accepted. + * Writes submitted after it refuse. Busy holders are the host's to judge and + * are refused before submission. + */ +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" }; + const previous = db.query("SELECT id,principal_id,operation_id,generation FROM chat_lifecycles WHERE operation_id=?") + .get(input.operationId) as { id: string; principal_id: string; operation_id: string; generation: number } | null; + if (previous) { + // The same key for the same owner and target is the same operation. + return previous.principal_id === input.principalId && previous.id === targetId(input.target) + ? receipt(db, previous) : { status: "refused", reason: "unavailable" }; + } + if ("sessionId" in input.target ? isRetired(db, "session", input.target.sessionId) : isRetired(db, "dialogue_owner", input.target.ownerId)) + 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 (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); + 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]]; + for (const [kind, ids] of kinds) for (const id of ids) fence.run(kind, id, chat.id); + const stores: ChatStore[] = [...(chat.backendId !== null ? ["native" as const] : []), "dialogue", "tasks", "projections", "drafts"]; + const intent = db.prepare("INSERT INTO chat_retirement_stores(lifecycle_id,store,outcome,updated_at) VALUES(?,?,'pending',?)"); + for (const store of stores) intent.run(chat.id, store, input.at); + // Old cursors and live epochs lose authority; content stays for its owners to remove. + for (const owner of chat.identities.dialogueOwners) db.prepare("UPDATE dialogue_owners SET generation=? WHERE id=?").run(generation, owner); + for (const conversation of chat.identities.conversations) db.prepare("UPDATE dialogue_conversations SET closed=1 WHERE id=?").run(conversation); + return receipt(db, { id: chat.id, operation_id: input.operationId, generation }); + }).immediate(); +} +/** Whether a stale provisional target is the caller'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; +} + +/** The retirement's current non-content outcome for its owner, or null. */ +export function chatRetirement(db: Database, operationId: string, principalId: string): RetireChatResult | null { + const row = db.query("SELECT id,principal_id,operation_id,generation FROM chat_lifecycles WHERE operation_id=?") + .get(operationId) as { id: string; principal_id: string; operation_id: string; generation: number } | null; + return row && row.principal_id === principalId ? receipt(db, row) : null; +} + +/** + * A store owner reports its cleanup under the retirement's intent. Idempotent; + * a confirmed removal is final, and a store not selected at retirement is refused. + */ +export function recordChatCleanup(db: Database, lifecycleId: string, store: ChatStore, outcome: Exclude, at: number): ChatRetirementStatus { + return db.transaction(() => { + const row = db.query("SELECT outcome FROM chat_retirement_stores WHERE lifecycle_id=? AND store=?").get(lifecycleId, store) as { outcome: ChatStoreOutcome } | null; + if (!row) throw new Error("Chat cleanup store was not selected"); + if (row.outcome !== "removed" && row.outcome !== outcome) + db.prepare("UPDATE chat_retirement_stores SET outcome=?,updated_at=? WHERE lifecycle_id=? AND store=?").run(outcome, at, lifecycleId, store); + return cleanupStatus(stored(db, lifecycleId)); + }).immediate(); +} diff --git a/packages/ui-server/src/ws/conversation-storage.ts b/packages/ui-server/src/ws/conversation-storage.ts index dc148e5340..a061ead00f 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 { assertLive, isRetired, nativeTaskRetired, ChatRetiredError } from "./chat-lifecycle.js"; /** UTF-16 characters of completed result context per conversation; oldest admitted goes first. */ export const MAX_RETAINED_RESULT_CHARS = 16_000; @@ -20,6 +21,7 @@ export interface StoredConversation extends StoredConversationEpoch { } export function saveConversationEpoch(db: Database, state: StoredConversationEpoch): void { db.transaction(() => { + 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(?,?,?,?,?,?) @@ -35,6 +37,10 @@ export function saveConversationEpoch(db: Database, state: StoredConversationEpo export function saveConversationTask(db: Database, principalId: string, receipt: ConversationWorkReceipt, facts?: string): void { if (receipt.provenance !== "contextual" || !conversationWorkReceiptSchema.safeParse(receipt).success) throw new Error("Invalid contextual receipt"); db.transaction(() => { + // Consumed identities of a retired chat stay consumed after its rows are + // evicted or cleared: none of them executes or records an outcome again (#3228). + assertLive(db, [["conversation", receipt.conversationId], ["task", receipt.taskId], ["request", receipt.requestId], ["session", receipt.sessionId]]); + if (nativeTaskRetired(db, receipt.conversationId, receipt.epoch, receipt.nativeHandle)) throw new ChatRetiredError(); const owner = db.query("SELECT principal_id FROM conversation_epochs WHERE id=?").get(receipt.conversationId) as { principal_id: string } | null; if (owner?.principal_id !== principalId) throw new Error("Conversation ownership mismatch"); const old = db.query("SELECT task_id,request_id,receipt,result_facts FROM conversation_tasks WHERE conversation_id=? AND epoch=? AND native_handle=?") @@ -70,6 +76,7 @@ export function saveConversationTask(db: Database, principalId: string, receipt: }).immediate(); } export function loadConversation(db: Database, id: string, principalId: string): StoredConversation | null { + if (isRetired(db, "conversation", id)) return null; const row = db.query("SELECT epoch,session_id,agent_provider_id FROM conversation_epochs WHERE id=? AND principal_id=?") .get(id, principalId) as { epoch: number; session_id: string | null; agent_provider_id: string | null } | null; if (!row) return null; diff --git a/packages/ui-server/src/ws/dialogue-storage.ts b/packages/ui-server/src/ws/dialogue-storage.ts index 4de4bb432d..5bd8750d87 100644 --- a/packages/ui-server/src/ws/dialogue-storage.ts +++ b/packages/ui-server/src/ws/dialogue-storage.ts @@ -9,6 +9,7 @@ import { dialogueEvidenceSchema, dialogueRecordSchema, } from "@schlessera/brain-ui-sdk/schemas"; +import { assertLive, isRetired } from "./chat-lifecycle.js"; export interface DialogueOwner { id: string; @@ -98,6 +99,8 @@ function activeEpochFor(db:Database, owner:DialogueOwner, principalId:string, ro export function openDialogue(db: Database, input: DialogueOpen, activeEpochs?:ReadonlyMap, pending:readonly PendingDialogueEpoch[]=[]): DialogueOwner { return db .transaction(() => { + // A retired chat's identities never open again (#3228). + assertLive(db, [["conversation", input.conversationId], ["session", input.sessionId], ["dialogue_owner", input.historyOwnerId]]); const known = db .query("SELECT * FROM dialogue_conversations WHERE id=?") .get(input.conversationId) as { @@ -132,6 +135,7 @@ export function openDialogue(db: Database, input: DialogueOpen, activeEpochs?:Re )?.id !== owner.id) ) throw new Error("Dialogue provisional owner unavailable"); + if (owner) assertLive(db, [["dialogue_owner", owner.id]]); if (!owner) { const id = input.conversationId; db.prepare( @@ -178,6 +182,9 @@ export function bindDialogue( .query("SELECT owner_id FROM dialogue_conversations WHERE id=?") .get(conversationId) as { owner_id: string } | null; if (!c) return null; + // A later adoption into or out of a retired chat refuses; an earlier one + // already joined the retirement's exact identity set (#3228). + assertLive(db, [["conversation", conversationId], ["session", sessionId], ["dialogue_owner", c.owner_id]]); const owner = dialogueOwner(db, { ownerId: c.owner_id }, principalId)!; if (owner.session_id && owner.session_id !== sessionId) throw new Error("Dialogue session cannot change"); @@ -237,8 +244,10 @@ export function appendDialogue( throw new Error("Dialogue record exceeds bounds"); return db .transaction(() => { + assertLive(db, [["dialogue_owner", input.ownerId]]); const owner = dialogueOwner(db, input, input.principalId); if (!owner) throw new Error("Dialogue owner unavailable"); + assertLive(db, [["dialogue_owner", owner.id], ["session", owner.session_id], ["conversation", evidence.kind === "voice" ? evidence.conversationId : undefined]]); if (evidence.kind === "voice") { const c = db .query( @@ -287,8 +296,12 @@ export function readDialogue( target: DialogueTarget, activeEpochs?: ReadonlyMap ): DialoguePage | null { - const owner = dialogueOwner(db, target, principalId); + // A retired chat reads as absent, without revealing that it existed. + if (target.sessionId ? isRetired(db, "session", target.sessionId) : target.ownerId && isRetired(db, "dialogue_owner", target.ownerId)) return null; + const owner = dialogueOwner(db, { ...target, generation: undefined }, principalId); if (!owner) return null; + if (target.generation !== undefined && owner.generation !== target.generation) + throw new Error("Dialogue generation changed"); if (target.cursor) { if (target.cursor.length > 2048) throw new Error("Invalid dialogue cursor"); const cursor = JSON.parse( @@ -397,6 +410,8 @@ export function closeDialogue( partial = false ): void { db.transaction(() => { + // Retirement already closed every epoch of the chat. + if (isRetired(db, "conversation", conversationId)) return; const c = db .query("SELECT owner_id FROM dialogue_conversations WHERE id=?") .get(conversationId) as { owner_id: string } | null; diff --git a/packages/ui-server/src/ws/session-catalog-writes.ts b/packages/ui-server/src/ws/session-catalog-writes.ts index 032dbcd182..f04cda630e 100644 --- a/packages/ui-server/src/ws/session-catalog-writes.ts +++ b/packages/ui-server/src/ws/session-catalog-writes.ts @@ -27,6 +27,7 @@ import * as work from "./session-work.js"; import { saveTurnFailure, type RecordedTurnFailure } from "./turn-failures.js"; import { saveConversationEpoch, saveConversationTask } from "./conversation-storage.js"; +import { recordChatCleanup, retireChat, type ChatStore, type ChatStoreOutcome, type RetireChatInput } from "./chat-lifecycle.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) @@ -183,6 +184,8 @@ export function setup(db: Database, options: SessionCatalogWriteOptions = {}): W dialogueAppend: (input: import("./dialogue-storage.js").DialogueAppend) => appendDialogue(db, input), dialogueBind: (conversationId: string, principalId: string, sessionId: string) => bindDialogue(db, conversationId, principalId, sessionId), conversationEpoch: (state: import("./conversation-storage.js").StoredConversationEpoch) => saveConversationEpoch(db, state), + retireChat: (input: RetireChatInput) => retireChat(db, input), + chatCleanup: (lifecycleId: string, store: ChatStore, outcome: Exclude, at: number) => recordChatCleanup(db, lifecycleId, store, outcome, at), conversationTask: (principalId: string, receipt: import("@schlessera/brain-ui-sdk/protocol").ConversationWorkReceipt, facts?: string) => saveConversationTask(db, principalId, receipt, facts), localExchange: (sessionId: string, exchange: LocalExchange, delivered: boolean, at: number) => saveLocalExchange(db, sessionId, exchange, delivered, at), exchangesDelivered: (sessionId: string, exchangeIds: string[], at: number) => markLocalExchangesDelivered(db, sessionId, exchangeIds, at), diff --git a/packages/ui-server/src/ws/session-catalog.ts b/packages/ui-server/src/ws/session-catalog.ts index efeddadbd5..fab6fd2f78 100644 --- a/packages/ui-server/src/ws/session-catalog.ts +++ b/packages/ui-server/src/ws/session-catalog.ts @@ -27,6 +27,7 @@ import { } from "./local-exchanges.js"; import { loadConversation } from "./conversation-storage.js"; +import { authorizedOwner, chatRetirement, isRetired, resolveChat, 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"; @@ -50,6 +51,21 @@ export interface SessionCatalog { dialogueAppend?(input: DialogueAppend): Promise; dialogueBind?(conversationId: string, principalId: string, sessionId: string): Promise; dialogueRead?(principalId: string, target: DialogueTarget): Promise; + /** + * Retire one chat's identities permanently (#3228). `busy` is the host's + * judgement of live effect holders over the chat's current identity set, + * asked at submission after ownership is known; a busy chat refuses before + * retirement. Authority, ownership, generation and adoption are decided + * again in the serialized writer. Removes no content and never reports a + * completed deletion by itself. + */ + retireChat?(input: RetireChatInput, busy: (identities: RetiredChatIdentities) => boolean): Promise; + /** A retirement's non-content outcome for its owner, or null. */ + chatRetirement?(operationId: string, principalId: string): Promise; + /** A selected store owner's cleanup report under the retirement's intent. */ + recordChatCleanup?(lifecycleId: string, store: ChatStore, outcome: Exclude): Promise; + /** Whether a chat identity is retired. Readers treat a retired chat as absent. */ + chatRetired?(target: ChatTarget | { conversationId: string }): boolean; saveConversationEpoch?(state: import("./conversation-storage.js").StoredConversationEpoch): Promise; saveConversationTask?(principalId: string, receipt: import("@schlessera/brain-ui-sdk/protocol").ConversationWorkReceipt, facts?: string): Promise; loadConversation?(id: string, principalId: string): Promise; @@ -270,16 +286,38 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi const pendingDialogueEpochs = new Set(); const retryGenerations = new Map(); const invalidatedRetries = new Set(); + const live = (owner: DialogueOwner | null) => owner && !isRetired(db(), "dialogue_owner", owner.id) ? owner : null; return { dialogueOwnerForConversation: (conversationId,principalId) => { + if(isRetired(db(),"conversation",conversationId)) return null; const row=db().query("SELECT owner_id FROM dialogue_conversations WHERE id=?").get(conversationId) as {owner_id:string}|null; - return row ? dialogueOwner(db(),{ownerId:row.owner_id},principalId) : null; + return row ? live(dialogueOwner(db(),{ownerId:row.owner_id},principalId)) : null; }, - dialogueOwnerForId: (ownerId,principalId) => dialogueOwner(db(),{ownerId},principalId), + dialogueOwnerForId: (ownerId,principalId) => isRetired(db(),"dialogue_owner",ownerId) ? null : live(dialogueOwner(db(),{ownerId},principalId)), dialogueOwnerForSession: sessionId => { + if(isRetired(db(),"session",sessionId)) return null; const row = db().query("SELECT principal_id FROM dialogue_owners WHERE session_id=?").get(sessionId) as {principal_id:string}|null; - return row ? dialogueOwner(db(),{sessionId},row.principal_id) : null; + return row ? live(dialogueOwner(db(),{sessionId},row.principal_id)) : null; + }, + async retireChat(input, busy) { + // 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" }; + const preview = resolveChat(db(), input.target); + if ("refused" in preview || preview.principalId !== 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") { + const owners = new Set(result.identities.dialogueOwners), conversations = new Set(result.identities.conversations); + for (const [id, scope] of activeDialogueEpochs) if (conversations.has(id) || owners.has(scope.owner.id)) activeDialogueEpochs.delete(id); + } + return result; }, + async chatRetirement(operationId, principalId) { await tail; return chatRetirement(db(), operationId, principalId); }, + recordChatCleanup: (lifecycleId, store, outcome) => submit("chatCleanup", lifecycleId, store, outcome, Date.now()), + chatRetired: target => "conversationId" in target ? isRetired(db(), "conversation", target.conversationId) + : "sessionId" in target ? isRetired(db(), "session", target.sessionId) : isRetired(db(), "dialogue_owner", target.ownerId), dialogueClose: (conversationId,principalId,epoch,partial) => { for(const scope of pendingDialogueEpochs) if(scope.input.conversationId===conversationId && scope.input.principalId===principalId && scope.input.epoch===epoch) scope.closed=true; const active=activeDialogueEpochs.get(conversationId); @@ -321,7 +359,7 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi async dialogueRead(principalId, target) { await tail; const page=readDialogue(db(), principalId, target, activeDialogueEpochs); - if(page || !target.sessionId || !hasUnretainedVoice(db(),principalId,target.sessionId)) return page; + if(page || !target.sessionId || isRetired(db(),"session",target.sessionId) || !hasUnretainedVoice(db(),principalId,target.sessionId)) return page; return {ownerId:target.sessionId,sessionId:target.sessionId,generation:1,through:0,records:[],coverage:"legacy"}; }, saveConversationEpoch: state => submit("conversationEpoch", state), diff --git a/packages/ui-server/tests/chat-lifecycle.test.ts b/packages/ui-server/tests/chat-lifecycle.test.ts new file mode 100644 index 0000000000..e0843440e9 --- /dev/null +++ b/packages/ui-server/tests/chat-lifecycle.test.ts @@ -0,0 +1,311 @@ +/** + * Chat identity retirement (#3228) on an actual file-backed SQLite write + * worker. Synthetic Odysseus fixtures only: no provider, backend or network. + */ +import { afterEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +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 { 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"; +import type { RetireChatInput, RetiredChatIdentities } from "../src/ws/chat-lifecycle.js"; +import * as controls from "./helpers/dialogue-test-writes.js"; + +const MARKER = "Odysseus hid the oar under the olive root"; +const CONTROL = "Penelope kept the loom unfinished"; +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); + +function voice(conversationId: string, sequence: number, text: string): Extract { + return { kind: "voice", conversationId, epoch: 1, providerId: "gemini-live", event: { + kind: "unassigned_input_fragment", sequence, text, timing: { kind: "unavailable" }, finalization: "unknown" } }; +} +function task(conversationId: string, index: number, sessionId?: string): Extract { + return { conversationId, epoch: 1, provenance: "contextual", taskId: `${conversationId}-task-${index}`, requestId: `${conversationId}-request-${index}`, + nativeHandle: `${conversationId}-native-${index}`, state: "completed", delivery: "returned", turnId: `${conversationId}-turn-${index}`, + recognized: MARKER, submitted: MARKER, ...(sessionId ? { sessionId } : {}) }; +} + +function open(path: string) { + const db = createUiDb(path), writer = openSqliteWriter(db); + const catalog = createSessionCatalog(() => db, undefined, undefined, { + writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(db, writer), + }); + const control = writer.channel({ url: controls.url, setup: controls.setup }, {}); + const holds: { gate: Int32Array; done: Promise }[] = []; + return { db, writer, catalog, + async hold() { + const gate = new Int32Array(new SharedArrayBuffer(8)); + holds.push({ gate, done: control.call("holdUntilReleased", gate) }); + const deadline = Date.now() + 2000; + while (!Atomics.load(gate, 1)) { if (Date.now() > deadline) throw Error("Ithaca writer did not hold"); await Bun.sleep(1); } + }, + release() { for (const { gate } of holds) { Atomics.store(gate, 0, 1); Atomics.notify(gate, 0); } }, + async close() { + this.release(); await Promise.all(holds.map(h => h.done)); + await catalog.settled!(); await control.close(); await writer.close(); db.close(); + }, + }; +} + +async function fixture() { + const root = mkdtempSync(join(tmpdir(), "odysseus-chat-lifecycle-")); roots.push(root); + 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; + 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 }; +} +async function seedChat(catalog: SessionCatalog, principalId: string, sessionId: string, conversationId: string, text: string) { + catalog.persistSessionStub(sessionId, "Plan the voyage home", null, "claude"); + const owner = await catalog.dialogueOpen!({ conversationId, principalId, epoch: 1, providerId: "gemini-live", sessionId }); + await catalog.dialogueAppend!({ ownerId: owner.id, principalId, generation: owner.generation, identity: `voice:${conversationId}:0`, evidence: voice(conversationId, 0, text) }); + await catalog.saveConversationEpoch!({ id: conversationId, principalId, epoch: 1, sessionId }); + await catalog.saveConversationTask!(principalId, task(conversationId, 1, sessionId), text); +} +const request = (principalId: string, overrides: Partial = {}): RetireChatInput => ({ + operationId: "retire-voyage", principalId, target: { sessionId: "voyage" }, + expected: { backendId: "claude", generation: 1 }, removableBackends: ["claude"], at: Date.now(), ...overrides, +}); +const idle = () => false; +const RETIRED = "This chat has been retired and cannot be used again."; +/** Settle to a comparable value; the writer's errors cross a thread boundary. */ +const settle = (p: Promise) => p.then(() => "written", (e: Error) => e.message); +const fences = (db: Database) => (db.query("SELECT COUNT(*) AS n FROM chat_lifecycles").get() as { n: number }).n; +async function readable(catalog: SessionCatalog, principalId: string, sessionId: string): Promise { + const page = await catalog.dialogueRead!(principalId, { sessionId }); + return (page?.records ?? []).map(r => r.evidence.kind === "voice" && "text" in r.evidence.event ? String(r.evidence.event.text) : ""); +} + +test("unauthorized, foreign, unknown, stale, unsupported and busy chats refuse before retirement without revealing existence", async () => { + const f = await fixture(); + try { + const { catalog, db } = f.host; + 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); + expect(foreign, "FOREIGN_REFUSAL_LEAKS_NOTHING").toEqual({ status: "refused", reason: "unavailable" }); + expect(missing).toEqual(foreign); + 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"); + await catalog.settled!(); + expect(await catalog.retireChat!(request(f.owner, { target: { sessionId: "scheria" } }), idle), "UNKNOWN_OWNERSHIP_REFUSES").toEqual({ status: "refused", reason: "unavailable" }); + expect(await catalog.retireChat!(request(f.owner, { expected: { backendId: "claude", generation: 2 } }), idle), "STALE_GENERATION_REFUSES").toEqual({ status: "refused", reason: "stale" }); + expect(await catalog.retireChat!(request(f.owner, { expected: { backendId: "pi", generation: 1 } }), idle), "STALE_BACKEND_REFUSES").toEqual({ status: "refused", reason: "stale" }); + expect(await catalog.retireChat!(request(f.owner, { removableBackends: [] }), idle), "UNSUPPORTED_BACKEND_REFUSES").toEqual({ status: "refused", reason: "unsupported" }); + expect(await catalog.retireChat!(request(f.owner), busyProbe), "BUSY_HOLDER_REFUSES").toEqual({ status: "refused", reason: "busy" }); + expect(consulted).toBe(1); + revokePrincipal(db, f.owner, Date.now()); + expect(await catalog.retireChat!(request(f.owner), idle), "REVOKED_OWNER_REFUSES").toEqual({ status: "refused", reason: "unauthorized" }); + expect(fences(db), "NO_RETIREMENT_AFTER_REFUSAL").toBe(0); + expect(await readable(catalog, f.owner, "voyage")).toEqual([MARKER]); + } finally { await f.host.close(); } +}); + +test("revocation while admission waits on the writer refuses at commit", async () => { + const f = await fixture(); + try { + await f.host.hold(); + const pending = f.host.catalog.retireChat!(request(f.owner), idle); + await Bun.sleep(20); + // Another connection, as a revocation request on another worker would be: + // the held app writer cannot take its turn until the release. + const other = new Database(f.path); other.exec("PRAGMA busy_timeout = 5000"); + try { revokePrincipal(other, f.owner, Date.now()); } finally { other.close(); } + f.host.release(); + expect(await pending, "COMMIT_RECHECKS_AUTHORITY").toEqual({ status: "refused", reason: "unauthorized" }); + 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 { + const { catalog, db } = f.host; + const owner = catalog.dialogueOwnerForSession!("voyage")!; + const cost = db.query("SELECT id,total_cost_usd,num_turns FROM sessions ORDER BY id").all(); + // Late callbacks already in flight when the retirement is submitted. + await f.host.hold(); + const retired = catalog.retireChat!(request(f.owner), idle); + await Bun.sleep(20); + const late = [ + catalog.dialogueAppend!({ ownerId: owner.id, principalId: f.owner, generation: owner.generation, identity: "voice:ithaca:1", evidence: voice("ithaca", 1, MARKER) }), + catalog.saveConversationTask!(f.owner, { ...task("ithaca", 1, "voyage"), delivery: "unknown" }, "replaced facts"), + catalog.saveConversationTask!(f.owner, task("ithaca", 2, "voyage"), MARKER), + catalog.dialogueOpen!({ conversationId: "ithaca", principalId: f.owner, epoch: 2, providerId: "gemini-live", sessionId: "voyage" }), + catalog.dialogueOpen!({ conversationId: "troy", principalId: f.owner, epoch: 1, providerId: "gemini-live", sessionId: "voyage" }), + catalog.saveConversationEpoch!({ id: "ithaca", principalId: f.owner, epoch: 2 }), + ].map(settle); + const control = catalog.dialogueAppend!({ ownerId: "circe", principalId: f.other, generation: 1, identity: "voice:circe:1", evidence: voice("circe", 1, CONTROL) }); + f.host.release(); + const result = await retired; + expect(result).toMatchObject({ status: "retired", lifecycleId: "voyage", operationId: "retire-voyage", generation: 2, cleanup: "pending", + stores: { native: "pending", dialogue: "pending", tasks: "pending", projections: "pending", drafts: "pending" } }); + if (result.status !== "retired") throw Error("unreachable"); + expect(result.identities).toEqual({ sessions: ["voyage"], dialogueOwners: ["ithaca"], conversations: ["ithaca"], + tasks: ["ithaca-task-1"], requests: ["ithaca-request-1"], nativeTasks: [JSON.stringify(["ithaca", 1, "ithaca-native-1"])] }); + const outcomes = await Promise.all(late); + expect(outcomes, "LATE_WRITES_REFUSED").toEqual(Array(6).fill(RETIRED)); + await control; + // No content was written or replaced under the retired identity. + expect(db.query("SELECT COUNT(*) AS n FROM dialogue_records WHERE owner_id='ithaca'").get()).toEqual({ n: 1 }); + expect(db.query("SELECT receipt IS NOT NULL AS kept, result_facts FROM conversation_tasks WHERE task_id='ithaca-task-1'").get()).toEqual({ kept: 1, result_facts: MARKER }); + expect(db.query("SELECT COUNT(*) AS n FROM conversation_tasks WHERE conversation_id='ithaca'").get()).toEqual({ n: 1 }); + // Readers treat it as absent; the unrelated chat is intact. + expect(await readable(catalog, f.owner, "voyage"), "RETIRED_READS_ABSENT").toEqual([]); + expect(await catalog.loadConversation!("ithaca", f.owner)).toBeNull(); + expect(catalog.dialogueOwnerForSession!("voyage")).toBeNull(); + expect(catalog.chatRetired!({ sessionId: "voyage" })).toBe(true); + expect(catalog.chatRetired!({ sessionId: "aeaea" })).toBe(false); + expect(await readable(catalog, f.other, "aeaea")).toEqual([CONTROL, CONTROL]); + expect((await catalog.loadConversation!("circe", f.other))?.results).toEqual([{ requestId: "circe-request-1", facts: CONTROL }]); + 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. + 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.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"); + expect(await catalog.recordChatCleanup!("voyage", "native", "unknown")).toBe("unknown"); + for (const store of ["native", "dialogue", "tasks", "projections"] as const) await catalog.recordChatCleanup!("voyage", store, "removed"); + expect(await catalog.recordChatCleanup!("voyage", "projections", "removed"), "PENDING_STORE_IS_NOT_COMPLETION").toBe("pending"); + expect(await catalog.recordChatCleanup!("voyage", "drafts", "removed")).toBe("removed"); + expect(await catalog.recordChatCleanup!("voyage", "native", "unknown"), "REMOVAL_IS_FINAL").toBe("removed"); + expect(() => db.exec("DELETE FROM chat_retired_identities"), "FENCES_ARE_PERMANENT").toThrow("permanent"); + } finally { await f.host.close(); } +}); + +test("fences survive content cascades and restart; consumed identities never execute again", async () => { + const f = await fixture(); + { + expect((await f.host.catalog.retireChat!(request(f.owner), idle)).status).toBe("retired"); + // What later content owners may remove, including the cascading task ledger. + f.host.db.exec(`DELETE FROM conversation_epochs WHERE id='ithaca'; + DELETE FROM dialogue_records WHERE owner_id='ithaca'; DELETE FROM dialogue_conversations WHERE owner_id='ithaca'; + DELETE FROM dialogue_owners WHERE id='ithaca'; DELETE FROM sessions WHERE id='voyage'`); + expect(f.host.db.query("SELECT COUNT(*) AS n FROM conversation_tasks WHERE conversation_id='ithaca'").get()).toEqual({ n: 0 }); + await f.host.close(); + const host = open(f.path); + try { + const { catalog } = host; + // Without the fence each of these would succeed against the scrubbed rows. + await catalog.saveConversationEpoch!({ id: "odyssey-new", principalId: f.owner, epoch: 1 }); + expect(await settle(catalog.saveConversationTask!(f.owner, { ...task("odyssey-new", 8), taskId: "ithaca-task-1" })), "CONSUMED_TASK_NEVER_REPLAYS").toBe(RETIRED); + expect(await settle(catalog.saveConversationTask!(f.owner, { ...task("odyssey-new", 9), requestId: "ithaca-request-1" })), "CONSUMED_REQUEST_NEVER_REPLAYS").toBe(RETIRED); + expect(await settle(catalog.saveConversationEpoch!({ id: "ithaca", principalId: f.owner, epoch: 1 }))).toBe(RETIRED); + expect(await settle(catalog.dialogueOpen!({ conversationId: "ithaca", principalId: f.owner, epoch: 1, providerId: "gemini-live" }))).toBe(RETIRED); + expect(await settle(catalog.dialogueOpen!({ conversationId: "troy", principalId: f.owner, epoch: 1, providerId: "gemini-live", sessionId: "voyage" })), "RETIRED_SESSION_NEVER_REOPENS").toBe(RETIRED); + expect(await catalog.loadConversation!("odyssey-new", f.owner)).toMatchObject({ requestIds: [] }); + expect(await readable(catalog, f.other, "aeaea")).toEqual([CONTROL]); + expect(await catalog.chatRetirement!("retire-voyage", f.owner)).toMatchObject({ status: "retired", generation: 2, cleanup: "pending" }); + } finally { await host.close(); } + } +}); + +for (const order of ["adoption-first", "retirement-first"] as const) test(`racing adoption is decided on one side of the retirement (${order})`, async () => { + const f = await fixture(); + try { + const { catalog } = f.host; + // A provisional chat (no backend session yet) about to be adopted into voyage. + const provisional = await catalog.dialogueOpen!({ conversationId: "ogygia", principalId: f.owner, epoch: 1, providerId: "gemini-live" }); + await catalog.dialogueAppend!({ ownerId: provisional.id, principalId: f.owner, generation: 1, identity: "voice:ogygia:0", evidence: voice("ogygia", 0, MARKER) }); + await f.host.hold(); + let bound: Promise, retired: ReturnType>; + if (order === "adoption-first") { + bound = settle(catalog.dialogueBind!("ogygia", f.owner, "voyage")); + retired = catalog.retireChat!(request(f.owner), idle); + } else { + retired = catalog.retireChat!(request(f.owner), idle); + await Bun.sleep(20); + bound = settle(catalog.dialogueBind!("ogygia", f.owner, "voyage")); + } + f.host.release(); + const result = await retired; + if (result.status !== "retired") throw Error(`not retired: ${JSON.stringify(result)}`); + if (order === "adoption-first") { + expect(await bound).toBe("written"); + expect(result.identities.conversations, "EARLIER_ADOPTION_EXPANDS_SET").toEqual(["ithaca", "ogygia"]); + expect(result.identities.dialogueOwners).toEqual(["ithaca", "ogygia"]); + expect(await settle(catalog.dialogueOpen!({ conversationId: "calypso", principalId: f.owner, epoch: 1, providerId: "gemini-live", historyOwnerId: "ogygia" })), + "ADOPTED_ALIAS_NEVER_REOPENS").toBe(RETIRED); + } else { + expect(await bound, "LATER_ADOPTION_REFUSED").toBe(RETIRED); + expect(result.identities.conversations).toEqual(["ithaca"]); + // The provisional chat stays its owner's own separate, unretired chat. + expect(catalog.dialogueOwnerForId!("ogygia", f.owner)).toMatchObject({ id: "ogygia", session_id: null, generation: 1 }); + expect((await catalog.dialogueRead!(f.owner, { ownerId: "ogygia" }))?.records).toHaveLength(1); + } + } finally { await f.host.close(); } +}); + +test("a provisional chat retires by its owner identity without a native store", async () => { + const f = await fixture(); + try { + const { catalog } = f.host; + await catalog.dialogueOpen!({ conversationId: "ogygia", principalId: f.owner, epoch: 1, providerId: "gemini-live" }); + const result = await catalog.retireChat!(request(f.owner, { operationId: "retire-ogygia", target: { ownerId: "ogygia" }, expected: { backendId: null, generation: 1 }, removableBackends: [] }), idle); + expect(result).toMatchObject({ status: "retired", lifecycleId: "ogygia", stores: { dialogue: "pending", tasks: "pending", projections: "pending", drafts: "pending" } }); + if (result.status === "retired") expect(result.stores.native).toBeUndefined(); + 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. + 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" }); + } finally { await f.host.close(); } +}); + +async function inbox(args: string[]) { + const child = Bun.spawn([process.execPath, join(import.meta.dir, "../src/bin/brain-ui-inbox.ts"), ...args], { stdout: "pipe", stderr: "pipe" }); + const [out, err, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + return { value: JSON.parse(out) as { ok: boolean }, err, code }; +} +test("a post-retirement backup restores its fences; an older backup restores text, the accepted recovery-point limit", async () => { + const f = await fixture(); + const brain = join(f.root, "brain"); mkdirSync(brain); + const before = join(f.root, "before.json"), after = join(f.root, "after.json"); + await f.host.close(); + expect(await inbox(["export", "--db", f.path, "--brain-root", brain, "--file", before, "--json"])).toMatchObject({ code: 0, err: "", value: { ok: true } }); + let host = open(f.path); + try { expect((await host.catalog.retireChat!(request(f.owner), idle)).status).toBe("retired"); } + finally { await host.close(); } + expect(await inbox(["export", "--db", f.path, "--brain-root", brain, "--file", after, "--json"])).toMatchObject({ code: 0, err: "", value: { ok: true } }); + const restore = async (file: string, name: string) => { + const dir = join(f.root, name), target = join(dir, "brain"); mkdirSync(target, { recursive: true }); + expect(await inbox(["restore", "--db", join(dir, "ui.db"), "--brain-root", target, "--file", file, "--json"])).toMatchObject({ code: 0, err: "", value: { ok: true } }); + return join(dir, "ui.db"); + }; + host = open(await restore(after, "after")); + try { + const { catalog } = host; + expect(catalog.chatRetired!({ sessionId: "voyage" }), "POST_RETIREMENT_IMAGE_KEEPS_FENCES").toBe(true); + expect(await readable(catalog, f.owner, "voyage")).toEqual([]); + expect(await settle(catalog.saveConversationTask!(f.owner, task("ithaca", 1, "voyage")))).toContain("retired"); + expect(await settle(catalog.dialogueOpen!({ conversationId: "ithaca", principalId: f.owner, epoch: 2, providerId: "gemini-live" }))).toContain("retired"); + expect(await readable(catalog, f.other, "aeaea")).toEqual([CONTROL]); + } finally { await host.close(); } + host = open(await restore(before, "before")); + try { + // Disclosed limitation, not a no-resurrection result: the older image predates the fence. + expect(host.catalog.chatRetired!({ sessionId: "voyage" })).toBe(false); + expect(await readable(host.catalog, f.owner, "voyage"), "OLDER_IMAGE_RESTORES_TEXT").toEqual([MARKER]); + } finally { await host.close(); } +}); From ef3f31771cfd1f720df050a1e18f2df4170cd112 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 12:53:56 +0000 Subject: [PATCH 2/4] docs: record the chat retirement ledger and its old-backup limit Re-anchor the moved dialogue/conversation/catalog citations, describe what #3228 built in the deletion design, disclose that a pre-retirement operational backup restores chat text, and add the ui-server changeset. Co-Authored-By: Claude Opus 5.5 --- .changeset/chat-identity-retirement.md | 5 +++++ docs/decisions/governed-writable-workers.md | 2 +- docs/inbox-recovery.md | 9 ++++++++ docs/plans/chat-history-deletion.md | 25 +++++++++++++++------ docs/plans/navigation-recovery.md | 2 +- 5 files changed, 34 insertions(+), 9 deletions(-) create mode 100644 .changeset/chat-identity-retirement.md diff --git a/.changeset/chat-identity-retirement.md b/.changeset/chat-identity-retirement.md new file mode 100644 index 0000000000..f1af532f0d --- /dev/null +++ b/.changeset/chat-identity-retirement.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +The UI database gains an internal, content-free ledger of retired chat identities (#3228, migration `073_chat_lifecycle.sql`). Nothing retires a chat yet: there is no endpoint, backend removal or UI, and no content is deleted. Once a later release retires a chat, its session, dialogue owners and aliases, conversations and consumed task and request identities stay refused permanently, across restarts and in operational backups taken afterwards. An operational backup taken before a retirement still restores that chat's text; the recovery documentation states this limit. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 382525498f..80076ee763 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1899,7 +1899,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:447`) + (`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:485`) must not feed any budget. **Enforcement:** diff --git a/docs/inbox-recovery.md b/docs/inbox-recovery.md index 5e2274a83e..e9bc735b26 100644 --- a/docs/inbox-recovery.md +++ b/docs/inbox-recovery.md @@ -29,6 +29,15 @@ marks incomplete continuity explicitly; it restores no microphone consent, audio, executable native response or permission grant. Re-indexing Markdown cannot recreate missing dialogue. +Retired chat identities (#3228) are minimized fences without content: the +chat, its former session, dialogue owners and aliases, conversations, consumed +task and request identities, the owner, terminal generation and per-store +cleanup outcomes. They are permanent within the installation. A backup taken +after a retirement restores them, and the restored host still refuses those +identities. **A backup taken before a retirement restores the chat's text and +predates its fence**: an older recovery point can bring deleted history back. +That limit is accepted; no ledger outside the image replays later retirements. + Activity spans/rollups preserve observed spend; principal records preserve identity attribution. Other UI state, including sessions, authentication records and settings, travels with the same image. The turn journal keeps its diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index a7f160d8df..78ff9c5144 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -4,8 +4,19 @@ This is the implementation design for [#3180](https://github.com/schlessera/brai source-audited against main `6fa3ec1305e8b52991252d6a28959a68c56be1c1` on 2026-11-01. The [binding decision](../decisions/chat-history-deletion.md) records the approved authority, extent and permanent-fence/backup policy. -Deletion runtime, endpoint and UI are not built. Approval supplies no automatic -expiry, routine live cutoff or implementation release commitment. +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:153-186`; +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 +targets before retiring, and makes later dialogue/task writers and readers +refuse the retired identities. It removes no content and reports every store +pending until that store's owner confirms removal. A typed native-only chat +with no recorded owner refuses as unknown ownership; no ownership is backfilled. +Native removal, host-copy cleanup, the endpoint and UI are not built. ## Selected local lifecycle @@ -113,16 +124,16 @@ must be tested through their installed runtime, not inferred from directory name Payloads include independent recognition/output evidence and backend range text; hashes/order/identity are not substitutes for erasing the payload. An owner can start unbound, bind to a backend session or merge into an existing owner through - aliases (`bindDialogue`, `packages/ui-server/src/ws/dialogue-storage.ts:169-212`). + aliases (`bindDialogue`, `packages/ui-server/src/ws/dialogue-storage.ts:173-219`). Resolve the complete alias/conversation set transactionally; do not delete only the current session key or confuse a provisional owner ID with a backend ID. - **Task recovery and facts.** `069_conversation_tasks.sql` and `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:35-71`). + (`saveConversationTask`, `packages/ui-server/src/ws/conversation-storage.ts:37-77`). Loading may return receipts/results even without a current provider session - (`loadConversation`, `packages/ui-server/src/ws/conversation-storage.ts:72-98`). + (`loadConversation`, `packages/ui-server/src/ws/conversation-storage.ts:78-105`). 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; @@ -178,8 +189,8 @@ must be tested through their installed runtime, not inferred from directory name handoff preparation, classifier callbacks, DialogueJournal routing/pending writes, ConversationHost receipts/results/output and frozen startup envelopes can retain or publish text. Catalog optimistic maps precede worker acknowledgements - (`rowEffects`, `packages/ui-server/src/ws/session-catalog.ts:227-240`; - `activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:269-272`). + (`rowEffects`, `packages/ui-server/src/ws/session-catalog.ts:243-256`; + `activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:285-288`). Both submission and worker commit need a generation check. - **Browser state.** Chat buffers/history chunks, shared timeline, session title/list cache, dialogue pages/cursors, recognition/generated/unsaved tails, diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 4d2343fd3d..7442d97504 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -387,7 +387,7 @@ implementation. Any PR moving these lines owns their citation repairs. - Host resume: (`case "session_resume": {`, `packages/ui-server/src/ws/dispatch.ts:648-712`). -- Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId) {`, `packages/ui-server/src/ws/session-catalog.ts:441-448`). +- Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId) {`, `packages/ui-server/src/ws/session-catalog.ts:479-486`). - Session summary shape: (`export interface ChatSession {`, `packages/ui-sdk/src/protocol.ts:1576-1592`). From 8867a48a4b3514f986718c9d9a1937df754e766b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 12:55:53 +0000 Subject: [PATCH 3/4] chore(ui-server): refresh the API report for the internal chat retirement seam SessionCatalog is exported only from @schlessera/brain-ui-server/internal, which the integration contract excludes; the new optional methods change no supported surface. Co-Authored-By: Claude Opus 5.5 --- api-report/ui-server.txt | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 8673230d96..9c2753d14e 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -435,6 +435,8 @@ signatures (every public export and the types it is made of) cancelActiveTurns(): boolean; close(): Promise; } + CHAT_STORES (packages/ui-server/src/ws/chat-lifecycle.ts) + const CHAT_STORES: readonly ["native", "dialogue", "tasks", "projections", "drafts"]; CapturedLog (packages/ui-server/src/observability/types.ts) export interface CapturedLog { scope: string; @@ -443,6 +445,18 @@ signatures (every public export and the types it is made of) attributes: FlatAttributes; timestamp: number; } + ChatRetirementStatus (packages/ui-server/src/ws/chat-lifecycle.ts) + export type ChatRetirementStatus = "pending" | "partial" | "unknown" | "removed"; + ChatStore (packages/ui-server/src/ws/chat-lifecycle.ts) + export type ChatStore = (typeof CHAT_STORES)[number]; + ChatStoreOutcome (packages/ui-server/src/ws/chat-lifecycle.ts) + export type ChatStoreOutcome = "pending" | "partial" | "unknown" | "removed"; + ChatTarget (packages/ui-server/src/ws/chat-lifecycle.ts) + export type ChatTarget = { + sessionId: string; + } | { + ownerId: string; + }; ClaudeUsageEvidence (packages/ui-server/src/ws/claude-usage-accounting.ts) export interface ClaudeUsageEvidence { title?: TitleEvidence; @@ -1636,6 +1650,42 @@ signatures (every public export and the types it is made of) failureMessage: string; prompt: string; } + RetireChatInput (packages/ui-server/src/ws/chat-lifecycle.ts) + export interface RetireChatInput { + operationId: string; + principalId: string; + target: ChatTarget; + expected: { + backendId: string | null; + generation: number; + }; + removableBackends: readonly string[]; + at: number; + } + RetireChatResult (packages/ui-server/src/ws/chat-lifecycle.ts) + export type RetireChatResult = { + status: "refused"; + reason: RetireRefusal; + } | { + status: "retired"; + lifecycleId: string; + operationId: string; + generation: number; + identities: RetiredChatIdentities; + cleanup: ChatRetirementStatus; + stores: Partial>; + }; + RetireRefusal (packages/ui-server/src/ws/chat-lifecycle.ts) + export type RetireRefusal = "unauthorized" | "unavailable" | "stale" | "unsupported" | "busy"; + RetiredChatIdentities (packages/ui-server/src/ws/chat-lifecycle.ts) + export interface RetiredChatIdentities { + sessions: string[]; + dialogueOwners: string[]; + conversations: string[]; + tasks: string[]; + requests: string[]; + nativeTasks: string[]; + } RunRollupRow (packages/ui-server/src/activity/store.ts) export interface RunRollupRow { runId: string; @@ -1745,6 +1795,12 @@ signatures (every public export and the types it is made of) dialogueAppend?(input: DialogueAppend): Promise; dialogueBind?(conversationId: string, principalId: string, sessionId: string): Promise; dialogueRead?(principalId: string, target: DialogueTarget): Promise; + retireChat?(input: RetireChatInput, busy: (identities: RetiredChatIdentities) => boolean): Promise; + chatRetirement?(operationId: string, principalId: string): Promise; + recordChatCleanup?(lifecycleId: string, store: ChatStore, outcome: Exclude): Promise; + chatRetired?(target: ChatTarget | { + conversationId: string; + }): boolean; saveConversationEpoch?(state: import("./conversation-storage.js").StoredConversationEpoch): Promise; saveConversationTask?(principalId: string, receipt: import("@schlessera/brain-ui-sdk/protocol").ConversationWorkReceipt, facts?: string): Promise; loadConversation?(id: string, principalId: string): Promise; From 80b3ce66afdeec7a02da7a7ae3adf8248988ce8a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 12:59:38 +0000 Subject: [PATCH 4/4] feat(ui-server): refuse new work, retries and projections for a retired session Session-keyed catalog writers (accepted work and dispatch revisions, retry retention and reservation, message sources, thinking levels, turn boundaries and failures, local exchanges, labels, handoff links, state room and the session row) refuse a retired session in the serialized writer, so a consumed revision or retry cannot run again and a scrubbed session row is not recreated with its title (#3228). Accounting and clearing stay open. Co-Authored-By: Claude Opus 5.5 --- .../src/ws/session-catalog-writes.ts | 38 +++++++++++-------- .../ui-server/tests/chat-lifecycle.test.ts | 9 +++++ 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/packages/ui-server/src/ws/session-catalog-writes.ts b/packages/ui-server/src/ws/session-catalog-writes.ts index f04cda630e..728cde6054 100644 --- a/packages/ui-server/src/ws/session-catalog-writes.ts +++ b/packages/ui-server/src/ws/session-catalog-writes.ts @@ -27,7 +27,7 @@ import * as work from "./session-work.js"; import { saveTurnFailure, type RecordedTurnFailure } from "./turn-failures.js"; import { saveConversationEpoch, saveConversationTask } from "./conversation-storage.js"; -import { recordChatCleanup, retireChat, type ChatStore, type ChatStoreOutcome, type RetireChatInput } from "./chat-lifecycle.js"; +import { assertLive, recordChatCleanup, retireChat, type ChatStore, type ChatStoreOutcome, type RetireChatInput } from "./chat-lifecycle.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) @@ -136,8 +136,13 @@ export function setup(db: Database, options: SessionCatalogWriteOptions = {}): W // Keep an invalidation even if its DELETE fails: later reservations must // never dispatch the obsolete row left behind. A successful new save resets it. const invalidatedRetries = new Set(); + // A retired chat's session accepts no new work, revision, retry, content or + // projection (#3228). Every write here runs serialized with the retirement, + // so the check and its write cannot straddle it. Accounting and clearing stay open. + const live = (sessionId: string) => assertLive(db, [["session", sessionId]]); return { saveRetryRequest(sessionId: string, turnId: string, principalId: string, request: ClientChatMessage, prompt: string, failure: TurnFailure) { + live(sessionId); retries.saveRetryRequest(db, sessionId, turnId, principalId, request, prompt, failure); invalidatedRetries.delete(sessionId); }, @@ -147,11 +152,13 @@ export function setup(db: Database, options: SessionCatalogWriteOptions = {}): W }, refuseRetry: (sessionId: string, requestId: string, principalId: string, message: string) => retries.refuseRetry(db, sessionId, requestId, principalId, message), reserveRetry(sessionId: string, turnId: string, requestId: string, principalId: string, expectedPrompt?: string) { + live(sessionId); if (invalidatedRetries.has(sessionId)) return { receipt: retries.refuseRetry(db, sessionId, requestId, principalId, "The original request is unavailable or is no longer the latest turn.") }; return retries.reserveRetry(db, sessionId, turnId, requestId, principalId, expectedPrompt); }, upsertSession(row: SessionRow) { + live(row.id); db.prepare(UPSERT_SESSION_SQL).run(row.id, row.title, row.at, row.at, row.costUsd, row.turns, row.providerId, row.backendId); }, claudeUsage(sessionId: string, backendId: string, turnId: string, evidence: ClaudeUsageEvidence, resumed: boolean, context?: ClaudeUsageContext) { @@ -159,24 +166,25 @@ export function setup(db: Database, options: SessionCatalogWriteOptions = {}): W accountClaudeUsage(db, store, pricing(), sessionId, backendId, turnId, evidence, resumed, context); }, stateRoom(sessionId: string, observation: StateRoomObservation) { + live(sessionId); db.query("INSERT INTO session_state_room (session_id, observation) VALUES (?, ?) ON CONFLICT(session_id) DO UPDATE SET observation = excluded.observation") .run(sessionId, JSON.stringify(observation)); }, - turnFailure: (sessionId: string, backendId: string, record: RecordedTurnFailure) => saveTurnFailure(db, sessionId, backendId, record), - acceptWork: (sessionId: string, input: { revision: number; requestId: string | null; backendId: string | null; at: number }) => - work.acceptWork(db, sessionId, input), - dispatchWork: (sessionId: string, input: { revision: number; turnId: string; backendId: string; startedAt: number }) => - work.dispatchWork(db, sessionId, input), - turnBoundary: (sessionId: string, backendId: string, boundary: work.TurnBoundary) => work.saveTurnBoundary(db, sessionId, backendId, boundary), - messageSource: (sessionId: string, text: string, source: MessageSource, effort: { thinkingLevel?: ThinkingLevel; turnId: string; files?: SharedFileMeta[] } | undefined, at: number) => - saveMessageSource(db, sessionId, text, source, effort, at), - effectiveThinkingLevel: (sessionId: string, turnId: string, level: ThinkingLevel) => saveEffectiveThinkingLevel(db, sessionId, turnId, level), + turnFailure: (sessionId: string, backendId: string, record: RecordedTurnFailure) => { live(sessionId); return saveTurnFailure(db, sessionId, backendId, record); }, + acceptWork: (sessionId: string, input: { revision: number; requestId: string | null; backendId: string | null; at: number }) => { live(sessionId); return work.acceptWork(db, sessionId, input); }, + dispatchWork: (sessionId: string, input: { revision: number; turnId: string; backendId: string; startedAt: number }) => { live(sessionId); return work.dispatchWork(db, sessionId, input); }, + turnBoundary: (sessionId: string, backendId: string, boundary: work.TurnBoundary) => { live(sessionId); return work.saveTurnBoundary(db, sessionId, backendId, boundary); }, + messageSource: (sessionId: string, text: string, source: MessageSource, effort: { thinkingLevel?: ThinkingLevel; turnId: string; files?: SharedFileMeta[] } | undefined, at: number) => { live(sessionId); return saveMessageSource(db, sessionId, text, source, effort, at); }, + effectiveThinkingLevel: (sessionId: string, turnId: string, level: ThinkingLevel) => { live(sessionId); return saveEffectiveThinkingLevel(db, sessionId, turnId, level); }, // A stub that failed to persist leaves no row to update: that is not a // recorded link, and saying so keeps the caller's key fail-closed. - handoff: (sessionId: string, handoffId: string, sourceSessionId: string, sourceTurns: number | null) => - db.query("UPDATE sessions SET handoff_from = ?, handoff_id = ?, handoff_from_turns = ? WHERE id = ? RETURNING id") - .get(sourceSessionId, handoffId, sourceTurns, sessionId) !== null, + handoff(sessionId: string, handoffId: string, sourceSessionId: string, sourceTurns: number | null) { + live(sessionId); + return db.query("UPDATE sessions SET handoff_from = ?, handoff_id = ?, handoff_from_turns = ? WHERE id = ? RETURNING id") + .get(sourceSessionId, handoffId, sourceTurns, sessionId) !== null; + }, label(sessionId: string, label: string, source: string) { + live(sessionId); db.prepare("UPDATE sessions SET label = ?, label_source = ? WHERE id = ?").run(label, source, sessionId); }, dialogueClose: (conversationId:string,principalId:string,epoch:number,partial:boolean) => closeDialogue(db,conversationId,principalId,epoch,partial), @@ -187,8 +195,8 @@ export function setup(db: Database, options: SessionCatalogWriteOptions = {}): W retireChat: (input: RetireChatInput) => retireChat(db, input), chatCleanup: (lifecycleId: string, store: ChatStore, outcome: Exclude, at: number) => recordChatCleanup(db, lifecycleId, store, outcome, at), conversationTask: (principalId: string, receipt: import("@schlessera/brain-ui-sdk/protocol").ConversationWorkReceipt, facts?: string) => saveConversationTask(db, principalId, receipt, facts), - localExchange: (sessionId: string, exchange: LocalExchange, delivered: boolean, at: number) => saveLocalExchange(db, sessionId, exchange, delivered, at), - exchangesDelivered: (sessionId: string, exchangeIds: string[], at: number) => markLocalExchangesDelivered(db, sessionId, exchangeIds, at), + localExchange: (sessionId: string, exchange: LocalExchange, delivered: boolean, at: number) => { live(sessionId); return saveLocalExchange(db, sessionId, exchange, delivered, at); }, + exchangesDelivered: (sessionId: string, exchangeIds: string[], at: number) => { live(sessionId); return markLocalExchangesDelivered(db, sessionId, exchangeIds, at); }, addCost(sessionId: string, costUsd: number) { db.prepare("UPDATE sessions SET total_cost_usd = COALESCE(total_cost_usd, 0) + ? WHERE id = ?").run(costUsd, sessionId); }, diff --git a/packages/ui-server/tests/chat-lifecycle.test.ts b/packages/ui-server/tests/chat-lifecycle.test.ts index e0843440e9..f9d005b0c6 100644 --- a/packages/ui-server/tests/chat-lifecycle.test.ts +++ b/packages/ui-server/tests/chat-lifecycle.test.ts @@ -211,6 +211,15 @@ test("fences survive content cascades and restart; consumed identities never exe expect(await settle(catalog.dialogueOpen!({ conversationId: "ithaca", principalId: f.owner, epoch: 1, providerId: "gemini-live" }))).toBe(RETIRED); expect(await settle(catalog.dialogueOpen!({ conversationId: "troy", principalId: f.owner, epoch: 1, providerId: "gemini-live", sessionId: "voyage" })), "RETIRED_SESSION_NEVER_REOPENS").toBe(RETIRED); expect(await catalog.loadConversation!("odyssey-new", f.owner)).toMatchObject({ requestIds: [] }); + // The session accepts no new revision, retry or projection, and its scrubbed row is not recreated. + const accepted: boolean[] = []; + catalog.acceptWork!("voyage", "request-after", "claude", stored => accepted.push(stored)); + catalog.acceptWork!("aeaea", "request-control", "claude", stored => accepted.push(stored)); + catalog.persistSessionStub("voyage", MARKER, null, "claude"); + expect(await settle(catalog.reserveRetry!("voyage", "voyage-turn", "retry-after", f.owner)), "RETIRED_SESSION_NEVER_RETRIES").toBe(RETIRED); + await catalog.settled!(); + expect(accepted, "RETIRED_SESSION_ACCEPTS_NO_REVISION").toEqual([false, true]); + expect(host.db.query("SELECT COUNT(*) AS n FROM sessions WHERE id='voyage'").get(), "RETIRED_SESSION_ROW_NOT_RECREATED").toEqual({ n: 0 }); expect(await readable(catalog, f.other, "aeaea")).toEqual([CONTROL]); expect(await catalog.chatRetirement!("retire-voyage", f.owner)).toMatchObject({ status: "retired", generation: 2, cleanup: "pending" }); } finally { await host.close(); }