Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/typed-chat-owner-bindings.md
Original file line number Diff line number Diff line change
@@ -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`.
2 changes: 1 addition & 1 deletion api-report/ui-server.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1910,7 +1910,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;
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1956,7 +1956,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:**
Expand Down
7 changes: 6 additions & 1 deletion docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1062,7 +1062,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
Expand Down
12 changes: 12 additions & 0 deletions docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,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
Expand Down
12 changes: 12 additions & 0 deletions docs/integration-contract/package-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,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.

<a id="typed-chat-owner-bindings-additive-3337"></a>

## 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
Expand Down
42 changes: 38 additions & 4 deletions docs/plans/chat-history-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@ 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
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
Expand Down Expand Up @@ -51,6 +52,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 `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
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
Expand Down Expand Up @@ -222,8 +256,8 @@ must be tested through their installed runtime, not inferred from directory name
handoff preparation, classifier callbacks, DialogueJournal routing/pending writes,
ConversationHost receipts/results/output and frozen startup envelopes can retain
or publish text. Catalog optimistic maps precede worker acknowledgements
(`rowEffects`, `packages/ui-server/src/ws/session-catalog.ts: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,
Expand Down
13 changes: 13 additions & 0 deletions packages/ui-server/migrations/076_chat_session_owners.sql
Original file line number Diff line number Diff line change
@@ -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
);
6 changes: 5 additions & 1 deletion packages/ui-server/src/ws/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,11 @@ export async function makeBridge(
coordinator.bindSession(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.
Expand Down
9 changes: 7 additions & 2 deletions packages/ui-server/src/ws/chat-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>(), conversations = new Set<string>(), principals = new Set<string>();
Expand All @@ -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=?),?)")
Expand Down
14 changes: 13 additions & 1 deletion packages/ui-server/src/ws/session-catalog-writes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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();
Expand Down
17 changes: 12 additions & 5 deletions packages/ui-server/src/ws/session-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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<void>("upsertSession", row));
};
/** Highest revision issued per session; it never goes down, so a failed acceptance's revision is never reused. */
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading