From 3cbdf5a3e93e32f272ef19e9d371f57ded957240 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 10:30:57 +0000 Subject: [PATCH 1/2] CONTRACT: feat(ui-server): bind typed chats to their creating owner so the owner can delete them When an authenticated typed request creates a backend session, the bridge offers its principal and the write worker records a content-free (session, principal) binding in the transaction that creates the session row (migration 075_chat_session_owners.sql). resolveChat counts it beside dialogue owners and voice epochs, so the owner can delete a new typed-only chat through POST /api/chat-deletions. Chats whose session existed before the binding, and native-only sessions first seen on a resume, still refuse as unavailable. Foreign callers get the same refusal as for a chat that does not exist. Disagreeing ownership records stay ambiguous. The binding is not a dialogue owner: no generation, alias or record, and no paging, list or retention read joins it. The deletion design records the difference. Additive: SessionCatalog.persistSessionStub takes an optional ownerPrincipalId; no request, receipt or frame shape changes. Refs #3337 Co-Authored-By: Claude Opus 5.5 --- .changeset/typed-chat-owner-bindings.md | 4 + api-report/ui-server.txt | 2 +- docs/decisions/async-collaboration.md | 2 +- docs/decisions/governed-writable-workers.md | 4 +- docs/decisions/session-handoff.md | 2 +- docs/decisions/voice-permission.md | 6 +- docs/http-api.md | 7 +- docs/integration-contract.md | 12 ++ docs/integration-contract/package-api.md | 12 ++ .../plans/async-collaboration-requirements.md | 4 +- docs/plans/async-collaboration.md | 4 +- docs/plans/chat-history-deletion.md | 42 ++++- docs/plans/navigation-recovery.md | 2 +- .../migrations/075_chat_session_owners.sql | 13 ++ packages/ui-server/src/ws/bridge.ts | 6 +- packages/ui-server/src/ws/chat-lifecycle.ts | 9 +- .../src/ws/session-catalog-writes.ts | 14 +- packages/ui-server/src/ws/session-catalog.ts | 17 +- .../tests/chat-session-owner.test.ts | 154 ++++++++++++++++++ 19 files changed, 289 insertions(+), 27 deletions(-) create mode 100644 .changeset/typed-chat-owner-bindings.md create mode 100644 packages/ui-server/migrations/075_chat_session_owners.sql create mode 100644 packages/ui-server/tests/chat-session-owner.test.ts diff --git a/.changeset/typed-chat-owner-bindings.md b/.changeset/typed-chat-owner-bindings.md new file mode 100644 index 0000000000..0449129f16 --- /dev/null +++ b/.changeset/typed-chat-owner-bindings.md @@ -0,0 +1,4 @@ +--- +"@schlessera/brain-ui-server": minor +--- +Typed chats can now be deleted by their owner. When an authenticated typed request creates a backend session, the host records a content-free owner binding, so `POST /api/chat-deletions` accepts that chat from its owner. Chats created before this change still refuse as `unavailable`, and other principals get the same answer as for a chat that does not exist. The session catalog's `persistSessionStub` takes an optional `ownerPrincipalId`. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index e61ecc0470..f88a958ff8 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1860,7 +1860,7 @@ signatures (every public export and the types it is made of) retryReceipt?(sessionId: string, requestId: string, principalId: string): ServerRetryReceipt; attachRetryRequest?(sessionId: string, messages: SessionHistoryMessage[]): SessionHistoryMessage[]; getStoredBackendId(sessionId: string): string | null; - persistSessionStub(sessionId: string, promptText: string, providerId: string | null, backendId: string): void; + persistSessionStub(sessionId: string, promptText: string, providerId: string | null, backendId: string, ownerPrincipalId?: string): void; persistSession(msg: ServerResultMessage, promptText: string, providerId: string | null, backendId: string): void; recordMessageSource?(sessionId: string, text: string, source: MessageSource, effort?: { thinkingLevel?: ThinkingLevel; diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index d6b60a7a30..b0e862fc64 100644 --- a/docs/decisions/async-collaboration.md +++ b/docs/decisions/async-collaboration.md @@ -204,7 +204,7 @@ permission and unwinds the turn. Already completed side effects are not undone by an abort. Attempt staging and cleanup therefore need idempotent recovery, with filesystem compensation outside SQLite transactions. Ordinary permission parking still exists (`requestPermission: (req) => {`, -`packages/ui-server/src/ws/bridge.ts:362-455`); it is not a durable Action store. +`packages/ui-server/src/ws/bridge.ts:366-459`); it is not a durable Action store. Resolution validates the stored effect again, checks current authority, records one resolution and applies the guarded state transition in one transaction. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index e20d344f75..b5e546dfa7 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -176,7 +176,7 @@ still holds. **Voice.** Ruling 1 makes voice `governed` too. Voice keeps its narrower membership (`VOICE_ALLOWED_TOOLS`, `packages/ui-backend-claude/src/tool-policy.ts:120`): no Bash, no raw `Write`/`Edit`, no archive, and approval returns false -(`const apply = createBrainApplication`, `packages/ui-server/src/ws/bridge.ts:666-671`). +(`const apply = createBrainApplication`, `packages/ui-server/src/ws/bridge.ts:670-675`). A voice turn therefore writes only through curated capture and update, now with a journal behind it. The writable mount gives voice no tool it lacked. Pi still refuses voice turns. @@ -1901,7 +1901,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:492`) + (`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:499`) must not feed any budget. **Enforcement:** diff --git a/docs/decisions/session-handoff.md b/docs/decisions/session-handoff.md index 43a0433eda..b2b1220306 100644 --- a/docs/decisions/session-handoff.md +++ b/docs/decisions/session-handoff.md @@ -160,7 +160,7 @@ its distinct retry treatment. Nothing archives, purges or automatically sends. The notice's presentation and actions are (`StateRoomNotice`, `packages/ui-react/src/components/chat/state-room-notice.tsx:22-100`); the host keeps the measurement and first quiet event (`if (msg.type === "result") {`, -`packages/ui-server/src/ws/bridge.ts:282-292`). +`packages/ui-server/src/ws/bridge.ts:286-296`). ### Historical state directories remain untouched diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 98f58d7964..b8288acb03 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -436,7 +436,7 @@ 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:450-456`, and the lookup computing -`remembered`, `ws/bridge.ts:372-392`), and 192 of 192 measured +`remembered`, `ws/bridge.ts:376-396`), and 192 of 192 measured approvals were kind `command`. ### When the announcement actually fires @@ -493,7 +493,7 @@ the request kind, and it patches the span (`onApprovalDecision`, `packages/ui-server/src/activity/recorder.ts:684-699`), fed from the bridge's `recorded()` wrapper -(`const recorded`, `packages/ui-server/src/ws/bridge.ts:414-429`). +(`const recorded`, `packages/ui-server/src/ws/bridge.ts:418-433`). One thing is missing and is a follow-up: **the event does not record the modality.** A denial decided by a phrase a microphone heard and one decided by a @@ -638,7 +638,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. purpose, so a grant that exists and is deliberately not applied can be logged — but refuses to answer from it or add to it for a tool the enforced allowlist left out (the lookup computing `remembered`, - `packages/ui-server/src/ws/bridge.ts:372-392`, + `packages/ui-server/src/ws/bridge.ts:376-396`, and the block computing `remembers`, `packages/ui-server/src/ws/dispatch.ts:450-456`). The evaluation happens diff --git a/docs/http-api.md b/docs/http-api.md index ecc9eb61b8..e077c2dd6e 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -1057,7 +1057,12 @@ 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 +first). A chat's recorded owner is its dialogue owner, its voice conversation's +principal or, since #3337 (additive), the authenticated principal whose typed +request created its backend session. A typed chat whose session already existed +before that binding (or that the host first saw on a resume) has no recorded +owner and stays `unavailable`; none is backfilled. Otherwise the chat is +retired and the answer is 200 with the SDK's `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 diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 6ab59be06a..de8f97ab0e 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -36,6 +36,18 @@ 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. +## Typed chat owner bindings (additive, #3337) + +A typed chat whose backend session an authenticated request created now records +that principal as its owner, so `POST /api/chat-deletions` accepts it from that +owner ([HTTP](http-api.md#explicit-chat-deletion-additive-3230)). Chats created +before the binding still refuse as `unavailable`. Foreign callers get the same +answer as for a chat that does not exist. The session catalog's +`persistSessionStub` gains an optional `ownerPrincipalId` +([package API](integration-contract/package-api.md#typed-chat-owner-bindings-additive-3337)). +No request, receipt, frame or field shape changes, and paging and retention of +undeleted chats are unchanged. This ships in a minor. + ## 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 b3fc1c3de3..28955ddac5 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -149,6 +149,18 @@ gains optional `chatDeletion` and the session catalog optional `cleanChatStore` [HTTP](../http-api.md#explicit-chat-deletion-additive-3230) and [wire](wire.md#explicit-chat-deletion-additive-3230) components. + + +## Typed chat owner bindings (additive, #3337) + +In `@schlessera/brain-ui-server`, the session catalog's `persistSessionStub` +takes an optional fifth argument, `ownerPrincipalId`. The bridge passes it only +when an authenticated typed request created the session. The catalog records it +as the chat's content-free owner binding only if that call creates the +session's row. A custom catalog that ignores the argument keeps today's +behaviour, so typed-only chats stay undeletable. Semantics are in the +[HTTP](../http-api.md#explicit-chat-deletion-additive-3230) component. + ## Native history removal (additive, #3229) `BackendCapabilities` adds optional `historyRemoval?: boolean`, and diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 9e5b2ca448..4b4546bc51 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -43,7 +43,7 @@ session. Three consequences: 1. **Background work cannot ask.** Cron runs (`sync`, `validate`, `maintain`, module jobs) have no human attached. `bridge.requestPermission` parks a promise that nobody will - resolve (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:362-456`), so autonomous work is confined to + resolve (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:366-460`), so autonomous work is confined to whatever is pre-approved, and anything requiring judgment is not attempted. 2. **Inbound material has no path.** A forwarded email, a shared link, a captured note has nowhere to land that the agent will act on later. The PWA share target stages into @@ -263,7 +263,7 @@ Stated before the requirements because five of them derive from it. threshold (~20s of the 30s lock budget). Below it nothing yields; above it the holder checkpoints/unwinds/releases. Test both edges and independent paths. - R26. **Abort-and-redo needs a checkpoint primitive.** `requestPermission` parks a bare - promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge.ts:406-464`) — while blocked on it the model cannot write anything, so + promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge.ts:410-468`) — while blocked on it the model cannot write anything, so "writes its findings, then aborts" has nowhere to run. The autonomous bridge must, in one server-side step: capture the checkpoint, create the Action and block the item, unwind without a live approval promise, preserving the tested timeout path's abort-then-drain order (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:396-402`). Aborting does **not** undo completed tool side diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 8c01113cc0..e3ca33b4dd 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -28,7 +28,7 @@ than last. ## Problem Frame Collaboration is synchronous-only: background work cannot ask (`requestPermission` parks a -promise nobody resolves — (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:362-456`)), inbound material +promise nobody resolves — (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:366-460`)), inbound material has no path that survives until the user is present, and no decision accumulates into standing authority. See origin for the full frame. @@ -134,7 +134,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. - **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 +- **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:366-460`). Timeout unwind is (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:396-402`). Durable escalation must checkpoint before unwinding; the existing ordinary bridge does not do that. - **Tool enforcement:** (`const enforcementHook: HookCallback`, `packages/ui-backend-claude/src/permission-hooks.ts:200-229`) closes measured bypasses. diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index d28d886b2c..49e8c51f24 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:156-189`; +(`retireChat`, `packages/ui-server/src/ws/chat-lifecycle.ts:161-194`; 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 @@ -16,7 +16,8 @@ targets before retiring, and makes later dialogue/task writers and readers refuse the retired identities. It removes no content and reports every store pending until that store's owner confirms removal. A typed native-only chat with no recorded owner refuses as unknown ownership; no ownership is backfilled. -Host-copy cleanup, the endpoint and UI are not built. +Host-copy cleanup, the endpoint and UI are not built. (#3337, below, records an +owner for typed chats created after it.) **Built (#3229):** first-party native removal behind the optional `historyRemoval` backend capability @@ -49,6 +50,39 @@ 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. +**Built (#3337):** typed chats created from now on name their owner. Under the +[2026-11-02 ruling](https://github.com/schlessera/brain-kit/issues/3337#issuecomment-6586465475), +when an authenticated typed request creates a backend session, the host records a +content-free `(session, principal)` binding (migration `075_chat_session_owners.sql`). +The bridge offers the creator only on a new, non-host-work turn whose +authorization is current +(`const creator`, `packages/ui-server/src/ws/bridge.ts:245`). The write worker +binds the creator only in the transaction that creates the session's row +(`upsertSession(row: SessionRow)`, `packages/ui-server/src/ws/session-catalog-writes.ts:167-176`). +`resolveChat` counts the binding as one more ownership record beside dialogue +owners and voice epochs, so a disagreement among them still refuses as ambiguous +(`const creator`, `packages/ui-server/src/ws/chat-lifecycle.ts:91-92`). A typed +chat's owner can now delete it through `POST /api/chat-deletions`. A chat whose +session existed before the binding still refuses as `unavailable`, and so does a +native-only session the host first sees on a resume. A foreign principal gets +the same refusal as for a chat that does not exist. + +The binding is deliberately not a dialogue owner: + +- It has no generation, alias, conversation or record. It never opens or pages + dialogue, and no catalog read, list or retention pass joins it. A typed chat + is therefore reviewed at generation 1, as before, and undeleted chats page and + age exactly as they did. +- It is written once, by session creation, and never by a resume, an adoption, a + later turn or host work. It is never reassigned or backfilled. A dialogue owner + instead begins with a live conversation or the adoption of a host-only history, + and it binds or merges into a session later. +- It names the creating principal, not authority. Deletion still re-reads that + principal at commit: an agent, an ambient caller with no owner mapping, or a + revoked principal is refused as before, even if it created the session. +- Like the retirement fences, it is content-free identity data and stays after the + chat's stores are cleaned. + ## Selected local lifecycle Use a concrete ui-server lifecycle owner in the existing operational @@ -220,8 +254,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:248-261`; - `activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:290-293`). + (`rowEffects`, `packages/ui-server/src/ws/session-catalog.ts:254-267`; + `activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:297-300`). Both submission and worker commit need a generation check. - **Browser state.** Chat buffers/history chunks, shared timeline, session title/list cache, dialogue pages/cursors, recognition/generated/unsaved tails, diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 52dca629c1..6725cc3d55 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -387,7 +387,7 @@ implementation. Any PR moving these lines owns their citation repairs. - Host resume: (`case "session_resume": {`, `packages/ui-server/src/ws/dispatch.ts:649-720`). -- Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId) {`, `packages/ui-server/src/ws/session-catalog.ts:486-493`). +- Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId, ownerPrincipalId) {`, `packages/ui-server/src/ws/session-catalog.ts:493-500`). - Session summary shape: (`export interface ChatSession {`, `packages/ui-sdk/src/protocol.ts:1580-1596`). diff --git a/packages/ui-server/migrations/075_chat_session_owners.sql b/packages/ui-server/migrations/075_chat_session_owners.sql new file mode 100644 index 0000000000..0af14eb44c --- /dev/null +++ b/packages/ui-server/migrations/075_chat_session_owners.sql @@ -0,0 +1,13 @@ +-- Typed chat owner bindings (#3337). When an authenticated typed request +-- creates a backend session, the host records which principal created it, so +-- explicit deletion can name that chat's owner. Content-free by construction: +-- no prompt, title, label, transcript or free-form text. Written only when the +-- session row is first created; never backfilled for chats that already +-- existed, which keep refusing deletion as unknown ownership. Nothing here +-- references a content table, and no paging, retention or catalog read joins +-- it: it is consulted only when a chat is resolved for retirement. +CREATE TABLE chat_session_owners ( + session_id TEXT PRIMARY KEY, + principal_id TEXT NOT NULL, + created_at INTEGER NOT NULL +); diff --git a/packages/ui-server/src/ws/bridge.ts b/packages/ui-server/src/ws/bridge.ts index 10f2001702..0d6a30ff0d 100644 --- a/packages/ui-server/src/ws/bridge.ts +++ b/packages/ui-server/src/ws/bridge.ts @@ -239,7 +239,11 @@ export async function makeBridge( coordinator.bySession.set(msg.sessionId, turn); // Persist ownership the moment the identity exists — a turn that // later fails or is cancelled must not leave an unowned transcript. - catalog.persistSessionStub(msg.sessionId, promptText, turn.providerId, backendId); + // An authenticated typed request that created this session also binds + // its owner, content-free, so the owner can delete it (#3337). Resumes + // and host work bind nothing; the write binds only a new row. + const creator = !resumedSession && work === undefined && turn.turnId === turnId && authorization.valid && host.isPrincipalAuthorized(principalId) ? principalId : undefined; + catalog.persistSessionStub(msg.sessionId, promptText, turn.providerId, backendId, creator); // Governance events recorded before the row existed join it now (#1651). catalog.bindGovernanceEvents?.(turnId, msg.sessionId); // Submitted after the catalog row; every share read/effect joins this queue. diff --git a/packages/ui-server/src/ws/chat-lifecycle.ts b/packages/ui-server/src/ws/chat-lifecycle.ts index 0ef957f564..d4e61d2a07 100644 --- a/packages/ui-server/src/ws/chat-lifecycle.ts +++ b/packages/ui-server/src/ws/chat-lifecycle.ts @@ -71,8 +71,9 @@ interface Resolved { /** * The exact current identity set of a chat, from verified ownership records * only: canonical dialogue owners (with every alias an earlier adoption - * joined) and recorded voice conversation epochs. A chat with no such record, - * or with records naming different principals, has unknown ownership. + * joined), recorded voice conversation epochs and the typed session-creation + * binding (#3337). A chat with no such record, or with records naming + * different principals, has unknown ownership. */ export function resolveChat(db: Database, target: ChatTarget): Resolved | { refused: "unavailable" | "stale" } { const owners = new Set(), conversations = new Set(), principals = new Set(); @@ -85,6 +86,10 @@ export function resolveChat(db: Database, target: ChatTarget): Resolved | { refu for (const row of db.query("SELECT id,principal_id FROM conversation_epochs WHERE session_id=?").all(sessionId) as { id: string; principal_id: string }[]) { conversations.add(row.id); principals.add(row.principal_id); } + // The principal whose typed request created the session (#3337). It joins + // the other records: a disagreement is still ambiguous ownership. + const creator = db.query("SELECT principal_id FROM chat_session_owners WHERE session_id=?").get(sessionId) as { principal_id: string } | null; + if (creator) principals.add(creator.principal_id); } else { if (!target.ownerId || target.ownerId.length > MAX_ID) return { refused: "unavailable" }; const owner = db.query("SELECT id,principal_id,session_id,generation FROM dialogue_owners WHERE id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=?),?)") diff --git a/packages/ui-server/src/ws/session-catalog-writes.ts b/packages/ui-server/src/ws/session-catalog-writes.ts index acb5d1987c..7cce2c13b5 100644 --- a/packages/ui-server/src/ws/session-catalog-writes.ts +++ b/packages/ui-server/src/ws/session-catalog-writes.ts @@ -43,6 +43,12 @@ export const UPSERT_SESSION_SQL = `INSERT INTO sessions (id, title, created_at, /** One `sessions` upsert, with its clock taken where it was submitted. */ export interface SessionRow { id: string; title: string; at: number; costUsd: number; turns: number; providerId: string | null; backendId: string | null; + /** + * The authenticated principal whose typed request created this session + * (#3337). Bound only if this upsert creates the row; an existing session + * (a legacy chat, a resume) never gains or changes an owner here. + */ + ownerPrincipalId?: string | null; } export interface ClaudeUsageContext { billingMode?: BillingMode; pricingRoute?: PricingRoute; principalId?: string } @@ -160,7 +166,13 @@ export function setup(db: Database, options: SessionCatalogWriteOptions = {}): W }, upsertSession(row: SessionRow) { live(row.id); - db.prepare(UPSERT_SESSION_SQL).run(row.id, row.title, row.at, row.at, row.costUsd, row.turns, row.providerId, row.backendId); + const owner = row.ownerPrincipalId; + if (!owner) { db.prepare(UPSERT_SESSION_SQL).run(row.id, row.title, row.at, row.at, row.costUsd, row.turns, row.providerId, row.backendId); return; } + db.transaction(() => { + const created = !db.query("SELECT 1 FROM sessions WHERE id=?").get(row.id); + db.prepare(UPSERT_SESSION_SQL).run(row.id, row.title, row.at, row.at, row.costUsd, row.turns, row.providerId, row.backendId); + if (created) db.prepare("INSERT OR IGNORE INTO chat_session_owners(session_id,principal_id,created_at) VALUES(?,?,?)").run(row.id, owner, row.at); + })(); }, claudeUsage(sessionId: string, backendId: string, turnId: string, evidence: ClaudeUsageEvidence, resumed: boolean, context?: ClaudeUsageContext) { const { store, pricing } = account(); diff --git a/packages/ui-server/src/ws/session-catalog.ts b/packages/ui-server/src/ws/session-catalog.ts index 5c320f38a0..848cb12a01 100644 --- a/packages/ui-server/src/ws/session-catalog.ts +++ b/packages/ui-server/src/ws/session-catalog.ts @@ -129,7 +129,13 @@ export interface SessionCatalog { sessionId: string, promptText: string, providerId: string | null, - backendId: string + backendId: string, + /** + * The authenticated principal whose typed request created the session + * (#3337). Recorded as its content-free owner binding only when this call + * creates the session's row; omitted for resumes and host work. + */ + ownerPrincipalId?: string ): void; /** Persist session accounting on the terminal `result` frame. */ persistSession( @@ -274,8 +280,9 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi const pendingRow = (sessionId: string) => (rowEffects.get(sessionId) ?? []).some(effect => "upsert" in effect); const storedBackendId = (sessionId: string) => pendingValue(sessionId, "backendId") ?? committedRow(sessionId)?.backendId ?? null; const hasRow = (sessionId: string) => pendingRow(sessionId) || db().query("SELECT 1 FROM sessions WHERE id = ?").get(sessionId) !== null; - const upsert = (sessionId: string, promptText: string, providerId: string | null, backendId: string, costUsd: number, turns: number) => { - const row: writes.SessionRow = { id: sessionId, title: promptText.slice(0, 100), at: Date.now(), costUsd, turns, providerId, backendId }; + const upsert = (sessionId: string, promptText: string, providerId: string | null, backendId: string, costUsd: number, turns: number, ownerPrincipalId?: string) => { + const row: writes.SessionRow = { id: sessionId, title: promptText.slice(0, 100), at: Date.now(), costUsd, turns, providerId, backendId, + ...(ownerPrincipalId ? { ownerPrincipalId } : {}) }; return track(rowEffects, sessionId, { upsert: { providerId, backendId } }, submit("upsertSession", row)); }; /** Highest revision issued per session; it never goes down, so a failed acceptance's revision is never reused. */ @@ -483,8 +490,8 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi getStoredBackendId: storedBackendId, - persistSessionStub(sessionId, promptText, providerId, backendId) { - upsert(sessionId, promptText, providerId, backendId, 0, 0).catch(err => reportWriteFailure(sessionId, err)); + persistSessionStub(sessionId, promptText, providerId, backendId, ownerPrincipalId) { + upsert(sessionId, promptText, providerId, backendId, 0, 0, ownerPrincipalId).catch(err => reportWriteFailure(sessionId, err)); }, persistSession(msg, promptText, providerId, backendId) { diff --git a/packages/ui-server/tests/chat-session-owner.test.ts b/packages/ui-server/tests/chat-session-owner.test.ts new file mode 100644 index 0000000000..f0a0b2b436 --- /dev/null +++ b/packages/ui-server/tests/chat-session-owner.test.ts @@ -0,0 +1,154 @@ +/** + * Typed chat owner bindings (#3337) through the real host, run loop, bridge, + * dispatch and file-backed SQLite write worker, then `POST /api/chat-deletions`. + * A typed request that creates a session binds its authenticated owner, so + * that owner can delete it; a chat whose session existed before the binding + * still refuses as unknown ownership, a resume binds nothing, and other + * principals learn nothing about whether the chat exists. A scripted backend + * and synthetic Odysseus text only: no model, key or network. + */ +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 { ClientMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import type { AppEnv } from "../src/app-env.js"; +import { createStaticBackendRegistry } from "../src/agent/backend.js"; +import { createUiDb } from "../src/db/client.js"; +import { createPrincipal, isUsablePrincipal, resolvePrincipal } from "../src/db/principals.js"; +import { openSqliteWriter } from "../src/db/write-worker.js"; +import { createOffloopActivityStore } from "../src/activity/store-writes.js"; +import type { WSContext } from "../src/ws/clients.js"; +import { handleClientMessage as dispatch } from "../src/ws/dispatch.js"; +import { WsHost } from "../src/ws/host.js"; +import { createSessionCatalog } from "../src/ws/session-catalog.js"; +import { createChatDeletion } from "../src/ws/chat-deletion.js"; +import { createChatDeletionRoutes } from "../src/routes/chat-deletions.js"; +import { makeFakeBackend } from "./helpers/fake-backend.js"; +import { testAuthorization } from "./helpers/principal.js"; + +const MARKER = "Odysseus hid the oar under the olive root"; +const cleanups: Array<() => Promise | void> = []; +afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await 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 root = mkdtempSync(join(tmpdir(), "odysseus-chat-owner-")); + const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db); + const catalog = createSessionCatalog(() => db, undefined, undefined, { writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(db, writer) }); + // Each new typed request opens the next named session; a resume keeps its own. + const fresh = ["voyage", "scylla"]; + let finished = 0; + const backend = { + ...makeFakeBackend({ + id: "fixture", + capabilities: { historyRemoval: true }, + startTurn: async (req: StartTurnRequest) => { + const sessionId = req.sessionId ?? fresh.shift()!; + req.bridge.emit({ type: "session_info", sessionId, isNew: !req.sessionId }); + req.bridge.emit({ type: "result", sessionId, numTurns: 1, durationMs: 1, isError: false, outcome: "success" }); + finished++; + }, + }), + async removeSessionHistory() { return { outcome: "removed" as const }; }, + }; + const host = new WsHost({ registry: createStaticBackendRegistry([backend], backend.id), catalog, isPrincipalValid: () => true, + isPrincipalAuthorized: id => { const current = resolvePrincipal(db, id); return !!current && isUsablePrincipal(current, Date.now()); } }); + const owner = resolvePrincipal(db, createPrincipal(db, { authMethod: "password", label: "Odysseus phone", ttlSeconds: 86_400 }).id)!; + const other = createPrincipal(db, { authMethod: "passkey", label: "Penelope tablet", ttlSeconds: 86_400 }).id; + const agent = createPrincipal(db, { authMethod: "delegated", label: "Mentor agent", createdBy: owner.id, ttlSeconds: 86_400 }).id; + host.chatDeletion = createChatDeletion({ catalog, backends: async () => [backend], busy: identities => host.chatBusy(identities), + retired: (principalId, retirement) => host.chatRetired(principalId, retirement) }); + const ws: WSContext = { send: () => {} }; + host.clients.add(ws, owner.id); + const connection = { principal: owner, authorization: testAuthorization(owner.id) }; + 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(); }); + app.route("/api", createChatDeletionRoutes({ deletion: host.chatDeletion, principalValid: p => { const current = resolvePrincipal(db, p.id); return !!current && isUsablePrincipal(current, Date.now()); } })); + cleanups.push(async () => { host.coordinator.reset(); host.close(); await catalog.settled!(); await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); }); + return { + db, catalog, owner, other, agent, + /** One typed request, through dispatch and the run loop, settled on the writer. */ + async type(text: string, sessionId?: string) { + const before = finished; + await dispatch(host, ws, { type: "chat_message", text, attachments: [], ...(sessionId ? { sessionId } : {}) } as ClientMessage, connection); + await until(() => finished > before && !host.coordinator.isTurnActive() && host.coordinator.bySession.size === 0); + await catalog.settled!(); + }, + remove: (principalId: string, sessionId: string, operationId = `delete-${sessionId}-${principalId}`) => app.request("/api/chat-deletions", { + method: "POST", headers: { "content-type": "application/json", "x-odysseus-principal": principalId }, + body: JSON.stringify({ operationId, target: { sessionId }, expected: { backendId: "fixture", generation: 1 } }) }), + }; +} +const bindings = (db: Database) => db.query("SELECT session_id AS sessionId, principal_id AS principalId FROM chat_session_owners ORDER BY session_id").all(); + +test("a typed chat created now is deletable by its owner; one created before the binding still refuses as unavailable", async () => { + const w = world(); + // A chat a host recorded before #3337: the same row, with no binding. + w.db.prepare("INSERT INTO sessions (id, title, created_at, last_active_at, total_cost_usd, num_turns, provider_id, backend_id) VALUES (?,?,?,?,0,1,NULL,?)") + .run("aeaea", "Ask Circe the way", 1, 1, "fixture"); + + await w.type(`Plan the voyage home. ${MARKER}`); + // Resuming a legacy chat by typing is not creating it: no owner is guessed, + // whether the host recorded its row before (aeaea) or only the backend + // holds it (ogygia, a native-only session the host first sees on resume). + await w.type("Ask Circe again", "aeaea"); + await w.type("Ask Calypso for a raft", "ogygia"); + // Nor does a creator offered for an existing row bind it. + w.catalog.persistSessionStub("aeaea", "Ask Circe the way", null, "fixture", w.owner.id); + await w.catalog.settled!(); + // A follow-up on the new chat keeps its single, unchanged owner. + await w.type("And past the Sirens?", "voyage"); + expect(bindings(w.db), "ONLY_CREATED_SESSIONS_BIND").toEqual([{ sessionId: "voyage", principalId: w.owner.id }]); + // The binding is content-free and adds no dialogue owner: paging and retention are untouched. + expect(JSON.stringify(w.db.query("SELECT * FROM chat_session_owners").all()).includes("voyage home"), "BINDING_IS_CONTENT_FREE").toBe(false); + expect(w.db.query("SELECT COUNT(*) AS n FROM dialogue_owners").get(), "NO_DIALOGUE_OWNER_CREATED").toEqual({ n: 0 }); + expect(await w.catalog.dialogueRead!(w.owner.id, { sessionId: "voyage" }), "DIALOGUE_PAGING_UNCHANGED").toEqual(await w.catalog.dialogueRead!(w.owner.id, { sessionId: "aeaea" })); + + for (const sessionId of ["aeaea", "ogygia"]) { + const legacy = await w.remove(w.owner.id, sessionId); + expect(legacy.status, "LEGACY_TYPED_CHAT_UNAVAILABLE").toBe(404); + expect(await legacy.json()).toMatchObject({ error: "CHAT_DELETION_REFUSED", reason: "unavailable" }); + } + + const deleted = await w.remove(w.owner.id, "voyage"); + expect(deleted.status, "NEW_TYPED_CHAT_DELETABLE_BY_OWNER").toBe(200); + expect(await deleted.json()).toMatchObject({ generation: 2, status: "removed", stores: { native: "removed", dialogue: "removed" } }); + expect(w.db.query("SELECT kind, principal_id AS principalId FROM chat_lifecycles WHERE id='voyage'").get()).toEqual({ kind: "session", principalId: w.owner.id }); + expect(w.db.query("SELECT id FROM chat_lifecycles").all(), "LEGACY_CHATS_NOT_RETIRED").toEqual([{ id: "voyage" }]); +}); + +test("other principals refuse a bound typed chat exactly as they refuse one that does not exist", async () => { + const w = world(); + await w.type(`Plan the voyage home. ${MARKER}`); + await w.type("Steer between Scylla and Charybdis"); + expect(bindings(w.db)).toEqual([{ sessionId: "scylla", principalId: w.owner.id }, { sessionId: "voyage", principalId: w.owner.id }]); + + const foreign = await w.remove(w.other, "voyage"); + const missing = await w.remove(w.other, "nowhere"); + const foreignBody = await foreign.json(), missingBody = await missing.json(); + expect(foreign.status, "FOREIGN_OWNER_UNAVAILABLE").toBe(404); + expect(foreignBody, "FOREIGN_REFUSAL_LEAKS_NOTHING").toEqual(missingBody); + expect([missing.status, missingBody.reason]).toEqual([404, "unavailable"]); + // An agent the owner created holds no owner authority over its chats. + const agent = await w.remove(w.agent, "voyage"); + expect([agent.status, (await agent.json()).reason], "AGENT_CANNOT_DELETE").toEqual([403, "unauthorized"]); + expect(w.db.query("SELECT COUNT(*) AS n FROM chat_lifecycles").get(), "NOTHING_RETIRED_BY_OTHERS").toEqual({ n: 0 }); + + // A binding naming a different principal than a recorded voice owner is ambiguous, never resolved for either. + await w.catalog.saveConversationEpoch!({ id: "sirens", principalId: w.other, epoch: 1, sessionId: "scylla" }); + await w.catalog.settled!(); + for (const principal of [w.owner.id, w.other]) { + const conflict = await w.remove(principal, "scylla"); + expect([conflict.status, (await conflict.json()).reason], "CONFLICTING_OWNERS_UNAVAILABLE").toEqual([404, "unavailable"]); + } + + expect((await w.remove(w.owner.id, "voyage")).status, "OWNER_STILL_DELETES").toBe(200); +}); From 88ff54458e8fccd4fdac19434cd2e4dcc515f871 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 15:30:43 +0000 Subject: [PATCH 2/2] fix(ui-server): renumber the chat session owners migration to 076 origin/main now ships 075_hygiene_media_operations.journal.sql (#3421). Move this PR's migration past it so no two migrations share a number. Co-Authored-By: Claude Opus 5.5 --- docs/plans/chat-history-deletion.md | 2 +- ...{075_chat_session_owners.sql => 076_chat_session_owners.sql} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename packages/ui-server/migrations/{075_chat_session_owners.sql => 076_chat_session_owners.sql} (100%) diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index cb4176080a..f08ed6df25 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -55,7 +55,7 @@ and draft routes refuse drafts bound to it. Browser invalidation (#3231) is not **Built (#3337):** typed chats created from now on name their owner. Under the [2026-11-02 ruling](https://github.com/schlessera/brain-kit/issues/3337#issuecomment-6586465475), when an authenticated typed request creates a backend session, the host records a -content-free `(session, principal)` binding (migration `075_chat_session_owners.sql`). +content-free `(session, principal)` binding (migration `076_chat_session_owners.sql`). The bridge offers the creator only on a new, non-host-work turn whose authorization is current (`const creator`, `packages/ui-server/src/ws/bridge.ts:245`). The write worker diff --git a/packages/ui-server/migrations/075_chat_session_owners.sql b/packages/ui-server/migrations/076_chat_session_owners.sql similarity index 100% rename from packages/ui-server/migrations/075_chat_session_owners.sql rename to packages/ui-server/migrations/076_chat_session_owners.sql