From 7153284b8c21f689f038744118d5e133df2b25fc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 18:40:37 +0000 Subject: [PATCH 1/3] CONTRACT: feat(ui-server): delete an owner's chat across local stores with truthful outcomes Add `POST /api/chat-deletions` (#3230). For the authenticated owner it refuses busy work, unsupported backends and stale reviews before anything is retired, then retires the chat, ends its live conversation epochs, tells the owner's declaring clients with `chat_retired`, and asks every selected store to remove its copies under the retirement's operation: the backend's native history, dialogue records, task receipt text and result facts, session title/label and projections, and drafts positively bound to the chat with their images and receipt fingerprints. A host store reports `removed` only when a read-back finds nothing selected; anything else stays pending, partial or unknown, and a repeated request or a host restart retries it under the same operation. Consumed task, request, retry and draft-send identities stay as replay fences. The content-free receipt always lists what local deletion keeps. A retired chat is absent from every list, read, resume, recovery and live-startup path for every client, rechecked after each await, and the host's history preparation refuses it as the final synchronous gate. Draft routes refuse drafts bound to it with `DRAFT_CHAT_RETIRED`. The SDK exports the request, receipt, frame, capability and schema; the HTTP, wire and package contract components, the API reports and the deletion design record it. Citations moved by these edits are re-anchored. Refs #3230 Co-Authored-By: Claude Opus 5.5 --- .changeset/chat-deletion-endpoint.md | 20 ++ api-report/ui-sdk.txt | 90 +++++- api-report/ui-server.txt | 38 +++ docs/decisions/answer-delivery.md | 2 +- docs/decisions/claude-code-runtime.md | 4 +- .../design-kit/sessions-and-drafts.md | 2 +- docs/decisions/governed-writable-workers.md | 2 +- docs/decisions/http-api-boundary.md | 8 +- docs/decisions/scheduled-tasks.md | 2 +- docs/decisions/session-principals.md | 6 +- docs/decisions/voice-permission.md | 8 +- docs/http-api-coverage.md | 11 +- docs/http-api.md | 46 +++ docs/integration-contract.md | 16 + docs/integration-contract/package-api.md | 18 ++ docs/integration-contract/wire.md | 44 ++- .../live-conversation-investigation.md | 4 +- .../plans/async-collaboration-requirements.md | 4 +- docs/plans/async-collaboration.md | 6 +- docs/plans/chat-history-deletion.md | 36 ++- docs/plans/navigation-recovery.md | 12 +- docs/plans/storage-accounting.md | 2 +- docs/plans/voice-conversation.md | 6 +- .../hooks/websocket-handlers/connection.ts | 5 +- packages/ui-sdk/src/protocol.ts | 74 ++++- packages/ui-sdk/src/schemas.ts | 9 + packages/ui-server/src/app.ts | 13 +- packages/ui-server/src/drafts/store.ts | 19 +- .../ui-server/src/routes/chat-deletions.ts | 62 ++++ packages/ui-server/src/routes/sessions.ts | 16 +- packages/ui-server/src/ws/chat-deletion.ts | 105 ++++++ packages/ui-server/src/ws/chat-lifecycle.ts | 30 +- .../ui-server/src/ws/chat-store-cleanup.ts | 88 +++++ packages/ui-server/src/ws/connection.ts | 4 +- packages/ui-server/src/ws/conversation.ts | 30 ++ packages/ui-server/src/ws/dispatch.ts | 8 + packages/ui-server/src/ws/host.ts | 35 +- packages/ui-server/src/ws/live-history.ts | 25 +- packages/ui-server/src/ws/recovery.ts | 3 + .../src/ws/session-catalog-writes.ts | 2 + packages/ui-server/src/ws/session-catalog.ts | 9 +- packages/ui-server/src/ws/session-recovery.ts | 16 +- .../ui-server/tests/chat-deletion.test.ts | 305 ++++++++++++++++++ .../tests/helpers/http-mount-lifetimes.ts | 1 + .../tests/http-supported-mounts.test.ts | 3 + .../ui-server/tests/ws-chat-deletion.test.ts | 125 +++++++ 46 files changed, 1288 insertions(+), 86 deletions(-) create mode 100644 .changeset/chat-deletion-endpoint.md create mode 100644 packages/ui-server/src/routes/chat-deletions.ts create mode 100644 packages/ui-server/src/ws/chat-deletion.ts create mode 100644 packages/ui-server/src/ws/chat-store-cleanup.ts create mode 100644 packages/ui-server/tests/chat-deletion.test.ts create mode 100644 packages/ui-server/tests/ws-chat-deletion.test.ts diff --git a/.changeset/chat-deletion-endpoint.md b/.changeset/chat-deletion-endpoint.md new file mode 100644 index 0000000000..e834e31d30 --- /dev/null +++ b/.changeset/chat-deletion-endpoint.md @@ -0,0 +1,20 @@ +--- +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-react": patch +--- + +An authenticated owner can delete its own chat's local history with +`POST /api/chat-deletions` (#3230). The chat is retired first; then its +backend's native history, canonical dialogue, task receipt text, session +projections and positively bound drafts are removed, each confirmed by its +own store. The receipt reports every store's outcome (`removed`, `pending`, +`partial` or `unknown`) and always lists what local deletion keeps: +independent saved content, effects and their audit, provider copies, backups +and offline devices. A repeated operation, or a host restart, finishes an +unconfirmed cleanup. Agents, ambient callers without an owner mapping and +other principals are refused, as are busy chats and backends that cannot +remove native history. A deleted chat is absent from every list, read, +resume, recovery and live-startup path, even for an older client; capable +clients of the same owner receive `chat_retired`. The SDK adds the request, +receipt, frame, capability and schema, and drafts gain `DRAFT_CHAT_RETIRED`. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 68adea4aed..a5b0a960e1 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -57,8 +57,15 @@ export "." (./src/index.ts) type BrainStats type BudgetObservation type BudgetScope + CHAT_DELETION_CAPABILITY CONVERSATION_CAPABILITY_KEYS CONVERSATION_LIMITS + type ChatDeletionOutcome + type ChatDeletionReceipt + type ChatDeletionRefusal + type ChatDeletionRequest + type ChatDeletionRetained + type ChatDeletionStore type ChatFileAttachment type ChatImageAttachment type ChatSession @@ -262,6 +269,7 @@ export "." (./src/index.ts) type ServerAskUserListRequest type ServerAskUserRankRequest type ServerAskUserRequest + type ServerChatRetired type ServerConversationClosed type ServerConversationEvent type ServerConversationOpened @@ -502,10 +510,17 @@ export "./client" (./src/client/index.ts) type BridgeToolName type BudgetObservation type BudgetScope + CHAT_DELETION_CAPABILITY COMPLETE_SHARE_CONTRACT COMPLETE_SHARE_INPUT_SCHEMA CONVERSATION_CAPABILITY_KEYS CONVERSATION_LIMITS + type ChatDeletionOutcome + type ChatDeletionReceipt + type ChatDeletionRefusal + type ChatDeletionRequest + type ChatDeletionRetained + type ChatDeletionStore type ChatFileAttachment type ChatImageAttachment type ChatSession @@ -782,6 +797,7 @@ export "./client" (./src/client/index.ts) type ServerAskUserListRequest type ServerAskUserRankRequest type ServerAskUserRequest + type ServerChatRetired type ServerConversationClosed type ServerConversationEvent type ServerConversationOpened @@ -1331,8 +1347,15 @@ export "./protocol" (./src/protocol.ts) type BrainStats type BudgetObservation type BudgetScope + CHAT_DELETION_CAPABILITY CONVERSATION_CAPABILITY_KEYS CONVERSATION_LIMITS + type ChatDeletionOutcome + type ChatDeletionReceipt + type ChatDeletionRefusal + type ChatDeletionRequest + type ChatDeletionRetained + type ChatDeletionStore type ChatFileAttachment type ChatImageAttachment type ChatSession @@ -1528,6 +1551,7 @@ export "./protocol" (./src/protocol.ts) type ServerAskUserListRequest type ServerAskUserRankRequest type ServerAskUserRequest + type ServerChatRetired type ServerConversationClosed type ServerConversationEvent type ServerConversationOpened @@ -1794,6 +1818,7 @@ export "./schemas" (./src/schemas.ts) serverAskUserListRequestSchema serverAskUserRankRequestSchema serverAskUserRequestSchema + serverChatRetiredSchema serverConversationClosedSchema serverConversationEventSchema serverConversationOpenedSchema @@ -1974,10 +1999,17 @@ export "./server" (./src/server/index.ts) type BridgeToolName type BudgetObservation type BudgetScope + CHAT_DELETION_CAPABILITY COMPLETE_SHARE_CONTRACT COMPLETE_SHARE_INPUT_SCHEMA CONVERSATION_CAPABILITY_KEYS CONVERSATION_LIMITS + type ChatDeletionOutcome + type ChatDeletionReceipt + type ChatDeletionRefusal + type ChatDeletionRequest + type ChatDeletionRetained + type ChatDeletionStore type ChatFileAttachment type ChatImageAttachment type ChatSession @@ -2287,6 +2319,7 @@ export "./server" (./src/server/index.ts) type ServerAskUserListRequest type ServerAskUserRankRequest type ServerAskUserRequest + type ServerChatRetired type ServerConversationClosed type ServerConversationEvent type ServerConversationOpened @@ -5531,6 +5564,8 @@ signatures (every public export and the types it is made of) } BudgetScope (packages/ui-sdk/src/turn-budgets.ts) export type BudgetScope = "turn" | "session" | "day"; + CHAT_DELETION_CAPABILITY (packages/ui-sdk/src/protocol.ts) + const CHAT_DELETION_CAPABILITY: "chatDeletion"; COMPLETE_SHARE_CONTRACT (packages/ui-sdk/src/tool-contracts/inbox.ts) const COMPLETE_SHARE_CONTRACT: import("./contract.js").ToolContract<"complete_share", z.ZodObject<{ files: z.ZodArray; open(cacheName: string): Promise; } + ChatDeletionOutcome (packages/ui-sdk/src/protocol.ts) + export type ChatDeletionOutcome = "pending" | "partial" | "unknown" | "removed"; + ChatDeletionReceipt (packages/ui-sdk/src/protocol.ts) + export interface ChatDeletionReceipt { + operationId: string; + generation: number; + status: ChatDeletionOutcome; + stores: Partial>; + retained: ChatDeletionRetained[]; + } + ChatDeletionRefusal (packages/ui-sdk/src/protocol.ts) + export type ChatDeletionRefusal = "unauthorized" | "unavailable" | "stale" | "unsupported" | "busy"; + ChatDeletionRequest (packages/ui-sdk/src/protocol.ts) + export interface ChatDeletionRequest { + operationId: string; + target: { + sessionId: string; + } | { + historyOwnerId: string; + }; + expected: { + backendId: string | null; + generation: number; + }; + } + ChatDeletionRetained (packages/ui-sdk/src/protocol.ts) + export type ChatDeletionRetained = "independent_content" | "effects_and_audit" | "provider_copies" | "backups" | "offline_devices"; + ChatDeletionStore (packages/ui-sdk/src/protocol.ts) + export type ChatDeletionStore = "native" | "dialogue" | "tasks" | "projections" | "drafts"; ChatFileAttachment (packages/ui-sdk/src/protocol.ts) export interface ChatFileAttachment { kind: "file"; @@ -6327,7 +6391,7 @@ signatures (every public export and the types it is made of) revision: number; } DraftErrorCode (packages/ui-sdk/src/protocol.ts) - export type DraftErrorCode = "DRAFT_CONFLICT" | "DRAFT_DELETED" | "DRAFT_TOO_LARGE" | "DRAFT_CAPACITY" | "DRAFT_NOT_FOUND" | "DRAFT_INVALID" | "DRAFT_PRECONDITION_REQUIRED" | "DRAFT_KEY_REUSED" | "DRAFT_NOT_ACCEPTED"; + export type DraftErrorCode = "DRAFT_CONFLICT" | "DRAFT_DELETED" | "DRAFT_TOO_LARGE" | "DRAFT_CAPACITY" | "DRAFT_NOT_FOUND" | "DRAFT_INVALID" | "DRAFT_PRECONDITION_REQUIRED" | "DRAFT_KEY_REUSED" | "DRAFT_NOT_ACCEPTED" | "DRAFT_CHAT_RETIRED"; DraftErrorResponse (packages/ui-sdk/src/protocol.ts) export type DraftErrorResponse = { error: "DRAFT_CONFLICT"; @@ -6362,6 +6426,9 @@ signatures (every public export and the types it is made of) } | { error: "DRAFT_NOT_ACCEPTED"; message: string; + } | { + error: "DRAFT_CHAT_RETIRED"; + message: string; }; DraftListResponse (packages/ui-sdk/src/protocol.ts) export interface DraftListResponse { @@ -9595,6 +9662,13 @@ signatures (every public export and the types it is made of) requestId: string; questions: AskUserQuestion[]; } + ServerChatRetired (packages/ui-sdk/src/protocol.ts) + export interface ServerChatRetired { + type: "chat_retired"; + sessionId?: string; + historyOwnerIds: string[]; + generation: number; + } ServerConversationClosed (packages/ui-sdk/src/protocol.ts) export interface ServerConversationClosed { type: "conversation_closed"; @@ -9725,7 +9799,7 @@ signatures (every public export and the types it is made of) instruction?: string; } ServerMessage (packages/ui-sdk/src/protocol.ts) - export type ServerMessage = ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage; + export type ServerMessage = ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage | ServerChatRetired; ServerMessageBlocks (packages/ui-sdk/src/protocol.ts) export interface ServerMessageBlocks extends SessionScoped { type: "message_blocks"; @@ -15309,6 +15383,13 @@ signatures (every public export and the types it is made of) turnId: z.ZodOptional; type: z.ZodLiteral<"ask_user_request">; }, z.core.$loose>; + serverChatRetiredSchema (packages/ui-sdk/src/schemas.ts) + const serverChatRetiredSchema: z.ZodObject<{ + generation: z.ZodNumber; + historyOwnerIds: z.ZodArray; + sessionId: z.ZodOptional; + type: z.ZodLiteral<"chat_retired">; + }, z.core.$loose>; serverConversationClosedSchema (packages/ui-sdk/src/schemas.ts) const serverConversationClosedSchema: z.ZodObject<{ conversationId: z.ZodString; @@ -16328,6 +16409,11 @@ signatures (every public export and the types it is made of) outputTokens: z.ZodOptional; }, z.core.$loose>>>; }, z.core.$loose>; + }, z.core.$loose>, z.ZodObject<{ + generation: z.ZodNumber; + historyOwnerIds: z.ZodArray; + sessionId: z.ZodOptional; + type: z.ZodLiteral<"chat_retired">; }, z.core.$loose>, z.ZodObject<{ attachmentCount: z.ZodOptional; files: z.ZodOptional>>>; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 9c2753d14e..e61ecc0470 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -445,6 +445,23 @@ signatures (every public export and the types it is made of) attributes: FlatAttributes; timestamp: number; } + ChatDeletion (packages/ui-server/src/ws/chat-deletion.ts) + export type ChatDeletion = ReturnType; + ChatDeletionDeps (packages/ui-server/src/ws/chat-deletion.ts) + export interface ChatDeletionDeps { + catalog: Pick; + backends(): Promise; + busy(identities: RetiredChatIdentities): boolean; + retired(principalId: string, retirement: Retired): void; + } + ChatDeletionResult (packages/ui-server/src/ws/chat-deletion.ts) + export type ChatDeletionResult = { + status: "refused"; + reason: RetireRefusal; + } | { + status: "retired"; + receipt: ChatDeletionReceipt; + }; 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) @@ -1191,6 +1208,8 @@ signatures (every public export and the types it is made of) refresh(lock: KeyedLock): void; close(): Promise; } + HostChatStore (packages/ui-server/src/ws/chat-store-cleanup.ts) + export type HostChatStore = Exclude; HostVersionRequirements (packages/ui-server/src/app.ts) export interface HostVersionRequirements { brainCli?: string; @@ -1672,11 +1691,16 @@ signatures (every public export and the types it is made of) operationId: string; generation: number; identities: RetiredChatIdentities; + backendId: string | null; cleanup: ChatRetirementStatus; stores: Partial>; }; RetireRefusal (packages/ui-server/src/ws/chat-lifecycle.ts) export type RetireRefusal = "unauthorized" | "unavailable" | "stale" | "unsupported" | "busy"; + Retired (packages/ui-server/src/ws/chat-deletion.ts) + type Retired = Extract; RetiredChatIdentities (packages/ui-server/src/ws/chat-lifecycle.ts) export interface RetiredChatIdentities { sessions: string[]; @@ -1798,6 +1822,8 @@ signatures (every public export and the types it is made of) retireChat?(input: RetireChatInput, busy: (identities: RetiredChatIdentities) => boolean): Promise; chatRetirement?(operationId: string, principalId: string): Promise; recordChatCleanup?(lifecycleId: string, store: ChatStore, outcome: Exclude): Promise; + cleanChatStore?(lifecycleId: string, store: HostChatStore): Promise; + unfinishedChatRetirements?(): Promise>; chatRetired?(target: ChatTarget | { conversationId: string; }): boolean; @@ -2113,6 +2139,7 @@ signatures (every public export and the types it is made of) } WsHost (packages/ui-server/src/ws/host.ts) export class WsHost { + chatDeletion?: import("./chat-deletion.js").ChatDeletion; readonly journal?: import("../brain/turn-journal.js").TurnJournal; readonly brainPath?: string; readonly governedTurns?: import("../brain/governed-turn.js").GovernedTurns; @@ -2178,6 +2205,11 @@ signatures (every public export and the types it is made of) export function createApp(options?: CreateAppOptions): Promise; createBrainClient (packages/ui-server/src/brain/client.ts) export function createBrainClient(opts: BrainClientOptions): BrainClient; + createChatDeletion (packages/ui-server/src/ws/chat-deletion.ts) + export function createChatDeletion(deps: ChatDeletionDeps): { + delete(input: Omit): Promise; + reconcile(): Promise; + }; createConsoleLoggerProvider (packages/ui-server/src/observability/loggers.ts) export function createConsoleLoggerProvider(options?: ConsoleLoggerProviderOptions): LoggerProvider; createGeminiConversationProvider (packages/ui-server/src/voice/gemini-conversation.ts) @@ -2418,6 +2450,12 @@ signatures (every public export and the types it is made of) export function resolveServerConfig(env?: EnvRecord): ServerConfig; summary (packages/ui-server/src/brain/turn-journal.ts) function summary(turnId: string): TurnJournalSummary; + unfinishedChatRetirements (packages/ui-server/src/ws/chat-lifecycle.ts) + export function unfinishedChatRetirements(db: Database): Array & { + principalId: string; + }>; websocket re-exported from hono withBrainDb (packages/ui-server/src/db/brain-db.ts) export function withBrainDb(brainPath: string, options: OpenBrainDbOptions, fn: (db: Database, schemaVersion: number) => T): T; diff --git a/docs/decisions/answer-delivery.md b/docs/decisions/answer-delivery.md index 28c82b40c7..da8e641e8a 100644 --- a/docs/decisions/answer-delivery.md +++ b/docs/decisions/answer-delivery.md @@ -82,7 +82,7 @@ carries, no longer by position. The host also re-sends a session's pending questions after `session_resume` (`resendPendingAsks(host, ws, msg.sessionId)`, -`packages/ui-server/src/ws/dispatch.ts:677`). Before this, a resume replaced +`packages/ui-server/src/ws/dispatch.ts:678`). Before this, a resume replaced the transcript and left only a history card behind, which was the second symptom. diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 855164e62d..1c94531c8d 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -64,7 +64,7 @@ next to it. of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, `packages/ui-server/src/brain/client.ts:142-210`, called at - `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:442`). + `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:444`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, `packages/core/src/cli/commands/doctor.ts:503-507`) — the user's own Claude Code on their own machine, to check the MCP registration, not the server's @@ -212,7 +212,7 @@ unnecessary. `node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs`. The boot probe below turns either into a refusal to start, for the same reason a missing backend refuses to boot (`A missing (or unrecognized) agent backend`, - `packages/ui-server/src/app.ts:380-385`). + `packages/ui-server/src/app.ts:382-387`). - **The published range is still a caret, and that bounds what this repo can guarantee.** `@schlessera/brain-backend-claude` depends on `^0.3.241`, and a host resolves it in its own lockfile. A host can bump the SDK — and so the diff --git a/docs/decisions/design-kit/sessions-and-drafts.md b/docs/decisions/design-kit/sessions-and-drafts.md index 24b295a01f..3e97e028b5 100644 --- a/docs/decisions/design-kit/sessions-and-drafts.md +++ b/docs/decisions/design-kit/sessions-and-drafts.md @@ -341,7 +341,7 @@ event deletes the whole set. Draft content never enters this record (§5). null, no time is printed. - **`lastActiveAt` and `lastTouched` are never read.** A newer `lastActiveAt` can mean that a new turn started - (`export interface ChatSession`, `packages/ui-sdk/src/protocol.ts:1576-1606`), + (`export interface ChatSession`, `packages/ui-sdk/src/protocol.ts:1580-1610`), and `lastTouched` is LRU bookkeeping for buffer eviction. **Merging snapshots and live frames.** diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index d9cc2a6595..5c9a980f61 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:485`) + (`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:492`) must not feed any budget. **Enforcement:** diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index e82378d919..c2dd936bc6 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:884`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:905`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1095`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:886`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:907`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1106`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1115-1136`). That order establishes access; +`packages/ui-server/src/app.ts:1126-1147`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/scheduled-tasks.md b/docs/decisions/scheduled-tasks.md index 56e193bfef..41980aa855 100644 --- a/docs/decisions/scheduled-tasks.md +++ b/docs/decisions/scheduled-tasks.md @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`: (`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`). The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`). - Production app wiring supplies recovery and budgets, without a dispatcher - (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:506-522`). + (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:508-524`). A scripted nonempty ready-item test still reports no claim, attempt or Activity root. That proves disabled wiring, not safe execution of a schedule. - Headless plumbing checks backend support, a usable principal, lifetime and diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 58fc171748..efc4a2deaf 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:890` | mounted **before** the guard at `authGuard(authMode`, `app.ts:905`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:915` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1095-1112` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:892` | mounted **before** the guard at `authGuard(authMode`, `app.ts:907`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:917` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1106-1123` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 3111320063..5b58226874 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -426,7 +426,7 @@ exchange over a security decision is a second chance for noise to produce a grant. **"Always allow" cannot be given by voice.** It is a persistent policy change -(the block computing `remembers`, `packages/ui-server/src/ws/dispatch.ts:449-455`) +(the block computing `remembers`, `packages/ui-server/src/ws/dispatch.ts:450-456`) and it is the one decision on the card with no keyboard shortcut, by D37's ruling 5, and the reason given there is exactly the one that applies here: *"a letter that grants standing @@ -435,7 +435,7 @@ permission by reflex is the one footgun in the vocabulary"* A microphone is a reflex surface with worse recognition than a keyboard. This costs nothing measurable: the server already refuses `always` for kind `command` requests -(the block computing `remembers`, `dispatch.ts:449-455`, and the lookup computing +(the block computing `remembers`, `dispatch.ts:450-456`, and the lookup computing `remembered`, `ws/bridge.ts:372-392`), and 192 of 192 measured approvals were kind `command`. @@ -505,7 +505,7 @@ provenance. The wire needs nothing new: a spoken refusal is an ordinary `tool_denial` (in `handleClientMessage`, the arm `case "tool_denial"`, -`packages/ui-server/src/ws/dispatch.ts:496-519`) with a message naming the +`packages/ui-server/src/ws/dispatch.ts:497-520`) with a message naming the phrase that produced it. ## Containment: shared with #51, deliberately not identical @@ -640,7 +640,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. left out (the lookup computing `remembered`, `packages/ui-server/src/ws/bridge.ts:372-392`, and the block computing `remembers`, - `packages/ui-server/src/ws/dispatch.ts:449-455`). + `packages/ui-server/src/ws/dispatch.ts:450-456`). The evaluation happens before the lookup, which is what this record asked for. diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index fb74f8a5f4..f6a05c6d96 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -7,7 +7,7 @@ fake backends and injected transports keep the checks keyless. Each ordinary row runs the named `mounted supported handler: METHOD PATH` test in [http-supported-mounts.test.ts](../packages/ui-server/tests/http-supported-mounts.test.ts) -(`checkHandler`, `packages/ui-server/tests/http-supported-mounts.test.ts:171-190`). +(`checkHandler`, `packages/ui-server/tests/http-supported-mounts.test.ts:174-193`). The explicit [lifetime audit](../packages/ui-server/tests/helpers/http-mount-lifetimes.ts) permits a bounded group of immutable readers to share startup, with a new owner per case. Principal enumeration, activity ownership, CLI dispatch, caches, @@ -115,6 +115,7 @@ row's real mounting check. They do not establish mounting by themselves. | `GET /api/sessions/:sessionId/turns/:turnId/revert/plan` | `mounted supported handler: GET /api/sessions/:sessionId/turns/:turnId/revert/plan` | RV | | `GET /api/sessions/:sessionId/turns/:turnId/revert` | `mounted supported handler: GET /api/sessions/:sessionId/turns/:turnId/revert` | RV | | `GET /api/sessions/:sessionId/turns/:turnId/revert/:operationId` | `mounted supported handler: GET /api/sessions/:sessionId/turns/:turnId/revert/:operationId` | RV | +| `POST /api/chat-deletions` | `mounted supported handler: POST /api/chat-deletions` | CD | | `POST /api/sessions/:sessionId/turns/:turnId/revert` | `mounted supported handler: POST /api/sessions/:sessionId/turns/:turnId/revert` | RV | | `GET /api/sessions/:sessionId/turns/:turnId/journal` | `mounted supported handler: GET /api/sessions/:sessionId/turns/:turnId/journal` | J | | `GET /api/sessions/:sessionId/turns/:turnId/journal/:sequence/preview` | `mounted supported handler: GET /api/sessions/:sessionId/turns/:turnId/journal/:sequence/preview` | J | @@ -518,3 +519,11 @@ exercise two processes, cancellation, cache failure and parent SIGKILL. [Delivery tests](../packages/ui-server/tests/storage-notify.test.ts) use the existing injected transport, including concurrent native senders and SIGKILL after dispatch entry; they never contact a push provider. + +CD: [Chat deletion on a real file-backed writer](../packages/ui-server/tests/chat-deletion.test.ts) +covers per-store removal against a whole-database marker scan, unrelated chat and +unbound draft controls, replay refusal, honest partial/unknown outcomes, restart +reconciliation, and the endpoint's owner, agent, ambient, foreign, stale and revoked +cases. [The WebSocket host test](../packages/ui-server/tests/ws-chat-deletion.test.ts) +covers busy refusal, a resume held across retirement, admission and recovery refusal +and targeted `chat_retired` delivery. diff --git a/docs/http-api.md b/docs/http-api.md index 2a5decfa32..320aee6ead 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -141,6 +141,7 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/sessions/:sessionId/turns/:turnId/revert/plan` | S | Review eligible and excluded history paths | Current human principal; exact session/turn; optional action revert/restore. | | GET | `/api/sessions/:sessionId/turns/:turnId/revert` | S | Read latest original history receipt | Bound to current principal/session/source turn; never retries effects. | | GET | `/api/sessions/:sessionId/turns/:turnId/revert/:operationId` | S | Reconcile one original operation | Same bound identity; missing receipt stays unavailable. | +| POST | `/api/chat-deletions` | S | Delete the caller's own chat's local history | Authenticated owner only; stable caller operation identity; content-free per-store outcomes (#3230). | | POST | `/api/sessions/:sessionId/turns/:turnId/revert` | S | Start a user-only journaled revert or restoration | Stable caller operation identity; raw stale-state comparison; gate and shared server locks. | | GET | `/api/sessions/:sessionId/turns/:turnId/journal` | S | Read retained turn observations | Exact session/turn ownership; nullable unknown facts and explicit expiry. | | GET | `/api/sessions/:sessionId/turns/:turnId/journal/:sequence/preview` | S | Read a bounded text preview | Raw UTF-8 bytes; explicit size/line/binary fallback, no coercion. | @@ -577,6 +578,10 @@ optional list without discarding healthy backends; registry-level failure is Message shapes follow the SDK/wire history contract. An unknown/unavailable backend or history failure is 500 `{ error }`; the route does not translate missing sessions into a universal 404 or provide a separate history deadline. +A chat deleted under [explicit chat deletion](#explicit-chat-deletion-additive-3230) +(additive, #3230) is the one exception: before or after its history is read it +answers 404 `{ error: "SESSION_NOT_FOUND", message }` with no messages, and it +is absent from `GET /api/sessions`, including `retainedConversations`. @@ -1025,6 +1030,47 @@ true }`, disclosing nothing about the session. An unknown session is 404 that failed or timed out when none had the session, is 500 `{ error: "SESSION_RECOVERY_FAILED", message }`, never a successful `unknown`. + + +## Explicit chat deletion (additive, #3230) + +**POST /api/chat-deletions** deletes the authenticated owner's own chat's local +history under the [approved policy](decisions/chat-history-deletion.md). It is +mounted, and `server_hello.capabilities.chatDeletion: true` is sent, only by a +host whose catalog can retire chats. The body is the SDK's `ChatDeletionRequest`: +`operationId` (a client-minted key, at most 2048 characters), `target` naming +exactly one of `{ sessionId }` or `{ historyOwnerId }`, and `expected: { backendId, +generation }`, what the caller reviewed (a dialogue page's `generation`, or 1 for a +chat with no host-retained dialogue). Any other shape is 400 +`{ error: "INVALID_CHAT_DELETION", message }`. Every response is +`Cache-Control: no-store`. + +Before anything is retired, a refusal is `{ error: "CHAT_DELETION_REFUSED", +reason, message }`: 403 `unauthorized` (not a usable owner principal: agents, +ambient callers without an owner mapping and revoked principals), 404 +`unavailable` (absent, foreign, already retired under another key, or with no +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). 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 +`independent_content`, `effects_and_audit`, `provider_copies`, `backups` and +`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 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 +reported deletion. Receipts and errors carry no chat text, title, raw path or +free-form failure. No success claims secure erasure, provider forgetting or an +undone effect, and an older backup can restore deleted text. + +Draft routes refuse a draft bound to a deleted chat with 410 +`{ error: "DRAFT_CHAT_RETIRED", message }`, list omits it, and `GET` answers 404. + ## Imported track UI transport (#526) The paired UI uses authenticated `POST /api/track-upload` multipart intake and diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 180d6e88d4..e950eda931 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,22 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## Explicit local chat deletion (additive, #3230) + +An authenticated owner can delete its own chat's local history with +`POST /api/chat-deletions` ([HTTP](http-api.md#explicit-chat-deletion-additive-3230)), +on a host that sends `server_hello.capabilities.chatDeletion: true`. The answer +is a content-free `ChatDeletionReceipt` with per-store outcomes and the always +retained categories. Capable clients of the same owner receive the new +`chat_retired` frame ([wire](integration-contract/wire.md#explicit-chat-deletion-additive-3230)). +A deleted chat is absent from `GET /api/sessions`, `GET /api/sessions/:id` +(404 `SESSION_NOT_FOUND`), recovery, resume and live startup; draft routes add +410 `DRAFT_CHAT_RETIRED`. The SDK exports the request, receipt, frame, capability +and schema ([package API](integration-contract/package-api.md#explicit-chat-deletion-additive-3230)). +No existing field, frame or route changes meaning for an undeleted chat. This +ships in a minor; the [approved policy](decisions/chat-history-deletion.md) is the +explicit retention exception, and no breaking ruling is required. + ## Native history removal (additive, #3229) `BackendCapabilities.historyRemoval?` and the optional diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 83799f623c..359dac9599 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -131,6 +131,24 @@ passes its origin to `startInferenceRelay` as the new internal origin, and a turn without a relay refuses to start. The first-party Claude and pi backends implement all three. + + +## Explicit chat deletion (additive, #3230) + +`@schlessera/brain-ui-sdk/protocol` (and the root and `./client` entries that re-export it) exports `CHAT_DELETION_CAPABILITY` +(`"chatDeletion"`), `ChatDeletionRequest`, `ChatDeletionReceipt`, +`ChatDeletionStore`, `ChatDeletionOutcome`, `ChatDeletionRetained`, +`ChatDeletionRefusal` and `ServerChatRetired`, now a member of `ServerMessage`. +`DraftErrorCode` and `DraftErrorResponse` gain `DRAFT_CHAT_RETIRED`. +`@schlessera/brain-ui-sdk/schemas` exports `serverChatRetiredSchema`, and +`parseServerMessage` accepts the frame. A client that switches exhaustively over +`ServerMessage["type"]` needs a case for `chat_retired`; the host sends it only to +connections that declared the capability. In `@schlessera/brain-ui-server`, `WsHost` +gains optional `chatDeletion` and the session catalog optional `cleanChatStore` and +`unfinishedChatRetirements`, host wiring reachable from its exports. Semantics are in the +[HTTP](../http-api.md#explicit-chat-deletion-additive-3230) and +[wire](wire.md#explicit-chat-deletion-additive-3230) components. + ## Native history removal (additive, #3229) `BackendCapabilities` adds optional `historyRemoval?: boolean`, and diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index fed2bda928..3cc4623605 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -22,7 +22,7 @@ states that overlapping writable windows share observations. `observedAt` names the retained window observation, not a guessed receipt time. The type is defined by (`TurnJournalSummary`, `packages/ui-sdk/src/turn-journal.ts:2-29`); validation uses -(`turnJournalSummarySchema`, `packages/ui-sdk/src/schemas.ts:1048-1066`). +(`turnJournalSummarySchema`, `packages/ui-sdk/src/schemas.ts:1049-1067`). `actor` additionally accepts `user` for a server-recorded history operation. Optional `kind` is `turn` or `revert`; a revert may name its original `sourceTurnId`. These facts do not create an assistant message or an inference @@ -104,8 +104,8 @@ previous observation rather than adding it. The frame never opens a message, reopens run state or moves focus. Older clients may ignore it. The same optional `budget` is retained on `TurnJournalSummary` and replayed with the existing single below-turn disclosure. The additive types and validation are -(`ServerUsage`, `packages/ui-sdk/src/protocol.ts:3808-3814`) and -(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1887-1889`). +(`ServerUsage`, `packages/ui-sdk/src/protocol.ts:3876-3882`) and +(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1895-1897`). Budget list-price inference cost is separate from the journal's billing-aware `costUsd`. Unpriced totals remain null; known lower bounds, estimated rates, @@ -1770,6 +1770,37 @@ that this draft's request started that session, which is the only proof `POST /api/drafts/:draftId/bind` accepts. Draft text and images never enter logs, push payloads or the transcript store. + + +### Explicit chat deletion (additive, #3230) + +A host that answers `POST /api/chat-deletions` ([HTTP API](../http-api.md#explicit-chat-deletion-additive-3230)) +sends `server_hello.capabilities.chatDeletion: true` (`CHAT_DELETION_CAPABILITY`). +When an owner's chat is retired, the host ends that chat's live conversation +epochs (`conversation_closed`, reason `stopped`; nothing earlier sent to a +provider is rewritten, and a later conversation needs a new identity and an +explicit Start) and sends one frame to that owner's connections whose +`client_hello` declared the same flag: + +```ts +ServerChatRetired = { + type: "chat_retired"; + sessionId?: string; // the backend session, when the chat had one + historyOwnerIds: string[]; // every host history owner and alias; may be empty + generation: number; // the retired chat's terminal history generation +}; +``` + +A client clears every local projection of that chat, stops resending, +autosaving and retrying for it, and treats a later history response for it as +stale. No other principal and no undeclared connection receives it. Enforcement +does not depend on the frame: for every client, `session_resume`, chat admission +and any session-scoped request naming the chat answer `error` `SESSION_NOT_FOUND`; +a history read already in flight when the chat is retired publishes no +`session_history`; recovery reads answer not found; dialogue reads return +nothing; and live startup never opens or seeds a provider for it. A device that +is offline keeps what it cached until it reconnects; nothing remote can erase it. + ### Session recovery (additive, #964) @@ -2369,12 +2400,11 @@ generations; old cursors fail and generation changes invalidate capture consent. Migration `071_session_dialogue.sql` adds operational owners, source mappings, records and aliases, independent of `brain.db` and native provider history. Operational backup retains the archive under its exact-schema compatibility -rules. Re-indexing Markdown cannot rebuild it. No current general chat-deletion -route is invented. The [#3180 policy decision](../decisions/chat-history-deletion.md) +rules. Re-indexing Markdown cannot rebuild it. The [#3180 policy decision](../decisions/chat-history-deletion.md) approves authenticated own-chat local deletion, including the explicit #3177 native-preservation exception, permanent minimized identity/replay fences and -accepted old-backup restoration limits. Runtime deletion remains unbuilt; this -records policy without adding frames, endpoints or changing shipped retention. +accepted old-backup restoration limits. [Explicit chat deletion](#explicit-chat-deletion-additive-3230) +(#3230) implements it; nothing else changes this history's retention. Independent saved content/effects, provider copies and backups remain excluded and must be disclosed. Clearing browser state on authentication teardown does not delete retained chat history. diff --git a/docs/investigations/live-conversation-investigation.md b/docs/investigations/live-conversation-investigation.md index 69dfc805e4..77203e94f5 100644 --- a/docs/investigations/live-conversation-investigation.md +++ b/docs/investigations/live-conversation-investigation.md @@ -297,12 +297,12 @@ matcher. An isolated ambiguous refusal denies all **current** pending requests; an exact refusal can name one. With none pending, it is ordinary input. Bind each denial to existing IDs, echoed turn and `channel:"voice"`; the server still rejects voice grants -(`if (msg.channel === "voice")`, `packages/ui-server/src/ws/dispatch.ts:409-432`). +(`if (msg.channel === "voice")`, `packages/ui-server/src/ws/dispatch.ts:410-433`). Never add a spoken approve or always-allow path. On the evidence date the denial handler removed/resolved a matched request but provided no dedicated denial receipt at that branch; #957 added one -(`case "tool_denial"`, `packages/ui-server/src/ws/dispatch.ts:496-519`). The +(`case "tool_denial"`, `packages/ui-server/src/ws/dispatch.ts:497-520`). The integration therefore needs host-authoritative resolution/replay: denied, already granted, expired, or unknown/disconnected. Speak a denial confirmation only for a confirmed denied outcome. A visual grant winning the race remains diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index bdaf19c5cf..6cf3ae4ef3 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:905`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:907`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode @@ -336,7 +336,7 @@ Stated before the requirements because five of them derive from it. item makes no model call **and creates no Activity run** · T1 batch classification · T2 full agent run · T3 the user. - R39. **T1 batches are bounded by tokens and bytes, not count.** One share's text may carry ~200 KB - (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2401`), so "up to 20 items" is ~4 MB before overhead. + (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2469`), so "up to 20 items" is ~4 MB before overhead. Per-item truncation, a batch token budget, and independent structured outputs per item. - R40. **Every model-bearing operation is billed, recorded, classified, and counted**: T1 batches, T2 runs, retries, redo re-derivation, state compaction, premise revalidation, diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 34ed5d5786..a9a55c4ad5 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:27-44`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:905`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:907`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:362-456`). Timeout unwind is @@ -154,7 +154,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. (`async deliverPending(notifier) {`, `packages/ui-server/src/activity/push-sender.ts:218-286`) are run-bound and do not maintain an Actions aggregate count. - **Share provenance/limits:** (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:101`) assigns the source in server code. - (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2401`) bounds text, not binary uploads; + (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2469`) bounds text, not binary uploads; extracted T1 context needs its own byte/token bound. - **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1336-1348`) gates WS starts; (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`) owns tool locks. @@ -807,7 +807,7 @@ recovered tick after killing the interval - T1: one batched classification call producing **independent structured output per item**, so one malformed item does not poison the batch - Batching bounded by a **token/byte budget**, not a count, with per-item truncation — a single - share may carry ~200 KB (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2401`). Budget: **40k input tokens per + share may carry ~200 KB (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2469`). Budget: **40k input tokens per batch, 4k per item** - **Batch completeness is verified, and missing items are re-submitted individually.** Every submitted item id must come back; any that does not is retried alone, then escalated if it diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 8931d4daea..d28d886b2c 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:153-186`; +(`retireChat`, `packages/ui-server/src/ws/chat-lifecycle.ts:156-189`; 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 @@ -31,6 +31,24 @@ replaced files instead of touching them. The host records the native store under the retirement (`removeRetiredNativeHistory`, `packages/ui-server/src/ws/native-history-removal.ts:29-48`); coordinating it with the other stores and restart reconciliation remains with the endpoint work. +**Built (#3230):** the coordinated deletion and its endpoint +([HTTP](../http-api.md#explicit-chat-deletion-additive-3230), +[wire](../integration-contract/wire.md#explicit-chat-deletion-additive-3230)). +One operation (`createChatDeletion`, `packages/ui-server/src/ws/chat-deletion.ts:46-104`) +refuses busy work, retires the chat, ends its live epochs, notifies the owner's +capable clients, then asks the native store and each host store to remove their +copies; restart reconciliation resumes any unconfirmed store under the original +operation. Host stores (`cleanChatStore`, `packages/ui-server/src/ws/chat-store-cleanup.ts:80-88`) +confirm removal only by reading back that nothing selected remains: dialogue +records, task receipt text and result facts, session title/label and the text, +digest and classification projections, and positively bound drafts with their +images and receipt fingerprints. Consumed task, request, retry and draft-send +identities stay as replay fences. Policy proposals, turn scope, provider-exposure +and masking lineage, Activity, Inbox, governance, journals and usage accounting are +retained as independent records and disclosed. HTTP and WebSocket list, read, +resume, recovery and live-startup paths refuse a retired chat after every await, +and draft routes refuse drafts bound to it. Browser invalidation (#3231) is not built. + ## Selected local lifecycle Use a concrete ui-server lifecycle owner in the existing operational @@ -92,7 +110,7 @@ consent for a replacement identity. Existing [session principals](../decisions/s and [operational recovery](../inbox-recovery.md) remain binding. There is no general delete operation: `createSessionRoutes` only lists/reads -(`createSessionRoutes`, `packages/ui-server/src/routes/sessions.ts:8-147`). +(`createSessionRoutes`, `packages/ui-server/src/routes/sessions.ts:9-157`). `AgentBackend` exposes native list/read and read-only storage roots, not deletion (`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:750-804`). A storage root is not removal authority. Future supported package/HTTP/wire changes need their @@ -159,7 +177,7 @@ must be tested through their installed runtime, not inferred from directory name readable projections according to the adopted extent. Retained digests can reveal guessed short text; discard unnecessary hashes, not just plaintext. Native history joins several of these owners - (`prepareHistory`, `packages/ui-server/src/ws/host.ts:638-650`). + (`prepareHistory`, `packages/ui-server/src/ws/host.ts:641-656`). - **Independent session ledgers.** `retry_receipts`, `session_work`, `turn_boundaries`, draft send/save/upload receipts and revisions, handoff IDs/lineage, Claude usage deduplication, worker profiles, provider-exposure and born-masked lineage are @@ -202,8 +220,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:243-256`; - `activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:285-288`). + (`rowEffects`, `packages/ui-server/src/ws/session-catalog.ts:248-261`; + `activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:290-293`). 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, @@ -235,7 +253,7 @@ cron scratch-pin refresh; backend native resume/archive/restore; and all browser restore, resend, draft autosave and answer-delivery callbacks. Activity/Inbox/ journal APIs remain independent retained surfaces under the selected exclusion. Concrete entry points include `readSessionRecovery` -(`readSessionRecovery`, `packages/ui-server/src/ws/recovery.ts:209-220`), +(`readSessionRecovery`, `packages/ui-server/src/ws/recovery.ts:209-222`), `FailureReplay` (`FailureReplay`, `packages/ui-server/src/ws/turn-failures.ts:63-89`), and both handoff stages (`startHandoff`, `packages/ui-server/src/ws/handoff.ts:100-110`; `prepareHandoff`, `packages/ui-server/src/ws/handoff.ts:273-285`). Draft autosave @@ -246,10 +264,10 @@ The paired WS dispatcher is `packages/ui-server/src/ws/dispatch.ts`; gating its resume case alone would leave HTTP, background readers and provider startup open. Existing ordinary history publication checks concurrent turn changes -(`publishHistory`, `packages/ui-server/src/ws/host.ts:564-598`). Future deletion +(`publishHistory`, `packages/ui-server/src/ws/host.ts:567-601`). Future deletion must additionally invalidate it even when no turn starts or ends. Startup reads native history, canonical evidence and completed facts, and freezes a snapshot -(`readLiveHistory`, `packages/ui-server/src/ws/live-history.ts:8-65`). Recheck the +(`readLiveHistory`, `packages/ui-server/src/ws/live-history.ts:9-74`). Recheck the lifecycle after each await and immediately before provider open/seed. A native-only chat with no dialogue owner still needs a fence; checking only page generation leaves that path unprotected. @@ -280,7 +298,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1205-1254`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1216-1265`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:274-287`). A caller deadline diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 7442d97504..45f87b2bf9 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -383,21 +383,21 @@ implementation. Any PR moving these lines owns their citation repairs. - Single background drawer row: [`const backgroundSessionId =`](https://github.com/schlessera/brain-kit/blob/ea8506b0eb511a3e16dba685d250d34e5340afa4/packages/ui-react/src/components/chat/session-drawer.tsx#L59-L60), before #950 replaced it with the Working group. -- Host reconnect: (`const runningTurns = [...coordinator.running].filter((t) => t.sessionId);`, `packages/ui-server/src/ws/connection.ts:128-193`). +- Host reconnect: (`const runningTurns = [...coordinator.running].filter((t) => t.sessionId);`, `packages/ui-server/src/ws/connection.ts:130-195`). -- Host resume: (`case "session_resume": {`, `packages/ui-server/src/ws/dispatch.ts:648-712`). +- Host resume: (`case "session_resume": {`, `packages/ui-server/src/ws/dispatch.ts:649-720`). -- Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId) {`, `packages/ui-server/src/ws/session-catalog.ts:479-486`). +- Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId) {`, `packages/ui-server/src/ws/session-catalog.ts:486-493`). -- Session summary shape: (`export interface ChatSession {`, `packages/ui-sdk/src/protocol.ts:1576-1592`). +- Session summary shape: (`export interface ChatSession {`, `packages/ui-sdk/src/protocol.ts:1580-1596`). - Run identity: (`const runId = turn.turnId;`, `packages/ui-server/src/activity/recorder.ts:154-155`). -- Outcome vocabulary: (`export type ActivitySpanOutcome =`, `packages/ui-sdk/src/protocol.ts:2983-3006`). +- Outcome vocabulary: (`export type ActivitySpanOutcome =`, `packages/ui-sdk/src/protocol.ts:3051-3074`). - Activity resolution: (`.get("/activity/runs", (c) => {`, `packages/ui-server/src/routes/activity.ts:145-283`). -- API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:905`). +- API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:907`). - Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:1102-1147`). diff --git a/docs/plans/storage-accounting.md b/docs/plans/storage-accounting.md index 46011afcd8..d714607df2 100644 --- a/docs/plans/storage-accounting.md +++ b/docs/plans/storage-accounting.md @@ -67,7 +67,7 @@ Source anchors, checked against the reviewed commit: The completed #94 and #398 provide existing stats/maintenance foundations. - C: snapshot fields (`snapshotOf`, `packages/core/src/lib/stats-history.ts:132-172`), thinning (`thin`, `packages/core/src/lib/stats-history.ts:232-244`). -- D: effective path/journal resolution (`createApp`, `packages/ui-server/src/app.ts:301-337`), +- D: effective path/journal resolution (`createApp`, `packages/ui-server/src/app.ts:303-339`), WAL store (`createUiDb`, `packages/ui-server/src/db/client.ts:27-44`), and private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:108-114`). - E: live/archive paths (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`). diff --git a/docs/plans/voice-conversation.md b/docs/plans/voice-conversation.md index 3d430eefbd..9cc55f574b 100644 --- a/docs/plans/voice-conversation.md +++ b/docs/plans/voice-conversation.md @@ -207,7 +207,7 @@ existing pronunciation overrides only as disclosed text correction, retaining the distinction between recognized words and submitted text. The present `AsrEvent` carries partial/final text and `endsTurn`, not confidence, overlap evidence or an output transcript (`AsrEvent`, -`packages/ui-sdk/src/protocol.ts:1853`). #317 must resolve those gaps rather +`packages/ui-sdk/src/protocol.ts:1857`). #317 must resolve those gaps rather than pretending that dictation supplies them. Assistant text remains the generated answer; playback progress is a separate @@ -356,7 +356,7 @@ require their own live window and are not silently added to an earlier snapshot. Send each denial using the existing `tool_denial`, `toolUseId`, echoed `turnId`, `channel: "voice"` and a message naming the recognized phrase and ambiguity where applicable (`ClientToolDenial`, -`packages/ui-sdk/src/protocol.ts:736-744`). Before transmitting or playing a +`packages/ui-sdk/src/protocol.ts:739-747`). Before transmitting or playing a queued announcement, recheck liveness. Duplicate/late events do not decide a replacement request. "brain, stop" outside a pending window is ordinary transcript text, including as a possible single-question answer. @@ -380,7 +380,7 @@ requests (`drainPendingForTurn`, `packages/ui-server/src/ws/turns.ts:704-738`). Clear the correlated card's actionable state on the host terminal outcome even if no `tool_result` arrives; the current terminal-frame contract is (`ServerResultMessage`, -`packages/ui-sdk/src/protocol.ts:1115-1125`). Keep the existing card/receipt in +`packages/ui-sdk/src/protocol.ts:1119-1129`). Keep the existing card/receipt in the transcript with "Expired · denied" and no live approval controls. Speak once: "I stopped without doing it. Ask me again when you can look at a screen." Cancellation similarly resolves only the requests of the cancelled turn. diff --git a/packages/ui-react/src/hooks/websocket-handlers/connection.ts b/packages/ui-react/src/hooks/websocket-handlers/connection.ts index 0bc98d4adc..2365a46809 100644 --- a/packages/ui-react/src/hooks/websocket-handlers/connection.ts +++ b/packages/ui-react/src/hooks/websocket-handlers/connection.ts @@ -5,7 +5,7 @@ type ConnectionFrame = | "dialogue_history" | "scope_decision_receipt" | "server_hello" | "location_request" | "error" | "inbox_snapshot" | "inbox_delta" | "tool_resolution" | "session_queue" | "conversation_opened" | "conversation_closed" - | "conversation_event" | "conversation_work" | "conversation_output" | "conversation_permission"; + | "conversation_event" | "conversation_work" | "conversation_output" | "conversation_permission" | "chat_retired"; export const connectionFrameHandlers = { dialogue_history: () => {}, @@ -44,6 +44,9 @@ export const connectionFrameHandlers = { tool_resolution: () => {}, // Pending follow-ups (#1002) are consumed by the connection before demux. session_queue: () => {}, + // Browser invalidation is #3231's: this client does not declare + // `chatDeletion`, so the host never sends it this frame. + chat_retired: () => {}, conversation_opened: () => {}, conversation_closed: () => {}, conversation_event: () => {}, diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 2570849b9c..f46cfc0705 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -566,7 +566,8 @@ export type DraftErrorCode = | "DRAFT_INVALID" | "DRAFT_PRECONDITION_REQUIRED" | "DRAFT_KEY_REUSED" - | "DRAFT_NOT_ACCEPTED"; + | "DRAFT_NOT_ACCEPTED" + | "DRAFT_CHAT_RETIRED"; /** A draft route's failure body, discriminated by `error`. */ export type DraftErrorResponse = @@ -585,7 +586,9 @@ export type DraftErrorResponse = /** 409: this `Idempotency-Key` already named a different request. */ | { error: "DRAFT_KEY_REUSED"; message: string } /** 409: no accepted message of that session carried this draft and request. */ - | { error: "DRAFT_NOT_ACCEPTED"; message: string }; + | { error: "DRAFT_NOT_ACCEPTED"; message: string } + /** 410 (additive, #3230): the draft's chat was deleted. Nothing was stored; save the local content as a new, unbound draft. */ + | { error: "DRAFT_CHAT_RETIRED"; message: string }; // ============================================================ // Session recovery (additive; #964, design D52 §4 and §6) @@ -833,7 +836,8 @@ export type ServerMessage = | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal - | ServerUsage; + | ServerUsage + | ServerChatRetired; /** * First frame a server sends after a socket opens (rev 2, additive). Clients @@ -2318,6 +2322,70 @@ export interface ServerSessionQueue { dropped?: Array<{ id: string; requestId?: string; reason: string }>; } +// ============================================================ +// Explicit local chat deletion (additive, #3230) +// ============================================================ + +/** + * `server_hello`/`client_hello` capability (additive, #3230). A host that + * advertises it answers `POST /api/chat-deletions`, and sends `chat_retired` + * to the deleting owner's connections that declared the same flag. Old + * clients are refused server-side: a retired chat is absent from every list, + * read, resume and recovery path whether or not a client understood the frame. + */ +export const CHAT_DELETION_CAPABILITY = "chatDeletion"; + +/** The local stores one deletion selects. `native` exists only for a backend session. */ +export type ChatDeletionStore = "native" | "dialogue" | "tasks" | "projections" | "drafts"; +/** + * One store's cleanup, or the whole operation's: `removed` only when the store + * confirmed it; the whole operation is `removed` only when every selected store did. + * `unknown` dominates `partial`, which dominates `pending`. + */ +export type ChatDeletionOutcome = "pending" | "partial" | "unknown" | "removed"; +/** What local deletion never removes. Every receipt lists all of them. */ +export type ChatDeletionRetained = "independent_content" | "effects_and_audit" | "provider_copies" | "backups" | "offline_devices"; +/** Why a deletion was refused before anything was retired. */ +export type ChatDeletionRefusal = "unauthorized" | "unavailable" | "stale" | "unsupported" | "busy"; + +/** `POST /api/chat-deletions` body. */ +export interface ChatDeletionRequest { + /** Client-minted idempotency key. Repeating it returns the same operation and retries its unfinished stores. */ + operationId: string; + /** A backend session, or a host-only history owner never bound to one. */ + target: { sessionId: string } | { historyOwnerId: string }; + /** + * What the caller reviewed: the chat's backend (null for a host-only + * history) and its history generation (a dialogue page's `generation`, or 1 + * for a chat with no host-retained dialogue). Any difference refuses as stale. + */ + expected: { backendId: string | null; generation: number }; +} + +/** `POST /api/chat-deletions` success: the chat is retired; `status` says how far cleanup got. */ +export interface ChatDeletionReceipt { + operationId: string; + /** The retired chat's terminal history generation. */ + generation: number; + status: ChatDeletionOutcome; + stores: Partial>; + retained: ChatDeletionRetained[]; +} + +/** + * Server → Client (additive, #3230). The owner retired this chat. Clear every + * local projection of it and stop resending, autosaving or retrying for it; a + * later history response for it is stale. Sent only to the owner's + * connections that declared {@link CHAT_DELETION_CAPABILITY}. + */ +export interface ServerChatRetired { + type: "chat_retired"; + sessionId?: string; + /** Every host history owner and alias the chat had; empty for a native-only chat. */ + historyOwnerIds: string[]; + generation: number; +} + // ============================================================ // File Manager // ============================================================ diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index c3e0052fbe..59c39f0552 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -82,6 +82,7 @@ import type { ServerLocationRequest, ServerMaskRequest, ServerMessage, + ServerChatRetired, DialogueEvidence, DialogueRecord, DialoguePage, ClientDialogueRead, ServerDialogueHistory, ServerResultMessage, MessageBlock, @@ -1884,6 +1885,13 @@ export const serverSessionQueueSchema = z.looseObject({ .optional(), }) satisfies z.ZodType; +export const serverChatRetiredSchema = z.looseObject({ + type: z.literal("chat_retired"), + sessionId: id.optional(), + historyOwnerIds: z.array(id).max(256), + generation: z.number().int().min(1), +}) satisfies z.ZodType; + export const serverUsageSchema = z.looseObject({ type:z.literal("usage"),sessionId:id.optional(),turnId:id, usage:turnUsageSchema,observedAt:z.number().int().nonnegative(),budget:turnBudgetReceiptSchema.optional().catch(undefined), }) satisfies z.ZodType; @@ -1898,6 +1906,7 @@ export const serverMessageSchema = z.discriminatedUnion("type", [ serverScopeDecisionReceiptSchema, serverTurnJournalSchema, serverUsageSchema, + serverChatRetiredSchema, serverRetryReceiptSchema, serverHelloSchema, serverTextDeltaSchema, diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index be0eea1fc4..5deb592e02 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -46,6 +46,8 @@ import { createBrainRoutes } from "./routes/brain.js"; import { createSessionProfiles } from "./ws/session-profiles.js"; import { createSessionProfileRoutes } from "./routes/session-profiles.js"; import { createSessionRoutes } from "./routes/sessions.js"; +import { createChatDeletionRoutes } from "./routes/chat-deletions.js"; +import { createChatDeletion } from "./ws/chat-deletion.js"; import { createDraftRoutes } from "./routes/drafts.js"; import { createSessionRecoveryRoutes } from "./routes/session-recovery.js"; import { supportsSessionRecovery } from "./ws/recovery.js"; @@ -963,7 +965,16 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.prepareHistory(id, messages), - settled: () => host.historySettled() })); + settled: () => host.historySettled(), retired: target => host.catalog.chatRetired?.(target) === true })); + // Explicit local chat deletion (#3230), on a catalog that can retire chats. + if (host.catalog.retireChat && host.catalog.cleanChatStore) { + const chatDeletion = host.chatDeletion = createChatDeletion({ catalog: host.catalog, backends: () => registry.getBackends(), + busy: identities => host.chatBusy(identities), retired: (principalId, retirement) => host.chatRetired(principalId, retirement) }); + app.route("/api", createChatDeletionRoutes({ deletion: chatDeletion, principalValid: principal => host.isPrincipalValid(principal) })); + // A deletion an earlier process left unfinished resumes under its own operation. + void chatDeletion.reconcile().catch(err => brainLog.emit({ severityText: "WARN", body: "chat deletion reconciliation failed", + attributes: { error: err instanceof Error ? err.message : String(err) } })); + } app.route("/api", createJournalRoutes({ journal })); const storageHistory = createStorageHistory(db, config.brainPath, { writer }); bootCleanup.push(() => storageHistory.close()); diff --git a/packages/ui-server/src/drafts/store.ts b/packages/ui-server/src/drafts/store.ts index f6996f7080..eb3e68569f 100644 --- a/packages/ui-server/src/drafts/store.ts +++ b/packages/ui-server/src/drafts/store.ts @@ -22,6 +22,7 @@ import { createDraftWrites } from "./writes.js"; import type { SqliteWriter } from "../db/write-worker.js"; import { isUsablePrincipal, resolvePrincipal } from "../db/principals.js"; +import { isRetired } from "../ws/chat-lifecycle.js"; /** * Per-session composer drafts stored on the host (#979, D52 §5–6). @@ -208,6 +209,12 @@ export function createDraftStore( "SELECT attachment_id, mime, name, bytes, size_bytes, attached FROM session_draft_attachments WHERE draft_id = ?" ); + /** A draft bound to a deleted chat (#3230) is never read, extended or rebound. */ + const retired = (sessionId: string | null | undefined) => !!sessionId && isRetired(db, "session", sessionId); + function refuseRetired(sessionId: string | null | undefined): void { + if (retired(sessionId)) throw new DraftError(410, { error: "DRAFT_CHAT_RETIRED", message: "This draft's chat was deleted. Nothing was stored." }); + } + function readDraft(draftId: string): DraftRow | null { return selectDraft.get(draftId) as DraftRow | null; } @@ -240,6 +247,8 @@ export function createDraftStore( } function conflict(row: DraftRow): DraftError { + // A conflict carries the current content: never for a deleted chat's draft. + if (retired(row.session_id)) return new DraftError(410, { error: "DRAFT_CHAT_RETIRED", message: "This draft's chat was deleted. Nothing was stored." }); return new DraftError(409, { error: "DRAFT_CONFLICT", message: "This draft changed on another device.", @@ -299,7 +308,8 @@ export function createDraftStore( authorize(principalId); const rows = db.query( `SELECT draft_id, session_id, revision, text, attachment_ids, updated_at, deleted_at FROM session_drafts - WHERE deleted_at IS NULL ORDER BY updated_at DESC, draft_id ASC LIMIT ?` + WHERE deleted_at IS NULL AND (session_id IS NULL OR session_id NOT IN (SELECT id FROM chat_retired_identities WHERE kind = 'session')) + ORDER BY updated_at DESC, draft_id ASC LIMIT ?` ).all(limits.maxDrafts) as DraftRow[]; const drafts: DraftSummary[] = rows.map((row) => ({ draftId: row.draft_id, @@ -317,7 +327,7 @@ export function createDraftStore( return db.transaction(() => { authorize(principalId); const row = readDraft(draftId); - if (!row) throw notFound(); + if (!row || retired(row.session_id)) throw notFound(); if (row.deleted_at !== null) throw deleted(row); return toDraft(row); })(); @@ -328,6 +338,7 @@ export function createDraftStore( const at = now(); authorize(principalId); sweepPending(at); + refuseRetired(input.sessionId); const fingerprint = sha256("save", String(input.ifMatch), JSON.stringify([input.sessionId, input.text, input.attachmentIds])); const replay = receipt(draftId, "save", input.idempotencyKey, fingerprint); if (replay !== undefined) return replay as DraftSaveResponse; @@ -416,6 +427,7 @@ export function createDraftStore( const at = now(); authorize(principalId); sweepPending(at); + refuseRetired(readDraft(draftId)?.session_id); const fingerprint = sha256("attachment", input.mime, input.name ?? "", input.bytes); const replay = receipt(draftId, "attachment", input.idempotencyKey, fingerprint) as DraftAttachmentResponse | undefined; if (replay !== undefined) { @@ -472,6 +484,7 @@ export function createDraftStore( return db.transaction((): DraftBindResponse => { const at = now(); authorize(principalId); + refuseRetired(input.sessionId); const send = db .query("SELECT session_id FROM session_draft_sends WHERE draft_id = ? AND request_id = ?") .get(draftId, input.requestId) as { session_id: string } | null; @@ -511,7 +524,7 @@ export function createDraftStore( ).run(draftId); } const row = readDraft(draftId); - if (!row || row.deleted_at !== null) return "kept"; + if (!row || row.deleted_at !== null || retired(row.session_id) || retired(input.sessionId)) return "kept"; const source = input.resumed ? input.sessionId : input.sourceSessionId ?? null; if (row.session_id !== source) return "kept"; if (row.revision !== revision) { diff --git a/packages/ui-server/src/routes/chat-deletions.ts b/packages/ui-server/src/routes/chat-deletions.ts new file mode 100644 index 0000000000..98ad1fe057 --- /dev/null +++ b/packages/ui-server/src/routes/chat-deletions.ts @@ -0,0 +1,62 @@ +import { Hono } from "hono"; +import type { ChatDeletionRefusal, ChatDeletionRequest } from "@schlessera/brain-ui-sdk/protocol"; +import type { AppEnv } from "../app-env.js"; +import type { Principal } from "../db/principals.js"; +import type { ChatDeletion } from "../ws/chat-deletion.js"; + +const MAX_ID = 2048; +const id = (value: unknown): value is string => typeof value === "string" && value.length > 0 && value.length <= MAX_ID; + +/** A content-free refusal: the reason category alone, never whether someone else's chat exists. */ +const REFUSALS: Record = { + unauthorized: { status: 403, message: "Only the chat's owner, signed in as a person, can delete it." }, + unavailable: { status: 404, message: "This chat is not available to delete." }, + stale: { status: 409, message: "This chat changed since it was reviewed. Review it again before deleting." }, + unsupported: { status: 409, message: "This chat's backend cannot remove its history, so nothing was deleted." }, + busy: { status: 409, message: "This chat has work in progress. Stop or finish it first; nothing was deleted." }, +}; + +function parse(body: unknown): ChatDeletionRequest | null { + if (!body || typeof body !== "object" || Array.isArray(body)) return null; + const { operationId, target, expected } = body as Record; + if (!id(operationId) || !target || typeof target !== "object" || !expected || typeof expected !== "object") return null; + const t = target as Record, e = expected as Record; + const keys = Object.keys(t); + if (keys.length !== 1 || !(("sessionId" in t && id(t.sessionId)) || ("historyOwnerId" in t && id(t.historyOwnerId)))) return null; + if (!(e.backendId === null || id(e.backendId)) || typeof e.generation !== "number" || !Number.isSafeInteger(e.generation) || e.generation < 1) return null; + return { operationId, target: "sessionId" in t ? { sessionId: t.sessionId as string } : { historyOwnerId: t.historyOwnerId as string }, + expected: { backendId: e.backendId as string | null, generation: e.generation } }; +} + +/** + * `POST /api/chat-deletions` (additive, #3230): an authenticated owner + * deletes its own chat's local history. Retirement happens before any store is + * touched; the receipt reports each selected store's outcome and what local + * deletion never removes. Repeating an operation ID retries its unfinished + * stores. Agents, ambient callers without an owner mapping, revoked and + * foreign principals are refused without content or existence leakage. + */ +export function createChatDeletionRoutes(deps: { deletion: ChatDeletion; principalValid: (principal: Principal) => boolean }): Hono { + return new Hono().post("/chat-deletions", async (c) => { + c.header("Cache-Control", "no-store"); + const principal = c.get("principal"); + if (!principal) return c.json({ error: "Authentication required", authRequired: true }, 401); + const request = parse(await c.req.json().catch(() => null)); + if (!request) return c.json({ error: "INVALID_CHAT_DELETION", message: "Name one chat, an operation ID and what was reviewed." }, 400); + let result; + try { + result = await deps.deletion.delete({ operationId: request.operationId, principalId: principal.id, + target: "sessionId" in request.target ? { sessionId: request.target.sessionId } : { ownerId: request.target.historyOwnerId }, + expected: request.expected }); + } catch { + return c.json({ error: "CHAT_DELETION_FAILED", message: "The host could not record this deletion. Nothing is reported as deleted; try again." }, 500); + } + // Revoked while the stores were cleaned: the operation continues, the caller learns nothing. + if (!deps.principalValid(principal)) return c.json({ error: "Authentication required", authRequired: true }, 401); + if (result.status === "refused") { + const refusal = REFUSALS[result.reason]; + return c.json({ error: "CHAT_DELETION_REFUSED", reason: result.reason, message: refusal.message }, refusal.status); + } + return c.json(result.receipt); + }); +} diff --git a/packages/ui-server/src/routes/sessions.ts b/packages/ui-server/src/routes/sessions.ts index c47e9927b0..0ad115ce9f 100644 --- a/packages/ui-server/src/routes/sessions.ts +++ b/packages/ui-server/src/routes/sessions.ts @@ -3,7 +3,8 @@ import type { AppEnv } from "../app-env.js"; import type { Database } from "bun:sqlite"; import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; import type { BackendRegistry } from "../agent/backend.js"; -import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { SESSION_NOT_FOUND, type SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { ChatRetiredError } from "../ws/chat-lifecycle.js"; export function createSessionRoutes(deps: { registry: BackendRegistry; @@ -19,6 +20,8 @@ export function createSessionRoutes(deps: { * earlier run are not listed: nothing would refresh them. */ labels?: boolean; + /** Whether a chat identity is retired (#3230). A retired chat is absent from every list and read. */ + retired?: (target: { sessionId: string } | { ownerId: string }) => boolean; }): Hono { const { registry, db } = deps; const pending = new Map>(); @@ -88,7 +91,8 @@ export function createSessionRoutes(deps: { }) ) ); - const listed = results.flatMap((result) => result.status === "fulfilled" ? result.value : []); + const listed = results.flatMap((result) => result.status === "fulfilled" ? result.value : []) + .filter((session) => !deps.retired?.({ sessionId: session.id })); // A handoff destination names its source (#61). The title is the one // the source's own backend lists, else the catalog's first prompt. const titles = new Map(listed.map((session) => [session.id, session.title])); @@ -118,7 +122,7 @@ export function createSessionRoutes(deps: { const retainedRows = c.req.query("includeRetainedConversations") === "true" && principal ? db.query("SELECT id,created_at FROM dialogue_owners WHERE principal_id=? AND session_id IS NULL AND id>? ORDER BY id LIMIT 201").all(principal.id,after ?? "") as {id:string;created_at:number}[] : undefined; - const retainedConversations = retainedRows?.slice(0,200); + const retainedConversations = retainedRows?.slice(0,200).filter(row => !deps.retired?.({ ownerId: row.id })); const retainedAfter = retainedRows && retainedRows.length > 200 ? retainedConversations!.at(-1)!.id : undefined; return c.json({ sessions, ...(retainedConversations ? {retainedConversations} : {}), ...(retainedAfter ? {retainedAfter} : {}), ...(unavailableBackends.length ? { unavailableBackends } : {}) }); } catch (err) { @@ -131,13 +135,19 @@ export function createSessionRoutes(deps: { .get("/sessions/:id", async (c) => { const id = c.req.param("id"); + // Rechecked after every await: a chat retired mid-read publishes nothing (#3230). + const gone = () => deps.retired?.({ sessionId: id }) === true; + const absent = () => c.json({ error: SESSION_NOT_FOUND, message: "This host has no such session." }, 404); try { await deps.settled?.(); + if (gone()) return absent(); const backend = await registry.getBackendForSession(getStoredBackendId(id)); const messages = await backend.getHistory(id); await deps.settled?.(); + if (gone()) return absent(); return c.json({ id, messages: deps.prepareHistory?.(id, messages) ?? messages }); } catch (err) { + if (err instanceof ChatRetiredError || gone()) return absent(); return c.json( { error: err instanceof Error ? err.message : "Failed to get session" }, 500 diff --git a/packages/ui-server/src/ws/chat-deletion.ts b/packages/ui-server/src/ws/chat-deletion.ts new file mode 100644 index 0000000000..1e0933ab71 --- /dev/null +++ b/packages/ui-server/src/ws/chat-deletion.ts @@ -0,0 +1,105 @@ +/** + * Explicit local chat deletion (#3230): one owner-authorized operation + * retires the chat, retires its live readers and holders, then asks every + * selected store to remove its copies under the same intent. Completion is + * reported only when every store confirmed removal; anything else stays + * pending, partial or unknown and is retried under the same operation, by a + * repeated request or by restart reconciliation. Outcomes carry store + * categories only: no text, title, raw path or free-form error. + * Policy: docs/decisions/chat-history-deletion.md. + */ +import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; +import type { ChatDeletionReceipt, ChatDeletionRetained } from "@schlessera/brain-ui-sdk/protocol"; +import type { RetireChatInput, RetireChatResult, RetireRefusal, RetiredChatIdentities } from "./chat-lifecycle.js"; +import { HOST_CHAT_STORES } from "./chat-store-cleanup.js"; +import { removableBackendIds, removeRetiredNativeHistory } from "./native-history-removal.js"; +import type { SessionCatalog } from "./session-catalog.js"; + +type Retired = Extract; + +/** + * What local deletion never removes, in every receipt: independent saved + * content, effects and their audit, copies a provider already holds, backups + * (an older one can restore text), and devices that are offline until they + * reconnect and learn the chat was retired. + */ +export const CHAT_DELETION_RETAINED: readonly ChatDeletionRetained[] = ["independent_content", "effects_and_audit", "provider_copies", "backups", "offline_devices"]; + +export interface ChatDeletionDeps { + catalog: Pick; + /** The installed backends; only those advertising and implementing removal are eligible. */ + backends(): Promise; + /** Effect-owning work on these identities refuses deletion before retirement. */ + busy(identities: RetiredChatIdentities): boolean; + /** Retire live holders and tell the owner's clients. Runs on every retired outcome; idempotent. */ + retired(principalId: string, retirement: Retired): void; +} + +export type ChatDeletionResult = { status: "refused"; reason: RetireRefusal } | { status: "retired"; receipt: ChatDeletionReceipt }; + +/** The wire receipt: store categories and outcomes only. */ +export function chatDeletionReceipt(retirement: Retired): ChatDeletionReceipt { + return { operationId: retirement.operationId, generation: retirement.generation, status: retirement.cleanup, + stores: { ...retirement.stores }, retained: [...CHAT_DELETION_RETAINED] }; +} + +export function createChatDeletion(deps: ChatDeletionDeps) { + // One cleanup per retirement in this process; a concurrent repeat joins it. + const running = new Map>(); + + async function cleanup(retirement: Retired, backends: readonly AgentBackend[]): Promise { + const { catalog } = deps; + if (!catalog.cleanChatStore || !catalog.recordChatCleanup) throw new Error("This catalog cannot clean up chats"); + if (retirement.stores.native !== undefined && retirement.stores.native !== "removed") { + const backend = backends.find(candidate => candidate.id === retirement.backendId); + await removeRetiredNativeHistory(catalog, backend, retirement); + } + for (const store of HOST_CHAT_STORES) { + if (retirement.stores[store] === undefined || retirement.stores[store] === "removed") continue; + // A store that cannot run stays partial: content may remain until the retry. + await catalog.cleanChatStore(retirement.lifecycleId, store).catch(() => catalog.recordChatCleanup!(retirement.lifecycleId, store, "partial")); + } + } + + function complete(retirement: Retired, backends: readonly AgentBackend[]): Promise { + const existing = running.get(retirement.lifecycleId); + if (existing) return existing; + const work = cleanup(retirement, backends).finally(() => { if (running.get(retirement.lifecycleId) === work) running.delete(retirement.lifecycleId); }); + running.set(retirement.lifecycleId, work); + return work; + } + + return { + /** + * Retire and clean up one chat for its authenticated owner. A repeated + * operation key returns the same operation and retries its unfinished + * stores; it never authorizes a replacement chat. + */ + async delete(input: Omit): Promise { + const { catalog } = deps; + if (!catalog.retireChat || !catalog.chatRetirement) throw new Error("This catalog cannot retire chats"); + const backends = await deps.backends(); + const result = await catalog.retireChat({ ...input, removableBackends: removableBackendIds(backends), at: Date.now() }, deps.busy); + if (result.status === "refused") return result; + deps.retired(input.principalId, result); + await complete(result, backends); + const current = await catalog.chatRetirement(result.operationId, input.principalId); + return { status: "retired", receipt: chatDeletionReceipt((current ?? result) as Retired) }; + }, + /** + * Restart reconciliation: finish every retirement a store has not + * confirmed, under its original operation. Fences were already durable; + * live holders of an earlier process are gone with it. + */ + async reconcile(): Promise { + const pending = await deps.catalog.unfinishedChatRetirements?.() ?? []; + if (!pending.length) return; + const backends = await deps.backends(); + for (const retirement of pending) { + deps.retired(retirement.principalId, retirement); + await complete(retirement, backends).catch(() => {}); + } + }, + }; +} +export type ChatDeletion = ReturnType; diff --git a/packages/ui-server/src/ws/chat-lifecycle.ts b/packages/ui-server/src/ws/chat-lifecycle.ts index 973b542363..0ef957f564 100644 --- a/packages/ui-server/src/ws/chat-lifecycle.ts +++ b/packages/ui-server/src/ws/chat-lifecycle.ts @@ -46,6 +46,8 @@ export type ChatRetirementStatus = "pending" | "partial" | "unknown" | "removed" export type RetireChatResult = | { status: "refused"; reason: RetireRefusal } | { status: "retired"; lifecycleId: string; operationId: string; generation: number; identities: RetiredChatIdentities; + /** The backend whose native store was selected, or null for a provisional chat. */ + backendId: string | null; cleanup: ChatRetirementStatus; stores: Partial> }; const MAX_ID = 2048; @@ -131,14 +133,15 @@ export function cleanupStatus(stores: Partial outcome === "removed") ? "removed" : "pending"; } -function identitiesOf(db: Database, lifecycleId: string): RetiredChatIdentities { +export 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 { +function receipt(db: Database, row: { id: string; operation_id: string; generation: number; backend_id: string | null }): 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 }; + return { status: "retired", lifecycleId: row.id, operationId: row.operation_id, generation: row.generation, identities: identitiesOf(db, row.id), + backendId: row.backend_id, cleanup: cleanupStatus(stores), stores }; } const targetId = (target: ChatTarget) => "sessionId" in target ? target.sessionId : target.ownerId; @@ -154,8 +157,8 @@ export function retireChat(db: Database, input: RetireChatInput): RetireChatResu 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; + 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. return previous.principal_id === input.principalId && previous.id === targetId(input.target) @@ -181,7 +184,7 @@ export function retireChat(db: Database, input: RetireChatInput): RetireChatResu // 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 }); + 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. */ @@ -194,11 +197,22 @@ function ownsAlias(db: Database, input: RetireChatInput): boolean { /** 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; + const row = db.query("SELECT id,principal_id,operation_id,generation,backend_id FROM chat_lifecycles WHERE operation_id=?") + .get(operationId) as { id: string; principal_id: string; operation_id: string; generation: number; backend_id: string | null } | null; return row && row.principal_id === principalId ? receipt(db, row) : null; } +/** + * Every retirement whose cleanup is not yet confirmed by each selected store, + * oldest first: the restart reconciliation's work list (#3230). Content-free. + */ +export function unfinishedChatRetirements(db: Database): Array & { principalId: string }> { + const rows = db.query(`SELECT id,principal_id,operation_id,generation,backend_id FROM chat_lifecycles + WHERE id IN (SELECT lifecycle_id FROM chat_retirement_stores WHERE outcome!='removed') ORDER BY retired_at,id`) + .all() as { id: string; principal_id: string; operation_id: string; generation: number; backend_id: string | null }[]; + return rows.map(row => ({ ...receipt(db, row) as Extract, principalId: row.principal_id })); +} + /** * 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. diff --git a/packages/ui-server/src/ws/chat-store-cleanup.ts b/packages/ui-server/src/ws/chat-store-cleanup.ts new file mode 100644 index 0000000000..1c2aa01c2a --- /dev/null +++ b/packages/ui-server/src/ws/chat-store-cleanup.ts @@ -0,0 +1,88 @@ +/** + * Host-owned copies of one retired chat (#3230): canonical dialogue, task + * receipts and result facts, session projections and positively bound drafts. + * Each store's owner removes its content under the retirement's own intent and + * confirms removal only by reading back that nothing selected remains. + * Minimized identity and replay fences stay: chat, alias, conversation, task, + * request and native-handle identities live in `chat_retired_identities`, and + * the content-free ledger rows that refuse replays (`retry_receipts`, draft + * send records, consumed task keys) are kept without their text. + * + * Retained on purpose, as independent owners the policy excludes: Activity, + * Inbox and governance records, turn journals, policy proposals, turn scope, + * provider-exposure and masking lineage, usage accounting, worker profiles and + * handoff lineage identifiers. They are disclosed, never claimed removed. + * Policy: docs/decisions/chat-history-deletion.md. + */ +import type { Database } from "bun:sqlite"; +import { identitiesOf, recordChatCleanup, type ChatRetirementStatus, type ChatStore } from "./chat-lifecycle.js"; + +/** The stores a host owns itself; `native` belongs to the chat's backend. */ +export type HostChatStore = Exclude; +export const HOST_CHAT_STORES: readonly HostChatStore[] = ["dialogue", "tasks", "projections", "drafts"]; + +/** A fingerprint no request can produce: an old idempotency key now always refuses. */ +const RETIRED_FINGERPRINT = "retired"; + +const marks = (values: readonly string[]) => values.map(() => "?").join(","); +const count = (db: Database, sql: string, values: readonly string[]) => + values.length ? (db.query(sql.replace("(?)", `(${marks(values)})`)).get(...values) as { n: number }).n : 0; +const run = (db: Database, sql: string, values: readonly string[], ...before: (string | number)[]) => { + if (values.length) db.prepare(sql.replace("(?)", `(${marks(values)})`)).run(...before, ...values); +}; + +/** Session projections that carry readable text, digests of it, or classified copies. */ +const PROJECTION_TABLES = ["message_blocks", "classification_confidence", "message_sources", "local_exchanges", + "retry_requests", "turn_failures", "turn_boundaries", "session_state_room"] as const; + +function scrub(db: Database, lifecycleId: string, store: HostChatStore, at: number): number { + const ids = identitiesOf(db, lifecycleId); + switch (store) { + case "dialogue": + // Owners, aliases and conversations are identities; the records are the text. + run(db, "DELETE FROM dialogue_records WHERE owner_id IN (?)", ids.dialogueOwners); + return count(db, "SELECT COUNT(*) AS n FROM dialogue_records WHERE owner_id IN (?)", ids.dialogueOwners); + case "tasks": + // Keys stay consumed; the submitted and recognized text and facts go. + run(db, "UPDATE conversation_tasks SET receipt=NULL,result_facts=NULL WHERE conversation_id IN (?)", ids.conversations); + return count(db, "SELECT COUNT(*) AS n FROM conversation_tasks WHERE conversation_id IN (?) AND (receipt IS NOT NULL OR result_facts IS NOT NULL)", ids.conversations); + case "projections": { + // The catalog row keeps cost, turns, backend and handoff identities. + run(db, "UPDATE sessions SET title=NULL,label=NULL,label_source=NULL WHERE id IN (?)", ids.sessions); + for (const table of PROJECTION_TABLES) run(db, `DELETE FROM ${table} WHERE session_id IN (?)`, ids.sessions); + return count(db, "SELECT COUNT(*) AS n FROM sessions WHERE id IN (?) AND (title IS NOT NULL OR label IS NOT NULL OR label_source IS NOT NULL)", ids.sessions) + + PROJECTION_TABLES.reduce((sum, table) => sum + count(db, `SELECT COUNT(*) AS n FROM ${table} WHERE session_id IN (?)`, ids.sessions), 0); + } + case "drafts": { + // Only drafts positively bound to a retired session; unbound and other chats' drafts stay. + const drafts = ids.sessions.length ? (db.query(`SELECT draft_id FROM session_drafts WHERE session_id IN (${marks(ids.sessions)})`) + .all(...ids.sessions) as { draft_id: string }[]).map(row => row.draft_id) : []; + const actor = (db.query("SELECT principal_id FROM chat_lifecycles WHERE id=?").get(lifecycleId) as { principal_id: string }).principal_id; + // A live draft becomes a tombstone at its next revision, so a stale save conflicts. + run(db, `UPDATE session_drafts SET revision=revision+1,text='',attachment_ids='[]',size_bytes=0,updated_at=?,updated_by=?,deleted_at=?,deleted_reason='deleted' + WHERE deleted_at IS NULL AND draft_id IN (?)`, drafts, at, actor, at); + run(db, "UPDATE session_drafts SET text='',attachment_ids='[]',size_bytes=0 WHERE draft_id IN (?)", drafts); + run(db, "DELETE FROM session_draft_attachments WHERE draft_id IN (?)", drafts); + run(db, "UPDATE session_draft_receipts SET fingerprint=?,response_json='null' WHERE draft_id IN (?)", drafts, RETIRED_FINGERPRINT); + return count(db, "SELECT COUNT(*) AS n FROM session_drafts WHERE draft_id IN (?) AND (text!='' OR attachment_ids!='[]' OR deleted_at IS NULL)", drafts) + + count(db, "SELECT COUNT(*) AS n FROM session_draft_attachments WHERE draft_id IN (?)", drafts) + + count(db, `SELECT COUNT(*) AS n FROM session_draft_receipts WHERE draft_id IN (?) AND (fingerprint!='${RETIRED_FINGERPRINT}' OR response_json!='null')`, drafts); + } + } +} + +/** + * Remove one host store's copies of a retired chat and record the outcome + * under its intent: `removed` only when the read-back finds nothing selected. + * Idempotent, and the retry for an interrupted or partial cleanup. A store + * that was not selected at retirement is refused. + */ +export function cleanChatStore(db: Database, lifecycleId: string, store: HostChatStore, at: number): ChatRetirementStatus { + if (!HOST_CHAT_STORES.includes(store)) throw new Error("Not a host chat store"); + const selected = db.query("SELECT outcome FROM chat_retirement_stores WHERE lifecycle_id=? AND store=?").get(lifecycleId, store) as { outcome: string } | null; + if (!selected) throw new Error("Chat cleanup store was not selected"); + let remaining: number; + try { remaining = db.transaction(() => scrub(db, lifecycleId, store, at)).immediate(); } + catch { return recordChatCleanup(db, lifecycleId, store, "partial", at); } + return recordChatCleanup(db, lifecycleId, store, remaining === 0 ? "removed" : "partial", at); +} diff --git a/packages/ui-server/src/ws/connection.ts b/packages/ui-server/src/ws/connection.ts index 310e9f2b95..fdf1f71c84 100644 --- a/packages/ui-server/src/ws/connection.ts +++ b/packages/ui-server/src/ws/connection.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import { upgradeWebSocket, websocket } from "hono/bun"; import type { MiddlewareHandler } from "hono"; -import { ASK_RECEIPTS_CAPABILITY, LIVENESS_CAPABILITY, PROTOCOL_REV, SESSION_RECOVERY_CAPABILITY } from "@schlessera/brain-ui-sdk/protocol"; +import { ASK_RECEIPTS_CAPABILITY, CHAT_DELETION_CAPABILITY, LIVENESS_CAPABILITY, PROTOCOL_REV, SESSION_RECOVERY_CAPABILITY } from "@schlessera/brain-ui-sdk/protocol"; import { parseClientMessage } from "@schlessera/brain-ui-sdk/schemas"; import { withTurnScope } from "./frames.js"; import { resendPendingInteractive } from "./resend.js"; @@ -114,6 +114,8 @@ export function createWsHandlers(host: WsHost, principal: Principal) { // GET /api/sessions/:id/recovery answers, and replays carry // host-proven turn ids (#964). ...(supportsSessionRecovery(host) ? { [SESSION_RECOVERY_CAPABILITY]: true } : {}), + // POST /api/chat-deletions answers, and `chat_retired` reaches declaring clients (#3230). + ...(host.chatDeletion ? { [CHAT_DELETION_CAPABILITY]: true } : {}), }, // Beside `capabilities`, whose values every shipped client parses // as booleans (#979). diff --git a/packages/ui-server/src/ws/conversation.ts b/packages/ui-server/src/ws/conversation.ts index 4ff97476b9..d40fc33969 100644 --- a/packages/ui-server/src/ws/conversation.ts +++ b/packages/ui-server/src/ws/conversation.ts @@ -1,5 +1,6 @@ import { withinStorageBudget } from "../db/settlement.js"; import { readLiveHistory } from "./live-history.js"; +import { ChatRetiredError } from "./chat-lifecycle.js"; import { requireKnownSession } from "./session-recovery.js"; /** * Host orchestration for live conversations (#957). @@ -292,6 +293,10 @@ export class ConversationHost { const history = await withinStorageBudget(readLiveHistory(this.host, principalId, conversation.sessionId ? { sessionId: conversation.sessionId } : { ownerId: conversation.historyOwnerId }, authorized), "Live history"); if (!authorized()) return; + // Deletion may have retired this chat while its history was read (#3230): never open or seed a provider for it. + const retired = this.host.catalog.chatRetired; + if (retired && (retired({ conversationId: conversation.id }) || (conversation.sessionId && retired({ sessionId: conversation.sessionId })) + || (conversation.historyOwnerId && retired({ ownerId: conversation.historyOwnerId })))) throw new ChatRetiredError(); if (!this.disclosed(msg)) { this.endEpoch(conversation,"refused",undefined,epoch); this.detach(conversation); this.refuse(ws,"CONVERSATION_DISCLOSURE","The voice service changed. Review its disclosure and select Start. Nothing was sent to the voice service.",msg.requestId); return; @@ -1208,6 +1213,31 @@ export class ConversationHost { } } + private retiredTargets(identities: { sessions: readonly string[]; dialogueOwners: readonly string[]; conversations: readonly string[] }): Conversation[] { + return [...this.conversations.values()].filter(conversation => identities.conversations.includes(conversation.id) + || (conversation.sessionId !== undefined && identities.sessions.includes(conversation.sessionId)) + || (conversation.historyOwnerId !== undefined && identities.dialogueOwners.includes(conversation.historyOwnerId))); + } + + /** Effect-owning voice work on a chat: queued or unsettled host tasks refuse its deletion (#3230). */ + busy(identities: { sessions: readonly string[]; dialogueOwners: readonly string[]; conversations: readonly string[] }): boolean { + return this.retiredTargets(identities).some(conversation => conversation.queue.length > 0 || conversation.receipts.some(work => !work.settled)); + } + + /** + * A retired chat (#3230): end its live epochs, stop capture and playback, + * close the provider session and forget the retained receipts and output. + * Nothing earlier sent to the provider is rewritten; a later conversation + * needs a new identity and an explicit Start. + */ + retire(identities: { sessions: readonly string[]; dialogueOwners: readonly string[]; conversations: readonly string[] }): void { + for (const conversation of this.retiredTargets(identities)) { + this.endEpoch(conversation, "stopped", "This chat was deleted. Nothing more was sent to the voice service."); + this.detach(conversation); + this.conversations.delete(conversation.id); + } + } + /** Host teardown: end every epoch, close every provider session, forget all. */ closeAll(): void { for (const conversation of this.conversations.values()) { diff --git a/packages/ui-server/src/ws/dispatch.ts b/packages/ui-server/src/ws/dispatch.ts index 106aecd65e..57034a9b21 100644 --- a/packages/ui-server/src/ws/dispatch.ts +++ b/packages/ui-server/src/ws/dispatch.ts @@ -1,4 +1,5 @@ import { requireKnownSession } from "./session-recovery.js"; +import { ChatRetiredError } from "./chat-lifecycle.js"; import { resolveChatFiles, withTrackFiles } from "../tracks/read.js"; import { SHARE_MAX_FILES, SHARE_MAX_TOTAL_BYTES, type SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; import { estimateDecodedBase64Bytes } from "./attachments.js"; @@ -698,6 +699,13 @@ export async function handleClientMessage( host.reportSessionResume(msg.sessionId, "unauthorized"); return; } + // Retired while its history was read (#3230): absent, not a load failure. + if (err instanceof ChatRetiredError) { + host.reportSessionResume(msg.sessionId, "error", { error: "retired" }); + host.sendMessage(ws, { type: "error", code: "SESSION_NOT_FOUND", sessionId: msg.sessionId, + message: "This conversation is not available on this host. Start a New conversation; your draft is kept." }); + return; + } const message = err instanceof Error ? err.message : "Failed to load session"; if (!resumeReported) host.reportSessionResume(msg.sessionId, "error", { error: message }); host.reportTurnFailed("SESSION_LOAD_ERROR", { sessionId: msg.sessionId }, message); diff --git a/packages/ui-server/src/ws/host.ts b/packages/ui-server/src/ws/host.ts index b7bb3e6362..ef2b043723 100644 --- a/packages/ui-server/src/ws/host.ts +++ b/packages/ui-server/src/ws/host.ts @@ -2,7 +2,8 @@ import { StorageSettlementIndeterminate, withinStorageBudget } from "../db/settl import { DialogueJournal } from "./dialogue.js"; import { type AskUserFormLimits } from "@schlessera/brain-ui-sdk/tool-contracts"; import { resolveAskUserFormLimits } from "@schlessera/brain-ui-sdk/internal/client"; -import { FOLLOW_UP_QUEUE_CAPABILITY, type ServerMessage, type ServerSessionQueue } from "@schlessera/brain-ui-sdk/protocol"; +import { CHAT_DELETION_CAPABILITY, FOLLOW_UP_QUEUE_CAPABILITY, type ServerMessage, type ServerSessionQueue } from "@schlessera/brain-ui-sdk/protocol"; +import { ChatRetiredError, type RetiredChatIdentities } from "./chat-lifecycle.js"; import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; import type { TurnClassifier } from "../classification/classify-turn.js"; import { ClientSet, sendTo, type WSContext } from "./clients.js"; @@ -254,6 +255,8 @@ export function turnLogAttributes(turn: TurnLogContext): Record export class WsHost { /** @internal Concrete user history service mounted by this host, not agent authority. */ turnReverts?: import("../brain/turn-revert.js").TurnReverts; + /** Explicit local chat deletion (#3230); present when the host answers `POST /api/chat-deletions`. */ + chatDeletion?: import("./chat-deletion.js").ChatDeletion; /** @internal Concrete host-owned scope observation and process control. */ readonly scope?: import("../brain/turn-scope.js").TurnScope; readonly journal?: import("../brain/turn-journal.js").TurnJournal; @@ -636,6 +639,9 @@ export class WsHost { * @internal Host wiring (#1053). */ prepareHistory(sessionId: string, messages: SessionHistoryMessage[], strictSources = false): SessionHistoryMessage[] { + // The last synchronous step before any history is published (#3230): + // a chat retired while its native history was read publishes nothing. + if (this.catalog.chatRetired?.({ sessionId })) throw new ChatRetiredError(); // Turn ids first: boundaries were observed on the backend's own messages. messages = this.catalog.attachTurnBoundaries?.(sessionId, messages) ?? messages; if (this.journal) messages = messages.map(message => message.role === "assistant" && message.turnId @@ -649,6 +655,33 @@ export class WsHost { return this.catalog.attachRetryRequest?.(sessionId, joined) ?? joined; } + /** + * Effect-owning work on a chat refuses its deletion (#3230): a running or + * starting turn, queued follow-ups, or unsettled live-conversation tasks. + * The owner stops or reconciles them first; deletion never cancels them. + * @internal Host wiring. + */ + chatBusy(identities: RetiredChatIdentities): boolean { + for (const sessionId of identities.sessions) { + if (this.coordinator.bySession.has(sessionId) || this.coordinator.startingBySession.has(sessionId) + || this.coordinator.pendingFollowUps(sessionId).length > 0) return true; + } + return this.conversations?.busy(identities) ?? false; + } + + /** + * A chat was retired (#3230): end its live conversation epochs and tell the + * owner's capable clients to drop their projections of it. Readers already + * refuse it, so a client that never learns this still cannot read it. + * @internal Host wiring. + */ + chatRetired(principalId: string, retirement: { identities: RetiredChatIdentities; generation: number }): void { + this.conversations?.retire(retirement.identities); + const sessionId = retirement.identities.sessions[0]; + this.clients.broadcast({ type: "chat_retired", ...(sessionId ? { sessionId } : {}), historyOwnerIds: [...retirement.identities.dialogueOwners], + generation: retirement.generation }, undefined, CHAT_DELETION_CAPABILITY, principalId); + } + /** * A turn's backend call resolved: counted, and logged with its duration. * @internal Host wiring (#1053). diff --git a/packages/ui-server/src/ws/live-history.ts b/packages/ui-server/src/ws/live-history.ts index 54c630c1ea..f51068ae60 100644 --- a/packages/ui-server/src/ws/live-history.ts +++ b/packages/ui-server/src/ws/live-history.ts @@ -3,24 +3,33 @@ import type { DialoguePage, DialogueRecord, SessionHistoryMessage } from "@schle import type { ConversationHistoryEnvelope, HistoricalItem, HistoryGapReason } from "@schlessera/brain-ui-sdk/server"; import type { WsHost } from "./host.js"; import type { DialogueTarget } from "./dialogue-storage.js"; +import { ChatRetiredError } from "./chat-lifecycle.js"; /** No request replay, provider call or mutation of the native transcript. */ export async function readLiveHistory(host: WsHost, principalId: string, target: DialogueTarget, authorized: () => boolean): Promise { - if (!authorized()) return; + // A chat retired during any await is never frozen into a provider seed (#3230). + const live = () => { + if (!authorized()) return false; + const retired = host.catalog.chatRetired; + if (retired && (target.sessionId ? retired({ sessionId: target.sessionId }) : target.ownerId !== undefined && retired({ ownerId: target.ownerId }))) + throw new ChatRetiredError(); + return true; + }; + if (!live()) return; // Drain observations already accepted before sampling the journal high-water. await host.historySettled(); - if (!authorized()) return; + if (!live()) return; const page = await host.catalog.dialogueRead?.(principalId, target); - if (!authorized()) return; + if (!live()) return; let messages: SessionHistoryMessage[] = []; if (target.sessionId) { const backend = await host.registry.getBackendForSession(host.catalog.getStoredBackendId(target.sessionId)); - if (!authorized()) return; + if (!live()) return; const native = await backend.getHistory(target.sessionId); - if (!authorized()) return; + if (!live()) return; await host.historySettled(); - if (!authorized()) return; + if (!live()) return; // Fail closed on provenance read errors: a task wrapper must never default to typed. messages = host.prepareHistory(target.sessionId, native, true); } @@ -29,7 +38,7 @@ export async function readLiveHistory(host: WsHost, principalId: string, target: const facts: Array<{ item: HistoricalItem; turnId: string; requestId: string }> = []; for (const id of conversations) { const stored = await host.catalog.loadConversation?.(id, principalId); - if (!authorized()) return; + if (!live()) return; if (!stored || stored.id !== id || stored.principalId !== principalId || stored.sessionId !== target.sessionId) continue; for (const receipt of stored.receipts) { // Retained receipts can expose contradictory positive provenance, never @@ -55,7 +64,7 @@ export async function readLiveHistory(host: WsHost, principalId: string, target: } }); } } - if (!authorized()) return; + if (!live()) return; // A replaced/adopted generation cannot be treated as the sampled owner. if (page) { const current = host.catalog.dialogueOwnerForId?.(page.ownerId, principalId); diff --git a/packages/ui-server/src/ws/recovery.ts b/packages/ui-server/src/ws/recovery.ts index a413bd87ec..91afed4751 100644 --- a/packages/ui-server/src/ws/recovery.ts +++ b/packages/ui-server/src/ws/recovery.ts @@ -209,6 +209,8 @@ function boundedHistory(read: Promise): Promise { export async function readSessionRecovery(host: WsHost, sessionId: string, principal: Principal): Promise { if (!host.isPrincipalValid(principal)) return { kind: "unauthorized" }; const { catalog, coordinator } = host; + // A retired chat has no recovery state to report (#3230). + if (catalog.chatRetired?.({ sessionId })) return { kind: "not_found" }; const known = () => coordinator.bySession.has(sessionId) || coordinator.startingBySession.has(sessionId) || @@ -233,6 +235,7 @@ export async function readSessionRecovery(host: WsHost, sessionId: string, princ } // Authorization is re-read after every asynchronous step. if (!host.isPrincipalValid(principal)) return { kind: "unauthorized" }; + if (catalog.chatRetired?.({ sessionId })) return { kind: "not_found" }; if (!found && !known()) { // A backend that failed or timed out might hold it: that is a failed // read, not an absent session. diff --git a/packages/ui-server/src/ws/session-catalog-writes.ts b/packages/ui-server/src/ws/session-catalog-writes.ts index 728cde6054..acb5d1987c 100644 --- a/packages/ui-server/src/ws/session-catalog-writes.ts +++ b/packages/ui-server/src/ws/session-catalog-writes.ts @@ -28,6 +28,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"; 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) @@ -194,6 +195,7 @@ export function setup(db: Database, options: SessionCatalogWriteOptions = {}): W 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), + chatStoreCleanup: (lifecycleId: string, store: HostChatStore, at: number) => cleanChatStore(db, lifecycleId, store, 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) => { live(sessionId); return saveLocalExchange(db, sessionId, exchange, delivered, at); }, exchangesDelivered: (sessionId: string, exchangeIds: string[], at: number) => { live(sessionId); return 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 fab6fd2f78..5c320f38a0 100644 --- a/packages/ui-server/src/ws/session-catalog.ts +++ b/packages/ui-server/src/ws/session-catalog.ts @@ -27,7 +27,8 @@ 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 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 * as retries from "./retry-requests.js"; import * as work from "./session-work.js"; import { attachTurnFailures, type RecordedTurnFailure } from "./turn-failures.js"; @@ -64,6 +65,10 @@ export interface SessionCatalog { 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; + /** A host store removes its copies of a retired chat and records the read-back outcome (#3230). */ + cleanChatStore?(lifecycleId: string, store: HostChatStore): Promise; + /** Retirements some selected store has not confirmed yet, for restart reconciliation (#3230). */ + unfinishedChatRetirements?(): 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; @@ -316,6 +321,8 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi }, async chatRetirement(operationId, principalId) { await tail; return chatRetirement(db(), operationId, principalId); }, recordChatCleanup: (lifecycleId, store, outcome) => submit("chatCleanup", lifecycleId, store, outcome, Date.now()), + cleanChatStore: (lifecycleId, store) => submit("chatStoreCleanup", lifecycleId, store, Date.now()), + async unfinishedChatRetirements() { await tail; return unfinishedChatRetirements(db()); }, 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) => { diff --git a/packages/ui-server/src/ws/session-recovery.ts b/packages/ui-server/src/ws/session-recovery.ts index 338d2ddb2e..0b1512b36a 100644 --- a/packages/ui-server/src/ws/session-recovery.ts +++ b/packages/ui-server/src/ws/session-recovery.ts @@ -11,15 +11,20 @@ export async function requireKnownSession(host: WsHost, ws: WSContext, connectio await withinStorageBudget(Promise.resolve(host.catalog.settled?.()), "Session admission settlement"); if (connection.authorization.expiresAt <= Date.now()) host.expireAuthorizationContexts(); if (host.closing || connection.closed || !connection.authorization.valid) return false; + // A retired chat is gone for every caller, however its id was retained (#3230). + if (host.catalog.chatRetired?.({ sessionId })) { + host.sendMessage(ws, { type: "error", sessionId, ...(requestId ? { requestId } : {}), code: "SESSION_NOT_FOUND", + message: "This conversation is not available on this host. Start a New conversation; your draft is kept." }); + return false; + } // Older catalogs may expose ownership without the optional existence read. - const exists = host.catalog.hasSession?.(sessionId) - ?? (host.catalog.getStoredBackendId(sessionId) !== null ? true : undefined); + const exists = existsInCatalog(host, sessionId); if (exists === true) return true; if (exists === false) { const recovery = await readSessionRecovery(host, sessionId, connection.principal); if (connection.authorization.expiresAt <= Date.now()) host.expireAuthorizationContexts(); if (host.closing || connection.closed || !connection.authorization.valid || recovery.kind === "unauthorized") return false; - if (recovery.kind === "ok") { + if (recovery.kind === "ok" && !host.catalog.chatRetired?.({ sessionId })) { if (allowImportedHistory) return true; // Imported history is real, but a read cannot invent a catalog/profile binding. host.sendMessage(ws, { type: "error", code: "CONVERSATION_STORAGE", sessionId, ...(requestId ? { requestId } : {}), @@ -46,3 +51,8 @@ export async function requireKnownSession(host: WsHost, ws: WSContext, connectio } return false; } + +function existsInCatalog(host: WsHost, sessionId: string): boolean | undefined { + return host.catalog.hasSession?.(sessionId) + ?? (host.catalog.getStoredBackendId(sessionId) !== null ? true : undefined); +} diff --git a/packages/ui-server/tests/chat-deletion.test.ts b/packages/ui-server/tests/chat-deletion.test.ts new file mode 100644 index 0000000000..2e28cb8dd6 --- /dev/null +++ b/packages/ui-server/tests/chat-deletion.test.ts @@ -0,0 +1,305 @@ +/** + * Explicit local chat deletion (#3230) on an actual file-backed SQLite write + * worker: per-store removal, honest partial/unknown outcomes, restart + * reconciliation, the authenticated endpoint and the read gates that keep a + * retired chat absent. Backends are minimal seam doubles; concrete native + * removal is proven against the installed runtimes in the backend packages. + * Synthetic Odysseus fixtures only: no provider, network or real transcript. + */ +import { afterEach, expect, test } from "bun:test"; +import type { Database } from "bun:sqlite"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Hono } from "hono"; +import type { ChatDeletionRetained, ConversationWorkReceipt, DialogueEvidence, SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { AgentBackend, SessionHistoryRemovalOutcome, SessionHistoryRemovalRequest } from "@schlessera/brain-ui-sdk/server"; +import type { AppEnv } from "../src/app-env.js"; +import { createUiDb } from "../src/db/client.js"; +import { createPrincipal, isUsablePrincipal, resolveAmbientPrincipal, resolvePrincipal, revokePrincipal } from "../src/db/principals.js"; +import { openSqliteWriter } from "../src/db/write-worker.js"; +import { createOffloopActivityStore } from "../src/activity/store-writes.js"; +import { createDraftStore, DraftError } from "../src/drafts/store.js"; +import { createSessionCatalog, type SessionCatalog } from "../src/ws/session-catalog.js"; +import { ChatRetiredError, type RetiredChatIdentities } from "../src/ws/chat-lifecycle.js"; +import { createChatDeletion, type ChatDeletionDeps } from "../src/ws/chat-deletion.js"; +import { createChatDeletionRoutes } from "../src/routes/chat-deletions.js"; +import { createSessionRoutes } from "../src/routes/sessions.js"; +import { readLiveHistory } from "../src/ws/live-history.js"; +import type { BackendRegistry } from "../src/agent/backend.js"; +import type { WsHost } from "../src/ws/host.js"; + +const MARKER = "Odysseus hid the oar under the olive root"; +const CONTROL = "Penelope kept the loom unfinished"; +const UNBOUND = "Telemachus drafted a letter to Nestor"; +const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); + +const capabilities = { resume: true, permissions: true, thinking: true, attachments: true, askUser: true, costReporting: true, concurrentSessions: true, followUp: true }; +function backend(outcomes: Array, calls: SessionHistoryRemovalRequest[] = [], history: () => Promise = async () => []): AgentBackend { + return { id: "claude", capabilities: { ...capabilities, historyRemoval: true }, async removeSessionHistory(req: SessionHistoryRemovalRequest) { + calls.push(req); + const next = outcomes.shift() ?? "removed"; + if (next instanceof Error) throw next; + return { outcome: next }; + }, async listSessions() { return [{ id: "voyage", title: null, createdAt: 1, lastActiveAt: 2, totalCostUsd: 0, numTurns: 0 }, { id: "aeaea", title: null, createdAt: 1, lastActiveAt: 1, totalCostUsd: 0, numTurns: 0 }]; }, + getHistory: history } as unknown as AgentBackend; +} + +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) }); + return { db, catalog, async close() { await catalog.settled!(); await writer.close(); db.close(); } }; +} + +function voice(conversationId: string, text: string): DialogueEvidence { + return { kind: "voice", conversationId, epoch: 1, providerId: "gemini-live", event: { + kind: "unassigned_input_fragment", sequence: 0, text, timing: { kind: "unavailable" }, finalization: "unknown" } }; +} +function task(conversationId: string, sessionId: string, text: string): ConversationWorkReceipt { + return { conversationId, epoch: 1, provenance: "contextual", taskId: `${conversationId}-task`, requestId: `${conversationId}-request`, + nativeHandle: `${conversationId}-native`, state: "completed", delivery: "returned", turnId: `${conversationId}-turn`, recognized: text, submitted: text, sessionId }; +} + +/** Every host copy the selected stores own, each carrying the chat's marker. */ +async function seedChat(host: ReturnType, principalId: string, sessionId: string, conversationId: string, text: string) { + const { catalog, db } = host; + catalog.persistSessionStub(sessionId, text, 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, text) }); + await catalog.saveConversationEpoch!({ id: conversationId, principalId, epoch: 1, sessionId }); + await catalog.saveConversationTask!(principalId, task(conversationId, sessionId, text), text); + await catalog.settled!(); + const at = Date.now(); + db.prepare("UPDATE sessions SET title=?,label=?,label_source='labeller',total_cost_usd=1.5,num_turns=3 WHERE id=?").run(text, text, sessionId); + db.prepare("INSERT INTO message_blocks VALUES(?,?,?,?)").run(sessionId, `hash:${text}`, JSON.stringify([{ type: "text", text }]), at); + db.prepare("INSERT INTO classification_confidence(session_id,pass_id,candidate_id,recorded_at,candidate_kind,question,answer_type,choice,confidence,threshold,cleared,outcome) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)") + .run(sessionId, "p", "c", at, "table", text, "choice", text, 0.9, 0.5, 1, "kept"); + db.prepare("INSERT INTO message_sources(session_id,text_hash,ordinal,source,created_at,turn_id,track_files) VALUES(?,?,?,?,?,?,?)").run(sessionId, `hash:${text}`, 0, "typed", at, "t1", JSON.stringify([text])); + db.prepare("INSERT INTO local_exchanges(session_id,exchange_id,command,prompt,answer,context,created_at) VALUES(?,?,?,?,?,?,?)").run(sessionId, "x1", "/note", text, text, text, at); + db.prepare("INSERT INTO retry_requests VALUES(?,?,?,?,?,?)").run(sessionId, "t1", principalId, JSON.stringify({ text }), text, text); + db.prepare("INSERT INTO retry_receipts VALUES(?,?,?,?)").run(`${sessionId}-retry`, sessionId, principalId, "accepted"); + db.prepare("INSERT INTO turn_failures VALUES(?,?,?,?,?,?)").run(sessionId, "claude", 0, "t1", `digest:${text}`, JSON.stringify({ message: text })); + db.prepare("INSERT INTO turn_boundaries VALUES(?,?,?,?,?)").run(sessionId, "claude", 0, `digest:${text}`, "t1"); + db.prepare("INSERT INTO session_state_room VALUES(?,?)").run(sessionId, JSON.stringify({ note: text })); + const drafts = createDraftStore(db); + drafts.save(principalId, `${sessionId}-draft`, { ifMatch: 0, idempotencyKey: `${sessionId}-save`, sessionId, text, attachmentIds: [] }); + const { attachmentId } = drafts.upload(principalId, `${sessionId}-draft`, { idempotencyKey: `${sessionId}-upload`, mime: "image/png", name: text, + bytes: new Uint8Array([...PNG, ...new TextEncoder().encode(text)]) }); + drafts.save(principalId, `${sessionId}-draft`, { ifMatch: 1, idempotencyKey: `${sessionId}-save-2`, sessionId, text, attachmentIds: [attachmentId] }); +} + +/** Every table and column, including BLOBs, that still holds `needle`. */ +function holding(db: Database, needle: string): string[] { + const hits: string[] = []; + for (const { name } of db.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all() as { name: string }[]) { + for (const { name: column } of db.query(`PRAGMA table_info("${name}")`).all() as { name: string }[]) { + const row = db.query(`SELECT COUNT(*) AS n FROM "${name}" WHERE instr(CAST("${column}" AS BLOB), CAST(? AS BLOB)) > 0`).get(needle) as { n: number }; + if (row.n) hits.push(`${name}.${column}`); + } + } + return hits; +} + +async function fixture() { + const root = mkdtempSync(join(tmpdir(), "odysseus-chat-deletion-")); 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, 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 }; +} + +function deletionFor(catalog: SessionCatalog, native: AgentBackend, overrides: Partial = {}) { + const retired: Array<{ principalId: string; identities: RetiredChatIdentities }> = []; + const deletion = createChatDeletion({ catalog, backends: async () => [native], busy: () => false, + retired: (principalId, retirement) => { retired.push({ principalId, identities: retirement.identities }); }, ...overrides }); + return { deletion, retired }; +} +const voyage = (principalId: string, operationId = "delete-voyage") => ({ operationId, principalId, target: { sessionId: "voyage" }, expected: { backendId: "claude", generation: 1 } }); +const RETAINED: ChatDeletionRetained[] = ["independent_content", "effects_and_audit", "provider_copies", "backups", "offline_devices"]; + +test("deletion removes every selected host copy, keeps minimized fences and leaves unrelated chats and drafts intact", async () => { + const f = await fixture(); + try { + const { db, catalog } = f.host; + expect(holding(db, MARKER).length, "MARKER_SEEDED_IN_EVERY_STORE").toBeGreaterThanOrEqual(15); + const calls: SessionHistoryRemovalRequest[] = []; + const { deletion, retired } = deletionFor(catalog, backend(["removed"], calls)); + const result = await deletion.delete(voyage(f.owner)); + expect(result).toEqual({ status: "retired", receipt: { operationId: "delete-voyage", generation: 2, status: "removed", + stores: { dialogue: "removed", drafts: "removed", native: "removed", projections: "removed", tasks: "removed" }, retained: RETAINED } }); + expect(calls, "NATIVE_REMOVED_UNDER_THE_SAME_OPERATION").toEqual([{ operationId: "delete-voyage", sessionId: "voyage" }]); + expect(retired.map(r => r.principalId), "LIVE_HOLDERS_RETIRED_ONCE").toEqual([f.owner]); + expect(holding(db, MARKER), "NO_SELECTED_COPY_REMAINS").toEqual([]); + // The unrelated chat, the unbound draft and the retired chat's accounting stay. + expect(holding(db, CONTROL).length, "CONTROL_CHAT_INTACT").toBeGreaterThanOrEqual(15); + expect(holding(db, UNBOUND), "UNBOUND_DRAFT_INTACT").toEqual(["session_drafts.text"]); + expect(db.query("SELECT total_cost_usd AS cost,num_turns AS turns,backend_id AS backend FROM sessions WHERE id='voyage'").get(), "ACCOUNTING_KEPT") + .toEqual({ cost: 1.5, turns: 3, backend: "claude" }); + // Minimized replay fences survive without their text. + expect(db.query("SELECT task_id,request_id,receipt,result_facts FROM conversation_tasks WHERE conversation_id='ithaca'").all(), "TASK_KEYS_STAY_CONSUMED") + .toEqual([{ task_id: "ithaca-task", request_id: "ithaca-request", receipt: null, result_facts: null }]); + expect(db.query("SELECT state FROM retry_receipts WHERE request_id='voyage-retry'").get()).toEqual({ state: "accepted" }); + expect(db.query("SELECT kind,id FROM chat_retired_identities ORDER BY kind,id").all()).toEqual([ + { kind: "conversation", id: "ithaca" }, { kind: "dialogue_owner", id: "ithaca" }, { kind: "native_task", id: JSON.stringify(["ithaca", 1, "ithaca-native"]) }, + { kind: "request", id: "ithaca-request" }, { kind: "session", id: "voyage" }, { kind: "task", id: "ithaca-task" }]); + // Replays refuse: an old task key, a draft save under the retired chat, and the old idempotency key. + expect(await catalog.saveConversationTask!(f.owner, task("ithaca", "voyage", MARKER), MARKER).then(() => "written", (e: Error) => e.message), "TASK_REPLAY_REFUSED") + .toBe("This chat has been retired and cannot be used again."); + const drafts = createDraftStore(db); + const refusal = (fn: () => unknown) => { try { fn(); return "stored"; } catch (e) { return e instanceof DraftError ? `${e.status} ${e.body.error}` : String(e); } }; + expect(refusal(() => drafts.save(f.owner, "voyage-draft", { ifMatch: 1, idempotencyKey: "voyage-save", sessionId: "voyage", text: MARKER, attachmentIds: [] })), "DRAFT_REPLAY_REFUSED") + .toBe("410 DRAFT_CHAT_RETIRED"); + expect(refusal(() => drafts.save(f.owner, "new-draft", { ifMatch: 0, idempotencyKey: "new", sessionId: "voyage", text: MARKER, attachmentIds: [] })), "NEW_BOUND_DRAFT_REFUSED") + .toBe("410 DRAFT_CHAT_RETIRED"); + expect(drafts.list(f.owner).drafts.map(d => d.draftId).sort(), "LISTS_ONLY_LIVE_CHATS").toEqual(["aeaea-draft", "unbound-draft"]); + expect(holding(db, MARKER), "REFUSED_REPLAYS_WROTE_NOTHING").toEqual([]); + // A repeat returns the same operation; another key for the same chat reveals nothing. + expect(await deletion.delete(voyage(f.owner)), "REPEAT_IS_THE_SAME_OPERATION").toEqual(result); + expect(calls.length, "REPEAT_DOES_NOT_REMOVE_AGAIN").toBe(1); + expect(await deletion.delete(voyage(f.owner, "another-key"))).toEqual({ status: "refused", reason: "unavailable" }); + } finally { await f.host.close(); } +}); + +test("unsupported backends, busy work and other principals refuse before anything is retired", async () => { + const f = await fixture(); + try { + const { db, catalog } = f.host; + const unsupported = { ...backend([]), capabilities }; + expect(await deletionFor(catalog, unsupported).deletion.delete(voyage(f.owner)), "UNSUPPORTED_REFUSES").toEqual({ status: "refused", reason: "unsupported" }); + const busy = deletionFor(catalog, backend([]), { busy: identities => identities.sessions.includes("voyage") }); + 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(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); + } finally { await f.host.close(); } +}); + +test("a failed store stays partial or unknown, and restart reconciliation completes it under the same operation", async () => { + const f = await fixture(); + let reopened: ReturnType | undefined; + try { + const { db, catalog } = f.host; + // The dialogue owner cannot remove its records yet: an interrupted cleanup. + db.exec("CREATE TRIGGER hold_dialogue BEFORE DELETE ON dialogue_records BEGIN SELECT RAISE(ABORT,'Ithaca dialogue cleanup interrupted'); END"); + const first = await deletionFor(catalog, backend([new Error("Scylla took the transcript")])).deletion.delete(voyage(f.owner)); + expect(first, "UNKNOWN_AND_PARTIAL_ARE_HONEST").toEqual({ status: "retired", receipt: { operationId: "delete-voyage", generation: 2, status: "unknown", + stores: { dialogue: "partial", drafts: "removed", native: "unknown", projections: "removed", tasks: "removed" }, retained: RETAINED } }); + expect(holding(db, MARKER), "ONLY_THE_FAILED_STORE_HOLDS_TEXT").toEqual(["dialogue_records.payload"]); + const second = await deletionFor(catalog, backend(["partial"])).deletion.delete(voyage(f.owner)); + expect(second.status === "retired" && second.receipt.stores.native, "NATIVE_PARTIAL_IS_NOT_COMPLETE").toBe("partial"); + expect(second.status === "retired" && second.receipt.status).toBe("partial"); + db.exec("DROP TRIGGER hold_dialogue"); + await f.host.close(); + // A new process: the fences held, and reconciliation finishes the same operation. + reopened = open(f.path); + expect(reopened.catalog.chatRetired!({ sessionId: "voyage" }), "FENCE_SURVIVES_RESTART").toBe(true); + const calls: SessionHistoryRemovalRequest[] = []; + const { deletion, retired } = deletionFor(reopened.catalog, backend(["removed"], calls)); + await deletion.reconcile(); + expect(calls, "RECONCILED_UNDER_THE_ORIGINAL_OPERATION").toEqual([{ operationId: "delete-voyage", sessionId: "voyage" }]); + expect(retired.map(r => r.principalId)).toEqual([f.owner]); + expect(await reopened.catalog.chatRetirement!("delete-voyage", f.owner)).toMatchObject({ cleanup: "removed", + stores: { dialogue: "removed", drafts: "removed", native: "removed", projections: "removed", tasks: "removed" } }); + expect(holding(reopened.db, MARKER), "RECONCILED_NOTHING_REMAINS").toEqual([]); + expect(holding(reopened.db, CONTROL).length).toBeGreaterThanOrEqual(15); + // Nothing left to do: a further reconciliation touches no backend. + await deletion.reconcile(); + expect(calls.length).toBe(1); + } 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(); }); + for (const route of routes) app.route("/api", route); + return app; +} +const post = (app: Hono, principalId: string | undefined, body: unknown) => app.request("/api/chat-deletions", { method: "POST", + headers: { "content-type": "application/json", ...(principalId ? { "x-odysseus-principal": principalId } : {}) }, body: JSON.stringify(body) }); +const requestBody = (operationId = "delete-voyage") => ({ operationId, target: { sessionId: "voyage" }, expected: { backendId: "claude", generation: 1 } }); + +test("the endpoint admits only the authenticated owner and answers with content-free categories", async () => { + const f = await fixture(); + try { + const { db, catalog } = f.host; + const { deletion } = deletionFor(catalog, backend([])); + const app = routesApp(db, createChatDeletionRoutes({ deletion, principalValid: p => { const current = resolvePrincipal(db, p.id); return !!current && isUsablePrincipal(current, Date.now()); } })); + const ambient = resolveAmbientPrincipal(db, "tailscale", "odysseus@ithaca.example", "Ithaca tailnet").id; + expect((await post(app, undefined, requestBody())).status, "UNAUTHENTICATED").toBe(401); + expect((await post(app, f.owner, { operationId: "x", target: { sessionId: "voyage", historyOwnerId: "ithaca" }, expected: { backendId: "claude", generation: 1 } })).status, "AMBIGUOUS_TARGET").toBe(400); + const refusals = []; + for (const principal of [f.agent, ambient, f.other]) { + 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 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 }); + const accepted = await post(app, f.owner, requestBody()); + const text = await accepted.text(); + expect(accepted.status).toBe(200); + expect(accepted.headers.get("cache-control")).toBe("no-store"); + expect(JSON.parse(text)).toEqual({ operationId: "delete-voyage", generation: 2, status: "removed", + stores: { dialogue: "removed", drafts: "removed", native: "removed", projections: "removed", tasks: "removed" }, retained: RETAINED }); + expect(text.includes(MARKER) || text.includes("ithaca"), "RECEIPT_CARRIES_NO_TEXT_OR_IDENTITIES").toBe(false); + // Revoked after the retirement: the operation's outcome is not disclosed. + revokePrincipal(db, f.owner, Date.now()); + expect((await post(app, f.owner, requestBody())).status, "REVOKED_CALLER_LEARNS_NOTHING").toBe(401); + } finally { await f.host.close(); } +}); + +test("a session read held across retirement publishes nothing, and lists omit the retired chat", async () => { + const f = await fixture(); + try { + const { db, catalog } = f.host; + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + let reads = 0; + const native = backend([], [], async () => { reads++; await held; return [{ role: "user", content: MARKER }] as SessionHistoryMessage[]; }); + const registry = { getBackends: async () => [native], getBackendForSession: async () => native } as unknown as BackendRegistry; + const retired = (target: { sessionId: string } | { ownerId: string }) => catalog.chatRetired!(target); + const app = routesApp(db, createSessionRoutes({ registry, db, settled: () => catalog.settled!(), retired, prepareHistory: (_, messages) => messages })); + const reading = app.request("/api/sessions/voyage", { headers: { "x-odysseus-principal": f.owner } }); + while (!reads) await Bun.sleep(1); + await deletionFor(catalog, native).deletion.delete(voyage(f.owner)); + release(); + const response = await reading; + const body = await response.text(); + expect(response.status, "HELD_READ_REFUSED_AFTER_RETIREMENT").toBe(404); + expect(body.includes(MARKER), "HELD_READ_PUBLISHES_NO_MARKER").toBe(false); + const list = await (await app.request("/api/sessions?includeRetainedConversations=true", { headers: { "x-odysseus-principal": f.owner } })).json(); + expect(list.sessions.map((s: { id: string }) => s.id), "LIST_OMITS_RETIRED").toEqual(["aeaea"]); + } finally { await f.host.close(); } +}); + +test("live startup history held across retirement never seeds a provider", async () => { + const f = await fixture(); + try { + const { catalog } = f.host; + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + let reads = 0; + const native = backend([], [], async () => { reads++; await held; return [{ role: "user", content: MARKER }] as SessionHistoryMessage[]; }); + // The host's own synchronous gate is exercised elsewhere; this one has none, so the startup gate alone must refuse. + const host = { catalog, historySettled: () => catalog.settled!(), registry: { getBackendForSession: async () => native }, + prepareHistory: (_: string, messages: SessionHistoryMessage[]) => messages } as unknown as WsHost; + const reading = readLiveHistory(host, f.owner, { sessionId: "voyage" }, () => true).then(seed => ({ seed }), (error: unknown) => ({ error })); + while (!reads) await Bun.sleep(1); + await deletionFor(catalog, native).deletion.delete(voyage(f.owner)); + release(); + const outcome = await reading; + expect("error" in outcome && outcome.error instanceof ChatRetiredError, "STARTUP_SEED_REFUSED_AFTER_RETIREMENT").toBe(true); + expect(JSON.stringify(outcome).includes(MARKER)).toBe(false); + } finally { await f.host.close(); } +}); diff --git a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts index 7a1f04d043..91f39451bc 100644 --- a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts +++ b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts @@ -81,6 +81,7 @@ export const mountLifetimes: Record = { "GET /api/sessions/:sessionId/turns/:turnId/revert/plan": { path: "/api/sessions/fixture-session/turns/unknown/revert/plan", status: 409, body: { error: "No retained eligible history is available." } }, "GET /api/sessions/:sessionId/turns/:turnId/revert": { path: "/api/sessions/fixture-session/turns/unknown/revert", status: 200, body: { receipt: null } }, "GET /api/sessions/:sessionId/turns/:turnId/revert/:operationId": { path: "/api/sessions/fixture-session/turns/unknown/revert/odysseus_unknown", status: 404, body: { error: "Original operation receipt unavailable; no effect was retried." } }, + "POST /api/chat-deletions": { init: json("POST", { operationId: "fixture-deletion", target: { sessionId: "fixture-session" }, expected: { backendId: "fixture", generation: 1 } }), + status: 404, body: { error: "CHAT_DELETION_REFUSED", reason: "unavailable" }, verify: async (r, t) => { expect(r.headers.get("cache-control")).toBe("no-store"); + expect(t.app.db.query("SELECT COUNT(*) AS n FROM chat_lifecycles").get()).toEqual({ n: 0 }); } }, "POST /api/sessions/:sessionId/turns/:turnId/revert": { path: "/api/sessions/fixture-session/turns/unknown/revert", status: 409, init: json("POST", { id: "odysseus_unknown" }), body: { error: "This turn is not available for a user history operation." } }, "GET /api/sessions/:sessionId/turns/:turnId/journal": { path: "/api/sessions/fixture-session/turns/unknown/journal", status: 404, body: { error: "No retained journal is available for this turn." } }, "GET /api/sessions/:sessionId/turns/:turnId/journal/:sequence/preview": { path: "/api/sessions/fixture-session/turns/unknown/journal/1/preview", status: 404, body: { error: "Journal detail expired or unavailable." } }, diff --git a/packages/ui-server/tests/ws-chat-deletion.test.ts b/packages/ui-server/tests/ws-chat-deletion.test.ts new file mode 100644 index 0000000000..b5bf247cc6 --- /dev/null +++ b/packages/ui-server/tests/ws-chat-deletion.test.ts @@ -0,0 +1,125 @@ +/** + * Chat deletion (#3230) through the real host, run loop, catalog and + * dispatch: busy refusal, a resume held across retirement, admission and + * recovery refusing a retired chat, and targeted `chat_retired` delivery. + * A scripted backend, synthetic Odysseus text; no model, key or network. + */ +import { afterEach, expect, test } from "bun:test"; +import { CHAT_DELETION_CAPABILITY, type ClientMessage, type ServerMessage, type SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { createUiDb } from "../src/db/client"; +import { createPrincipal, resolvePrincipal } from "../src/db/principals"; +import type { WSContext } from "../src/ws/clients"; +import { createWsHandlers } from "../src/ws/connection"; +import { handleClientMessage as dispatch } from "../src/ws/dispatch"; +import { WsHost } from "../src/ws/host"; +import { readSessionRecovery } from "../src/ws/recovery"; +import { createSessionCatalog } from "../src/ws/session-catalog"; +import { createChatDeletion } from "../src/ws/chat-deletion"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import { testAuthorization } from "./helpers/principal"; + +const MARKER = "Odysseus hid the oar under the olive root"; +const cleanups: Array<() => void> = []; +afterEach(() => { for (const cleanup of cleanups.splice(0).reverse()) cleanup(); }); + +async function until(cond: () => boolean, timeoutMs = 3000): Promise { + const start = Date.now(); + while (!cond()) { if (Date.now() - start > timeoutMs) throw new Error("until: timed out"); await Bun.sleep(2); } +} + +function world() { + const db = createUiDb(":memory:"); + const transcript: SessionHistoryMessage[] = []; + let finish: (() => void) | undefined; + let hold: Promise | undefined; + let reads = 0; + const backend = { + ...makeFakeBackend({ + id: "fixture", + capabilities: { historyRemoval: true }, + async getHistory() { reads++; await hold; return structuredClone(transcript); }, + startTurn: (req: StartTurnRequest) => new Promise(resolve => { + req.bridge.emit({ type: "session_info", sessionId: "voyage", isNew: true }); + transcript.push({ role: "user", content: req.prompt, toolCalls: [] }); + finish = () => { + transcript.push({ role: "assistant", content: `${MARKER}, answered.`, toolCalls: [] }); + req.bridge.emit({ type: "result", sessionId: "voyage", numTurns: 1, durationMs: 1, isError: false, outcome: "success" }); + resolve(); + }; + }), + }), + async removeSessionHistory() { transcript.splice(0); return { outcome: "removed" as const }; }, + }; + const catalog = createSessionCatalog(() => db); + const host = new WsHost({ registry: createStaticBackendRegistry([backend], backend.id), catalog, isPrincipalValid: () => true }); + 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; + host.chatDeletion = createChatDeletion({ catalog, backends: async () => [backend], busy: identities => host.chatBusy(identities), + retired: (principalId, retirement) => host.chatRetired(principalId, retirement) }); + const client = (principalId: string, capabilities?: Record) => { + const frames: ServerMessage[] = []; + const ws: WSContext = { send: data => frames.push(JSON.parse(data)) }; + host.clients.add(ws, principalId); + host.clients.setCapabilities(ws, capabilities); + return { ws, frames }; + }; + const main = client(owner.id, { [CHAT_DELETION_CAPABILITY]: true }); + const connection = { principal: owner, authorization: testAuthorization(owner.id) }; + cleanups.push(() => { finish?.(); host.coordinator.reset(); host.close(); db.close(); }); + return { + db, host, catalog, owner, other, main, client, connection, + send: (msg: ClientMessage) => dispatch(host, main.ws, msg, connection), + finish: () => finish!(), + holdHistory() { let release!: () => void; hold = new Promise(resolve => { release = resolve; }); reads = 0; return release; }, + reads: () => reads, + remove: (operationId: string) => host.chatDeletion!.delete({ operationId, principalId: owner.id, target: { sessionId: "voyage" }, expected: { backendId: "fixture", generation: 1 } }), + }; +} + +test("deletion refuses a running turn, then a resume held across retirement publishes nothing and the chat stays absent", async () => { + const w = world(); + const hello: ServerMessage[] = []; + await createWsHandlers(w.host, w.owner).onOpen(undefined as never, { send: (d: string) => hello.push(JSON.parse(d)), close: () => {} }); + const advertised = hello.find(frame => frame.type === "server_hello"); + expect(advertised?.type === "server_hello" && advertised.capabilities?.[CHAT_DELETION_CAPABILITY], "HELLO_ADVERTISES_CHAT_DELETION").toBe(true); + + await w.send({ type: "chat_message", text: `Plan the voyage home. ${MARKER}`, attachments: [] } as ClientMessage); + await until(() => w.host.coordinator.bySession.has("voyage")); + // The chat's recorded owner: a voice conversation bound to it. + await w.catalog.dialogueOpen!({ conversationId: "ithaca", principalId: w.owner.id, epoch: 1, providerId: "gemini-live", sessionId: "voyage" }); + expect(await w.remove("busy-attempt"), "RUNNING_TURN_REFUSES").toEqual({ status: "refused", reason: "busy" }); + w.finish(); + await until(() => !w.host.coordinator.isTurnActive()); + await w.host.failureReplay.wait("voyage"); + + const peer = w.client(w.owner.id, { [CHAT_DELETION_CAPABILITY]: true }); + const oldClient = w.client(w.owner.id); + const stranger = w.client(w.other, { [CHAT_DELETION_CAPABILITY]: true }); + const release = w.holdHistory(); + const from = w.main.frames.length; + const resume = w.send({ type: "session_resume", sessionId: "voyage" }); + await until(() => w.reads() > 0); + const deleted = await w.remove("delete-voyage"); + expect(deleted.status === "retired" && deleted.receipt.status, "DELETION_COMPLETES").toBe("removed"); + release(); + await resume; + const resumed = w.main.frames.slice(from); + expect(resumed.some(frame => frame.type === "session_history"), "HELD_RESUME_PUBLISHES_NO_HISTORY").toBe(false); + expect(JSON.stringify(resumed).includes(MARKER)).toBe(false); + expect(resumed.find(frame => frame.type === "error"), "HELD_RESUME_REPORTS_ABSENT").toMatchObject({ code: "SESSION_NOT_FOUND", sessionId: "voyage" }); + + // Targeted invalidation: the owner's declaring connections only. + const notice: ServerMessage = { type: "chat_retired", sessionId: "voyage", historyOwnerIds: ["ithaca"], generation: 2 }; + expect(peer.frames.filter(frame => frame.type === "chat_retired"), "OWNER_PEER_INVALIDATED").toEqual([notice]); + expect(oldClient.frames.some(frame => frame.type === "chat_retired"), "UNDECLARED_CLIENT_NOT_SENT").toBe(false); + expect(stranger.frames.some(frame => frame.type === "chat_retired"), "OTHER_PRINCIPAL_NOT_SENT").toBe(false); + + // An old client that never learned of it is refused server-side. + const later = w.main.frames.length; + await w.send({ type: "session_resume", sessionId: "voyage" }); + expect(w.main.frames.slice(later), "RESUME_AFTER_DELETION_REFUSED").toEqual([expect.objectContaining({ type: "error", code: "SESSION_NOT_FOUND", sessionId: "voyage" })]); + expect(await readSessionRecovery(w.host, "voyage", w.owner), "RECOVERY_REPORTS_ABSENT").toEqual({ kind: "not_found" }); + expect(() => w.host.prepareHistory("voyage", [{ role: "user", content: MARKER, toolCalls: [] }]), "PREPARE_HISTORY_FINAL_GATE").toThrow("This chat has been retired"); +}); From f05710d7d19b4a77c6fbad1a69461ad284f5f0e1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 18:46:06 +0000 Subject: [PATCH 2/3] test(ui-sdk): cover chat_retired in the frame inventory and count the deletion route The schema inventory requires a sample for every ServerMessage member, and the HTTP specification's prose counts must equal the mounted routes (#3230). Refs #3230 Co-Authored-By: Claude Opus 5.5 --- docs/http-api.md | 4 ++-- packages/ui-sdk/tests/server-schemas.test.ts | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/http-api.md b/docs/http-api.md index 320aee6ead..9446e20dfb 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, session-recovery interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant and retained-journal/user-revert routes mounted by `createApp`: 159 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, session-recovery interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, retained-journal/user-revert and chat-deletion routes mounted by `createApp`: 160 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -193,7 +193,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 159 declared endpoints are mounted regardless of backend, renderer or +All 160 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. diff --git a/packages/ui-sdk/tests/server-schemas.test.ts b/packages/ui-sdk/tests/server-schemas.test.ts index 893c4223d9..2a35c9ea63 100644 --- a/packages/ui-sdk/tests/server-schemas.test.ts +++ b/packages/ui-sdk/tests/server-schemas.test.ts @@ -127,6 +127,7 @@ const SAMPLES: ServerMessage[] = [ { type: "handoff_draft", handoffId: "h-ithaca-01-p1", state: "ready", text: "Odysseus is sailing home.", runId: "r1", costUsd: 0.03 }, { type: "handoff_receipt", handoffId: "h-ithaca-01", state: "created", sessionId: "s2" }, { type: "tool_resolution", toolUseId: "t1", outcome: "expired", sessionId: "s1", turnId: "turn-1", reason: "Turn timed out" }, + { type: "chat_retired", sessionId: "s1", historyOwnerIds: ["ithaca"], generation: 2 }, { type: "session_queue", sessionId: "s1", From eb2b4de1537cbd037330001e3278534b1064d641 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 18:48:33 +0000 Subject: [PATCH 3/3] test(ci): re-pin the audited connection frame handlers after adding chat_retired Re-audited `connectionFrameHandlers` (#3230): the only change is the `chat_retired` union member and a no-op arrow handler that reads no runtime input, so the registry keeps its private, finite, single-call-site shape. Refs #3230 Co-Authored-By: Claude Opus 5.5 --- scripts/source-browser-dispatch.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/source-browser-dispatch.ts b/scripts/source-browser-dispatch.ts index 7676d58494..22b525565f 100644 --- a/scripts/source-browser-dispatch.ts +++ b/scripts/source-browser-dispatch.ts @@ -42,7 +42,7 @@ const declarations=[ { "owner": "packages/ui-react/src/hooks/websocket-handlers/connection.ts", "name": "connectionFrameHandlers", - "source": "6f326e9a67bafbda3f3939be28515aff5324d3cbe5e4a41949616a0fc73b202c" + "source": "b20f60edcd8c3438d3ecc38952d7b5a7850adf4549c2eb6495a79b22596cad1e" }, { "owner": "packages/ui-react/src/hooks/websocket-handlers/handoff.ts",