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 c07fca033d..4ab50a379b 100644
--- a/api-report/ui-server.txt
+++ b/api-report/ui-server.txt
@@ -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;
diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md
index 7d439204b7..96ab3673a2 100644
--- a/docs/decisions/governed-writable-workers.md
+++ b/docs/decisions/governed-writable-workers.md
@@ -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:**
diff --git a/docs/http-api.md b/docs/http-api.md
index a964a05c16..8d13a5b322 100644
--- a/docs/http-api.md
+++ b/docs/http-api.md
@@ -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
diff --git a/docs/integration-contract.md b/docs/integration-contract.md
index 201105253f..0650dc7e8a 100644
--- a/docs/integration-contract.md
+++ b/docs/integration-contract.md
@@ -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
diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md
index 0655416966..7f0746cf58 100644
--- a/docs/integration-contract/package-api.md
+++ b/docs/integration-contract/package-api.md
@@ -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.
+
+
+## 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/chat-history-deletion.md b/docs/plans/chat-history-deletion.md
index 7e7158e1cf..833c8f6c53 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
@@ -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
@@ -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,
diff --git a/packages/ui-server/migrations/076_chat_session_owners.sql b/packages/ui-server/migrations/076_chat_session_owners.sql
new file mode 100644
index 0000000000..0af14eb44c
--- /dev/null
+++ b/packages/ui-server/migrations/076_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 b6742f2d69..2d5618fbe6 100644
--- a/packages/ui-server/src/ws/bridge.ts
+++ b/packages/ui-server/src/ws/bridge.ts
@@ -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.
diff --git a/packages/ui-server/src/ws/chat-lifecycle.ts b/packages/ui-server/src/ws/chat-lifecycle.ts
index 43232abe7c..03e986c93f 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..83d720477c
--- /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 () => { await 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);
+});