From 3bb4006c29f751565125fdf7830df241a2c2f7f2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 15:51:28 +0000 Subject: [PATCH 1/5] CONTRACT: feat(ui-sdk): negotiate native history removal on the backend seam Add the optional `historyRemoval` capability and `removeSessionHistory()` method to `AgentBackend` (#3229), with content-free `removed`, `partial` and `unknown` outcomes that map onto the retirement ledger's per-store outcomes. A backend that does not advertise and implement both is unsupported, so a host refuses deletion before retiring anything; the conformance suite checks that the flag and method agree. The shared internal fence writes a durable, content-free tombstone before anything is removed, holds sessions for turns and readers, keeps one removal per session across a bounded caller wait, and removes only named artifacts, refusing links, hard links, special files and redirected roots. The display, prompt and observation stores expose the names they already used. Co-Authored-By: Claude Opus 5.5 --- .changeset/native-history-removal.md | 8 + api-report/ui-sdk.txt | 28 +++ docs/integration-contract.md | 12 + docs/integration-contract/package-api.md | 37 +++ packages/ui-sdk/src/internal.ts | 6 + packages/ui-sdk/src/server/backend.ts | 53 +++++ packages/ui-sdk/src/server/index.ts | 3 + .../src/server/native-history-removal.ts | 225 ++++++++++++++++++ .../src/server/native-observation-storage.ts | 6 +- .../src/server/session-prompt-context.ts | 9 +- packages/ui-sdk/src/server/session-replay.ts | 9 +- packages/ui-sdk/src/testing/index.ts | 4 +- 12 files changed, 394 insertions(+), 6 deletions(-) create mode 100644 .changeset/native-history-removal.md create mode 100644 packages/ui-sdk/src/server/native-history-removal.ts diff --git a/.changeset/native-history-removal.md b/.changeset/native-history-removal.md new file mode 100644 index 0000000000..0ef9a34cf5 --- /dev/null +++ b/.changeset/native-history-removal.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-backend-claude": minor +"@schlessera/brain-backend-pi": minor +"@schlessera/brain-ui-server": patch +--- + +Backends can remove one explicitly retired chat's local native history (#3229). `BackendCapabilities.historyRemoval` and the optional `AgentBackend.removeSessionHistory()` are new; the Claude and Pi backends implement them. A removal first fences the session permanently, so it is no longer listed, read, resumed, archived or restored, even after a restart. It then waits for the session's running turns and readers, and removes the live, archived, staged and conflict copies, subordinate and branch files, display and prompt metadata and file observations. Links, hard links, redirected storage and replaced files are left untouched and reported as `partial`, never as removed. Nothing exposes deletion to users yet: the endpoint and interface are separate work, and provider-held copies and backups are outside local removal. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 2daad53c63..68adea4aed 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1045,12 +1045,15 @@ export "./internal" (./src/internal.ts) type QuestionObservation REFERENCE_POOL_CHECKPOINT_BYTES RTK_WORKER_ENV + type RemovalRun type ReplayReceipt type Reservation type RestrictedEnvelope STALE_NATIVE_WRITE SUBPROCESS_ENV type SessionPromptFacts + type SessionRetirement + type SessionRetirementOptions type StateLedger TURN_TEMP_BUDGET_ENV TURN_TEMP_BYTES_ENV @@ -1128,9 +1131,11 @@ export "./internal" (./src/internal.ts) classifyOutwardCall claudeMaskFilename claudeReportedMaskPath + combineRemovalOutcomes compileWorkerCommandPolicy createLimitTracker createNativeBrainManagerClient + createSessionRetirement createStateLedger createTurnTempPressure createTurnTempPromoter @@ -1164,11 +1169,13 @@ export "./internal" (./src/internal.ts) mib mountPointsUnder nativeFileVersion + nativeObservationIdentity nativeWorkerStartupInput observeClassification observeOutwardPlan outputStagingLimit outwardTarget + ownedNames parseCliProviderOrigins parseNativeBrainDelta parseWorkerStateBytes @@ -1198,6 +1205,8 @@ export "./internal" (./src/internal.ts) recoveredWorkerFile recoveredWorkerFiles relayedProviderKeys + removeMetadataFile + removeOwnedArtifact requestPolicyPermission requireWorkerHost requireWorkerHostAsync @@ -1213,7 +1222,9 @@ export "./internal" (./src/internal.ts) runMaintenanceWorker runMaintenanceWorkerSync sessionPromptContext + sessionPromptContextLocation sessionReplay + sessionReplayLocation startEgressProxy startInferenceRelay startProviderRelay @@ -2313,6 +2324,9 @@ export "./server" (./src/server/index.ts) type ServerUsage type SessionDraftLimits type SessionHistoryMessage + type SessionHistoryRemovalOutcome + type SessionHistoryRemovalRequest + type SessionHistoryRemovalResult type SessionRecovery type SessionRecoveryLatest type SessionRecoveryPending @@ -3474,6 +3488,7 @@ signatures (every public export and the types it is made of) }[]; listSessions(): Promise; getHistory(sessionId: string): Promise; + removeSessionHistory?(req: SessionHistoryRemovalRequest): Promise; } AgentPolicyRead (packages/ui-sdk/src/protocol.ts) export interface AgentPolicyRead { @@ -5230,6 +5245,7 @@ signatures (every public export and the types it is made of) costReporting: boolean; concurrentSessions: boolean; followUp: boolean; + historyRemoval?: boolean; } BackendContractHarness (packages/ui-sdk/src/testing/index.ts) export interface BackendContractHarness { @@ -9926,6 +9942,18 @@ signatures (every public export and the types it is made of) turnId?: string; journal?: import("./turn-journal.js").TurnJournalSummary; } + SessionHistoryRemovalOutcome (packages/ui-sdk/src/server/backend.ts) + export type SessionHistoryRemovalOutcome = "removed" | "partial" | "unknown"; + SessionHistoryRemovalRequest (packages/ui-sdk/src/server/backend.ts) + export interface SessionHistoryRemovalRequest { + operationId: string; + sessionId: string; + signal?: AbortSignal; + } + SessionHistoryRemovalResult (packages/ui-sdk/src/server/backend.ts) + export interface SessionHistoryRemovalResult { + outcome: SessionHistoryRemovalOutcome; + } SessionRecovery (packages/ui-sdk/src/protocol.ts) export interface SessionRecovery { sessionId: string; diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 81969fc67c..180d6e88d4 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,18 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## Native history removal (additive, #3229) + +`BackendCapabilities.historyRemoval?` and the optional +`AgentBackend.removeSessionHistory?()` let a host remove one explicitly retired +chat's locally owned native history, with content-free `removed`, `partial` +and `unknown` outcomes. A backend that does not advertise and implement both is +unsupported, and deletion refuses before retirement. The first-party Claude and +Pi backends implement it. No wire frame, HTTP route, CLI `--json` shape or MCP +tool changes; the deletion endpoint is not part of this change. See +[the package component](integration-contract/package-api.md#native-history-removal-additive-3229). +This ships in a minor; no breaking ruling is required. + ## Agent runner unavailable in maintenance workers (additive, 0.45.0, #3243) A credential-free maintenance worker's launcher sets diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index c1d09ed1d0..83799f623c 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -131,6 +131,43 @@ passes its origin to `startInferenceRelay` as the new internal origin, and a turn without a relay refuses to start. The first-party Claude and pi backends implement all three. +## Native history removal (additive, #3229) + +`BackendCapabilities` adds optional `historyRemoval?: boolean`, and +`AgentBackend` adds optional `removeSessionHistory?(req: +SessionHistoryRemovalRequest): Promise`, exported +from `@schlessera/brain-ui-sdk/server` with +`SessionHistoryRemovalRequest` (`{ operationId: string; sessionId: string; +signal?: AbortSignal }`), `SessionHistoryRemovalResult` (`{ outcome }`) and +`SessionHistoryRemovalOutcome` (`"removed" | "partial" | "unknown"`). +Removal is supported only when the capability is `true` and the method exists; +the conformance suite in `@schlessera/brain-ui-sdk/testing` checks that they +agree. A host refuses deletion of a chat on any other backend before it +retires anything; older backends remain valid and simply do not support it. + +A host calls it only for a chat its owner explicitly retired, under that +retirement's operation identity, as the +[deletion policy](../decisions/chat-history-deletion.md) allows. Before its first +await the backend fences the session durably and permanently: `listSessions` +omits it, `getHistory` returns `[]`, and resume, follow-up, archive and +restore refuse it, after a restart too. It then waits for the session's running +turns and readers to drain and removes every native artifact it owns: live, +archived, staged and conflict copies, subordinate and branch files, display and +prompt metadata and file observations. Only names derived from the validated +session identity are touched; a link, hard-linked file, redirected root or +artifact whose own header names another session is left in place. + +The outcome is content-free and maps onto the host's per-store ledger: +`removed` only when every owned artifact is confirmed absent and the installed +runtime no longer lists the session; `partial` while owned content may remain, +including when `signal` aborts the caller's wait first (the removal keeps its +single owner and finishes after a genuine drain); `unknown` when an unexpected +failure left the state unconfirmed. Every outcome but `removed` is retried under +the same operation. A second operation for the same session, an invalid +identity or a redirected tombstone root rejects with `BackendRequestError`. +Previously sent provider bytes are never rewritten, and provider-held copies +are outside it. The first-party Claude and Pi backends implement it. + ## Inbox provenance (additive, #2741) The intake `createInboxIntake` returns adds `person(input, key, principal)`: diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index 120495f7d8..db12731403 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -100,3 +100,9 @@ export { promptPrefixFingerprint } from "./server/prompt-fingerprint.js"; export { rewriteWorkerRtk } from "./server/worker-rtk.js"; export { acquireHostCredentialExclusion, HostCredentialExclusionError, type HostCredentialDomain } from "./server/credential-exclusion.js"; + +export { combineRemovalOutcomes, createSessionRetirement, ownedNames, removeMetadataFile, removeOwnedArtifact } from "./server/native-history-removal.js"; +export type { RemovalRun, SessionRetirement, SessionRetirementOptions } from "./server/native-history-removal.js"; +export { sessionReplayLocation } from "./server/session-replay.js"; +export { sessionPromptContextLocation } from "./server/session-prompt-context.js"; +export { nativeObservationIdentity } from "./server/native-observation-storage.js"; diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index 91095123d6..8e7e93933d 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -100,6 +100,12 @@ export interface BackendCapabilities { * false → the host queues them as the session's next turn (status: queued). */ followUp: boolean; + /** + * Implements `removeSessionHistory` for an explicitly retired chat (#3229). + * Absent or false: removal is unsupported, and a host refuses the deletion + * before it retires anything. + */ + historyRemoval?: boolean; } export type PermissionDecision = @@ -693,6 +699,42 @@ export function isCompletedAutonomousToolCall( return mode?.completedToolCalls?.some((call) => call.toolName === toolName && JSON.stringify(canonical(call.input)) === key) ?? false; } +/** + * Remove one retired chat's locally owned native history (#3229). The host + * calls it only after its own retirement committed, under that retirement's + * operation identity; it is never a client path or a storage-root operation. + * + * @experimental Part of the `AgentBackend` seam. + */ +export interface SessionHistoryRemovalRequest { + /** The host retirement's operation identity. A repeat joins or re-runs the same removal; another identity for the same session is refused. */ + operationId: string; + /** The backend's own session identity, as `listSessions` reports it. */ + sessionId: string; + /** + * Bounds the caller's wait only. When it aborts first the result is + * `partial`: the removal keeps its ownership, finishes after the session's + * holders genuinely drain, and admits no replacement writer meanwhile. + */ + signal?: AbortSignal; +} + +/** + * Content-free, matching the host lifecycle ledger's per-store outcomes: + * `removed` only when every owned artifact is confirmed absent and the + * installed runtime no longer lists the session; `partial` while owned + * content may remain (a holder still draining, or a link, alias, replaced or + * unattributable artifact left untouched); `unknown` when an unexpected + * failure left the store's state unconfirmed. Every outcome but `removed` is + * retryable under the same operation. + * + * @experimental Part of the `AgentBackend` seam. + */ +export type SessionHistoryRemovalOutcome = "removed" | "partial" | "unknown"; + +/** @experimental Part of the `AgentBackend` seam. */ +export interface SessionHistoryRemovalResult { outcome: SessionHistoryRemovalOutcome } + /** Mid-turn user message for a RUNNING session (capabilities.followUp). */ export interface FollowUpRequest { sessionId: string; @@ -748,6 +790,17 @@ export interface AgentBackend { listSessions(): Promise; /** Normalized-at-read history; backends own raw transcripts. */ getHistory(sessionId: string): Promise; + /** + * Only with `capabilities.historyRemoval` (#3229). Before its first await + * the session is fenced, durably and permanently: `listSessions` omits it, + * `getHistory` returns `[]`, and resume, follow-up, archive and restore + * refuse it. Its running turns and readers then drain, and every owned + * native artifact (live, archived, staged and conflict copies, subordinate + * files, display and prompt metadata, file observations) is removed after + * identity checks. Rejects with `BackendRequestError` for an invalid + * request or another operation's session; never deletes outside its own roots. + */ + removeSessionHistory?(req: SessionHistoryRemovalRequest): Promise; } /** diff --git a/packages/ui-sdk/src/server/index.ts b/packages/ui-sdk/src/server/index.ts index 7eee780d92..9ee47a9ba0 100644 --- a/packages/ui-sdk/src/server/index.ts +++ b/packages/ui-sdk/src/server/index.ts @@ -9,6 +9,9 @@ export type { AutonomousTurnOptions, CompletedAutonomousToolCall, FollowUpRequest, + SessionHistoryRemovalRequest, + SessionHistoryRemovalOutcome, + SessionHistoryRemovalResult, PermissionDecision, PermissionRequest, AskUserResult, diff --git a/packages/ui-sdk/src/server/native-history-removal.ts b/packages/ui-sdk/src/server/native-history-removal.ts new file mode 100644 index 0000000000..82f100355b --- /dev/null +++ b/packages/ui-sdk/src/server/native-history-removal.ts @@ -0,0 +1,225 @@ +/** + * Explicit removal of one retired chat's native history (#3229), shared by + * the first-party backends. Each backend names the exact artifacts it owns; + * this module fences the session, waits for its holders and removes those + * artifacts without following a link or touching anything else. + * Policy: docs/decisions/chat-history-deletion.md. + */ +import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, rmdirSync, unlinkSync, writeSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { BackendRequestError } from "./backend.js"; +import type { SessionHistoryRemovalOutcome, SessionHistoryRemovalRequest, SessionHistoryRemovalResult } from "./backend.js"; + +const MAX_OPERATION = 2048; +const TOMBSTONE_BYTES = 4096; + +/** Unknown dominates partial; removed only when every part was. */ +export function combineRemovalOutcomes(outcomes: readonly SessionHistoryRemovalOutcome[]): SessionHistoryRemovalOutcome { + if (outcomes.includes("unknown")) return "unknown"; + return outcomes.every(outcome => outcome === "removed") ? "removed" : "partial"; +} + +function syncDirectory(path: string): void { + const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + try { fsyncSync(fd); } finally { closeSync(fd); } +} +const realDirectory = (path: string) => { + const info = lstatSync(path); + return info.isDirectory() && realpathSync(path) === path; +}; +/** Every entry below a directory is a plain file with one name or a real directory. */ +function ownedTree(path: string): boolean { + for (const name of readdirSync(path)) { + const child = join(path, name), info = lstatSync(child); + if (info.isDirectory()) { if (!ownedTree(child)) return false; } + else if (!info.isFile() || info.nlink !== 1) return false; + } + return true; +} +function removeTree(path: string): void { + for (const name of readdirSync(path)) { + const child = join(path, name); + if (lstatSync(child).isDirectory()) removeTree(child); + else unlinkSync(child); + } + syncDirectory(path); + rmdirSync(path); +} + +/** + * Remove one owned file or directory tree at `root/name`. `removed` when it is + * absent afterwards (already absent included); `partial`, touching nothing, + * when the root is redirected or the artifact is a link, a hard-linked file, a + * special file, or a tree containing any of these: its bytes could belong to, + * or remain reachable through, something this chat does not own. + */ +export function removeOwnedArtifact(root: string, name: string): SessionHistoryRemovalOutcome { + if (!name || name.includes("/") || name.includes("\\") || name === "." || name === "..") throw new Error("Invalid owned artifact name"); + if (!existsSync(root)) { + // A missing root holds nothing, unless it is a dangling link. + try { lstatSync(root); } catch { return "removed"; } + return "partial"; + } + if (!realDirectory(root)) return "partial"; + const path = join(root, name); + let info; + try { info = lstatSync(path); } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return "removed"; + throw error; + } + if (info.isDirectory()) { + if (!ownedTree(path)) return "partial"; + removeTree(path); + } else if (info.isFile() && info.nlink === 1) unlinkSync(path); + else return "partial"; + syncDirectory(root); + return "removed"; +} + +/** The names directly in `root` that `owned` selects; none for a missing root. */ +export function ownedNames(root: string, owned: (name: string) => boolean): string[] { + if (!existsSync(root) || !realDirectory(root)) return []; + return readdirSync(root).filter(owned); +} + +/** A host-owned metadata file and any temp copy its atomic writer left behind. */ +export function removeMetadataFile(location: { dir: string; name: string }): SessionHistoryRemovalOutcome { + const temps = ownedNames(location.dir, name => name.startsWith(`${location.name}.`) && name.endsWith(".tmp")); + return combineRemovalOutcomes([location.name, ...temps].map(name => removeOwnedArtifact(location.dir, name))); +} + +export interface SessionRetirementOptions { + /** + * Host-owned, content-free tombstones: one file per retired session, holding + * only its operation identity. Resolved on use, so constructing a backend + * never validates or creates its storage. + */ + directory: () => string; + /** The backend's own session-identity rule; a tombstone is named by it. */ + validSessionId: (id: string) => boolean; +} +export interface RemovalRun { + /** Synchronous, after every holder has drained: no turn, reader or archive step interleaves with it. */ + remove(sessionId: string): SessionHistoryRemovalOutcome; + /** Asks the installed runtime whether it still lists the session; a listed session is not removed. */ + stillListed(sessionId: string): Promise; + /** Drops in-memory runtime state (resident sessions, observation caches) once holders drained. */ + release?(sessionId: string): void | Promise; +} + +/** + * The fence a backend consults on every list, read, resume, follow-up, + * archive and restore path, and the single-flight removal behind it. + * Durable: a tombstone written before anything is removed keeps refusing the + * session after a restart, and a crash at any later boundary is reconciled by + * repeating the same operation. + */ +export function createSessionRetirement(options: SessionRetirementOptions) { + const retired = new Set(); + const holders = new Map void> }>(); + const jobs = new Map }>(); + + function tombstone(sessionId: string): string | undefined { + let path: string; + // Storage that cannot be resolved holds no tombstone; the in-memory fence still applies. + try { path = join(options.directory(), sessionId); } catch { return undefined; } + let fd: number; + try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + // Unreadable or aliased: still a fence, with no operation to match. + return ""; + } + try { + const info = lstatSync(path); + if (!info.isFile() || info.size > TOMBSTONE_BYTES) return ""; + return readFileSync(fd, "utf8"); + } catch { return ""; } finally { closeSync(fd); } + } + function isRetired(sessionId: string): boolean { + if (retired.has(sessionId)) return true; + if (!options.validSessionId(sessionId)) return false; + if (tombstone(sessionId) === undefined) return false; + retired.add(sessionId); + return true; + } + function writeTombstone(sessionId: string, operationId: string): void { + const root = options.directory(); + let missing = root; + const create: string[] = []; + while (!existsSync(missing)) { create.unshift(missing); missing = dirname(missing); } + if (!realDirectory(missing)) throw new BackendRequestError("Chat retirement storage is redirected"); + for (const dir of create) { + try { mkdirSync(dir, { mode: 0o700 }); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; } + if (!realDirectory(dir)) throw new BackendRequestError("Chat retirement storage is redirected"); + syncDirectory(dirname(dir)); + } + const fd = openSync(join(root, sessionId), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); + try { writeSync(fd, operationId); fsyncSync(fd); } finally { closeSync(fd); } + syncDirectory(root); + } + function drained(sessionId: string): Promise { + const entry = holders.get(sessionId); + return entry ? new Promise(resolve => entry.idle.push(resolve)) : Promise.resolve(); + } + + return { + isRetired, + /** For a list path: drop retired sessions, read after the list's own await. */ + filter(sessions: readonly T[]): T[] { return sessions.filter(session => !isRetired(session.id)); }, + /** Hold a session open for a turn or reader. Refuses a retired one; release once its last write or publication is done. */ + hold(sessionId: string): () => void { + if (isRetired(sessionId)) throw new BackendRequestError(`Cannot resume unknown session: ${sessionId}`); + const entry = holders.get(sessionId) ?? { count: 0, idle: [] }; + entry.count++; holders.set(sessionId, entry); + let released = false; + return () => { + if (released) return; + released = true; + if (--entry.count > 0) return; + holders.delete(sessionId); + for (const resolve of entry.idle.splice(0)) resolve(); + }; + }, + async remove(req: SessionHistoryRemovalRequest, run: RemovalRun): Promise { + if (typeof req?.operationId !== "string" || !req.operationId || req.operationId.length > MAX_OPERATION || + typeof req.sessionId !== "string" || !options.validSessionId(req.sessionId)) + throw new BackendRequestError("Invalid session history removal request"); + const { operationId, sessionId } = req; + let job = jobs.get(sessionId); + if (job && job.operationId !== operationId) throw new BackendRequestError("Another removal owns this session"); + if (!job) { + const recorded = tombstone(sessionId); + if (recorded !== undefined && recorded !== operationId) throw new BackendRequestError("Another removal owns this session"); + // Fence first, synchronously: nothing admitted after this line can hold the session. + retired.add(sessionId); + if (recorded === undefined) writeTombstone(sessionId, operationId); + const done = (async (): Promise => { + await drained(sessionId); + try { + await run.release?.(sessionId); + const outcome = run.remove(sessionId); + if (outcome !== "removed") return outcome; + return await run.stillListed(sessionId) ? "partial" : "removed"; + } catch { return "unknown"; } + })(); + job = { operationId, done }; + jobs.set(sessionId, job); + const settled = job; + void done.finally(() => { if (jobs.get(sessionId) === settled) jobs.delete(sessionId); }); + } + const signal = req.signal; + if (!signal) return { outcome: await job.done }; + if (signal.aborted) return { outcome: "partial" }; + let onAbort: (() => void) | undefined; + const aborted = new Promise(resolve => { + onAbort = () => resolve("partial"); + signal.addEventListener("abort", onAbort, { once: true }); + }); + try { return { outcome: await Promise.race([job.done, aborted]) }; } + finally { signal.removeEventListener("abort", onAbort!); } + }, + }; +} +export type SessionRetirement = ReturnType; diff --git a/packages/ui-sdk/src/server/native-observation-storage.ts b/packages/ui-sdk/src/server/native-observation-storage.ts index 653f784aa7..61dd0946b9 100644 --- a/packages/ui-sdk/src/server/native-observation-storage.ts +++ b/packages/ui-sdk/src/server/native-observation-storage.ts @@ -34,11 +34,15 @@ async function syncDirectory(path: string): Promise { const handle = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); try { await handle.sync(); } finally { await handle.close(); } } +/** The record's name below its directory, from the brain's real path; removal (#3229) uses it too. */ +export function nativeObservationIdentity(realBrainPath: string, sessionId: string): string { + return digest(JSON.stringify([realBrainPath, sessionId])); +} async function location(storage: NativeObservationStorage): Promise<{ path: string; identity: string }> { const brain = await realpath(storage.brainPath), root = resolve(storage.directory); if (brain === root || brain.startsWith(root + "/")) throw new Error("Native observation storage must not contain the brain."); await directory(root, brain); - const identity = digest(JSON.stringify([brain, storage.sessionId])); + const identity = nativeObservationIdentity(brain, storage.sessionId); return { path: join(root, identity + ".json"), identity }; } function validVersion(value: unknown): value is NativeFileVersion { diff --git a/packages/ui-sdk/src/server/session-prompt-context.ts b/packages/ui-sdk/src/server/session-prompt-context.ts index ad595c053f..009f07b0a2 100644 --- a/packages/ui-sdk/src/server/session-prompt-context.ts +++ b/packages/ui-sdk/src/server/session-prompt-context.ts @@ -18,9 +18,14 @@ function directory(path: string): void { mkdirSync(path, { mode: 0o700 }); } +/** Where one session's prompt context lives; removal (#3229) uses the same names. */ +export function sessionPromptContextLocation(root: string, brainPath: string, sessionId: string): { dir: string; name: string } { + return { dir: resolve(root, "prompt-context", digest(realpathSync(brainPath))), name: `${digest(sessionId)}.json` }; +} + export function sessionPromptContext(root: string, brainPath: string, sessionId: string) { const brain = realpathSync(brainPath); - const dir = resolve(root, "prompt-context", digest(brain)); + const { dir, name } = sessionPromptContextLocation(root, brainPath, sessionId); // Walk ancestors without creating them first. let ancestor = dir; while (!existsSync(ancestor)) ancestor = dirname(ancestor); @@ -28,7 +33,7 @@ export function sessionPromptContext(root: string, brainPath: string, sessionId: if (actual === brain || actual.startsWith(brain + "/") || brain.startsWith(actual + "/")) { throw new Error("Session prompt storage must be outside the authoritative brain"); } - const path = join(dir, `${digest(sessionId)}.json`); + const path = join(dir, name); function read(): Snapshot { let fd: number; try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } diff --git a/packages/ui-sdk/src/server/session-replay.ts b/packages/ui-sdk/src/server/session-replay.ts index 4edd05c056..f749f770e3 100644 --- a/packages/ui-sdk/src/server/session-replay.ts +++ b/packages/ui-sdk/src/server/session-replay.ts @@ -15,9 +15,14 @@ function directory(path: string): void { } directory(dirname(path)); mkdirSync(path, { mode: 0o700 }); } +/** Where one session's display metadata lives; removal (#3229) uses the same names. */ +export function sessionReplayLocation(root: string, brainPath: string, sessionId: string): { dir: string; name: string } { + const brain = existsSync(brainPath) ? realpathSync(brainPath) : resolve(brainPath); + return { dir: resolve(root, "session-replay", digest(brain)), name: `${digest(sessionId)}.json` }; +} /** Concrete first-party storage, keyed by native session, message and text part. */ export function sessionReplay(root: string, brainPath: string, sessionId: string) { - const brain = existsSync(brainPath) ? realpathSync(brainPath) : resolve(brainPath), dir = resolve(root, "session-replay", digest(brain)); + const brain = existsSync(brainPath) ? realpathSync(brainPath) : resolve(brainPath), { dir, name } = sessionReplayLocation(root, brainPath, sessionId); let ancestor = dir; while (!existsSync(ancestor)) ancestor = dirname(ancestor); const actual = resolve(realpathSync(ancestor), dir.slice(ancestor.length).replace(/^\//, "")); @@ -26,7 +31,7 @@ export function sessionReplay(root: string, brainPath: string, sessionId: string if (!outside) throw new Error("Session replay storage must be outside the authoritative brain"); if (existsSync(dir)) directory(dir); }; - const path = join(dir, `${digest(sessionId)}.json`); + const path = join(dir, name); function read(): Snapshot { let fd: number; try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } diff --git a/packages/ui-sdk/src/testing/index.ts b/packages/ui-sdk/src/testing/index.ts index 6d4537dd7f..94437c462b 100644 --- a/packages/ui-sdk/src/testing/index.ts +++ b/packages/ui-sdk/src/testing/index.ts @@ -311,8 +311,10 @@ export function runBackendContract( for (const key of keys) { expect(typeof backend.capabilities[key]).toBe("boolean"); } - const optional = (["autonomous", "restrictedAutonomous"] as const).filter((key) => Object.hasOwn(backend.capabilities, key)); + const optional = (["autonomous", "restrictedAutonomous", "historyRemoval"] as const).filter((key) => Object.hasOwn(backend.capabilities, key)); for (const key of optional) expect(typeof backend.capabilities[key]).toBe("boolean"); + // Advertised history removal (#3229) is implemented; an unadvertised one is never called. + if (backend.capabilities.historyRemoval) expect(typeof backend.removeSessionHistory).toBe("function"); // The restricted envelope is a kind of autonomous turn, never claimed alone. if (backend.capabilities.restrictedAutonomous) expect(backend.capabilities.autonomous).toBe(true); expect(Object.keys(backend.capabilities).sort()).toEqual([...keys, ...optional].sort()); From 0eeaeaf5e1899ae08cd0337931d451ed0b68f9b0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 15:51:28 +0000 Subject: [PATCH 2/5] feat(backends): remove a retired chat's Claude and Pi native history Both first-party backends advertise history removal (#3229). Claude removes the live transcript and subordinate tree, the archived, staged and conflict copies and the index entry; Pi removes every SessionManager tree whose own header names the session in this brain, under the canonical and the older SDK-managed name, so inactive branches go too. Both remove display and prompt metadata and file observations, and confirm through the installed runtime's own listing. Listing, reading, resume, follow-up, archive and restore refuse a retired session, after a restart too. Turns and history reads hold their session, so a removal waits for their last native write, and a read never publishes what it found once the chat is retired. Co-Authored-By: Claude Opus 5.5 --- packages/ui-backend-claude/src/backend.ts | 24 +- packages/ui-backend-claude/src/history.ts | 20 +- .../src/transcript-archive.ts | 56 ++++- packages/ui-backend-claude/src/turn-runner.ts | 18 +- .../ui-backend-claude/tests/backend.test.ts | 1 + .../tests/native-history-removal.test.ts | 212 ++++++++++++++++++ packages/ui-backend-pi/src/backend.ts | 31 ++- packages/ui-backend-pi/src/history.ts | 22 +- packages/ui-backend-pi/src/session-runtime.ts | 3 + packages/ui-backend-pi/src/session-storage.ts | 49 +++- packages/ui-backend-pi/src/turn-runner.ts | 17 +- packages/ui-backend-pi/tests/backend.test.ts | 1 + .../tests/native-history-removal.test.ts | 153 +++++++++++++ 13 files changed, 582 insertions(+), 25 deletions(-) create mode 100644 packages/ui-backend-claude/tests/native-history-removal.test.ts create mode 100644 packages/ui-backend-pi/tests/native-history-removal.test.ts diff --git a/packages/ui-backend-claude/src/backend.ts b/packages/ui-backend-claude/src/backend.ts index 0b1efa335e..76e44453a2 100644 --- a/packages/ui-backend-claude/src/backend.ts +++ b/packages/ui-backend-claude/src/backend.ts @@ -1,4 +1,4 @@ -import { transcriptPaths } from "./transcript-archive.js"; +import { listArchivedSessions, removeClaudeSession, retiredDirectory, transcriptPaths } from "./transcript-archive.js"; import { getSessionMessages as sdkGetSessionMessages, listSessions as sdkListSessions, @@ -18,7 +18,8 @@ import { DEFAULT_CONFIRM_BASH_PATTERNS } from "@schlessera/brain-ui-sdk/server"; import { createHistory } from "./history.js"; import type { BackendLogFn, ClaudeBackendOptions } from "./options.js"; import { resolveClaudeProfiles } from "./options.js"; -import { resolveTurnTempLimits, resolveWorkerStateLimits } from "@schlessera/brain-ui-sdk/internal"; +import { createSessionRetirement, resolveTurnTempLimits, resolveWorkerStateLimits } from "@schlessera/brain-ui-sdk/internal"; +import { isSessionId } from "./worker-state.js"; import { getProfile, listProfiles, listUnavailableProfiles } from "./profiles.js"; import { selectedInferenceUpstream, turnEnv } from "./sdk-options.js"; import { createClaudeTurnRunner } from "./turn-runner.js"; @@ -84,8 +85,11 @@ export function createClaudeBackend(options: ClaudeBackendOptions): AgentBackend `[claude-backend] ignoring unparseable confirmBashPatterns entry ${JSON.stringify(source)}: ${message}` ) ); + // Explicit chat deletion (#3229): one durable fence for every native path. + const retirement = createSessionRetirement({ directory: () => retiredDirectory(options.brainPath), validSessionId: isSessionId }); const history = createHistory({ brainPath: options.brainPath, + retirement, listSessionsFn: options.listSessionsFn ?? sdkListSessions, getSessionMessagesFn: options.getSessionMessagesFn ?? sdkGetSessionMessages, }); @@ -97,7 +101,8 @@ export function createClaudeBackend(options: ClaudeBackendOptions): AgentBackend attrs ?? "" )); const writeLock = options.writeLock ?? createKeyedLock(); - const { startTurn, followUp } = createClaudeTurnRunner({ + const { startTurn, followUp, forget } = createClaudeTurnRunner({ + retirement, backend: options, resolveProfiles, confirmPatterns, @@ -124,6 +129,7 @@ export function createClaudeBackend(options: ClaudeBackendOptions): AgentBackend // next tool result, without interrupting the running step (#1003, // turn-input.ts). followUp: true, + historyRemoval: true, }; return { @@ -165,5 +171,17 @@ export function createClaudeBackend(options: ClaudeBackendOptions): AgentBackend getHistory(sessionId: string): Promise { return history.getHistory(sessionId); }, + removeSessionHistory(req) { + return retirement.remove(req, { + release: forget, + remove: (id) => removeClaudeSession(id, { brainPath: options.brainPath }), + // The installed SDK's own listing, archive included, is the last word. + async stillListed(id) { + const listSessionsFn = options.listSessionsFn ?? sdkListSessions; + const live = await listSessionsFn({ dir: options.brainPath }); + return live.some(session => session.sessionId === id) || listArchivedSessions({ brainPath: options.brainPath }).some(session => session.id === id); + }, + }); + }, }; } diff --git a/packages/ui-backend-claude/src/history.ts b/packages/ui-backend-claude/src/history.ts index 0225085f34..3123ed8264 100644 --- a/packages/ui-backend-claude/src/history.ts +++ b/packages/ui-backend-claude/src/history.ts @@ -13,6 +13,7 @@ import type { TurnFailure, } from "@schlessera/brain-ui-sdk"; import { subscriptionAuthAction } from "@schlessera/brain-ui-sdk"; +import type { SessionRetirement } from "@schlessera/brain-ui-sdk/internal"; import { listArchivedSessions, restoreArchivedSession, transcriptPaths } from "./transcript-archive.js"; import { isSessionId } from "./worker-state.js"; import { usageLimitText } from "./usage-limit.js"; @@ -31,6 +32,8 @@ export interface HistoryDeps { env?: Record; listSessionsFn?: typeof sdkListSessions; getSessionMessagesFn?: typeof sdkGetSessionMessages; + /** Explicitly retired sessions (#3229): never listed, read or restored. */ + retirement?: Pick; } export interface History { @@ -73,17 +76,26 @@ export function createHistory(deps: HistoryDeps): History { let archived: ReturnType = []; try { archived = listArchivedSessions(deps); } catch (error) { console.warn("Claude transcript archive listing failed", error); } - return [...live, ...archived.filter(s => !ids.has(s.id)).map(s => ({ + const listed = [...live, ...archived.filter(s => !ids.has(s.id)).map(s => ({ ...s, totalCostUsd: 0, numTurns: 0, }))]; + // After the awaits: a session retired while the SDK listed is not listed. + return deps.retirement ? deps.retirement.filter(listed) : listed; } async function getHistory( sessionId: string ): Promise { - if (isSessionId(sessionId)) restoreArchivedSession(sessionId, deps); - const root = dirname(dirname(transcriptPaths(dir, deps.env).live)); - return buildSessionHistory(sessionId, getSessionMessagesFn, dir, deps.env, sessionReplay(root, dir, sessionId).texts()); + // A retired chat reads as an unknown one, and its archive is never restored. + if (deps.retirement?.isRetired(sessionId)) return []; + // A removal waits for this read; the read never publishes what it found once retired. + const release = deps.retirement && isSessionId(sessionId) ? deps.retirement.hold(sessionId) : undefined; + try { + if (isSessionId(sessionId)) restoreArchivedSession(sessionId, deps); + const root = dirname(dirname(transcriptPaths(dir, deps.env).live)); + const history = await buildSessionHistory(sessionId, getSessionMessagesFn, dir, deps.env, sessionReplay(root, dir, sessionId).texts()); + return deps.retirement?.isRetired(sessionId) ? [] : history; + } finally { release?.(); } } return { listSessions, getHistory }; diff --git a/packages/ui-backend-claude/src/transcript-archive.ts b/packages/ui-backend-claude/src/transcript-archive.ts index 60059ac2cc..43a0cea802 100644 --- a/packages/ui-backend-claude/src/transcript-archive.ts +++ b/packages/ui-backend-claude/src/transcript-archive.ts @@ -5,7 +5,8 @@ import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readd import { mkdir, open, rename, rm } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; -import { WorkerHostError } from "@schlessera/brain-ui-sdk/internal"; +import { WorkerHostError, combineRemovalOutcomes, nativeObservationIdentity, ownedNames, removeMetadataFile, removeOwnedArtifact, sessionPromptContextLocation, sessionReplayLocation } from "@schlessera/brain-ui-sdk/internal"; +import type { SessionHistoryRemovalOutcome } from "@schlessera/brain-ui-sdk/server"; import { envSnapshot } from "./config/env.js"; import { directory, files, isSessionId, regular, validateSessionId } from "./worker-state.js"; @@ -38,6 +39,16 @@ export function transcriptPaths(brainPath: string, env: Record): string { + return join(transcriptPaths(brainPath, env).archive, "retired"); +} +/** A tombstone, aliased or not, fences the session: archive and restore never touch it again. */ +function retiredOnDisk(archive: string, id: string): boolean { + try { lstatSync(join(archive, "retired", id)); return true; } + catch (error) { return (error as NodeJS.ErrnoException).code !== "ENOENT"; } +} + function syncTree(path: string) { for (const name of readdirSync(path)) { const child = join(path, name); @@ -147,7 +158,8 @@ export function restoreArchivedSession(id: string, options: ArchiveOptions): voi validateSessionId(id); const { live, archive } = transcriptPaths(options.brainPath, options.env); const source = join(archive, id); - if (!existsSync(source)) return; + // A retired chat's archived copy is never restored, even if its removal has not finished. + if (!existsSync(source) || retiredOnDisk(archive, id)) return; const record = manifest(archive, id); // Never overwrite a newer live version. Archiving only takes idle files, so // a live file that differs is the newer one: keep it in place, set the @@ -230,7 +242,7 @@ export async function archiveIdleSessions(options: ArchiveOptions): Promise): SessionHistoryRemovalOutcome { + validateSessionId(id); + const { live, archive } = transcriptPaths(options.brainPath, options.env); + const config = dirname(dirname(live)); + const outcomes: SessionHistoryRemovalOutcome[] = [ + removeOwnedArtifact(live, `${id}.jsonl`), + removeOwnedArtifact(live, id), + removeOwnedArtifact(archive, id), + ...ownedNames(archive, name => name.startsWith(`.conflict-${id}-`) || name.startsWith(`.pending-${id}-`)) + .map(name => removeOwnedArtifact(archive, name)), + ]; + // The index carries titles: drop this entry and keep every other one as it was. + const indexPath = join(archive, "index.json"); + if (existsSync(indexPath)) { + const entries = JSON.parse(regular(indexPath, METADATA_BYTES).toString()) as ArchivedSession[]; + if (!Array.isArray(entries)) throw new Error("Invalid transcript archive index"); + if (entries.some(entry => entry?.id === id)) index(archive, entries.filter(entry => entry?.id !== id)); + } + if (existsSync(options.brainPath)) { + const brain = realpathSync(options.brainPath); + outcomes.push( + removeMetadataFile({ dir: join(archive, "native-observations"), name: `${nativeObservationIdentity(brain, id)}.json` }), + removeMetadataFile(sessionReplayLocation(config, brain, id)), + removeMetadataFile(sessionPromptContextLocation(config, brain, id))); + } else outcomes.push("unknown"); + return combineRemovalOutcomes(outcomes); +} diff --git a/packages/ui-backend-claude/src/turn-runner.ts b/packages/ui-backend-claude/src/turn-runner.ts index ae88720018..8efd70bce9 100644 --- a/packages/ui-backend-claude/src/turn-runner.ts +++ b/packages/ui-backend-claude/src/turn-runner.ts @@ -63,6 +63,7 @@ import type { KeyedLock } from "@schlessera/brain-ui-sdk/server"; import { SessionTooLargeError } from "./worker-state.js"; import { workerStateClass } from "./worker-spawn.js"; import { archiveIdleSessions, transcriptPaths } from "./transcript-archive.js"; +import type { SessionRetirement } from "@schlessera/brain-ui-sdk/internal"; const BACKEND_ID = "claude"; @@ -86,6 +87,8 @@ export interface ClaudeTurnRunner { startTurn(req: StartTurnRequest): Promise; /** `AgentBackend.followUp`: deliver a message into the session's running turn. */ followUp(req: FollowUpRequest): Promise; + /** Drop a retired session's in-memory observation cache once its turns drained (#3229). */ + forget(sessionId: string): void; } export function createClaudeTurnRunner(options: { @@ -95,6 +98,8 @@ export function createClaudeTurnRunner(options: { writeLock: KeyedLock; lockWaitMs: number; log: BackendLogFn; + /** Explicit chat deletion (#3229): a retired session never resumes, and removal waits for its turn. */ + retirement?: Pick; }): ClaudeTurnRunner { // Busy-ness is PER SESSION: one running turn per session key. Resuming a // session that already has a running turn rejects BackendBusyError; a NEW @@ -108,7 +113,7 @@ export function createClaudeTurnRunner(options: { async function followUp(req: FollowUpRequest): Promise { // Keyed by the real session id only once the SDK reported it, which is // also when the host first learns it: a placeholder key never matches. - const turn = activeTurns.get(req.sessionId); + const turn = options.retirement?.isRetired(req.sessionId) ? undefined : activeTurns.get(req.sessionId); if (!turn?.input?.push(req.prompt, req.attachments)) { throw new BackendRequestError( `No running turn for session ${req.sessionId} to deliver a follow-up to.` @@ -123,6 +128,11 @@ export function createClaudeTurnRunner(options: { if (req.sessionId !== undefined && activeTurns.has(req.sessionId)) { throw new BackendBusyError(BACKEND_ID, req.sessionId); } + // A retired chat refuses resume as an unknown one. The hold lasts until the + // turn's last copy-out, so a removal never races this turn's native writes. + const holds: Array<() => void> = []; + if (req.sessionId !== undefined && options.retirement) holds.push(options.retirement.hold(req.sessionId)); + const releaseHolds = () => { for (const release of holds.splice(0)) release(); }; // The session is claimed the moment startTurn is called (#1063): a live // follow-up offered meanwhile joins this turn's input, which is held until @@ -192,6 +202,7 @@ export function createClaudeTurnRunner(options: { input.close(); turnLock?.close(); activeTurns.delete(turnKey); + releaseHolds(); throw error; } @@ -661,6 +672,8 @@ export function createClaudeTurnRunner(options: { activeTurns.delete(turnKey); activeTurns.set(sessionId, turn); turnKey = sessionId; + // A freshly minted identity was never retired; hold it like a resumed one. + if (options.retirement) holds.push(options.retirement.hold(sessionId)); } if (req.autonomous) { reportActivity({ kind: "autonomous_identity", runtimeSessionId: sessionId, @@ -825,11 +838,12 @@ export function createClaudeTurnRunner(options: { activeSessionIds: () => new Set(activeTurns.keys()), log: (message, error) => options.log("warn", message, { error: String(error) }), }), + releaseHolds, ]); } } - return { startTurn, followUp }; + return { startTurn, followUp, forget: (sessionId) => { fileVersionsBySession.delete(sessionId); } }; } async function cleanupTurn(actions: Array<() => unknown>): Promise { diff --git a/packages/ui-backend-claude/tests/backend.test.ts b/packages/ui-backend-claude/tests/backend.test.ts index dfc4a8ca6a..3a8eb6611a 100644 --- a/packages/ui-backend-claude/tests/backend.test.ts +++ b/packages/ui-backend-claude/tests/backend.test.ts @@ -304,6 +304,7 @@ describe("createClaudeBackend identity + profiles", () => { costReporting: true, concurrentSessions: true, followUp: true, + historyRemoval: true, }); }); diff --git a/packages/ui-backend-claude/tests/native-history-removal.test.ts b/packages/ui-backend-claude/tests/native-history-removal.test.ts new file mode 100644 index 0000000000..0e3b97e5a7 --- /dev/null +++ b/packages/ui-backend-claude/tests/native-history-removal.test.ts @@ -0,0 +1,212 @@ +/** + * Explicit removal of a retired chat's native Claude history (#3229), through + * the installed Agent SDK's own listing and reading against isolated synthetic + * Odysseus files. No live store, provider or network. + */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { getSessionMessages, listSessions } from "@anthropic-ai/claude-agent-sdk"; +import { BackendRequestError, type AgentBackend, type StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { nativeObservationIdentity, sessionPromptContextLocation, sessionReplayLocation } from "@schlessera/brain-ui-sdk/internal"; +import { createClaudeBackend } from "../src/backend.js"; +import { restoreArchivedSession, transcriptPaths } from "../src/transcript-archive.js"; + +const MARKER = "Odysseus hid the oar under the olive root"; +const CONTROL = "Penelope kept the loom unfinished"; +const TARGET = "0d755e05-1111-4111-8111-111111111111"; +const OTHER = "9e7e10e0-2222-4222-8222-222222222222"; +const ARCHIVED = "4c1e0a11-3333-4333-8333-333333333333"; +let root: string, brain: string, config: string, live: string, archive: string, previous: string | undefined; + +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), "odysseus-native-removal-"))); + brain = join(root, "ithaca"); config = join(root, "claude-config"); mkdirSync(brain); mkdirSync(config); + previous = process.env.CLAUDE_CONFIG_DIR; process.env.CLAUDE_CONFIG_DIR = config; + ({ live, archive } = transcriptPaths(brain, { CLAUDE_CONFIG_DIR: config })); + mkdirSync(live, { recursive: true }); mkdirSync(archive, { recursive: true }); +}); +afterEach(() => { + if (previous === undefined) delete process.env.CLAUDE_CONFIG_DIR; else process.env.CLAUDE_CONFIG_DIR = previous; + rmSync(root, { recursive: true, force: true }); +}); + +function transcript(id: string, text: string): string { + const base = { sessionId: id, cwd: brain, version: "2.1.0", userType: "external", isSidechain: false, gitBranch: "" }; + const user = crypto.randomUUID(), answer = crypto.randomUUID(); + return [ + { ...base, type: "user", uuid: user, parentUuid: null, timestamp: "2026-07-12T10:00:00.000Z", message: { role: "user", content: `Where is the oar? ${text}` } }, + { ...base, type: "assistant", uuid: answer, parentUuid: user, timestamp: "2026-07-12T10:00:01.000Z", + message: { id: `msg_${answer}`, type: "message", role: "assistant", model: "claude", content: [{ type: "text", text }], stop_reason: "end_turn", usage: { input_tokens: 1, output_tokens: 1 } } }, + ].map(line => JSON.stringify(line)).join("\n") + "\n"; +} +function metadata(id: string, text: string) { + const replay = sessionReplayLocation(config, brain, id), prompt = sessionPromptContextLocation(config, brain, id); + mkdirSync(replay.dir, { recursive: true }); mkdirSync(prompt.dir, { recursive: true }); + writeFileSync(join(replay.dir, replay.name), JSON.stringify({ texts: {}, receipts: { r: { id: "r", name: "brain_add", input: { text }, output: text, isError: false } } })); + writeFileSync(join(prompt.dir, prompt.name), JSON.stringify({ append: text, delivered: {}, turns: { t: { original: text, wireDigest: "0", facts: {} } } })); + const observations = join(archive, "native-observations"); mkdirSync(observations, { recursive: true }); + writeFileSync(join(observations, `${nativeObservationIdentity(brain, id)}.json`), JSON.stringify({ schema: 1, identity: text, incomplete: false, observed: [] })); +} +/** The target in every owned shape: live, subordinate, archived, staged, conflict, index, display, prompt, observations. */ +function archived(id: string, text: string) { + mkdirSync(join(archive, id)); writeFileSync(join(archive, id, `${id}.jsonl.gz`), Bun.gzipSync(new TextEncoder().encode(text))); + writeFileSync(join(archive, id, "manifest.json"), JSON.stringify({ session: { id, title: text, createdAt: 1, lastActiveAt: 1 }, files: [] })); +} +function seed() { + writeFileSync(join(live, `${TARGET}.jsonl`), transcript(TARGET, MARKER)); + mkdirSync(join(live, TARGET, "subagents"), { recursive: true }); + writeFileSync(join(live, TARGET, "subagents", "agent-telemachus.jsonl"), MARKER); + archived(TARGET, MARKER); + mkdirSync(join(archive, `.pending-${TARGET}-stage`)); writeFileSync(join(archive, `.pending-${TARGET}-stage`, "a.gz"), Bun.gzipSync(new TextEncoder().encode(MARKER))); + mkdirSync(join(archive, `.conflict-${TARGET}-1783850400000`)); writeFileSync(join(archive, `.conflict-${TARGET}-1783850400000`, "manifest.json"), MARKER); + // An unrelated archived chat shares the index. + archived(ARCHIVED, CONTROL); + writeFileSync(join(archive, "index.json"), JSON.stringify([{ id: TARGET, title: MARKER, createdAt: 1, lastActiveAt: 1 }, { id: ARCHIVED, title: CONTROL, createdAt: 1, lastActiveAt: 1 }])); + metadata(TARGET, MARKER); + const replay = sessionReplayLocation(config, brain, TARGET); + writeFileSync(join(replay.dir, `${replay.name}.crashed.tmp`), MARKER); + // The unrelated control chat, including a conflict copy whose name only resembles the target's. + writeFileSync(join(live, `${OTHER}.jsonl`), transcript(OTHER, CONTROL)); + mkdirSync(join(archive, `.conflict-${OTHER}-1`)); writeFileSync(join(archive, `.conflict-${OTHER}-1`, "manifest.json"), CONTROL); + metadata(OTHER, CONTROL); +} +/** Every byte under the config tree, gzip copies included. */ +function stored(path = config): string { + if (!existsSync(path)) return ""; + const info = lstatSync(path); + if (info.isSymbolicLink()) return ""; + if (info.isDirectory()) return readdirSync(path).map(name => stored(join(path, name))).join("\n"); + const bytes = readFileSync(path); + return path.endsWith(".gz") ? new TextDecoder().decode(Bun.gunzipSync(bytes)) : bytes.toString("utf8"); +} +const text = (history: Awaited>) => JSON.stringify(history); +function resume(backend: AgentBackend, sessionId: string): Promise { + return backend.startTurn({ prompt: "Continue the voyage", sessionId, signal: new AbortController().signal, + bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "deny", message: "no" }) } } as unknown as StartTurnRequest); +} +function gate() { + let open!: () => void, entered!: () => void; + const released = new Promise(resolve => { open = resolve; }), reached = new Promise(resolve => { entered = resolve; }); + return { open, entered, released, reached }; +} + +test("removes every owned artifact through the installed SDK and keeps the unrelated chat", async () => { + seed(); + const backend = createClaudeBackend({ brainPath: brain }); + expect(backend.capabilities.historyRemoval).toBe(true); + expect((await backend.listSessions()).map(session => session.id).sort()).toEqual([TARGET, OTHER, ARCHIVED].sort()); + expect(text(await backend.getHistory(TARGET))).toContain(MARKER); + expect(stored()).toContain(MARKER); + + expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET })).toEqual({ outcome: "removed" }); + + expect(stored(), "NO_OWNED_MARKER_REMAINS").not.toContain(MARKER); + expect((await listSessions({ dir: brain })).map(session => session.sessionId)).toEqual([OTHER]); + expect(await getSessionMessages(TARGET, { dir: brain })).toEqual([]); + expect((await backend.listSessions()).map(session => session.id).sort()).toEqual([OTHER, ARCHIVED].sort()); + expect(await backend.getHistory(TARGET)).toEqual([]); + expect(resume(backend, TARGET)).rejects.toBeInstanceOf(BackendRequestError); + // The tombstone is content-free: only the operation identity. + expect(readFileSync(join(archive, "retired", TARGET), "utf8")).toBe("retire-voyage"); + // The control chat is untouched and readable. + expect(text(await backend.getHistory(OTHER))).toContain(CONTROL); + expect(JSON.parse(readFileSync(join(archive, "index.json"), "utf8"))).toEqual([{ id: ARCHIVED, title: CONTROL, createdAt: 1, lastActiveAt: 1 }]); + expect(readFileSync(join(archive, `.conflict-${OTHER}-1`, "manifest.json"), "utf8")).toBe(CONTROL); + expect(stored()).toContain(CONTROL); + // Repeating the same operation is idempotent; another operation never re-owns the session. + expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET })).toEqual({ outcome: "removed" }); + expect(backend.removeSessionHistory!({ operationId: "retire-again", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); +}); + +test("a reader started before retirement drains first and publishes nothing after it", async () => { + seed(); + const reading = gate(); + const backend = createClaudeBackend({ brainPath: brain, getSessionMessagesFn: (async (...args: Parameters) => { + const messages = await getSessionMessages(...args); + reading.entered(); await reading.released; + return messages; + }) as typeof getSessionMessages }); + const read = backend.getHistory(TARGET); + await reading.reached; + const removal = backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET }); + // Fenced at once: a new reader, lister and resume see an unknown chat while removal waits. + expect(await backend.getHistory(TARGET)).toEqual([]); + expect((await backend.listSessions()).map(session => session.id).sort()).toEqual([OTHER, ARCHIVED].sort()); + expect(resume(backend, TARGET)).rejects.toBeInstanceOf(BackendRequestError); + // A bounded caller wait is partial, and the removal keeps its single owner. + const deadline = new AbortController(); deadline.abort(); + expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET, signal: deadline.signal })).toEqual({ outcome: "partial" }); + expect(backend.removeSessionHistory!({ operationId: "replacement", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); + expect(stored(), "REMOVAL_WAITS_FOR_THE_READER").toContain(MARKER); + reading.open(); + expect(text(await read), "RETIRED_READ_PUBLISHES_NOTHING").not.toContain(MARKER); + expect(await removal).toEqual({ outcome: "removed" }); + expect(stored()).not.toContain(MARKER); +}); + +test("a restarted backend keeps the fence, refuses restored archives and finishes the same operation", async () => { + seed(); + const reading = gate(); + const first = createClaudeBackend({ brainPath: brain, getSessionMessagesFn: (async (...args: Parameters) => { + reading.entered(); await reading.released; return getSessionMessages(...args); + }) as typeof getSessionMessages }); + const firstRead = first.getHistory(TARGET); + await reading.reached; + const deadline = new AbortController(); deadline.abort(); + // The process stops while the reader holds the chat: only the tombstone is durable. + expect(await first.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET, signal: deadline.signal })).toEqual({ outcome: "partial" }); + // And a crash had already taken part of the content. + rmSync(join(live, TARGET), { recursive: true }); + + const restarted = createClaudeBackend({ brainPath: brain }); + expect((await restarted.listSessions()).map(session => session.id).sort()).toEqual([OTHER, ARCHIVED].sort()); + expect(await restarted.getHistory(TARGET)).toEqual([]); + // An old backup brings an archived copy back after retirement. + if (!existsSync(join(archive, TARGET))) archived(TARGET, MARKER); + restoreArchivedSession(TARGET, { brainPath: brain }); + expect(readFileSync(join(live, `${TARGET}.jsonl`), "utf8")).toContain(MARKER); + expect(existsSync(join(archive, TARGET)), "RETIRED_ARCHIVE_NOT_RESTORED").toBe(true); + expect(restarted.removeSessionHistory!({ operationId: "replacement", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); + expect(await restarted.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET })).toEqual({ outcome: "removed" }); + expect(stored()).not.toContain(MARKER); + // The stopped process's reader, if it ever resumed, still publishes nothing. + reading.open(); + expect(text(await firstRead)).not.toContain(MARKER); +}); + +test("links, hard links and redirected roots stay untouched and keep the removal partial", async () => { + seed(); + const penelope = join(root, "penelope-letters"); mkdirSync(penelope); + writeFileSync(join(penelope, "letter.txt"), CONTROL); + // A live transcript replaced by a link, a subordinate link and a hard-linked display file. + rmSync(join(live, `${TARGET}.jsonl`)); symlinkSync(join(penelope, "letter.txt"), join(live, `${TARGET}.jsonl`)); + symlinkSync(penelope, join(live, TARGET, "letters")); + const replay = sessionReplayLocation(config, brain, TARGET); + linkSync(join(replay.dir, replay.name), join(penelope, "copy.json")); + const backend = createClaudeBackend({ brainPath: brain }); + + expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET })).toEqual({ outcome: "partial" }); + expect(readFileSync(join(penelope, "letter.txt"), "utf8")).toBe(CONTROL); + expect(lstatSync(join(live, `${TARGET}.jsonl`)).isSymbolicLink()).toBe(true); + expect(existsSync(join(live, TARGET, "letters"))).toBe(true); + expect(lstatSync(join(replay.dir, replay.name)).nlink, "HARD_LINK_NOT_UNLINKED").toBe(2); + expect(readFileSync(join(penelope, "copy.json"), "utf8")).toContain(MARKER); + // Everything the chat solely owns was still removed, and it stays fenced. + expect(existsSync(join(archive, TARGET))).toBe(false); + expect((await backend.listSessions()).map(session => session.id).sort()).toEqual([OTHER, ARCHIVED].sort()); + // A client path is never a session identity. + expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: "../penelope-letters" })).rejects.toBeInstanceOf(BackendRequestError); + expect(existsSync(penelope)).toBe(true); +}); + +test("a redirected archive root refuses before any removal", async () => { + seed(); + const elsewhere = join(root, "elsewhere"); mkdirSync(elsewhere); writeFileSync(join(elsewhere, "kept.txt"), CONTROL); + rmSync(archive, { recursive: true }); symlinkSync(elsewhere, archive); + const backend = createClaudeBackend({ brainPath: brain }); + expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); + expect(readdirSync(elsewhere)).toEqual(["kept.txt"]); + expect(readFileSync(join(live, `${TARGET}.jsonl`), "utf8")).toContain(MARKER); +}); diff --git a/packages/ui-backend-pi/src/backend.ts b/packages/ui-backend-pi/src/backend.ts index 4461c82b34..951f4fc74c 100644 --- a/packages/ui-backend-pi/src/backend.ts +++ b/packages/ui-backend-pi/src/backend.ts @@ -14,7 +14,9 @@ * storage under the agent dir) — this backend does not manage keys. */ import { join } from "path"; -import { piSessionDirectory } from "./session-storage.js"; +import { isPiSessionId, piRetiredDirectory, piSessionDirectory, removePiSession } from "./session-storage.js"; +import { SessionManager } from "@earendil-works/pi-coding-agent"; +import { createSessionRetirement } from "@schlessera/brain-ui-sdk/internal"; import { PI_PIPE_MAX_BYTES } from "./worker-protocol.js"; import type { AgentBackend, @@ -71,6 +73,7 @@ const CAPABILITIES: BackendCapabilities = { // injected into the running turn via followUp() (native pi queue-within-turn). concurrentSessions: true, followUp: true, + historyRemoval: true, }; export function createPiBackend(options: CreatePiBackendOptions): AgentBackend { @@ -112,7 +115,9 @@ export function createPiBackend(options: CreatePiBackendOptions): AgentBackend { }); const runtime = createSessionRuntime({ backend: options, sessionDir, resources }); const pool = createSessionPool(runtime, Boolean(options.sessionFactory)); - const startTurn = createPiTurnRunner(pool, options); + // Explicit chat deletion (#3229): one durable fence for every native path. + const retirement = createSessionRetirement({ directory: () => piRetiredDirectory(sessionDir), validSessionId: isPiSessionId }); + const startTurn = createPiTurnRunner(pool, options, retirement); return { id: PI_BACKEND_ID, @@ -129,12 +134,13 @@ export function createPiBackend(options: CreatePiBackendOptions): AgentBackend { return { autoAllowed, enforceAllowedTools: req.enforceAllowedTools, available: (req.noGrantSurface || req.autonomous) ? autoAllowed : Object.keys(names) as (keyof typeof names)[], lock: { withLock: (key, fn, admission) => lock.withKey(key, fn, admission) } }; }, // Only the worker path has a host inference relay to prove a recipient (#2695). - ...(!options.sessionFactory ? { inferenceOrigin: (req: { profileId?: string; sessionId?: string }) => piInferenceOrigin(options, sessionDir, req) } : {}), + ...(!options.sessionFactory ? { inferenceOrigin: async (req: { profileId?: string; sessionId?: string }) => + req.sessionId !== undefined && retirement.isRetired(req.sessionId) ? undefined : piInferenceOrigin(options, sessionDir, req) } : {}), startTurn, async followUp(req: FollowUpRequest): Promise { // Follow-up only lands in a RUNNING turn; the host queues it as the // session's next turn otherwise. - const entry = pool.sessions.get(req.sessionId); + const entry = retirement.isRetired(req.sessionId) ? undefined : pool.sessions.get(req.sessionId); if (!entry || !entry.running) { throw new BackendRequestError( `No running turn for session ${req.sessionId} to deliver a follow-up to.` @@ -152,10 +158,23 @@ export function createPiBackend(options: CreatePiBackendOptions): AgentBackend { }, storageRoots() { return [{ kind: "transcripts", path: sessionDir }]; }, listSessions(): Promise { - return listPiSessions(brainPath, sessionDir); + return listPiSessions(brainPath, sessionDir, retirement); }, getHistory(sessionId: string): Promise { - return getPiHistory(brainPath, sessionId, sessionDir); + return getPiHistory(brainPath, sessionId, sessionDir, retirement); + }, + removeSessionHistory(req) { + return retirement.remove(req, { + // Every turn has drained: a resident session is idle, so its runtime copy goes too. + release(id) { + const entry = pool.sessions.get(id); + if (entry) { pool.sessions.delete(id); try { entry.session.dispose(); } catch { /* Best effort, as eviction. */ } } + runtime.forget?.(id); + }, + remove: (id) => removePiSession(sessionDir, brainPath, id), + // The installed SessionManager's own listing is the last word. + stillListed: async (id) => (await SessionManager.list(brainPath, sessionDir)).some(info => info.id === id), + }); }, }; } diff --git a/packages/ui-backend-pi/src/history.ts b/packages/ui-backend-pi/src/history.ts index d6b30155f6..c2c1599700 100644 --- a/packages/ui-backend-pi/src/history.ts +++ b/packages/ui-backend-pi/src/history.ts @@ -32,14 +32,18 @@ import type { } from "@schlessera/brain-ui-sdk/server"; import { failureFromPiError } from "./turn-failure.js"; +import { isPiSessionId } from "./session-storage.js"; +import type { SessionRetirement } from "@schlessera/brain-ui-sdk/internal"; /** List the pi sessions rooted at this brain repo, newest activity first. */ export async function listPiSessions( cwd: string, - sessionDir?: string + sessionDir?: string, + retirement?: Pick ): Promise { const infos = await SessionManager.list(cwd, sessionDir); - const sessions = infos.map((info) => ({ + // After the await: a session retired while pi listed is not listed (#3229). + const sessions = infos.filter(info => !retirement?.isRetired(info.id)).map((info) => ({ id: info.id, title: info.name ?? firstLine(info.firstMessage) ?? null, createdAt: info.created.getTime(), @@ -60,8 +64,20 @@ export async function listPiSessions( export async function getPiHistory( cwd: string, sessionId: string, - sessionDir?: string + sessionDir?: string, + retirement?: Pick ): Promise { + // A retired chat reads as an unknown one (#3229). A removal waits for this + // read, which never publishes what it found once the chat is retired. + if (retirement?.isRetired(sessionId)) return []; + const release = retirement && isPiSessionId(sessionId) ? retirement.hold(sessionId) : undefined; + try { + const history = await readPiHistory(cwd, sessionId, sessionDir); + return retirement?.isRetired(sessionId) ? [] : history; + } finally { release?.(); } +} + +async function readPiHistory(cwd: string, sessionId: string, sessionDir?: string): Promise { const infos = await SessionManager.list(cwd, sessionDir); const info = infos.find((i) => i.id === sessionId); if (!info && !sessionDir) return []; diff --git a/packages/ui-backend-pi/src/session-runtime.ts b/packages/ui-backend-pi/src/session-runtime.ts index c3535ea3ee..8ea99642b9 100644 --- a/packages/ui-backend-pi/src/session-runtime.ts +++ b/packages/ui-backend-pi/src/session-runtime.ts @@ -9,6 +9,8 @@ import { resolveModelSpec } from "./profiles.js"; export interface SessionRuntime { newSession(profileId: string | undefined, env: SessionEnv): Promise<{ session: PiSessionLike; turnContext: TurnContext }>; openSession(sessionId: string, env: SessionEnv): Promise<{ session: PiSessionLike; turnContext: TurnContext }>; + /** Drop a retired session's in-memory observation cache once its turns drained (#3229). */ + forget?(sessionId: string): void; } export function createSessionRuntime(options: { @@ -34,5 +36,6 @@ export function createSessionRuntime(options: { return { newSession: (profileId, env) => acquire(env, profileId), openSession: (sessionId, env) => acquire(env, undefined, sessionId), + forget: (sessionId) => { nativeFileVersions.delete(sessionId); }, }; } diff --git a/packages/ui-backend-pi/src/session-storage.ts b/packages/ui-backend-pi/src/session-storage.ts index e313887583..86a836a145 100644 --- a/packages/ui-backend-pi/src/session-storage.ts +++ b/packages/ui-backend-pi/src/session-storage.ts @@ -1,8 +1,10 @@ -import { constants, closeSync, fstatSync, ftruncateSync, mkdirSync, openSync, readFileSync, realpathSync, writeFileSync, writeSync } from "node:fs"; +import { constants, closeSync, existsSync, fstatSync, ftruncateSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, writeFileSync, writeSync } from "node:fs"; import { homedir } from "node:os"; import { join, resolve, relative, sep } from "node:path"; import { createHash } from "node:crypto"; import { BackendRequestError } from "@schlessera/brain-ui-sdk/server"; +import type { SessionHistoryRemovalOutcome } from "@schlessera/brain-ui-sdk/server"; +import { combineRemovalOutcomes, nativeObservationIdentity, ownedNames, removeMetadataFile, removeOwnedArtifact, sessionPromptContextLocation, sessionReplayLocation } from "@schlessera/brain-ui-sdk/internal"; /** Server-owned state is never mounted writable into a worker. */ export function piSessionDirectory(brainPath: string, configured?: string): string { @@ -68,3 +70,48 @@ export function syncPiAuth(dir: string, original: string | undefined, content: s ftruncateSync(fd, Buffer.byteLength(content)); } finally { closeSync(fd); } } + +/** Server-minted Pi session identities, the only ones a removal or tombstone names. */ +export const isPiSessionId = (id: string) => /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(id); +/** Content-free tombstones of explicitly retired sessions (#3229); permanent. */ +export const piRetiredDirectory = (sessionDir: string) => join(sessionDir, "retired"); + +const HEADER_BYTES = 64 * 1024; +/** The session header of one plain, single-name transcript file, or undefined. */ +function header(path: string): { type?: unknown; id?: unknown; cwd?: unknown } | undefined { + let fd: number; + try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } catch { return undefined; } + try { + const stat = fstatSync(fd); + if (!stat.isFile() || stat.nlink !== 1) return undefined; + const buffer = Buffer.alloc(HEADER_BYTES), count = readSync(fd, buffer, 0, HEADER_BYTES, 0); + const line = buffer.subarray(0, count).toString("utf8").split("\n")[0]; + try { return JSON.parse(line!); } catch { return undefined; } + } finally { closeSync(fd); } +} + +/** + * Remove every artifact this backend owns for one retired session (#3229): + * the whole SessionManager tree (every branch, under its canonical name and + * any older SDK-managed name whose header names it in this brain), display + * and prompt metadata and file observations. A transcript is attributed by + * its own header, never by a matching name alone: a canonical name whose + * header is missing or names another session is left in place, partial. + */ +export function removePiSession(sessionDir: string, brainPath: string, id: string): SessionHistoryRemovalOutcome { + if (!isPiSessionId(id)) throw new BackendRequestError("Invalid server session identity"); + const outcomes: SessionHistoryRemovalOutcome[] = []; + for (const name of ownedNames(sessionDir, name => name.endsWith(".jsonl"))) { + const canonical = name === `${id}.jsonl`, found = header(join(sessionDir, name)); + const ours = found?.type === "session" && found.id === id; + if (ours && found.cwd === brainPath) outcomes.push(removeOwnedArtifact(sessionDir, name)); + else if (canonical) outcomes.push("partial"); + } + if (!existsSync(brainPath)) return combineRemovalOutcomes([...outcomes, "unknown"]); + const brain = realpathSync(brainPath); + outcomes.push( + removeMetadataFile({ dir: join(sessionDir, "native-observations"), name: `${nativeObservationIdentity(brain, id)}.json` }), + removeMetadataFile(sessionReplayLocation(sessionDir, brainPath, id)), + removeMetadataFile(sessionPromptContextLocation(sessionDir, brainPath, id))); + return combineRemovalOutcomes(outcomes); +} diff --git a/packages/ui-backend-pi/src/turn-runner.ts b/packages/ui-backend-pi/src/turn-runner.ts index 1b3a97332f..a4868786f1 100644 --- a/packages/ui-backend-pi/src/turn-runner.ts +++ b/packages/ui-backend-pi/src/turn-runner.ts @@ -9,6 +9,7 @@ import type { } from "@schlessera/brain-ui-sdk/server"; import { assertTurnPosture, BackendRequestError } from "@schlessera/brain-ui-sdk/server"; import { WorkerResourceLimitError } from "@schlessera/brain-ui-sdk/internal"; +import type { SessionRetirement } from "@schlessera/brain-ui-sdk/internal"; import { FIRST_PARTY_FAILURE_CLASSES } from "@schlessera/brain-ui-sdk/protocol"; import { resolveThinkingLevel } from "@schlessera/brain-ui-sdk/server"; import type { CreatePiBackendOptions } from "./backend-options.js"; @@ -34,9 +35,19 @@ const BACKEND_ID = "pi"; export function createPiTurnRunner( pool: SessionPool, - options: CreatePiBackendOptions + options: CreatePiBackendOptions, + retirement?: Pick ): (req: StartTurnRequest) => Promise { + // Explicit chat deletion (#3229): a retired chat refuses resume as an unknown + // one, and a removal waits until this turn's last native write has landed. return async function startTurn(req: StartTurnRequest): Promise { + const holds: Array<() => void> = []; + if (req.sessionId !== undefined && retirement) holds.push(retirement.hold(req.sessionId)); + try { await runTurn(req, (sessionId) => { if (retirement && sessionId !== req.sessionId) holds.push(retirement.hold(sessionId)); }); } + finally { for (const release of holds.splice(0)) release(); } + }; + + async function runTurn(req: StartTurnRequest, holdSession: (sessionId: string) => void): Promise { const startedAt = Date.now(); // pi has none of the runtime shortcuts the pairing guards against, but the // declaration is refused here too so it means the same on both backends. @@ -74,6 +85,8 @@ export function createPiTurnRunner( const { entry, isNew } = acquired; const { session, turnContext } = entry; const sessionId = session.sessionId; + try { holdSession(sessionId); } + catch (error) { pool.finish(entry); throw error; } // Scope every frame this turn emits to its session so a multiplexed client // can demux concurrent sessions. Follow-up frames flow through this same // emit (the subscription below stays live for the whole turn). @@ -270,7 +283,7 @@ export function createPiTurnRunner( isError: failed, ...(failure ? { failure } : {}), }); - }; + } } /** diff --git a/packages/ui-backend-pi/tests/backend.test.ts b/packages/ui-backend-pi/tests/backend.test.ts index 0d2a6ce7bc..2f15d4cbb8 100644 --- a/packages/ui-backend-pi/tests/backend.test.ts +++ b/packages/ui-backend-pi/tests/backend.test.ts @@ -24,6 +24,7 @@ describe("createPiBackend (no LLM)", () => { costReporting: true, concurrentSessions: true, followUp: true, + historyRemoval: true, }); } finally { brain.cleanup(); diff --git a/packages/ui-backend-pi/tests/native-history-removal.test.ts b/packages/ui-backend-pi/tests/native-history-removal.test.ts new file mode 100644 index 0000000000..b0d4a40d85 --- /dev/null +++ b/packages/ui-backend-pi/tests/native-history-removal.test.ts @@ -0,0 +1,153 @@ +/** + * Explicit removal of a retired chat's native Pi history (#3229), through the + * installed SessionManager's own listing and reading against isolated + * synthetic Odysseus files. No live store, provider or network. + */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { SessionManager, type AgentSessionEvent } from "@earendil-works/pi-coding-agent"; +import { BackendRequestError, type AgentBackend, type StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { nativeObservationIdentity, sessionPromptContextLocation, sessionReplayLocation } from "@schlessera/brain-ui-sdk/internal"; +import { createPiBackend, type PiSessionLike } from "../src/backend.js"; +import { savePiSession } from "../src/session-storage.js"; + +const MARKER = "Odysseus hid the oar under the olive root"; +const BRANCH = "Odysseus first tried the cave of the winds"; +const CONTROL = "Penelope kept the loom unfinished"; +let root: string, brain: string, sessionDir: string; + +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), "odysseus-pi-removal-"))); + brain = join(root, "ithaca"); sessionDir = join(root, "pi-sessions"); mkdirSync(brain); mkdirSync(sessionDir); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const usage = { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }; +const answer = (text: string, timestamp: number) => ({ role: "assistant", content: [{ type: "text", text }], api: "anthropic-messages", + provider: "anthropic", model: "m", usage, stopReason: "stop", timestamp }) as never; +/** A SessionManager tree under the SDK's own file name, with an inactive branch. */ +function tree(text: string, inactive?: string): string { + const manager = SessionManager.create(brain, sessionDir); + const user = manager.appendMessage({ role: "user", content: `Where is the oar? ${text}`, timestamp: 1 } as never); + if (inactive) { manager.appendMessage(answer(inactive, 2)); manager.branch(user); } + manager.appendMessage(answer(text, 3)); + return manager.getSessionId(); +} +function metadata(id: string, text: string) { + const replay = sessionReplayLocation(sessionDir, brain, id), prompt = sessionPromptContextLocation(sessionDir, brain, id); + mkdirSync(replay.dir, { recursive: true }); mkdirSync(prompt.dir, { recursive: true }); + writeFileSync(join(replay.dir, replay.name), JSON.stringify({ texts: {}, receipts: { r: { id: "r", name: "brain_add", input: { text }, output: text, isError: false } } })); + writeFileSync(join(prompt.dir, `${prompt.name}`), JSON.stringify({ append: text, delivered: {}, turns: {} })); + writeFileSync(join(prompt.dir, `${prompt.name}.crashed.tmp`), text); + const observations = join(sessionDir, "native-observations"); mkdirSync(observations, { recursive: true }); + writeFileSync(join(observations, `${nativeObservationIdentity(brain, id)}.json`), JSON.stringify({ schema: 1, identity: text, incomplete: false, observed: [] })); +} +function seed() { + const target = tree(MARKER, BRANCH), control = tree(CONTROL); + // The canonical server-owned copy of the same tree, as a later turn writes it. + const legacy = readdirSync(sessionDir).find(name => name.endsWith(`_${target}.jsonl`))!; + savePiSession(sessionDir, target, readFileSync(join(sessionDir, legacy), "utf8").trim().split("\n").map(line => JSON.parse(line))); + metadata(target, MARKER); metadata(control, CONTROL); + return { target, control }; +} +function stored(path = sessionDir): string { + if (!existsSync(path)) return ""; + const info = lstatSync(path); + if (info.isDirectory()) return readdirSync(path).map(name => stored(join(path, name))).join("\n"); + return info.isFile() ? readFileSync(path, "utf8") : ""; +} +const text = (history: Awaited>) => JSON.stringify(history); +const bridge = { emit: () => {}, requestPermission: async () => ({ behavior: "deny" as const, message: "no" }) }; +function resume(backend: AgentBackend, sessionId: string): Promise { + return backend.startTurn({ prompt: "Continue the voyage", sessionId, signal: new AbortController().signal, bridge } as unknown as StartTurnRequest); +} + +test("removes the whole session tree and its metadata through the installed SessionManager", async () => { + const { target, control } = seed(); + const backend = createPiBackend({ brainPath: brain, sessionDir }); + expect(backend.capabilities.historyRemoval).toBe(true); + // Both the SDK-named and the canonical copy of the target are listed. + expect([...new Set((await backend.listSessions()).map(session => session.id))].sort()).toEqual([target, control].sort()); + expect(text(await backend.getHistory(target))).toContain(MARKER); + // The inactive branch is not rendered, but it is stored. + expect(text(await backend.getHistory(target))).not.toContain(BRANCH); + expect(stored()).toContain(BRANCH); + + expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: target })).toEqual({ outcome: "removed" }); + + const after = stored(); + expect(after, "NO_OWNED_MARKER_REMAINS").not.toContain(MARKER); + expect(after, "NO_INACTIVE_BRANCH_REMAINS").not.toContain(BRANCH); + expect((await SessionManager.list(brain, sessionDir)).map(info => info.id)).toEqual([control]); + expect((await backend.listSessions()).map(session => session.id)).toEqual([control]); + expect(await backend.getHistory(target)).toEqual([]); + expect(resume(backend, target)).rejects.toBeInstanceOf(BackendRequestError); + expect(readFileSync(join(sessionDir, "retired", target), "utf8")).toBe("retire-voyage"); + expect(text(await backend.getHistory(control))).toContain(CONTROL); + expect(after).toContain(CONTROL); + + // A restarted backend keeps the fence, even against a transcript an old backup brings back. + const restarted = createPiBackend({ brainPath: brain, sessionDir }); + savePiSession(sessionDir, target, [{ type: "session", version: 3, id: target, timestamp: "2026-07-12T10:00:00.000Z", cwd: brain }, + { type: "message", id: "a1b2c3d4", parentId: null, timestamp: "2026-07-12T10:00:01.000Z", message: { role: "user", content: MARKER, timestamp: 1 } }]); + expect((await restarted.listSessions()).map(session => session.id)).toEqual([control]); + expect(await restarted.getHistory(target)).toEqual([]); + expect(restarted.removeSessionHistory!({ operationId: "replacement", sessionId: target })).rejects.toBeInstanceOf(BackendRequestError); + expect(await restarted.removeSessionHistory!({ operationId: "retire-voyage", sessionId: target })).toEqual({ outcome: "removed" }); + expect(stored()).not.toContain(MARKER); +}); + +test("a transcript is attributed by its header, and links stay untouched", async () => { + const { target, control } = seed(); + // The canonical name now holds another chat's tree: replaced, not owned. + const controlFile = readdirSync(sessionDir).find(name => name.endsWith(`_${control}.jsonl`))!; + rmSync(join(sessionDir, `${target}.jsonl`)); + writeFileSync(join(sessionDir, `${target}.jsonl`), readFileSync(join(sessionDir, controlFile))); + // And the display file has a second name elsewhere. + const penelope = join(root, "penelope-letters"); mkdirSync(penelope); + const replay = sessionReplayLocation(sessionDir, brain, target); + linkSync(join(replay.dir, replay.name), join(penelope, "copy.json")); + const backend = createPiBackend({ brainPath: brain, sessionDir }); + + expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: target })).toEqual({ outcome: "partial" }); + expect(readFileSync(join(sessionDir, `${target}.jsonl`), "utf8"), "REPLACED_FILE_NOT_DELETED").toContain(CONTROL); + expect(lstatSync(join(replay.dir, replay.name)).nlink, "HARD_LINK_NOT_UNLINKED").toBe(2); + // The tree its header attributes to the target is gone; the control chat is intact. + expect(readdirSync(sessionDir).some(name => name.endsWith(`_${target}.jsonl`))).toBe(false); + expect(readFileSync(join(sessionDir, controlFile), "utf8")).toContain(CONTROL); + expect(text(await backend.getHistory(control))).toContain(CONTROL); + expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: "../penelope-letters" })).rejects.toBeInstanceOf(BackendRequestError); + expect(existsSync(penelope)).toBe(true); +}); + +test("a running turn drains before removal and its resident session is disposed", async () => { + const { target } = seed(); + let finish!: () => void, disposed = false; + const listeners = new Set<(event: AgentSessionEvent) => void>(); + const session: PiSessionLike = { + sessionId: target, + subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, + prompt: () => new Promise(resolve => { finish = resolve; }), + async abort() { finish?.(); }, + getSessionStats: () => ({ cost: 0 }), + dispose() { disposed = true; }, + }; + const backend = createPiBackend({ brainPath: brain, sessionDir, sessionFactory: { + newSession: async () => session, openSession: async () => session } }); + const turn = resume(backend, target); + while (!finish) await Bun.sleep(1); + const removal = backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: target }); + const deadline = new AbortController(); deadline.abort(); + expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: target, signal: deadline.signal })).toEqual({ outcome: "partial" }); + expect(backend.removeSessionHistory!({ operationId: "replacement", sessionId: target })).rejects.toBeInstanceOf(BackendRequestError); + // Fenced at once: follow-up and resume refuse while the turn still holds the session. + expect(backend.followUp!({ sessionId: target, prompt: "And the bow?" })).rejects.toBeInstanceOf(BackendRequestError); + expect(stored(), "REMOVAL_WAITS_FOR_THE_TURN").toContain(MARKER); + finish(); await turn; + expect(await removal).toEqual({ outcome: "removed" }); + expect(disposed, "RESIDENT_SESSION_DISPOSED").toBe(true); + expect(stored()).not.toContain(MARKER); + expect(resume(backend, target)).rejects.toBeInstanceOf(BackendRequestError); +}); From 65746591f4d3a94b95f1369fc2982db28edc7ec1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 15:51:28 +0000 Subject: [PATCH 3/5] feat(ui-server): record native removal under the chat retirement `removableBackendIds` selects the retirement's removable backends from the capability and the method together, and `removeRetiredNativeHistory` asks the chat's backend to remove each retired session under the retirement's own operation, recording the native store's combined outcome (#3229). A missing or unsupported backend, a rejection or an elapsed wait never completes the store. Co-Authored-By: Claude Opus 5.5 --- .../src/ws/native-history-removal.ts | 48 ++++++++++ .../tests/native-history-removal.test.ts | 87 +++++++++++++++++++ 2 files changed, 135 insertions(+) create mode 100644 packages/ui-server/src/ws/native-history-removal.ts create mode 100644 packages/ui-server/tests/native-history-removal.test.ts diff --git a/packages/ui-server/src/ws/native-history-removal.ts b/packages/ui-server/src/ws/native-history-removal.ts new file mode 100644 index 0000000000..bcab65a7b6 --- /dev/null +++ b/packages/ui-server/src/ws/native-history-removal.ts @@ -0,0 +1,48 @@ +/** + * The native store's part of an explicit chat deletion (#3229): which + * backends can remove native history at all, and how one retired chat's + * removal is reported under its retirement. The endpoint, the other stores + * and restart reconciliation coordinate these calls (#3230). + * Policy: docs/decisions/chat-history-deletion.md. + */ +import type { AgentBackend, SessionHistoryRemovalOutcome } from "@schlessera/brain-ui-sdk/server"; +import type { ChatRetirementStatus, RetireChatResult } from "./chat-lifecycle.js"; +import type { SessionCatalog } from "./session-catalog.js"; + +/** + * `RetireChatInput.removableBackends`: only a backend that both advertises + * and implements removal. A chat on any other backend refuses as + * `unsupported` before anything is retired. + */ +export function removableBackendIds(backends: Iterable>): string[] { + return [...backends].filter(backend => backend.capabilities.historyRemoval === true && typeof backend.removeSessionHistory === "function") + .map(backend => backend.id); +} + +/** + * Ask the chat's backend to remove each retired native session under the + * retirement's own operation, and record the native store's combined outcome. + * Removal is confirmed only when the backend confirms every session; a + * missing or unsupported backend, a rejection and an elapsed `signal` are not + * completion. Repeating it under the same retirement is the retry. + */ +export async function removeRetiredNativeHistory( + catalog: Pick, + backend: Pick | undefined, + retirement: Extract, + signal?: AbortSignal, +): Promise { + // A provisional chat never had a native store selected. + if (retirement.stores.native === undefined) return undefined; + if (!catalog.recordChatCleanup) throw new Error("This catalog cannot record chat cleanup"); + const outcomes: SessionHistoryRemovalOutcome[] = []; + const supported = backend && removableBackendIds([backend]).length === 1; + for (const sessionId of retirement.identities.sessions) { + if (!supported) { outcomes.push("partial"); continue; } + try { + outcomes.push((await backend!.removeSessionHistory!({ operationId: retirement.operationId, sessionId, ...(signal ? { signal } : {}) })).outcome); + } catch { outcomes.push("unknown"); } + } + const outcome = outcomes.includes("unknown") ? "unknown" : outcomes.every(value => value === "removed") ? "removed" : "partial"; + return catalog.recordChatCleanup(retirement.lifecycleId, "native", outcome); +} diff --git a/packages/ui-server/tests/native-history-removal.test.ts b/packages/ui-server/tests/native-history-removal.test.ts new file mode 100644 index 0000000000..47af84b436 --- /dev/null +++ b/packages/ui-server/tests/native-history-removal.test.ts @@ -0,0 +1,87 @@ +/** + * The native store's part of a chat deletion (#3229) against the actual + * file-backed retirement ledger. Backends here are minimal seam doubles: the + * concrete native removal is proven against the installed runtimes in the + * Claude and Pi backend packages. Synthetic Odysseus fixtures, no network. + */ +import { afterEach, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { AgentBackend, SessionHistoryRemovalOutcome, SessionHistoryRemovalRequest } from "@schlessera/brain-ui-sdk/server"; +import { createUiDb } from "../src/db/client.js"; +import { createPrincipal } from "../src/db/principals.js"; +import { openSqliteWriter } from "../src/db/write-worker.js"; +import { createOffloopActivityStore } from "../src/activity/store-writes.js"; +import { createSessionCatalog } from "../src/ws/session-catalog.js"; +import type { RetireChatInput, RetireChatResult } from "../src/ws/chat-lifecycle.js"; +import { removableBackendIds, removeRetiredNativeHistory } from "../src/ws/native-history-removal.js"; + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); + +type Seam = Pick; +const capabilities = { resume: true, permissions: true, thinking: true, attachments: true, askUser: true, costReporting: true, concurrentSessions: true, followUp: true }; +function backend(id: string, outcomes: Array, calls: SessionHistoryRemovalRequest[] = []): Seam { + return { id, capabilities: { ...capabilities, historyRemoval: true }, async removeSessionHistory(req) { + calls.push(req); + const next = outcomes.shift()!; + if (next instanceof Error) throw next; + return { outcome: next }; + } }; +} + +async function fixture(backendId: string) { + const root = mkdtempSync(join(tmpdir(), "odysseus-native-ledger-")); roots.push(root); + const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db); + const catalog = createSessionCatalog(() => db, undefined, undefined, { writer, pricing: { resolve: () => null }, store: createOffloopActivityStore(db, writer) }); + const owner = createPrincipal(db, { authMethod: "password", label: "Odysseus phone", ttlSeconds: 86_400 }).id; + catalog.persistSessionStub("voyage", "Plan the voyage home", null, backendId); + const opened = await catalog.dialogueOpen!({ conversationId: "ithaca", principalId: owner, epoch: 1, providerId: "gemini-live", sessionId: "voyage" }); + expect(opened.generation).toBe(1); + const request = (removableBackends: string[]): RetireChatInput => ({ operationId: "retire-voyage", principalId: owner, target: { sessionId: "voyage" }, + expected: { backendId, generation: 1 }, removableBackends, at: Date.now() }); + return { db, catalog, owner, request, async close() { await catalog.settled!(); await writer.close(); db.close(); } }; +} +const retired = (result: RetireChatResult) => { if (result.status !== "retired") throw new Error(`not retired: ${JSON.stringify(result)}`); return result; }; + +test("only a backend that advertises and implements removal is removable; any other refuses before retirement", async () => { + const advertisedOnly: Seam = { id: "pi", capabilities: { ...capabilities, historyRemoval: true } }; + const implementedOnly: Seam = { id: "legacy", capabilities, removeSessionHistory: async () => ({ outcome: "removed" }) }; + expect(removableBackendIds([backend("claude", []), advertisedOnly, implementedOnly])).toEqual(["claude"]); + const f = await fixture("pi"); + try { + expect(await f.catalog.retireChat!(f.request(removableBackendIds([backend("claude", []), advertisedOnly])), () => false), + "UNSUPPORTED_REFUSES_BEFORE_RETIREMENT").toEqual({ status: "refused", reason: "unsupported" }); + expect((f.db.query("SELECT COUNT(*) AS n FROM chat_lifecycles").get() as { n: number }).n).toBe(0); + } finally { await f.close(); } +}); + +test("the native store completes only when the backend confirms, and retries under the same operation", async () => { + const f = await fixture("claude"); + try { + const calls: SessionHistoryRemovalRequest[] = []; + const claude = backend("claude", ["partial", new Error("disk went away"), "removed"], calls); + const result = retired(await f.catalog.retireChat!(f.request(removableBackendIds([claude])), () => false)); + expect(result.stores.native).toBe("pending"); + expect(await removeRetiredNativeHistory(f.catalog, claude, result), "PARTIAL_IS_NOT_COMPLETE").toBe("partial"); + expect(retired((await f.catalog.chatRetirement!("retire-voyage", f.owner))!)).toMatchObject({ cleanup: "partial", stores: { native: "partial" } }); + expect(await removeRetiredNativeHistory(f.catalog, claude, result), "REJECTION_IS_UNKNOWN").toBe("unknown"); + // The backend confirmed native removal; the other stores are still pending under #3230. + expect(await removeRetiredNativeHistory(f.catalog, claude, result)).toBe("pending"); + expect(calls.map(call => [call.operationId, call.sessionId])).toEqual([["retire-voyage", "voyage"], ["retire-voyage", "voyage"], ["retire-voyage", "voyage"]]); + const stores = Object.fromEntries((f.db.query("SELECT store,outcome FROM chat_retirement_stores").all() as { store: string; outcome: string }[]).map(row => [row.store, row.outcome])); + expect(stores).toEqual({ native: "removed", dialogue: "pending", tasks: "pending", projections: "pending", drafts: "pending" }); + } finally { await f.close(); } +}); + +test("a backend that is missing or no longer supports removal never completes the native store", async () => { + const f = await fixture("claude"); + try { + const result = retired(await f.catalog.retireChat!(f.request(["claude"]), () => false)); + expect(await removeRetiredNativeHistory(f.catalog, undefined, result), "MISSING_BACKEND_IS_PARTIAL").toBe("partial"); + expect(await removeRetiredNativeHistory(f.catalog, { id: "claude", capabilities }, result), "UNSUPPORTED_BACKEND_IS_PARTIAL").toBe("partial"); + const native = f.db.query("SELECT outcome FROM chat_retirement_stores WHERE store='native'").get() as { outcome: string }; + expect(native.outcome).toBe("partial"); + } finally { await f.close(); } +}); From 8aa56ea06c5b625ea00b17378380234b3df320a5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 15:51:28 +0000 Subject: [PATCH 4/5] docs: re-anchor moved backend citations and record the built native removal Co-Authored-By: Claude Opus 5.5 --- docs/decisions/async-collaboration.md | 2 +- docs/decisions/claude-code-runtime.md | 2 +- docs/decisions/governed-writable-workers.md | 6 ++-- docs/decisions/hardening.md | 2 +- docs/decisions/live-conversation.md | 2 +- docs/decisions/policy-write-boundary.md | 6 ++-- docs/decisions/runtime-requirements.md | 2 +- docs/decisions/voice-permission.md | 2 +- .../live-conversation-investigation.md | 4 +-- .../plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 31 +++++++++++++------ docs/plans/storage-accounting.md | 4 +-- docs/plans/storage-lifecycle.md | 2 +- 14 files changed, 41 insertions(+), 28 deletions(-) diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index 15557b7d6b..c64fe6f6f7 100644 --- a/docs/decisions/async-collaboration.md +++ b/docs/decisions/async-collaboration.md @@ -71,7 +71,7 @@ requires one enforcement mechanism with different named memberships for voice and unattended work. Keep that requirement when implementing availability control. Existing mandatory backend conformance supports safe rejection of an unsupported restricted request; silently ignoring it is forbidden. The current -optional inputs are (`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:602`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:626`). These are permission primitives, +optional inputs are (`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:608`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:632`). These are permission primitives, not a claim of filesystem or network containment. The ordinary Claude assembly loads project settings and appends bridge tools diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 5cf4074f1a..855164e62d 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -1311,7 +1311,7 @@ profile's `baseUrl` from `BRAIN_UI_CLAUDE_PROFILES`, else the server's `ANTHROPIC_BASE_URL`, else first-party inference. The relay forwards to that route, keeping its base path. Before the prompt is sent, the runner refuses a route whose origin is neither first-party nor listed -(`const selectedUpstream`, `packages/ui-backend-claude/src/turn-runner.ts:430-445`). +(`const selectedUpstream`, `packages/ui-backend-claude/src/turn-runner.ts:441-456`). Each dispatch checks the same list again before the credential is read. Native settings may repeat the server's route, compared as a canonical origin and base path, but never replace it. A discovered profile never carries a route or a diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 80076ee763..d9cc2a6595 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1360,10 +1360,10 @@ also preserves the previous observation: it supplied no new bytes Claude keeps these observations in its backend-owned session map (`const fileVersionsBySession`, -`packages/ui-backend-claude/src/turn-runner.ts:105`). Pi keeps them in its +`packages/ui-backend-claude/src/turn-runner.ts:110`). Pi keeps them in its backend-owned session runtime across fresh per-turn workers (`const nativeFileVersions`, -`packages/ui-backend-pi/src/session-runtime.ts:19`); internal RPC reports +`packages/ui-backend-pi/src/session-runtime.ts:21`); internal RPC reports observation phases for the actual granted native operation, not a supplied hash or authority. Both also retain observations in host-private records and restore them before resumed native tools run. Claude keeps these records beside its transcript @@ -1373,7 +1373,7 @@ the canonical brain root and native session identity; filenames contain only a SHA-256 identity. Atomic replacement, file and directory fsync, private modes, regular-file validation and a 16 MiB per-session metadata bound protect the record (`saveNativeObservations`, -`packages/ui-sdk/src/server/native-observation-storage.ts:66-79`). +`packages/ui-sdk/src/server/native-observation-storage.ts:70-83`). Saves wait on the file system off the hosted server's event loop, land in call order, and complete before the tool they guard proceeds (#2416). diff --git a/docs/decisions/hardening.md b/docs/decisions/hardening.md index c25faf6198..9750e1e431 100644 --- a/docs/decisions/hardening.md +++ b/docs/decisions/hardening.md @@ -144,7 +144,7 @@ instead, and treat 8 as the question it was answering. releases.** Dispatcher, store and page splits (U33) ship in the 0.34.x train, never in the container release. Because U28 changes frame production (`adapter.adapt(msg)`, - `packages/ui-backend-claude/src/turn-runner.ts:690`) and U33 changes frame + `packages/ui-backend-claude/src/turn-runner.ts:703`) and U33 changes frame consumption (`handleServerMessage`, `packages/ui-react/src/connection.ts:336`), the same symptom could come from either, so they are **0.34.0** (seam) and **0.34.1** (splits), each its own diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index 2a4d862347..4e489d0125 100644 --- a/docs/decisions/live-conversation.md +++ b/docs/decisions/live-conversation.md @@ -30,7 +30,7 @@ tool admission and execution, permissions, cancellation, terminal state and resynchronization. Engine task requests are advisory until mapped to committed user input. No native search, code-execution or alternate permission loop is enabled. Both adapters can delegate through the existing `AgentBackend` -(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:708-751`); +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:750-804`); the host serializes work in a session and uses capability-checked follow-ups. The [voice-permission decision](voice-permission.md) binds this interface. diff --git a/docs/decisions/policy-write-boundary.md b/docs/decisions/policy-write-boundary.md index 3fe86900e3..95052f02cb 100644 --- a/docs/decisions/policy-write-boundary.md +++ b/docs/decisions/policy-write-boundary.md @@ -640,7 +640,7 @@ result is held until the worker has exited and its state has been copied out, and the state is checked again then. A `statfs` of the tmpfs with no whole page free at either point, or a write error the worker reported, names the turn `worker_state_exceeded` (`const unsaved`, -`packages/ui-backend-claude/src/turn-runner.ts:301-308`). A result, success or +`packages/ui-backend-claude/src/turn-runner.ts:312-319`). A result, success or error, becomes an error result with that class and keeps its usage, so the client never presents unsaved output as saved; what was written before the limit is persisted with the usual checks, and if that copy-out is refused the @@ -651,9 +651,9 @@ the worker prints after it, and a refusal is recognized by its class from any copy of the module. A host cancellation outranks it. Cancellation is checked again after worker settlement, so a buffered SDK success or error cannot replace an accepted cancellation while exit or copy-out is pending -(`releaseTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:312-330`). +(`releaseTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:323-341`). Generated terminals also await worker settlement before emission -(`emitTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:374-414`). +(`emitTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:385-425`). **Residual:** a turn that fills the tmpfs and frees space again between those two checks is named only if the runtime printed the write error. diff --git a/docs/decisions/runtime-requirements.md b/docs/decisions/runtime-requirements.md index d4b76be441..9fd8899e7e 100644 --- a/docs/decisions/runtime-requirements.md +++ b/docs/decisions/runtime-requirements.md @@ -281,7 +281,7 @@ reciprocal host-version negotiation is involved. | `probeBackendRuntimes` (`export async function probeBackendRuntimes`, `packages/ui-server/src/agent/backend.ts:394-444`) | Forward validated host requirements; retain active-backend selection and separate unmeasured-pair logging. | | `BackendModuleContext` / `BackendRuntimeReport` (`export interface BackendModuleContext`, `packages/ui-sdk/src/server/backend-module.ts:96-111`; `export interface BackendRuntimeReport`, `packages/ui-sdk/src/server/backend-module.ts:118-131`) | Extend the existing construction context for optional minimums. Keep report identities and `measured` meanings; a compatibility result must never occupy `measured.matches`. | | `MEASURED_RUNTIME`, its guard and `scripts/measure-claude-runtime.ts` | Keep the constant, exact pair guard, keyless behavior probe and dated measurement receipts. A permitted pair can still be unmeasured. | -| Turn `reportRuntime` / `init` (`const reportRuntime`, `packages/ui-backend-claude/src/turn-runner.ts:216-223`; `if (msg.type === "system"`, `packages/ui-backend-claude/src/turn-runner.ts:674-689`) | Preserve actual per-turn SDK/runtime observations, billing/permission guards and normal failure terminal behavior. | +| Turn `reportRuntime` / `init` (`const reportRuntime`, `packages/ui-backend-claude/src/turn-runner.ts:227-234`; `if (msg.type === "system"`, `packages/ui-backend-claude/src/turn-runner.ts:687-702`) | Preserve actual per-turn SDK/runtime observations, billing/permission guards and normal failure terminal behavior. | | Index schema and graph floors | Remain reader-specific integer schema checks; do not compare them as SemVer or turn `brain.db` into authoritative state. | No new compatibility HTTP status field is required for enforcement. Keep diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index c96791bcc1..3111320063 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -620,7 +620,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. **Closed, by #141 (`42a4d86`), which closed #124.** A turn now declares `StartTurnRequest.enforceAllowedTools` -(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:602`) +(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:608`) — the declaration this record asked for, by that name — and under it: - The input-rewrite hooks no longer grant. `createAgentHook` and `createRtkHook` diff --git a/docs/investigations/live-conversation-investigation.md b/docs/investigations/live-conversation-investigation.md index c7d41aedca..69dfc805e4 100644 --- a/docs/investigations/live-conversation-investigation.md +++ b/docs/investigations/live-conversation-investigation.md @@ -254,7 +254,7 @@ requestId)`; actual tool requests additionally use their existing `toolUseId`. Only committed original input supplies `StartTurnRequest.prompt`. The host selects the pinned existing backend/profile, cancellation signal and `BackendBridge`, and enforces the voice posture on new voice turns -(`export interface StartTurnRequest`, `packages/ui-sdk/src/server/backend.ts:513-610`). +(`export interface StartTurnRequest`, `packages/ui-sdk/src/server/backend.ts:519-616`). Do not feed approximate fragments or native task descriptions directly into execution. Keep raw outputs/private memory in the host and return only reviewed bounded facts needed by the voice service. @@ -263,7 +263,7 @@ Backend reuse is structurally feasible for **both** adapters. `startTurn` is already asynchronous and accepts a host AbortSignal. A busy same-session turn is queued; new committed details use `followUp` only when the backend advertises it, otherwise remain queued/reviewable -(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:708-751`). +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:750-804`). Continued voice interaction never requires unsafe concurrent `startTurn`s. This is source evidence and design mapping, not a real provider/backend trial. diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index b546783c15..bdaf19c5cf 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -248,7 +248,7 @@ Stated before the requirements because five of them derive from it. - R24. **Headless execution needs a new request shape.** `StartTurnRequest` is additive: `StartTurnRequest.autonomous` carries explicit persistence, origin, tool policy and prompt configuration alongside the required permission postures - (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:513-603`); ordinary Claude turns create an SDK session, emit + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:519-609`); ordinary Claude turns create an SDK session, emit `session_info`, and persists history by default. The installed SDK supports `persistSession: false`; pi provides `SessionManager.inMemory`. Drive this mode with a synthetic checkpoint bridge and server-selected authority; the diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 65939d5ea0..34ed5d5786 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -1189,7 +1189,7 @@ and a server-selected tool policy. **Files:** - Modify: `packages/ui-sdk/src/server/backend.ts` (the additive `StartTurnRequest.autonomous` mode carries persistence, origin, tool policy and prompt configuration — - (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:513-603`)) + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:519-609`)) - Modify: `packages/ui-backend-claude/src/backend.ts` (`persistSession: false`, synthetic bridge) - Modify: `packages/ui-server/src/activity/recorder.ts` (server-selected diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 78ff9c5144..8931d4daea 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -16,7 +16,20 @@ targets before retiring, and makes later dialogue/task writers and readers refuse the retired identities. It removes no content and reports every store pending until that store's owner confirms removal. A typed native-only chat with no recorded owner refuses as unknown ownership; no ownership is backfilled. -Native removal, host-copy cleanup, the endpoint and UI are not built. +Host-copy cleanup, the endpoint and UI are not built. + +**Built (#3229):** first-party native removal behind the optional +`historyRemoval` backend capability +([package contract](../integration-contract/package-api.md#native-history-removal-additive-3229)). +Claude (`removeClaudeSession`, `packages/ui-backend-claude/src/transcript-archive.ts:296-322`) +and Pi (`removePiSession`, `packages/ui-backend-pi/src/session-storage.ts:101-117`) +name their owned artifacts; the shared fence +(`createSessionRetirement`, `packages/ui-sdk/src/server/native-history-removal.ts:117-224`) +writes a content-free tombstone before anything is removed, drains turns and +readers, and reports `partial` for links, hard links, redirected roots and +replaced files instead of touching them. The host records the native store +under the retirement (`removeRetiredNativeHistory`, `packages/ui-server/src/ws/native-history-removal.ts:29-48`); coordinating it with the other stores and +restart reconciliation remains with the endpoint work. ## Selected local lifecycle @@ -81,7 +94,7 @@ and [operational recovery](../inbox-recovery.md) remain binding. There is no general delete operation: `createSessionRoutes` only lists/reads (`createSessionRoutes`, `packages/ui-server/src/routes/sessions.ts:8-147`). `AgentBackend` exposes native list/read and read-only storage roots, not deletion -(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:708-751`). A storage root +(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:750-804`). A storage root is not removal authority. Future supported package/HTTP/wire changes need their actual contract assessment and a CONTRACT commit; additive capability negotiation ships in a minor. The approved retention exception is recorded before runtime @@ -99,24 +112,24 @@ must be tested through their installed runtime, not inferred from directory name - **Native Claude history.** Live JSONL, per-session subordinate files, titles, archive manifests/index/staged or conflict copies can contain readable text. History reads can restore archived files before reading the SDK transcript - (`createHistory`, `packages/ui-backend-claude/src/history.ts:41-90`; - `restoreArchivedSession`, `packages/ui-backend-claude/src/transcript-archive.ts:146-173`). + (`createHistory`, `packages/ui-backend-claude/src/history.ts:44-102`; + `restoreArchivedSession`, `packages/ui-backend-claude/src/transcript-archive.ts:157-185`). The live/archive roots are resolved by the backend - (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:30-39`). + (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`). Archive movement and crash recovery must join the same lifecycle fence - (`archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:217-274`). + (`archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:229-286`). Delete all owned branches/subagents/copies, not just the displayed branch. Unknown/unattributable archive remnants mean removal is incomplete. - **Native Pi history.** SessionManager JSONL trees retain inactive branches and tool results beyond the active branch rendered by `getPiHistory` - (`getPiHistory`, `packages/ui-backend-pi/src/history.ts:60-112`). Remove the entire + (`getPiHistory`, `packages/ui-backend-pi/src/history.ts:64-128`). Remove the entire backend-verified session tree and metadata, not a normalized history array. Runtime in-memory sessions, worker input/state copies and open descriptors must be quiescent as well; unlink alone does not stop a holder republishing. - **Native-adjacent host files.** Display text mappings and replay receipts include - tool inputs/outputs (`sessionReplay`, `packages/ui-sdk/src/server/session-replay.ts:19-73`). + tool inputs/outputs (`sessionReplay`, `packages/ui-sdk/src/server/session-replay.ts:24-78`). Prompt context retains original user text, the frozen append and delivered facts - (`sessionPromptContext`, `packages/ui-sdk/src/server/session-prompt-context.ts:21-82`). + (`sessionPromptContext`, `packages/ui-sdk/src/server/session-prompt-context.ts:26-87`). These hashed session files are outside the brain and are not fully enumerated by the backend's transcript roots. Removal must explicitly include them. - **Canonical dialogue and provenance.** `071_session_dialogue.sql` owns diff --git a/docs/plans/storage-accounting.md b/docs/plans/storage-accounting.md index dba10175e0..46011afcd8 100644 --- a/docs/plans/storage-accounting.md +++ b/docs/plans/storage-accounting.md @@ -70,8 +70,8 @@ Source anchors, checked against the reviewed commit: - D: effective path/journal resolution (`createApp`, `packages/ui-server/src/app.ts:301-337`), WAL store (`createUiDb`, `packages/ui-server/src/db/client.ts:27-44`), and private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:108-114`). -- E: live/archive paths (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:30-39`). -- F: session location (`piSessionDirectory`, `packages/ui-backend-pi/src/session-storage.ts:8-28`). +- E: live/archive paths (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`). +- F: session location (`piSessionDirectory`, `packages/ui-backend-pi/src/session-storage.ts:10-30`). - G: staging location (`shareStagingRoot`, `packages/ui-server/src/share/staging.ts:143-145`) and settlement-aware cleanup (`function claim`, `packages/ui-server/src/inbox/lifecycle-writes.ts:42-61`). [#807](https://github.com/schlessera/brain-kit/issues/807) supplies live-work diff --git a/docs/plans/storage-lifecycle.md b/docs/plans/storage-lifecycle.md index a2586ab417..300d0f78bf 100644 --- a/docs/plans/storage-lifecycle.md +++ b/docs/plans/storage-lifecycle.md @@ -82,7 +82,7 @@ Source foundations for the matrix: Server refresh refuses incomplete enumeration and confirms missing histories before releasing links (`function openScratchPins`, `packages/ui-server/src/cron/scratch-pins.ts:72-195`). - Claude publishes and verifies cold copies before deleting the live source - (`export async function archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:217-274`). + (`export async function archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:229-286`). - Journal collection requires no refs/reservations and only expires ended turns (`function collectObjects`, `packages/ui-server/src/brain/turn-journal.ts:300-320`). Retention is applied at admission From e248ecc5a1c9b88137538b3e499755ed9a6ad94a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 15:57:57 +0000 Subject: [PATCH 5/5] test(backends): await refusals and name the ownership assertions in native removal tests Co-Authored-By: Claude Opus 5.5 --- .../tests/native-history-removal.test.ts | 17 +++++++++-------- .../tests/native-history-removal.test.ts | 18 ++++++++++-------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/packages/ui-backend-claude/tests/native-history-removal.test.ts b/packages/ui-backend-claude/tests/native-history-removal.test.ts index 0e3b97e5a7..eb6c890d06 100644 --- a/packages/ui-backend-claude/tests/native-history-removal.test.ts +++ b/packages/ui-backend-claude/tests/native-history-removal.test.ts @@ -107,7 +107,7 @@ test("removes every owned artifact through the installed SDK and keeps the unrel expect(await getSessionMessages(TARGET, { dir: brain })).toEqual([]); expect((await backend.listSessions()).map(session => session.id).sort()).toEqual([OTHER, ARCHIVED].sort()); expect(await backend.getHistory(TARGET)).toEqual([]); - expect(resume(backend, TARGET)).rejects.toBeInstanceOf(BackendRequestError); + await expect(resume(backend, TARGET)).rejects.toBeInstanceOf(BackendRequestError); // The tombstone is content-free: only the operation identity. expect(readFileSync(join(archive, "retired", TARGET), "utf8")).toBe("retire-voyage"); // The control chat is untouched and readable. @@ -117,7 +117,7 @@ test("removes every owned artifact through the installed SDK and keeps the unrel expect(stored()).toContain(CONTROL); // Repeating the same operation is idempotent; another operation never re-owns the session. expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET })).toEqual({ outcome: "removed" }); - expect(backend.removeSessionHistory!({ operationId: "retire-again", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); + await expect(backend.removeSessionHistory!({ operationId: "retire-again", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); }); test("a reader started before retirement drains first and publishes nothing after it", async () => { @@ -134,11 +134,11 @@ test("a reader started before retirement drains first and publishes nothing afte // Fenced at once: a new reader, lister and resume see an unknown chat while removal waits. expect(await backend.getHistory(TARGET)).toEqual([]); expect((await backend.listSessions()).map(session => session.id).sort()).toEqual([OTHER, ARCHIVED].sort()); - expect(resume(backend, TARGET)).rejects.toBeInstanceOf(BackendRequestError); + await expect(resume(backend, TARGET)).rejects.toBeInstanceOf(BackendRequestError); // A bounded caller wait is partial, and the removal keeps its single owner. const deadline = new AbortController(); deadline.abort(); expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET, signal: deadline.signal })).toEqual({ outcome: "partial" }); - expect(backend.removeSessionHistory!({ operationId: "replacement", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); + await expect(backend.removeSessionHistory!({ operationId: "replacement", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); expect(stored(), "REMOVAL_WAITS_FOR_THE_READER").toContain(MARKER); reading.open(); expect(text(await read), "RETIRED_READ_PUBLISHES_NOTHING").not.toContain(MARKER); @@ -168,7 +168,7 @@ test("a restarted backend keeps the fence, refuses restored archives and finishe restoreArchivedSession(TARGET, { brainPath: brain }); expect(readFileSync(join(live, `${TARGET}.jsonl`), "utf8")).toContain(MARKER); expect(existsSync(join(archive, TARGET)), "RETIRED_ARCHIVE_NOT_RESTORED").toBe(true); - expect(restarted.removeSessionHistory!({ operationId: "replacement", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); + await expect(restarted.removeSessionHistory!({ operationId: "replacement", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); expect(await restarted.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET })).toEqual({ outcome: "removed" }); expect(stored()).not.toContain(MARKER); // The stopped process's reader, if it ever resumed, still publishes nothing. @@ -191,13 +191,14 @@ test("links, hard links and redirected roots stay untouched and keep the removal expect(readFileSync(join(penelope, "letter.txt"), "utf8")).toBe(CONTROL); expect(lstatSync(join(live, `${TARGET}.jsonl`)).isSymbolicLink()).toBe(true); expect(existsSync(join(live, TARGET, "letters"))).toBe(true); - expect(lstatSync(join(replay.dir, replay.name)).nlink, "HARD_LINK_NOT_UNLINKED").toBe(2); + expect(existsSync(join(replay.dir, replay.name)), "HARD_LINK_NOT_UNLINKED").toBe(true); + expect(lstatSync(join(replay.dir, replay.name)).nlink).toBe(2); expect(readFileSync(join(penelope, "copy.json"), "utf8")).toContain(MARKER); // Everything the chat solely owns was still removed, and it stays fenced. expect(existsSync(join(archive, TARGET))).toBe(false); expect((await backend.listSessions()).map(session => session.id).sort()).toEqual([OTHER, ARCHIVED].sort()); // A client path is never a session identity. - expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: "../penelope-letters" })).rejects.toBeInstanceOf(BackendRequestError); + await expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: "../penelope-letters" })).rejects.toBeInstanceOf(BackendRequestError); expect(existsSync(penelope)).toBe(true); }); @@ -206,7 +207,7 @@ test("a redirected archive root refuses before any removal", async () => { const elsewhere = join(root, "elsewhere"); mkdirSync(elsewhere); writeFileSync(join(elsewhere, "kept.txt"), CONTROL); rmSync(archive, { recursive: true }); symlinkSync(elsewhere, archive); const backend = createClaudeBackend({ brainPath: brain }); - expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); + await expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: TARGET })).rejects.toBeInstanceOf(BackendRequestError); expect(readdirSync(elsewhere)).toEqual(["kept.txt"]); expect(readFileSync(join(live, `${TARGET}.jsonl`), "utf8")).toContain(MARKER); }); diff --git a/packages/ui-backend-pi/tests/native-history-removal.test.ts b/packages/ui-backend-pi/tests/native-history-removal.test.ts index b0d4a40d85..9909430e76 100644 --- a/packages/ui-backend-pi/tests/native-history-removal.test.ts +++ b/packages/ui-backend-pi/tests/native-history-removal.test.ts @@ -83,7 +83,7 @@ test("removes the whole session tree and its metadata through the installed Sess expect((await SessionManager.list(brain, sessionDir)).map(info => info.id)).toEqual([control]); expect((await backend.listSessions()).map(session => session.id)).toEqual([control]); expect(await backend.getHistory(target)).toEqual([]); - expect(resume(backend, target)).rejects.toBeInstanceOf(BackendRequestError); + await expect(resume(backend, target)).rejects.toBeInstanceOf(BackendRequestError); expect(readFileSync(join(sessionDir, "retired", target), "utf8")).toBe("retire-voyage"); expect(text(await backend.getHistory(control))).toContain(CONTROL); expect(after).toContain(CONTROL); @@ -94,7 +94,7 @@ test("removes the whole session tree and its metadata through the installed Sess { type: "message", id: "a1b2c3d4", parentId: null, timestamp: "2026-07-12T10:00:01.000Z", message: { role: "user", content: MARKER, timestamp: 1 } }]); expect((await restarted.listSessions()).map(session => session.id)).toEqual([control]); expect(await restarted.getHistory(target)).toEqual([]); - expect(restarted.removeSessionHistory!({ operationId: "replacement", sessionId: target })).rejects.toBeInstanceOf(BackendRequestError); + await expect(restarted.removeSessionHistory!({ operationId: "replacement", sessionId: target })).rejects.toBeInstanceOf(BackendRequestError); expect(await restarted.removeSessionHistory!({ operationId: "retire-voyage", sessionId: target })).toEqual({ outcome: "removed" }); expect(stored()).not.toContain(MARKER); }); @@ -112,13 +112,15 @@ test("a transcript is attributed by its header, and links stay untouched", async const backend = createPiBackend({ brainPath: brain, sessionDir }); expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: target })).toEqual({ outcome: "partial" }); - expect(readFileSync(join(sessionDir, `${target}.jsonl`), "utf8"), "REPLACED_FILE_NOT_DELETED").toContain(CONTROL); - expect(lstatSync(join(replay.dir, replay.name)).nlink, "HARD_LINK_NOT_UNLINKED").toBe(2); + expect(existsSync(join(sessionDir, `${target}.jsonl`)), "REPLACED_FILE_NOT_DELETED").toBe(true); + expect(readFileSync(join(sessionDir, `${target}.jsonl`), "utf8")).toContain(CONTROL); + expect(existsSync(join(replay.dir, replay.name)), "HARD_LINK_NOT_UNLINKED").toBe(true); + expect(lstatSync(join(replay.dir, replay.name)).nlink).toBe(2); // The tree its header attributes to the target is gone; the control chat is intact. expect(readdirSync(sessionDir).some(name => name.endsWith(`_${target}.jsonl`))).toBe(false); expect(readFileSync(join(sessionDir, controlFile), "utf8")).toContain(CONTROL); expect(text(await backend.getHistory(control))).toContain(CONTROL); - expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: "../penelope-letters" })).rejects.toBeInstanceOf(BackendRequestError); + await expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: "../penelope-letters" })).rejects.toBeInstanceOf(BackendRequestError); expect(existsSync(penelope)).toBe(true); }); @@ -141,13 +143,13 @@ test("a running turn drains before removal and its resident session is disposed" const removal = backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: target }); const deadline = new AbortController(); deadline.abort(); expect(await backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: target, signal: deadline.signal })).toEqual({ outcome: "partial" }); - expect(backend.removeSessionHistory!({ operationId: "replacement", sessionId: target })).rejects.toBeInstanceOf(BackendRequestError); + await expect(backend.removeSessionHistory!({ operationId: "replacement", sessionId: target })).rejects.toBeInstanceOf(BackendRequestError); // Fenced at once: follow-up and resume refuse while the turn still holds the session. - expect(backend.followUp!({ sessionId: target, prompt: "And the bow?" })).rejects.toBeInstanceOf(BackendRequestError); + await expect(backend.followUp!({ sessionId: target, prompt: "And the bow?" })).rejects.toBeInstanceOf(BackendRequestError); expect(stored(), "REMOVAL_WAITS_FOR_THE_TURN").toContain(MARKER); finish(); await turn; expect(await removal).toEqual({ outcome: "removed" }); expect(disposed, "RESIDENT_SESSION_DISPOSED").toBe(true); expect(stored()).not.toContain(MARKER); - expect(resume(backend, target)).rejects.toBeInstanceOf(BackendRequestError); + await expect(resume(backend, target)).rejects.toBeInstanceOf(BackendRequestError); });