From 098db3b8acf93c87a5acbe0e09670cc59c15fab5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 05:12:30 +0100 Subject: [PATCH 01/24] CONTRACT: fix(ui-server): contain a safety-recording failure to what it puts at risk (#3812, #3810) A single turn's safety-write error used to set one durable flag for the whole brain, after which every turn in every chat was refused until an operator ran a script. The failure is now contained at the narrowest scope that durably takes it, and the host recovers by itself: - Before delivery (a failed begin, or a refused reservation whose producer holds its input) refuses that one turn with the retryable SAFETY_RECORDING_UNAVAILABLE error. Nothing latches. - Lost evidence after delivery marks only that turn's collection failed, so its chat keeps a permanent recording_failed gap and runs restricted. A reservation still open when its collection ends becomes the same gap. - Only when that chat fact cannot commit does the brain latch, through the emergency reserve or in-process. New turns still begin, each with a permanent gap committed before delivery, and run under the tainted policy. A turn is refused only when that restricted begin cannot commit (safety_recording_paused). A reconciler retries, backing off to once a minute, and clears the latch once the producers that predate it drained. - Boot resolves a set latch and pending reservations after restart classification; a legacy row that cannot migrate gaps its own turn. Every latch keeps its first cause and a count (safety_latch), logs one structured stderr line, and only a capacity check classifies as capacity. Every recovery is audited in safety_recoveries with trigger, actor, time and the cleared cause. Contract: additive error code SAFETY_RECORDING_UNAVAILABLE and failure classes safety_recording_unavailable / safety_recording_paused (docs/integration-contract/wire.md). Projection reasons are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../3812-safety-recording-containment.md | 15 + docs/decisions/session-safety-reviews.md | 33 ++ docs/integration-contract/wire.md | 8 + docs/plans/reviewable-session-safety.md | 6 +- packages/ui-sdk/src/protocol.ts | 4 +- .../085_safety_recording_containment.sql | 25 ++ packages/ui-server/src/db/client.ts | 14 +- .../src/governance/effective-safety.ts | 7 +- .../ui-server/src/governance/event-writes.ts | 177 +++++++++-- .../src/governance/safety-collector.ts | 13 +- .../ui-server/src/governance/safety-queue.ts | 17 +- .../ui-server/src/governance/safety-store.ts | 234 +++++++++++--- .../src/ws/bridge-capabilities/turn-error.ts | 8 + .../tests/approval-scope-isolation.test.ts | 11 +- .../tests/helpers/hold-safety-recovery.ts | 11 + .../tests/safety-containment.test.ts | 299 ++++++++++++++++++ .../tests/safety-history-loss.test.ts | 5 +- .../ui-server/tests/safety-ledger.test.ts | 60 ++-- .../tests/safety-loss-recovery.test.ts | 14 +- .../tests/safety-pi-delivery.test.ts | 8 +- .../ui-server/tests/safety-reviews.test.ts | 4 + .../tests/session-safety-boundaries.test.ts | 21 +- 22 files changed, 862 insertions(+), 132 deletions(-) create mode 100644 .changeset/3812-safety-recording-containment.md create mode 100644 packages/ui-server/migrations/085_safety_recording_containment.sql create mode 100644 packages/ui-server/tests/helpers/hold-safety-recovery.ts create mode 100644 packages/ui-server/tests/safety-containment.test.ts diff --git a/.changeset/3812-safety-recording-containment.md b/.changeset/3812-safety-recording-containment.md new file mode 100644 index 0000000000..e85542691c --- /dev/null +++ b/.changeset/3812-safety-recording-containment.md @@ -0,0 +1,15 @@ +--- +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-react": minor +--- + +A safety-recording failure now restricts only what it puts at risk, and the host recovers by itself (#3812, #3810). + +- **One turn, before delivery.** A failed safety begin, or a refused reservation that delivered nothing, refuses only that turn with the new retryable `SAFETY_RECORDING_UNAVAILABLE` error. The chat and the brain stay usable. +- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. It keeps running under its tainted policy; other chats are untouched. +- **The brain, only when the evidence store cannot take a scoped fact.** New turns still run, restricted, each with a permanent gap written before anything is sent. The server keeps retrying and clears the latch itself once the gaps are durable. A turn is refused only if even its restricted start cannot be written (`safety_recording_paused`). +- **Boot** resolves a set latch and pending reservations automatically instead of refusing every turn. +- **Diagnosable.** Each latch keeps its first cause and a count in the database, logs one structured line, and is shown to the owner as `safetyRecording` on `/api/status`. Errors are no longer all labelled `capacity`. Every recovery is recorded with who or what ran it. +- **Owner fallback.** `POST /api/status/safety-recording/recover` runs the same recovery when nothing is open. +- **PWA.** A message refused this way says that safety recording failed or is paused, instead of "The brain refused this message." diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index ed2eb31511..e75a33ca43 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -72,6 +72,39 @@ and failure capacity before ingestion; stop/restrict before overflow loses a signal. A failed pending write must not disappear into apparently normal state, including across restart. No test count or arbitrary cleanup TTL proves safety. +### A recording failure restricts what it puts at risk (#3812) + +Ruled by the maintainer on 2026-11-09, under +[proportionate containment](proportionate-containment.md). "Restricted" means +running under the tainted policy, not refusing. + +- **Before delivery** (a failed collection begin, or a refused reservation + whose producer holds its input until the event commits): the one turn is + refused with a retryable `SAFETY_RECORDING_UNAVAILABLE`. Nothing latches. +- **Lost after delivery**: the turn's own collection takes the failure and its + first cause, so its chat keeps a permanent gap projected as + `recording_failed` and that producer stops. Other chats are unaffected. A + reservation still open when its collection ends becomes the same gap. +- **Evidence store unwritable** (the chat fact cannot commit): the brain + latches through the emergency reserve, or, when even that fails, in the + host process. New turns still begin, each with a permanent + `recording_failed` gap committed before delivery, and run restricted. A turn + is refused only when that restricted begin itself cannot commit + (`safety_recording_paused`). The host keeps retrying, backing off to once a + minute, and clears the latch itself with `recoverSafetyRecording` semantics + once the producers that predate it have drained. +- **Boot** resolves a set latch and pending reservations after restart + classification, gaps first. A legacy row that cannot migrate gaps its own + turn. The server never boots into refusing every turn. + +Every latch keeps its first cause (class, message, bounded stack, call site, +turn, time) and a count, logs one structured line, and is visible to the owner +on `/api/status`. Every recovery is recorded with its trigger, actor, time and +cleared cause. The owner route (#3810) is a fallback with the strict +quiescence precondition. Only a capacity check classifies a failure as +`capacity`. No gap ever clears, and nothing here lets an unrecorded input +become clean. + ## Human authority and policy publication Initially **only a live password-mode human owner** may commit a verdict or diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 0729a6cb44..881d8ff4a8 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -173,6 +173,14 @@ value and never sends `apifyUsd`. A client that validated the earlier literals must accept both new values. `listPriceCostUsd` and `tokens` stay the agent's own completed inference. +A turn refused because its safety record could not be written ends with the +additive error code `SAFETY_RECORDING_UNAVAILABLE` (#3810, #3812) and the +additive failure classes `safety_recording_unavailable` (a one-turn failure +before delivery; retry) and `safety_recording_paused` (the brain-wide recorder +is failed and even the turn's restricted start could not commit; the host +recovers it by itself). Nothing reached the model in either case. A client +says so instead of reporting a refusal by the brain. + `budget_exceeded` and `budget_unavailable` are additive host failure classes. The former names a turn/session/day `budgetScope`; a day stop carries `resetsAt`. Neither automatically retries. A conversation block offers the diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index bdc411696c..5ab84d402c 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -512,7 +512,11 @@ The scope and recovery of that latch follow before any bytes are delivered refuses only its turn; lost evidence after delivery restricts only its chat; only an unwritable evidence store restricts the brain, and the host clears that itself once the gap facts are durable -(maintainer ruling, 2026-11-09, #3812). +(maintainer ruling, 2026-11-09, #3812). Under that latch a new turn still +begins, its permanent gap committed before delivery; only a turn whose +restricted begin cannot commit is refused. Restart resolves the latch and any +pending reservations itself, so "begins restricted" never means "refuses" +([the ruling as built](../decisions/session-safety-reviews.md#a-recording-failure-restricts-what-it-puts-at-risk-3812)). Permanent content-free retirement fences belong to the existing chat lifecycle, not a TTL cache. Never expire or evict them to fit the limits above. Enforce diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index a8cd5933a4..0030aba2ba 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -1366,7 +1366,7 @@ type FirstPartyFailureClass = | "auth_failure" | "rate_limit" | "overloaded" | "server_error" | "invalid_request" | "model_not_found" | "max_output_tokens" | "cloud_credential_error" | "worker_host_unsupported" | "session_too_large" | "worker_resource_limit" - | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "unknown"; + | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "safety_recording_unavailable" | "safety_recording_paused" | "unknown"; /** * First-party failure classes, shared by emitters and reviewed diagnostics. @@ -1400,6 +1400,8 @@ export const FIRST_PARTY_FAILURE_CLASSES: Readonly<{ [Class in FirstPartyFailure journal_capacity: "journal_capacity", journal_unavailable: "journal_unavailable", input_safety_unavailable: "input_safety_unavailable", + safety_recording_unavailable: "safety_recording_unavailable", + safety_recording_paused: "safety_recording_paused", unknown: "unknown", }); diff --git a/packages/ui-server/migrations/085_safety_recording_containment.sql b/packages/ui-server/migrations/085_safety_recording_containment.sql new file mode 100644 index 0000000000..5d054c2300 --- /dev/null +++ b/packages/ui-server/migrations/085_safety_recording_containment.sql @@ -0,0 +1,25 @@ +-- Safety-recording failures are contained to what they put at risk and keep +-- their cause (#3812, #3810). +-- +-- A collection begun while the brain-wide recorder was failed carries a +-- permanent pre-delivery gap: losing more of its evidence cannot weaken +-- anything, so it runs under its tainted policy instead of being refused. +ALTER TABLE safety_collections ADD COLUMN restricted_begin INTEGER NOT NULL DEFAULT 0; +-- The first cause of a chat-scoped failure: identifiers and error text only. +ALTER TABLE safety_collections ADD COLUMN failure_cause TEXT; +-- The first cause of the brain-wide latch. Later latches only count. +CREATE TABLE safety_latch ( + singleton INTEGER PRIMARY KEY CHECK(singleton=1), + since INTEGER NOT NULL, reason TEXT NOT NULL, site TEXT NOT NULL, turn_id TEXT, + error_class TEXT NOT NULL, message TEXT NOT NULL, stack TEXT, count INTEGER NOT NULL DEFAULT 1 +); +-- A latch already set before this migration has no recorded cause. +INSERT INTO safety_latch(singleton,since,reason,site,turn_id,error_class,message,stack) + SELECT 1,0,COALESCE(reason,'recording_failed'),'unknown',NULL,'unknown','The latch predates cause recording.',NULL + FROM safety_meta WHERE singleton=1 AND failed=1; +-- Every recovery: who or what cleared the latch, when, and the cause it cleared. +CREATE TABLE safety_recoveries ( + id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, + trigger TEXT NOT NULL CHECK(trigger IN ('boot','automatic','owner')), actor TEXT NOT NULL, + scope TEXT NOT NULL, cause TEXT, gapped INTEGER NOT NULL +); diff --git a/packages/ui-server/src/db/client.ts b/packages/ui-server/src/db/client.ts index 75f6de407a..13abc3208e 100644 --- a/packages/ui-server/src/db/client.ts +++ b/packages/ui-server/src/db/client.ts @@ -1,4 +1,4 @@ -import { migrateSafetyHistory, recoverSafetyCollections } from "../governance/safety-store.js"; +import { migrateSafetyHistory, recoverSafetyCollections, recoverSafetyRecording } from "../governance/safety-store.js"; import { Database } from "bun:sqlite"; import { readdirSync, readFileSync } from "fs"; import { join } from "path"; @@ -39,8 +39,18 @@ export function createUiDb(dbPath: string, options: CreateUiDbOptions = {}): Dat // unqualified here; each start then moves whatever they created into it. attachJournalDatabase(db, dbPath); runMigrations(db, options.log); - migrateSafetyHistory(db); + const migrated = migrateSafetyHistory(db); recoverSafetyCollections(db); + // Boot never starts into a state where every turn is refused for something + // it can resolve itself (#3812): after restart classification no producer + // is open, so a set latch or pending rows are resolved here, gaps first. + // If this cannot commit, the server still boots restricted and the + // governance writes keep retrying. + if (migrated) { + try { recoverSafetyRecording(db, { trigger: "boot", actor: "host" }); } + catch (error) { options.log?.emit({ severityText: "WARN", body: "safety recording could not be recovered at boot; turns run restricted and recovery is retried", + attributes: { "error.message": error instanceof Error ? error.message : String(error) } }); } + } const moved = moveJournalTables(db); if (moved) options.log?.emit({ severityText: "INFO", body: "moved journal tables into the journal database", attributes: { tables: moved } }); return db; diff --git a/packages/ui-server/src/governance/effective-safety.ts b/packages/ui-server/src/governance/effective-safety.ts index cec94b1bec..4874feb74d 100644 --- a/packages/ui-server/src/governance/effective-safety.ts +++ b/packages/ui-server/src/governance/effective-safety.ts @@ -14,7 +14,7 @@ export interface LiveTrustRevision { export function createEffectiveSafety(db: Database, options: { turnId: string; sessionId: () => string | null; policyHash: string | null; brain?: string; - writes?: Pick; + writes?: Pick & Partial>; authority(): { current: boolean; epoch: string }; trust?: LiveTrustRevision; signal?: AbortSignal; @@ -49,7 +49,10 @@ export function createEffectiveSafety(db: Database, options: { return { evidenceRevision, trustRevision, authorityEpoch: authority.epoch, scope: JSON.stringify([options.brain ?? db.filename, options.turnId, projection.session]), policyHash: options.policyHash, restricted: projection.restriction === "restricted", - recordingAvailable: !projection.reasons.some(reason => ["recording_pending", "recording_failed", "capacity"].includes(reason)), + // The facade also knows a turn begun restricted: its permanent gap + // covers anything it loses, so it runs under its tainted policy (#3812). + recordingAvailable: options.writes?.recordingAvailable ? options.writes.recordingAvailable(options.turnId, sessionId) + : !projection.reasons.some(reason => ["recording_pending", "recording_failed", "capacity"].includes(reason)), authorityCurrent: authority.current }; }; return { diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index 7df1c8e203..2b42f5e4ef 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -9,7 +9,9 @@ import { retainSafetyLoss, safetyQueue, notifySafetyChanged } from "./safety-queue.js"; import { prepareSafetyReview, commitSafetyReview, type SafetyReviewBody, type SafetyReviewer, type SafetyReviewReceipt } from "./safety-reviews.js"; import { beginSafetyCollection, acknowledgeSafety, endSafetyCollection, safetyProjection, reserveSafetyWrite, releaseSafetyWrite, - ensureSafetyEventCollection, latchSafety, SafetyUnavailable, safetyScopeTurns, type SafetyCollectionInput, type SafetyProjection } from "./safety-store.js"; + ensureSafetyEventCollection, recordSafetyFailure, recoverSafetyRecording, migrateSafetyHistory, logSafetyRecording, safetyRecordingStatus, + SafetyRecordingUnavailable, SafetyUnavailable, safetyScopeTurns, type SafetyCollectionInput, type SafetyProjection, + type SafetyFailureSite, type SafetyRecovery, type SafetyRecordingStatus } from "./safety-store.js"; import { Database } from "bun:sqlite"; import {assertLive,ChatRetiredError} from "../ws/chat-lifecycle.js"; @@ -23,28 +25,44 @@ export const url = import.meta.url; /** Worker side: every procedure is one of the synchronous writers, run on the write connection. */ export function setup(db: Database): WriteProcedures { + const retired=(turnId:string)=>!!db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(turnId); + // Writes the failure at the narrowest scope that takes it and tells the app + // side which one did, on the error itself: `chat`, `brain`, or `unrecorded`. + const contain=(error:unknown,turnId:string|null,site:SafetyFailureSite)=>{ + let scope:string; + try{scope=recordSafetyFailure(db,turnId,error,site);}catch{scope="unrecorded";} + if(error instanceof Error)try{Object.defineProperty(error,"safetyScope",{value:scope,enumerable:true,configurable:true});}catch{/* frozen: treated as unrecorded */} + }; return { safetyPrepareReview: (body:SafetyReviewBody,actor:SafetyReviewer) => prepareSafetyReview(db,body,actor), safetyCommitReview: (id:string,body:SafetyReviewBody,actor:SafetyReviewer,pending:boolean,failed:boolean=false) => commitSafetyReview(db,id,body,actor,pending,failed), record: (row: GovernanceEventRow) => { - try { return insertGovernanceEvent(db,row); } catch(error) { if(!(error instanceof ChatRetiredError)&&(row.kind==="taint"||row.kind==="taint_exposure"))latchSafety(db,row.turnId,error instanceof SafetyUnavailable?"capacity":"recording_failed"); throw error; } + try { return insertGovernanceEvent(db,row); } catch(error) { if(!(error instanceof ChatRetiredError)&&(row.kind==="taint"||row.kind==="taint_exposure"))contain(error,row.turnId,"record"); throw error; } }, - safetyBegin: (input:SafetyCollectionInput) => { try{return beginSafetyCollection(db,input);}catch(error){if(!(error instanceof ChatRetiredError))latchSafety(db,input.turnId,"capacity");throw error;} }, + // A failed begin is before any delivery: it refuses that turn alone and + // latches nothing (#3812). The app side names the retryable refusal. + safetyBegin: (input:SafetyCollectionInput) => beginSafetyCollection(db,input), safetyReady: (turnId:string,backendId:string,version:number) => acknowledgeSafety(db,turnId,backendId,version), safetyEnd: (turnId:string,loss=false) => { // Never seal an apparently complete epoch if its loss notice rolled // back. A failed retry leaves it open for restart classification. - if(loss&&!db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(turnId))latchSafety(db,turnId,"recording_failed"); + if(loss&&!retired(turnId))recordSafetyFailure(db,turnId,new SafetyUnavailable("Safety evidence was lost before its collection ended"),"safetyEnd"); endSafetyCollection(db,turnId); }, - safetyFail: (turnId:string|null) => {if(!turnId||!db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(turnId))latchSafety(db,turnId,"recording_failed");}, - safetyReserve: (row:GovernanceEventRow,id:string,bytes:number) => { + safetyFail: (turnId:string|null,cause?:{name:string;message:string;stack?:string}) => { + if(turnId&&retired(turnId))return null; + const error=cause?Object.assign(new Error(cause.message),{name:cause.name,stack:cause.stack}):new SafetyUnavailable("A safety producer failed; its evidence may be lost"); + return recordSafetyFailure(db,turnId,error,"safetyFail"); + }, + // A reservation precedes its event. When the producer holds its input + // until the event commits, a refused reservation delivered nothing. + safetyReserve: (row:GovernanceEventRow,id:string,bytes:number,beforeDelivery=false) => { try {const turnId=ensureSafetyEventCollection(db,row);reserveSafetyWrite(db,turnId,id,bytes,row.kind==="taint_exposure"?JSON.parse(row.payload).occurrenceId:undefined);} - catch(error){if(!(error instanceof ChatRetiredError))latchSafety(db,row.turnId,"capacity");throw error;} + catch(error){if(!(error instanceof ChatRetiredError)&&!beforeDelivery)contain(error,row.turnId,"safetyReserve");throw error;} }, safetyCommit: (row:GovernanceEventRow,id:string) => { try{return db.transaction(()=>{assertLive(db,[["session",row.sessionId]]);if(row.turnId&&db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(row.turnId))throw new ChatRetiredError();if(!db.query("SELECT 1 FROM safety_pending WHERE id=?").get(id))throw new SafetyUnavailable("Safety reservation absent");releaseSafetyWrite(db,id);return insertGovernanceEvent(db,row,true);}).immediate();} - catch(error){if(!(error instanceof ChatRetiredError))latchSafety(db,row.turnId,error instanceof SafetyUnavailable?"capacity":"recording_failed");throw error;} + catch(error){if(!(error instanceof ChatRetiredError))contain(error,row.turnId,"safetyCommit");throw error;} }, bind: (turnId: string, sessionId: string) => bindTurnEvents(db, turnId, sessionId), // Classification reads the turn's earlier events on the same connection, @@ -58,10 +76,12 @@ export interface GovernanceWrites { /** Host-only persistence; callers must establish live owner authority. No route or capability is enabled here. */ safetyPrepareReview(body:SafetyReviewBody,actor:SafetyReviewer):Promise; safetyCommitReview(id:string,body:SafetyReviewBody,actor:SafetyReviewer):Promise; + /** Refuses with `SafetyRecordingUnavailable` when the collection cannot commit; nothing is latched. */ safetyBegin(input:SafetyCollectionInput):Promise; safetyReady(turnId:string,backendId:string,version:number):Promise; safetyEnd(turnId:string):Promise; - safetyFail(turnId:string):Promise; + /** Marks the turn's chat failed (`cause` is error text only); the brain only when that cannot commit. */ + safetyFail(turnId:string,cause?:unknown):Promise; safety(turnId:string|null,sessionId:string|null):SafetyProjection; /** Input recording must be settled and healthy before any provider delivery. */ recordingAvailable(turnId:string|null,sessionId:string|null):boolean; @@ -72,7 +92,13 @@ export interface GovernanceWrites { */ record(input: GovernanceEventInput): Promise<{ id: number; recorded: boolean }>; /** Stores every distinct occurrence; only the exact host key deduplicates. Historical internal method name. */ - firstTaint(input: GovernanceEventInput<"taint">): Promise; + /** `beforeDelivery`: the producer holds the input until this settles, so a + * refused reservation delivered nothing and refuses only the turn. */ + firstTaint(input: GovernanceEventInput<"taint">, options?: { beforeDelivery?: boolean }): Promise; + /** The brain-wide recorder state the owner sees on `/api/status` (#3810). */ + recordingStatus(): SafetyRecordingStatus; + /** Owner fallback for automatic recovery, with the strict quiescence precondition. */ + recoverRecording(actor:string): SafetyRecovery; /** * The session's first taint (G6) as admission must see it: the committed * one, else one submitted and not yet committed. A pending taint has no row @@ -98,67 +124,124 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov const turns=safetyScopeTurns(db,turnId,sessionId); return [...pendingTaints].filter(p=>(p.turnId!==null&&turns.has(p.turnId))||(sessionId!==null&&p.sessionId===sessionId)); }; + // Retained in-process loss restricts only the chats it belongs to. + const lostInScope=(turnId:string|null,sessionId:string|null)=>{ + if(!shared.lostTurns.size)return false; + if(turnId!==null&&shared.lostTurns.has(turnId))return true; + for(const turn of safetyScopeTurns(db,turnId,sessionId))if(shared.lostTurns.has(turn))return true; + return false; + }; + const brainFailed=()=>shared.failed||!!(db.query("SELECT failed FROM safety_meta WHERE singleton=1").get() as {failed:number}|null)?.failed; + // A turn begun restricted carries a permanent gap before any delivery: + // nothing it loses can make its chat look complete, so it keeps running. + const covered=(turnId:string|null)=>turnId!==null&&!!db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND restricted_begin=1").get(turnId); + const retired=(turnId:string)=>!!db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(turnId); const call:typeof invoke=(name:string,...args:unknown[])=>{ shared.inflight++; return invoke(name,...args).finally(()=>{shared.inflight--;notifySafetyChanged(db);}); }; - const safetyFail=(turnId:string|null):Promise=>{ - if(!turnId||!db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(turnId))retainSafetyLoss(db,turnId); - return call("safetyFail",turnId); + const safetyFail=(turnId:string|null,cause?:unknown):Promise=>{ + const counted=!turnId||!retired(turnId); + // A turn with no collection has no chat to carry the fact: the brain does. + if(counted)retainSafetyLoss(db,turnId,turnId!==null&&!db.query("SELECT 1 FROM safety_collections WHERE turn_id=?").get(turnId)); + const wire=cause instanceof Error?{name:cause.constructor?.name&&cause.constructor.name!=="Error"?cause.constructor.name:cause.name,message:cause.message,stack:cause.stack} + :cause===undefined?undefined:{name:"Error",message:String(cause)}; + return call<"chat"|"brain"|null>("safetyFail",turnId,wire).then(scope=>{ + // The chat now carries the durable fact; its in-process copy is redundant. + if(scope==="chat"&&turnId)shared.lostTurns.delete(turnId); + if(scope==="brain")scheduleSafetyRecovery(db); + notifySafetyChanged(db); + },notice=>{ + // Neither the chat nor the brain fact committed: the store cannot take + // a write. Restrict the brain in-process until recovery commits one. + if(counted){retainSafetyLoss(db,turnId,true);scheduleSafetyRecovery(db);} + throw notice; + }); }; - const record = (input: GovernanceEventInput): Promise<{ id: number; recorded: boolean }> => { + const contained=(error:unknown,turnId:string|null)=>{ + const scope=(error as {safetyScope?:string}|null)?.safetyScope; + if(scope==="chat")return; + if(scope==="brain"){scheduleSafetyRecovery(db);return;} + retainSafetyLoss(db,turnId,true);scheduleSafetyRecovery(db); + }; + const record = (input: GovernanceEventInput, options: { beforeDelivery?: boolean } = {}): Promise<{ id: number; recorded: boolean }> => { const row = governanceEventRow(input); if (input.kind !== "taint" && input.kind !== "taint_exposure") return call("record", row); - if (shared.failed&&input.kind!=="taint_exposure") throw new Error("Safety occurrence writer requires recovery"); + const restricted=covered(row.turnId); + // A stopped producer stays stopped: its chat, or the brain, holds the failure. + if (!restricted&&input.kind!=="taint_exposure"&&(brainFailed()||(row.turnId!==null&&(shared.lostTurns.has(row.turnId) + ||!!db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND failure IS NOT NULL AND ended=0").get(row.turnId))))) + throw new Error("Safety occurrence writer requires recovery"); const bytes = Buffer.byteLength(JSON.stringify(row))+1024; const session = snapshot(()=>row.turnId===null&&row.sessionId===null ? [...pendingTaints].filter(p=>p.turnId===null&&p.sessionId===null) : pendingInScope(row.turnId,row.sessionId)); if (pendingTaints.size >= 4096 || shared.bytes + bytes > 16777216 || session.length >= 256 || session.reduce((sum, p) => sum + p.bytes, 0) + bytes > 1048576) { - void safetyFail(row.turnId).catch(()=>{}); + void safetyFail(row.turnId,new Error("Safety occurrence write capacity exceeded")).catch(()=>{}); throw new Error("Safety occurrence write capacity exceeded; ingestion must stop"); } const pending = { turnId: row.turnId, sessionId: row.sessionId, source: input.kind==="taint"?(input as GovernanceEventInput<"taint">).payload.source:"legacy_unknown" as const, bytes }; pendingTaints.add(pending); shared.bytes += bytes; notifySafetyChanged(db); - const reservation=crypto.randomUUID(); - const stored = call("safetyReserve",row,reservation,bytes).then(()=>call<{id:number;recorded:boolean}>("safetyCommit",row,reservation)); - return stored.catch(error => { if((error as {code?:string})?.code!=="chat_retired")retainSafetyLoss(db,row.turnId); throw error; }) - .finally(() => { pendingTaints.delete(pending); shared.bytes -= bytes; notifySafetyChanged(db); }); + const reservation=crypto.randomUUID();let reserved=false; + const stored = call("safetyReserve",row,reservation,bytes,!!options.beforeDelivery) + .then(()=>{reserved=true;return call<{id:number;recorded:boolean}>("safetyCommit",row,reservation);}); + return stored.catch(error => { + if((error as {code?:string})?.code==="chat_retired")throw error; + // Already permanently gapped before delivery: this loss changes nothing. + if(restricted){logSafetyRecording("safety evidence not recorded for a restricted turn",{"safety.scope":"turn","safety.turn_id":row.turnId, + "error.message":error instanceof Error?error.message:String(error)});return {id:0,recorded:false};} + if(!reserved&&options.beforeDelivery)throw new SafetyRecordingUnavailable(brainFailed(),error); + contained(error,row.turnId); + throw error; + }).finally(() => { pendingTaints.delete(pending); shared.bytes -= bytes; notifySafetyChanged(db); }); }; + if(brainFailed())scheduleSafetyRecovery(db); return { record, safetyPrepareReview: (body,actor)=>call("safetyPrepareReview",body,actor), safetyCommitReview(id,body,actor){ let pending=true; - try {pending=snapshot(()=>pendingInScope(null,body.session.sessionId).length>0);} + try {pending=snapshot(()=>pendingInScope(null,body.session.sessionId).length>0||lostInScope(null,body.session.sessionId));} catch(error){if(!(error instanceof ChatRetiredError))throw error;} // Retirement is an explicit worker-side receipt, including on retry. return call("safetyCommitReview",id,body,actor,pending,shared.failed); }, - async safetyBegin(input){if(shared.failed)throw new SafetyUnavailable("Safety recording requires recovery");return call("safetyBegin",input);}, + async safetyBegin(input){ + const paused=brainFailed(); + try{return await call("safetyBegin",{...input,restricted:paused});} + catch(error){ + if((error as {code?:string})?.code==="chat_retired")throw error; + // Before any delivery: refuse this turn alone, retryable, latch nothing. + const refusal=new SafetyRecordingUnavailable(paused||brainFailed(),error); + logSafetyRecording("safety recording refused one turn before delivery",{"safety.scope":"turn","safety.site":"safetyBegin","safety.turn_id":input.turnId, + "safety.paused":refusal.paused?1:0,"error.class":error instanceof Error?error.constructor?.name??error.name:"Error","error.message":error instanceof Error?error.message:String(error)}); + throw refusal; + } + }, safetyReady: (turnId,backendId,version)=>call("safetyReady",turnId,backendId,version), safetyEnd: turnId=>call("safetyEnd",turnId,shared.unscopedLoss||shared.lostTurns.has(turnId)), safetyFail, safety: (turnId,sessionId)=>snapshot(()=>{ const projection=safetyProjection(db,turnId,sessionId); - const local=pendingInScope(turnId,sessionId).length; - if(local||shared.failed){projection.restriction="restricted";projection.pendingCount=Math.max(local,projection.pendingCount); + const local=pendingInScope(turnId,sessionId).length,lost=shared.failed||lostInScope(turnId,sessionId); + if(local||lost){projection.restriction="restricted";projection.pendingCount=Math.max(local,projection.pendingCount); if(local&&!projection.reasons.includes("recording_pending"))projection.reasons.push("recording_pending"); - if(shared.failed){projection.coverage.state="incomplete";if(!projection.reasons.includes("recording_failed"))projection.reasons.push("recording_failed");}} + if(lost){projection.coverage.state="incomplete";if(!projection.reasons.includes("recording_failed"))projection.reasons.push("recording_failed");}} return projection; }), recordingAvailable(turnId,sessionId){ return snapshot(()=>{ - if(shared.failed||pendingInScope(turnId,sessionId).length)return false; + if(covered(turnId))return true; + if(shared.failed||lostInScope(turnId,sessionId)||pendingInScope(turnId,sessionId).length)return false; const state=safetyProjection(db,turnId,sessionId); return !state.reasons.some(reason=>["recording_failed","recording_pending","capacity"].includes(reason)); }); }, - firstTaint: input => record(input).then(result => result.recorded), + firstTaint: (input, options) => record(input, options).then(result => result.recorded), taint(turnId, sessionId) { return snapshot(()=>{ - if (shared.failed) return { eventId: 0, source: "legacy_unknown" }; + if (shared.failed||lostInScope(turnId,sessionId)) return { eventId: 0, source: "legacy_unknown" }; const committed = sessionTaint(db, turnId, sessionId); if (committed && committed.eventId>0) return committed; const pending=pendingInScope(turnId,sessionId)[0]; @@ -173,5 +256,43 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov }, roadblocks: (attribution, trace) => call("roadblocks", attribution, trace), replaySteering: () => call("replaySteering"), + recordingStatus: () => safetyRecordingStatus(db), + recoverRecording(actor){ + const result=recoverSafetyRecording(db,{trigger:"owner",actor}); + notifySafetyChanged(db);return result; + }, }; } + +/** + * Automatic recovery of the brain-wide recorder (#3812). Needs no judgment: + * it commits the permanent gaps and clears the latch, so it keeps trying, + * backing off to once a minute, and never stops at a retry count. + */ +export function scheduleSafetyRecovery(db:Database):void { + const queue=safetyQueue(db),state=queue.recovery; + if(state.timer)return; + const delay=Math.min(60000,250*2**Math.min(state.attempt,8)); + state.timer=setTimeout(()=>{ + state.timer=null; + if(!attemptSafetyRecovery(db)){state.attempt++;scheduleSafetyRecovery(db);} + else state.attempt=0; + },delay); + (state.timer as {unref?:()=>void}).unref?.(); +} +/** One automatic attempt. True once nothing brain-wide remains to recover. */ +export function attemptSafetyRecovery(db:Database):boolean { + const queue=safetyQueue(db); + try{ + const failed=queue.failed||!!(db.query("SELECT failed FROM safety_meta WHERE singleton=1").get() as {failed:number}|null)?.failed; + if(!failed)return true; + // A legacy row without its record or its gap must not be cleared over. + if(!migrateSafetyHistory(db))return false; + recoverSafetyRecording(db,{trigger:"automatic",actor:"host"}); + notifySafetyChanged(db); + return true; + }catch(error){ + // A closed database ends this host's attempts; anything else is retried. + return error instanceof Error&&/closed database|Cannot use a closed/i.test(error.message); + } +} diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index 4176e35fd6..dfa2f46bd3 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -5,6 +5,7 @@ import { inputTaintSignals, outputTaintSignals, type IngestionSignal } from "../ import { isMarkedUntrusted } from "../files/untrusted-marks.js"; import { occurrence } from "./occurrence.js"; import type { GovernanceWrites } from "./event-writes.js"; +import { SafetyRecordingUnavailable } from "./safety-store.js"; export function createSafetyCollector(db:Database,writes:GovernanceWrites,options:{turnId:string;bindingId:string;backendId:string; sessionId:()=>string|null;actor?:"interactive"|"voice";brainPath?:string;shellProxied:()=>boolean;signal:AbortSignal;onReady?:()=>void;stop?:(error:Error)=>void;policyHash?:string|null}):NonNullable { @@ -16,7 +17,11 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option const fail=async(error:unknown)=>{ const failures=[error]; try{options.stop?.(error instanceof Error?error:new Error(String(error)));}catch(stop){failures.push(stop);} - try{await writes.safetyFail(options.turnId);} + // Every record here commits before the backend releases its input. A + // refused reservation with a producer that did stop delivered nothing: + // only this turn is refused, and its chat keeps no gap (#3812). + if(failures.length===1&&error instanceof SafetyRecordingUnavailable&&error.beforeDelivery)throw error; + try{await writes.safetyFail(options.turnId,error);} catch(notice){throw new AggregateError([...failures,notice],`Safety input refused: ${String(error)}; failure notice could not commit`);} if(failures.length>1)throw new AggregateError(failures,`Safety input refused: ${String(error)}`); throw error; @@ -44,7 +49,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option for(const signal of inputTaintSignals(tool,input,options.brainPath,marked,options.shellProxied())){ if(op.signals.some(prior=>prior.detector===signal.detector&&prior.key===signal.key))continue; const item=occurrence(options.bindingId,signal.detector,op.id,"open");item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; - await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}}); + await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}},{beforeDelivery:true}); op.occurrences.push(item.id);op.signals.push(signal); } assertLive(); @@ -60,12 +65,12 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option // Each separately delivered external result segment has its own exposure. for(const _segment of (segments??[]).slice(1))for(const signal of op.signals.filter(signal=>["compute_input","external_mcp_input","attachment_input","tool_web_input"].includes(signal.detector))){ const item=occurrence(options.bindingId,signal.detector,op.id,"open");item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; - await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); + await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}},{beforeDelivery:true});op.occurrences.push(item.id); } // Record output independently, before the backend releases any of its bytes. for(const signal of outputTaintSignals(tool,output,options.brainPath,marked)){ const item=occurrence(options.bindingId,signal.detector,op.id,"open");item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; - await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); + await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}},{beforeDelivery:true});op.occurrences.push(item.id); } const state=finalized&&!['Bash','bash'].includes(tool)?"finalized":"interrupted_unknown"; for(const id of op.occurrences)await writes.record({...base(),kind:"taint_exposure",dedupeKey:id,payload:{occurrenceId:id,state}}); diff --git a/packages/ui-server/src/governance/safety-queue.ts b/packages/ui-server/src/governance/safety-queue.ts index 8df0772e15..29a667de37 100644 --- a/packages/ui-server/src/governance/safety-queue.ts +++ b/packages/ui-server/src/governance/safety-queue.ts @@ -3,10 +3,10 @@ import type { Database } from "bun:sqlite"; import type { SessionTaint } from "./session-taint.js"; type PendingSafety = {turnId:string|null;sessionId:string|null;source:SessionTaint["source"];bytes:number}; const queues=new WeakMap;bytes:number;failed:boolean;inflight:number; - lostTurns:Set;unscopedLoss:boolean;listeners:Set<()=>void>}>(); + lostTurns:Set;unscopedLoss:boolean;listeners:Set<()=>void>;recovery:{timer:ReturnType|null;attempt:number}}>(); export function safetyQueue(db:Database){ let queue=queues.get(db); - if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,lostTurns:new Set(),unscopedLoss:false,listeners:new Set()};queues.set(db,queue);} + if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,lostTurns:new Set(),unscopedLoss:false,listeners:new Set(),recovery:{timer:null,attempt:0}};queues.set(db,queue);} return queue; } @@ -16,11 +16,14 @@ export function notifySafetyChanged(db:Database):void { } } -/** Bounded, fail-closed fallback when the durable failure notice itself fails. - * Unscoped/overflow loss requires conservative coverage recovery for all epochs. */ -export function retainSafetyLoss(db:Database,turnId:string|null):void { - const queue=safetyQueue(db);queue.failed=true; - if(turnId===null||(!queue.lostTurns.has(turnId)&&queue.lostTurns.size>=4096))queue.unscopedLoss=true; +/** Bounded, fail-closed fallback while a durable failure notice is not yet + * committed. A known turn restricts only its own chat. Unscoped/overflow loss, + * or a notice that could not commit at all (`brainWide`), restricts the brain + * until automatic recovery commits conservative gaps for every affected epoch. */ +export function retainSafetyLoss(db:Database,turnId:string|null,brainWide=false):void { + const queue=safetyQueue(db); + if(turnId===null||(!queue.lostTurns.has(turnId)&&queue.lostTurns.size>=4096)){queue.unscopedLoss=true;queue.failed=true;} else queue.lostTurns.add(turnId); + if(brainWide)queue.failed=true; notifySafetyChanged(db); } diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index 750aa6a54c..dca2c68d4f 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -18,36 +18,113 @@ function actualGeneration(value:number):string { const VERDICT_BYTES = 2048, TERMINAL_BYTES = 2048; interface SafetySessionKey { sessionId: string; historyOwnerId: string; historyGeneration: string } export interface SafetyCollectionInput { turnId: string; bindingId: string; principalId: string | null; historyOwnerId?: string; - sessionId: string | null; backendId: string; sourceSessionId?: string; policyHash?: string|null; at: number } + sessionId: string | null; backendId: string; sourceSessionId?: string; policyHash?: string|null; at: number; + /** Begin under the brain-wide restriction: a permanent gap before any delivery. */ + restricted?: boolean } interface Collection { id: string; turn_id: string; session_id: string | null; principal_id: string | null; history_owner_id: string | null; generation: string; backend_id: string; started_at: number; ended: number; acknowledged: string; gap: string | null; failure: string | null; - policy_hash:string|null; start_revision: string; end_revision: string | null } + policy_hash:string|null; start_revision: string; end_revision: string | null; restricted_begin: number; failure_cause: string | null } interface Session { session_id: string; history_owner_id: string; generation: string; principal_id: string | null; classification: string; origin_turn: string | null; backend_id: string | null } export class SafetyUnavailable extends Error { constructor(message: string) { super(message); } } +/** A capacity check refused the write. Only this class latches as `capacity`. */ +export class SafetyCapacityExhausted extends SafetyUnavailable {} +/** + * A turn refused before any of its input reached the model, because its + * safety record could not be written. Nothing ran and nothing is latched, so + * a retry can succeed. `paused` means the brain-wide recorder is failed and + * even the restricted begin could not commit: the one case that refuses a + * turn outright instead of running it restricted (#3812). + */ +export class SafetyRecordingUnavailable extends Error { + readonly code = "safety_recording_unavailable"; + readonly beforeDelivery = true; + /** A capacity check refused it: retrying waits for room, not for luck. */ + readonly capacity: boolean; + constructor(readonly paused: boolean, cause?: unknown) { + const capacity = cause instanceof SafetyCapacityExhausted || (cause as { name?: string } | null)?.name === "SafetyCapacityExhausted"; + super(paused + ? "Safety recording is paused on this server, so this turn could not start. Nothing was sent. The server recovers it automatically." + : capacity ? `Safety recording has no room left (${(cause as Error).message}). Nothing was sent.` + : "Safety recording failed before anything was sent. Nothing ran; try again.", { cause }); + this.capacity = capacity; + } +} const one = (db: Database, sql: string, ...args: (string | number | null)[]) => db.query(sql).get(...args) as T; const collection = (db: Database, turn: string) => one(db,"SELECT * FROM safety_collections WHERE turn_id=?",turn); -const meta = (db: Database) => one<{revision:string;failed:number;used_rows:number;used_bytes:number;scope_rows:number;scope_bytes:number}>(db,"SELECT * FROM safety_meta WHERE singleton=1"); +const meta = (db: Database) => one<{revision:string;failed:number;reason:string|null;used_rows:number;used_bytes:number;scope_rows:number;scope_bytes:number}>(db,"SELECT * FROM safety_meta WHERE singleton=1"); export function advance(db: Database): string { const old=BigInt(meta(db).revision); - if(old>=MAX_REVISION) throw new SafetyUnavailable("Safety revision exhausted"); + if(old>=MAX_REVISION) throw new SafetyCapacityExhausted("Safety revision exhausted"); const next=String(old+1n); db.query("UPDATE safety_meta SET revision=? WHERE singleton=1").run(next); return next; } -/** Existing emergency cells are allocated before ingestion, never appended at overflow. */ -export function latchSafety(db:Database,turnId:string|null,reason:"recording_failed"|"capacity"):void { + +/** Where a safety-recording failure was raised. */ +export type SafetyFailureSite = "safetyBegin"|"safetyReserve"|"safetyCommit"|"record"|"safetyFail"|"safetyEnd"|"migrate"|"boot-pending"; +export type SafetyFailureReason = "recording_failed"|"capacity"; +/** A failure's cause: identifiers and error text only, never message content. */ +export interface SafetyFailureCause { errorClass:string; message:string; stack:string|null; site:SafetyFailureSite; turnId:string|null; at:number } +const clip=(text:string,bytes:number)=>{const buffer=Buffer.from(text);return buffer.length<=bytes?text:buffer.subarray(0,bytes).toString().replace(/�+$/,"");}; +export function safetyFailureCause(error:unknown,site:SafetyFailureSite,turnId:string|null,at=Date.now()):SafetyFailureCause { + const value=error instanceof Error?error:new Error(String(error)); + const named=value.constructor?.name; + return {errorClass:clip(named&&named!=="Error"?named:value.name||"Error",128),message:clip(value.message,512), + stack:value.stack?clip(value.stack.split("\n").slice(1,9).map(line=>line.trim()).join("\n"),2048):null,site,turnId,at}; +} +/** Honest classification: `capacity` only when a capacity check refused the write. */ +export function safetyFailureReason(error:unknown):SafetyFailureReason { + return error instanceof SafetyCapacityExhausted?"capacity":"recording_failed"; +} +/** One structured stderr line per latch, restriction or recovery. */ +export function logSafetyRecording(body:string,attributes:Record):void { + try{process.stderr.write(`${JSON.stringify({severityText:body.includes("recovered")?"WARN":"ERROR",body,attributes})}\n`);}catch{/* Logging never changes containment. */} +} +const causeAttributes=(scope:string,reason:string,cause:SafetyFailureCause)=>({"safety.scope":scope,"safety.reason":reason,"safety.site":cause.site, + "safety.turn_id":cause.turnId,"error.class":cause.errorClass,"error.message":cause.message}); + +/** Chat scope: marks only this turn's collection failed, with its first cause. + * Returns false when the turn has no collection to carry the fact. */ +export function failSafetyCollection(db:Database,turnId:string,reason:SafetyFailureReason,cause:SafetyFailureCause):boolean { + const marked=db.transaction(()=>{ + const c=collection(db,turnId);if(!c)return false; + db.query(`UPDATE safety_collections SET failure=CASE WHEN failure='capacity' THEN failure ELSE ? END, + failure_cause=COALESCE(failure_cause,?) WHERE id=?`).run(reason,JSON.stringify(cause),c.id); + advance(db);return true; + }).immediate(); + if(marked)logSafetyRecording("safety recording failed for one chat",causeAttributes("chat",reason,cause)); + return marked; +} +/** Brain scope: the evidence store could not take a scoped fact. Uses the + * emergency cells allocated before ingestion, never appended at overflow. + * The first cause is kept; later latches only count. */ +export function latchSafety(db:Database,turnId:string|null,reason:SafetyFailureReason,cause:SafetyFailureCause=safetyFailureCause(new Error("Safety recording latched"),"safetyFail",turnId)):void { db.transaction(()=>{ db.query("UPDATE safety_emergency_reserve SET padding=zeroblob(0) WHERE singleton=1").run(); db.query("UPDATE safety_meta SET failed=1,reason=CASE WHEN reason='capacity' THEN reason ELSE ? END WHERE singleton=1").run(reason); - if(turnId) db.query("UPDATE safety_collections SET failure=CASE WHEN failure='capacity' THEN failure ELSE ? END WHERE turn_id=?").run(reason,turnId); + db.query(`INSERT INTO safety_latch(singleton,since,reason,site,turn_id,error_class,message,stack) VALUES(1,?,?,?,?,?,?,?) + ON CONFLICT(singleton) DO UPDATE SET count=count+1`).run(cause.at,reason,cause.site,cause.turnId,cause.errorClass,cause.message,cause.stack); + if(turnId) db.query("UPDATE safety_collections SET failure=CASE WHEN failure='capacity' THEN failure ELSE ? END,failure_cause=COALESCE(failure_cause,?) WHERE turn_id=?").run(reason,JSON.stringify(cause),turnId); if(BigInt(meta(db).revision)(db,"SELECT generation FROM dialogue_owners WHERE id=?",c.history_owner_id):null; if(owner&&String(owner.generation)!==c.generation)throw new SafetyUnavailable("Safety history generation changed"); if(c.ended)throw new SafetyUnavailable("Safety collection ended; late input refused"); - if(!reserved&&(c.failure||meta(db).failed))throw new SafetyUnavailable("Safety collection requires recovery"); + // A collection begun restricted already carries its permanent gap: the + // brain-wide latch cannot make its evidence any less complete. + if(!reserved&&(c.failure||(meta(db).failed&&!c.restricted_begin)))throw new SafetyUnavailable("Safety collection requires recovery"); } function capacity(db:Database,c:Collection,rows:number,bytes:number):void { const all=meta(db); @@ -59,11 +136,11 @@ function capacity(db:Database,c:Collection,rows:number,bytes:number):void { FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE ${scope}`,...args); if(all.used_rows+all.scope_rows+pending.rows+rows>SAFETY_LIMITS.brainRows||all.used_bytes+all.scope_bytes+pending.bytes+bytes>SAFETY_LIMITS.brainBytes ||used.rows+localPending.rows+rows>SAFETY_LIMITS.sessionRows||used.bytes+localPending.bytes+bytes>SAFETY_LIMITS.sessionBytes) - throw new SafetyUnavailable("Safety ledger capacity exhausted"); + throw new SafetyCapacityExhausted("Safety ledger capacity exhausted"); if(c.session_id===null){ const unbound=one<{bytes:number}>(db,`SELECT COALESCE(SUM(r.reserved_bytes),0) bytes FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.session_id IS NULL`); - if(unbound.bytes+pending.bytes+bytes+one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL").n*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyUnavailable("Safety unbound byte capacity exhausted"); + if(unbound.bytes+pending.bytes+bytes+one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL").n*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted"); } } /** Must commit before any first-turn bytes or tool execution. Callbacks cannot create a session. */ @@ -73,7 +150,10 @@ export function beginSafetyCollection(db:Database,input:SafetyCollectionInput):s if(id!==null&&id!==undefined&&!/^[A-Za-z0-9_-]{1,128}$/.test(id))throw new SafetyUnavailable("Invalid bounded safety identity"); } if(!Number.isSafeInteger(input.at)||input.at<0)throw new SafetyUnavailable("Invalid safety clock"); - if(meta(db).failed)throw new SafetyUnavailable("Safety recording requires recovery"); + // While the brain-wide recorder is failed, a new turn still runs, restricted: + // its collection carries a permanent gap before any input is delivered, so + // nothing it loses can ever make its chat look complete (#3812). + const restricted=!!input.restricted||!!meta(db).failed; if(db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(input.turnId))throw new ChatRetiredError(); const previous=collection(db,input.turnId); if(previous){if(previous.id!==input.bindingId||previous.principal_id!==input.principalId||previous.backend_id!==input.backendId)throw new SafetyUnavailable("Conflicting safety collection"); live(db,previous);return previous.id;} @@ -91,27 +171,27 @@ export function beginSafetyCollection(db:Database,input:SafetyCollectionInput):s assertLive(db,[["dialogue_owner",owner]]); if(session?.principal_id&&session.principal_id!==input.principalId)throw new SafetyUnavailable("Safety principal mismatch"); const n=one<{n:number}>(db, input.sessionId?"SELECT COUNT(*) n FROM safety_collections WHERE session_id=?":"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL",...(input.sessionId?[input.sessionId]:[])); - if(n.n>=(input.sessionId?SAFETY_LIMITS.epochs:SAFETY_LIMITS.unbound))throw new SafetyUnavailable("Safety coverage capacity exhausted"); + if(n.n>=(input.sessionId?SAFETY_LIMITS.epochs:SAFETY_LIMITS.unbound))throw new SafetyCapacityExhausted("Safety coverage capacity exhausted"); if(input.sessionId===null){ const unbound=one<{bytes:number}>(db,`SELECT COALESCE(SUM(r.reserved_bytes),0) bytes FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.session_id IS NULL`); const pending=one<{bytes:number}>(db,`SELECT COALESCE(SUM(p.reserved_bytes),0) bytes FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE c.session_id IS NULL`); - if(unbound.bytes+pending.bytes+(n.n+1)*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyUnavailable("Safety unbound byte capacity exhausted"); + if(unbound.bytes+pending.bytes+(n.n+1)*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted"); } const ledger=meta(db),pending=one<{rows:number;bytes:number}>(db,"SELECT COALESCE(SUM(rows),0) rows,COALESCE(SUM(reserved_bytes),0) bytes FROM safety_pending"); - if(ledger.used_rows+ledger.scope_rows+pending.rows+1>SAFETY_LIMITS.brainRows||ledger.used_bytes+ledger.scope_bytes+pending.bytes+2048>SAFETY_LIMITS.brainBytes)throw new SafetyUnavailable("Safety identity capacity exhausted"); - if(owner&&one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE history_owner_id=? AND generation=?",owner,generation).n>=128)throw new SafetyUnavailable("Safety coverage capacity exhausted"); + if(ledger.used_rows+ledger.scope_rows+pending.rows+1>SAFETY_LIMITS.brainRows||ledger.used_bytes+ledger.scope_bytes+pending.bytes+2048>SAFETY_LIMITS.brainBytes)throw new SafetyCapacityExhausted("Safety identity capacity exhausted"); + if(owner&&one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE history_owner_id=? AND generation=?",owner,generation).n>=128)throw new SafetyCapacityExhausted("Safety coverage capacity exhausted"); if(input.policyHash!==undefined&&input.policyHash!==null&&!/^[a-f0-9]{64}$/.test(input.policyHash))throw new SafetyUnavailable("Invalid safety policy hash"); - const gap=uncollectedOwner?"missing_history_owner_collection":input.sessionId&&!session?.principal_id?"unknown_history_owner":session?.backend_id&&session.backend_id!==input.backendId?"backend_history_not_reconstructed":null; + const gap=restricted?"recording_failed":uncollectedOwner?"missing_history_owner_collection":input.sessionId&&!session?.principal_id?"unknown_history_owner":session?.backend_id&&session.backend_id!==input.backendId?"backend_history_not_reconstructed":null; db.query(`INSERT INTO safety_collections(id,turn_id,session_id,principal_id,history_owner_id,generation,backend_id,started_at,gap,start_revision) VALUES (?,?,?,?,?,?,?,?,?,?)`).run(input.bindingId,input.turnId,input.sessionId,input.principalId,owner,generation,input.backendId,input.at,gap,advance(db)); - db.query("UPDATE safety_collections SET policy_hash=? WHERE id=?").run(input.policyHash??null,input.bindingId); + db.query("UPDATE safety_collections SET policy_hash=?,restricted_begin=? WHERE id=?").run(input.policyHash??null,restricted?1:0,input.bindingId); db.query("UPDATE safety_meta SET scope_rows=scope_rows+1,scope_bytes=scope_bytes+2048 WHERE singleton=1").run(); if(input.sessionId)bindSafetyCollection(db,input.turnId,input.sessionId); if(input.sourceSessionId){ const sourceOwner=one<{principal_id:string|null}|null>(db,"SELECT principal_id FROM safety_sessions WHERE session_id=?",input.sourceSessionId); if(sourceOwner?.principal_id&&sourceOwner.principal_id!==input.principalId)throw new SafetyUnavailable("Safety fork history ownership mismatch"); safetyProjection(db,null,input.sourceSessionId); // Also validates retirement. - db.query("UPDATE safety_collections SET gap='inherited_history_not_reconstructed' WHERE id=?").run(input.bindingId); + db.query("UPDATE safety_collections SET gap=CASE WHEN restricted_begin=1 THEN gap ELSE 'inherited_history_not_reconstructed' END WHERE id=?").run(input.bindingId); const records=db.query(`SELECT r.* FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.session_id=? AND r.kind='occurrence' AND NOT EXISTS(SELECT 1 FROM safety_decisions d WHERE d.occurrence_id=r.id)`).iterate(input.sourceSessionId); for(const r of records){const payload=JSON.parse(r.payload);payload.occurrence=occurrence(input.bindingId,(r.detector??"tool_file_input") as Occurrence["detector"],null,"interrupted_unknown"); @@ -151,14 +231,14 @@ export function bindSafetyCollection(db:Database,turnId:string,sessionId:string) assertLive(db,[["session",sessionId],["dialogue_owner",owner]]); const {scope,args}=safetyScope(db,turnId,sessionId); const epochs=one<{n:number}>(db,`SELECT COUNT(*) n FROM safety_collections c WHERE ${scope}`,...args); - if(epochs.n>128)throw new SafetyUnavailable("Safety binding coverage capacity exhausted"); + if(epochs.n>128)throw new SafetyCapacityExhausted("Safety binding coverage capacity exhausted"); const totals=one<{rows:number;bytes:number}>(db,`SELECT COALESCE(SUM(r.reserved_rows),0) rows,COALESCE(SUM(r.reserved_bytes),0) bytes FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE ${scope}`,...args); const pending=one<{rows:number;bytes:number;count:number;serializedBytes:number}>(db,`SELECT COALESCE(SUM(p.rows),0) rows,COALESCE(SUM(p.reserved_bytes),0) bytes, COUNT(*) count,COALESCE(SUM(p.bytes),0) serializedBytes FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE ${scope}`,...args); - if(totals.rows+pending.rows>SAFETY_LIMITS.sessionRows||totals.bytes+pending.bytes>SAFETY_LIMITS.sessionBytes)throw new SafetyUnavailable("Safety binding capacity exhausted"); - if(pending.count>SAFETY_LIMITS.sessionPending||pending.serializedBytes>SAFETY_LIMITS.sessionPendingBytes)throw new SafetyUnavailable("Safety binding pending capacity exhausted"); + if(totals.rows+pending.rows>SAFETY_LIMITS.sessionRows||totals.bytes+pending.bytes>SAFETY_LIMITS.sessionBytes)throw new SafetyCapacityExhausted("Safety binding capacity exhausted"); + if(pending.count>SAFETY_LIMITS.sessionPending||pending.serializedBytes>SAFETY_LIMITS.sessionPendingBytes)throw new SafetyCapacityExhausted("Safety binding pending capacity exhausted"); const previous=one<{session_id:string;history_owner_id:string;generation:string}|null>(db,"SELECT * FROM safety_bindings WHERE turn_id=?",turnId); if(previous&&(previous.session_id!==sessionId||previous.history_owner_id!==owner||previous.generation!==gen))throw new SafetyUnavailable("Safety SessionKey binding changed"); db.query("INSERT INTO safety_bindings VALUES(?,?,?,?,?,?) ON CONFLICT DO NOTHING").run(c.id,turnId,sessionId,owner,gen,advance(db)); @@ -178,12 +258,12 @@ function appendRecord(db:Database,c:Collection,id:string,kind:"occurrence"|"expo const json=JSON.stringify(payload),bytes=Buffer.byteLength(JSON.stringify({id,collectionId:c.id,turnId:c.turn_id, session:{sessionId:c.session_id,historyOwnerId:c.history_owner_id,historyGeneration:c.generation},sequence:"18446744073709551615",observedAt:at, kind,occurrenceId,source,detector,state,payload})); - if(bytes>SAFETY_LIMITS.occurrenceBytes)throw new SafetyUnavailable("Safety occurrence byte limit exceeded"); + if(bytes>SAFETY_LIMITS.occurrenceBytes)throw new SafetyCapacityExhausted("Safety occurrence byte limit exceeded"); const previous=one(db,"SELECT * FROM safety_records WHERE id=?",id); if(previous){if(previous.collection_id!==c.id||(previous.detail_pruned ? previous.payload!==JSON.stringify({sha256:new Bun.CryptoHasher("sha256").update(json).digest("hex")}) : previous.payload!==json))throw new SafetyUnavailable("Conflicting safety occurrence identity");return;} const rows=kind==="occurrence"?(state==="finalized"?2:4):0, reserved=kind==="occurrence"?bytes+VERDICT_BYTES+(state==="finalized"?0:2*TERMINAL_BYTES):0; - if(kind==="exposure"&&bytes>TERMINAL_BYTES)throw new SafetyUnavailable("Safety terminal reserve exceeded"); + if(kind==="exposure"&&bytes>TERMINAL_BYTES)throw new SafetyCapacityExhausted("Safety terminal reserve exceeded"); capacity(db,c,rows,reserved); db.query("INSERT INTO safety_records VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,0)").run(id,c.id,advance(db),at,kind,occurrenceId,source,detector,state,json,bytes,rows,reserved); db.query("UPDATE safety_meta SET used_rows=used_rows+?,used_bytes=used_bytes+? WHERE singleton=1").run(rows,reserved); @@ -223,6 +303,13 @@ export function endSafetyCollection(db:Database,turnId:string):void { db.transaction(()=>{const c=collection(db,turnId);if(!c||c.ended)return; // Lost/incomplete hooks leave exposures open and therefore unresolved. db.query("UPDATE safety_collections SET ended=1,end_revision=? WHERE id=?").run(advance(db),c.id); + // A reservation still open at the end can never commit: an ended epoch + // refuses late input. Its possibly delivered input becomes this chat's + // permanent gap, so the chat runs restricted instead of staying pending. + if(one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_pending WHERE collection_id=?",c.id).n){ + db.query("UPDATE safety_collections SET failure=COALESCE(failure,'recording_failed'),gap=COALESCE(gap,'recording_failed_recovered') WHERE id=?").run(c.id); + db.query("DELETE FROM safety_pending WHERE collection_id=?").run(c.id); + } }).immediate(); } export interface SafetyProjection { session:SafetySessionKey|null;evidenceRevision:string;unresolvedCount:number;earliestUnresolvedId:string|null; @@ -301,7 +388,8 @@ export function recoverSafetyCollections(db:Database):void { db.transaction(()=>{ const n=one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE ended=0").n; if(n){db.query("UPDATE safety_collections SET gap=COALESCE(gap,'host_restart_unknown'),ended=1,end_revision=? WHERE ended=0").run(advance(db));} - if(one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_pending").n)latchSafety(db,null,"recording_failed"); + if(one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_pending").n) + latchSafety(db,null,"recording_failed",safetyFailureCause(new SafetyUnavailable("Safety reservations were pending at restart"),"boot-pending",null)); }).immediate(); } /** Prune only display bytes; identity, counts and reserved audit capacity survive. */ @@ -324,14 +412,18 @@ export function reserveSafetyWrite(db:Database,turnId:string,requestId:string,by const local=one<{n:number;bytes:number}>(db,`SELECT COUNT(*) n,COALESCE(SUM(p.bytes),0) bytes FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE ${scope}`,...args); if(global.n>=SAFETY_LIMITS.brainPending||global.bytes+bytes>SAFETY_LIMITS.brainPendingBytes||local.n>=SAFETY_LIMITS.sessionPending||local.bytes+bytes>SAFETY_LIMITS.sessionPendingBytes) - throw new SafetyUnavailable("Safety pending capacity exhausted"); + throw new SafetyCapacityExhausted("Safety pending capacity exhausted"); const rows=terminalOccurrenceId?0:4,reserved=terminalOccurrenceId?0:bytes+VERDICT_BYTES+2*TERMINAL_BYTES; capacity(db,c,rows,reserved); db.query("INSERT INTO safety_pending VALUES(?,?,?,?,?)").run(requestId,c.id,bytes,rows,reserved);advance(db); }).immediate(); } export function releaseSafetyWrite(db:Database,id:string):void {db.query("DELETE FROM safety_pending WHERE id=?").run(id);advance(db);} -export function migrateSafetyHistory(db:Database):void { +/** Appends legacy taint rows. A row that cannot be appended gives its turn a + * permanent gap instead; only when even that fails is the brain latched. + * Returns false while some legacy row has neither its record nor its gap. */ +export function migrateSafetyHistory(db:Database):boolean { + let complete=true; type Legacy={id:number;session_id:string|null;turn_id:string|null;at:number;kind:"taint";payload:string;schema_version:number;actor:GovernanceEventRow["actor"];model:string|null;profile:GovernanceEventRow["profile"];dedupe_key:string|null}; let after=0; for(;;){ @@ -339,11 +431,25 @@ export function migrateSafetyHistory(db:Database):void { AND NOT EXISTS(SELECT 1 FROM safety_legacy_events m WHERE m.event_id=g.id) AND NOT EXISTS(SELECT 1 FROM safety_retired_turns t WHERE t.turn_id=g.turn_id) AND NOT EXISTS(SELECT 1 FROM chat_retired_identities t WHERE t.kind='session' AND t.id=g.session_id) ORDER BY g.id LIMIT 100`).all(after); - if(!rows.length)return; + if(!rows.length)return complete; for(const r of rows){try{db.transaction(()=>{ const recordId=appendSafetyEvent(db,{sessionId:r.session_id,turnId:r.turn_id,at:r.at,kind:r.kind,payload:r.payload,version:r.schema_version,actor:r.actor,model:r.model,profile:r.profile,dedupeKey:r.dedupe_key}); db.query("INSERT INTO safety_legacy_events VALUES(?,?)").run(r.id,recordId!); - }).immediate();after=r.id;}catch{latchSafety(db,r.turn_id,"capacity");return;}} + }).immediate();}catch(error){ + const turnId=r.turn_id??`legacy_event_${r.id}`,reason=safetyFailureReason(error),cause=safetyFailureCause(error,"migrate",turnId); + try{db.transaction(()=>{ + ensureSafetyEventCollection(db,{sessionId:r.session_id,turnId,at:r.at,kind:r.kind,payload:r.payload,version:r.schema_version,actor:r.actor,model:r.model,profile:r.profile,dedupeKey:r.dedupe_key}); + failSafetyCollection(db,turnId,reason,cause); + db.query("UPDATE safety_collections SET ended=1,end_revision=COALESCE(end_revision,?) WHERE turn_id=?").run(advance(db),turnId); + }).immediate();} + catch(scoped){ + if(scoped instanceof ChatRetiredError){after=r.id;continue;} + complete=false; + try{latchSafety(db,r.turn_id,reason,cause);}catch{/* The unmigrated row is retried; the next boot latches again. */} + return complete; + } + } + after=r.id;} } } /** Bounded compact rows are for host tests/next slices, never authorization. */ @@ -373,23 +479,71 @@ export function ensureSafetyEventCollection(db:Database,row:GovernanceEventRow): return c.turn_id; } -/** Explicit host recovery after producers have stopped. Clears infrastructure - * failure only; historical gaps and unresolved identities never become clean. */ -export function recoverSafetyRecording(db:Database):void { - const local=safetyQueue(db); - if(local.pending.size||local.inflight)throw new SafetyUnavailable("Stop all safety producers before recovery"); +export type SafetyRecoveryTrigger = "boot"|"automatic"|"owner"; +export interface SafetyRecovery { recovered:boolean; trigger:SafetyRecoveryTrigger; actor:string; at:number; gapped:number; cause:SafetyLatchCause|null } +export interface SafetyLatchCause { reason:string; site:string; turnId:string|null; errorClass:string; message:string; stack:string|null; since:number; count:number } +const latchCause=(db:Database):SafetyLatchCause|null=>{ + const row=one<{since:number;reason:string;site:string;turn_id:string|null;error_class:string;message:string;stack:string|null;count:number}|null>(db,"SELECT * FROM safety_latch WHERE singleton=1"); + return row?{reason:row.reason,site:row.site,turnId:row.turn_id,errorClass:row.error_class,message:row.message,stack:row.stack,since:row.since,count:row.count}:null; +}; +/** What the owner sees about the brain-wide recorder (#3810). */ +export interface SafetyRecordingStatus { latched:boolean; since:number|null; reason:string|null; cause:SafetyLatchCause|null; retained:boolean; lastRecovery:Omit|null } +export function safetyRecordingStatus(db:Database):SafetyRecordingStatus { + return Database.prototype.transaction.call(db,()=>{ + const m=meta(db),local=safetyQueue(db),cause=latchCause(db); + const last=one<{at:number;trigger:SafetyRecoveryTrigger;actor:string;cause:string|null;gapped:number}|null>(db,"SELECT * FROM safety_recoveries ORDER BY id DESC LIMIT 1"); + return {latched:!!m.failed||local.failed,since:cause?.since??null,reason:m.failed?(m.reason??"recording_failed"):local.failed?"recording_failed":null,cause, + retained:local.failed&&!m.failed, + lastRecovery:last?{trigger:last.trigger,actor:last.actor,at:last.at,gapped:last.gapped,cause:last.cause?JSON.parse(last.cause) as SafetyLatchCause:null}:null}; + }).deferred() as SafetyRecordingStatus; +} + +/** + * Clears the brain-wide recorder failure once its gap facts are durable. + * Historical gaps and unresolved identities never become clean: every turn + * whose evidence may be lost keeps a permanent `recording_failed_recovered` + * gap, so its chat stays restricted until reviewed. + * + * `owner` and `boot` recovery require every producer to have stopped. + * `automatic` recovery runs beside turns begun restricted: their collections + * already carry a permanent gap, so it waits only for producers whose + * evidence could still be in flight (#3812). + */ +export function recoverSafetyRecording(db:Database,options:{trigger?:SafetyRecoveryTrigger;actor?:string}={}):SafetyRecovery { + const local=safetyQueue(db),trigger=options.trigger??"owner",actor=options.actor??"host",at=Date.now(); + const automatic=trigger==="automatic"; + const covered=(turnId:string|null)=>turnId!==null&&!!db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND (restricted_begin=1 OR failure IS NOT NULL)").get(turnId); + if(automatic?[...local.pending].some(p=>!local.unscopedLoss&&!covered(p.turnId)&&!(p.turnId!==null&&local.lostTurns.has(p.turnId))):(local.pending.size||local.inflight)) + throw new SafetyUnavailable("Stop all safety producers before recovery"); + let cause:SafetyLatchCause|null=null,gapped=0,recovered=false; db.transaction(()=>{ - if(one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE ended=0").n)throw new SafetyUnavailable("Stop all safety producers before recovery"); + const open=db.query<{turn_id:string;restricted_begin:number;failure:string|null},[]>("SELECT turn_id,restricted_begin,failure FROM safety_collections WHERE ended=0").all(); + if(automatic?open.some(c=>!local.unscopedLoss&&!c.restricted_begin&&!c.failure&&!local.lostTurns.has(c.turn_id)):open.length) + throw new SafetyUnavailable("Stop all safety producers before recovery"); const totals=meta(db); - if(totals.used_rows+totals.scope_rows>=SAFETY_LIMITS.brainRows||totals.used_bytes+totals.scope_bytes>=SAFETY_LIMITS.brainBytes)throw new SafetyUnavailable("Safety capacity must be recovered first"); + if(!totals.failed&&!local.failed&&!one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_pending").n)return; + if(totals.used_rows+totals.scope_rows>=SAFETY_LIMITS.brainRows||totals.used_bytes+totals.scope_bytes>=SAFETY_LIMITS.brainBytes)throw new SafetyCapacityExhausted("Safety capacity must be recovered first"); + cause=latchCause(db)??(local.failed?{reason:"recording_failed",site:"retained",turnId:null,errorClass:"SafetyUnavailable", + message:"Only this process retained the loss; its durable notice could not commit.",stack:null,since:at,count:1}:null); + const gap=(sql:string,...args:string[])=>{gapped+=db.query(`UPDATE safety_collections SET gap=COALESCE(gap,'recording_failed_recovered') WHERE gap IS NULL AND (${sql})`).run(...args).changes;}; // Reservations on ended epochs could never have released input: the event // and reservation consumption commit together. Retain the historical gap. - if(local.unscopedLoss)db.query("UPDATE safety_collections SET gap=COALESCE(gap,'recording_failed_recovered')").run(); - else for(const turnId of local.lostTurns)db.query("UPDATE safety_collections SET gap=COALESCE(gap,'recording_failed_recovered') WHERE turn_id=?").run(turnId); - db.query("UPDATE safety_collections SET gap=COALESCE(gap,'recording_failed_recovered') WHERE id IN (SELECT collection_id FROM safety_pending) OR failure IS NOT NULL").run(); + if(local.unscopedLoss)gap("1=1"); + else for(const turnId of local.lostTurns)gap("turn_id=?",turnId); + gap("id IN (SELECT collection_id FROM safety_pending) OR failure IS NOT NULL"); db.query("DELETE FROM safety_pending").run(); db.query("UPDATE safety_emergency_reserve SET padding=zeroblob(65536) WHERE singleton=1").run(); - db.query("UPDATE safety_meta SET failed=0,reason=NULL WHERE singleton=1").run();advance(db); + db.query("UPDATE safety_meta SET failed=0,reason=NULL WHERE singleton=1").run(); + db.query("DELETE FROM safety_latch").run(); + db.query("INSERT INTO safety_recoveries(at,trigger,actor,scope,cause,gapped) VALUES(?,?,?,'brain',?,?)").run(at,trigger,actor,cause?JSON.stringify(cause):null,gapped); + db.query("DELETE FROM safety_recoveries WHERE id NOT IN (SELECT id FROM safety_recoveries ORDER BY id DESC LIMIT 100)").run(); + advance(db);recovered=true; }).immediate(); - local.failed=false;local.lostTurns.clear();local.unscopedLoss=false; + if(recovered){ + local.failed=false;local.lostTurns.clear();local.unscopedLoss=false; + const c=cause as SafetyLatchCause|null; + logSafetyRecording("safety recording recovered for the brain",{"safety.scope":"brain","safety.trigger":trigger,"safety.actor":actor,"safety.gapped":gapped, + "safety.reason":c?.reason??null,"safety.site":c?.site??null,"error.class":c?.errorClass??null,"error.message":c?.message??null}); + } + return {recovered,trigger,actor,at,gapped,cause}; } diff --git a/packages/ui-server/src/ws/bridge-capabilities/turn-error.ts b/packages/ui-server/src/ws/bridge-capabilities/turn-error.ts index 92ae67c252..5e32fce511 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/turn-error.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/turn-error.ts @@ -3,6 +3,7 @@ import { WorkerHostError } from "@schlessera/brain-ui-sdk/internal"; import { BudgetExceeded, BudgetUnavailable } from "../../brain/turn-budgets.js"; import { JournalCapacityError } from "../../brain/journal-objects.js"; import { JournalStorageUnavailable } from "../../brain/journal-accounting.js"; +import { SafetyRecordingUnavailable } from "../../governance/safety-store.js"; import { withTurnScope } from "../frames.js"; import type { RunningTurn } from "../turns.js"; import type { WsHost } from "../host.js"; @@ -29,6 +30,13 @@ export function emitTurnError(host: WsHost, turn: RunningTurn, err: unknown): vo host.reportTurnFailed(errorClass.toUpperCase(), turn, message); host.sendToClients(withTurnScope({ type: "error", code: errorClass.toUpperCase(), message, failure: { errorClass, message }, ...correlation }, turn)); + } else if (err instanceof SafetyRecordingUnavailable) { + // Refused before delivery (#3812): retryable, and distinct from a refusal + // by the brain, so the client can say what happened (#3810). + const errorClass = err.paused ? "safety_recording_paused" : "safety_recording_unavailable"; + host.reportTurnFailed("SAFETY_RECORDING_UNAVAILABLE", turn, err.message); + host.sendToClients(withTurnScope({ type: "error", code: "SAFETY_RECORDING_UNAVAILABLE", message: err.message, + failure: { errorClass, message: err.message }, ...correlation }, turn)); } else if (err instanceof BackendBusyError) { host.reportTurnFailed("SESSION_BUSY", turn); host.sendToClients( diff --git a/packages/ui-server/tests/approval-scope-isolation.test.ts b/packages/ui-server/tests/approval-scope-isolation.test.ts index 0affaafa2c..f887db2a97 100644 --- a/packages/ui-server/tests/approval-scope-isolation.test.ts +++ b/packages/ui-server/tests/approval-scope-isolation.test.ts @@ -44,7 +44,7 @@ for (const mode of ["backward cursor", "exhausted admission"] as const) test(`ad } finally { await loss; await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } }); -for (const mode of ["other collection", "other occurrence", "own occurrence", "own exposure", "external exposure", "shared loss", "adoption", "adopted pending"] as const) { +for (const mode of ["other collection", "other occurrence", "own occurrence", "own exposure", "external exposure", "other chat loss", "own loss", "adoption", "adopted pending"] as const) { test(`pending approval follows its canonical safety scope: ${mode}`, async () => { const root = mkdtempSync(join(tmpdir(), "odysseus-approval-scope-")), path = join(root, "ui.db"), db = createUiDb(path); const writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer), store = createActivityStore(db); @@ -88,7 +88,7 @@ for (const mode of ["other collection", "other occurrence", "own occurrence", "o bridge.emit({ type: "session_info", sessionId: "ithaca", isNew: true }); await catalog.settled!(); expect(writes.safety("voyage", "ithaca").session?.historyOwnerId, "REAL_CREATED_SESSION_KEEPS_ITS_SAFETY_OWNER").toBe("binding-voyage"); - if (mode === "other occurrence" || mode === "shared loss") await other(); + if (mode === "other occurrence" || mode === "other chat loss") await other(); if (mode === "own exposure" || mode === "external exposure") await add("voyage"); if (mode === "adoption" || mode === "adopted pending") { openDialogue(db, { conversationId: "target-voice", principalId: principal.id, epoch: 1, providerId: "voice", sessionId: "ithaca" }); @@ -107,8 +107,9 @@ for (const mode of ["other collection", "other occurrence", "own occurrence", "o if (mode === "other collection") await other(); else if (mode === "other occurrence") await add("other"); else if (mode === "own occurrence") await add("voyage"); - else if (mode === "shared loss") { - await writes.safetyFail("other"); expect(controller.signal.aborted).toBe(false); + else if (mode === "other chat loss" || mode === "own loss") { + // A loss restricts its own chat only (#3812): another chat's keeps this approval. + await writes.safetyFail(mode === "own loss" ? "voyage" : "other"); expect(controller.signal.aborted).toBe(false); } else if (mode === "adoption") { bindDialogue(db, "scout-voice", principal.id, "ithaca"); expect(writes.safety("voyage", "ithaca").evidenceRevision).toBe(aggregate.evidenceRevision); @@ -140,7 +141,7 @@ for (const mode of ["other collection", "other occurrence", "own occurrence", "o } else await writes.record(event); } await writer.idle(); - const unrelated = mode === "other collection" || mode === "other occurrence"; + const unrelated = mode === "other collection" || mode === "other occurrence" || mode === "other chat loss"; if (unrelated) { expect(writes.safety("voyage", "ithaca").evidenceRevision).not.toBe(aggregate.evidenceRevision); expect(bridge.admissionSafety!.read(), "UNRELATED_SCOPE_MUST_KEEP_ADMISSION_SNAPSHOT").toEqual(before); diff --git a/packages/ui-server/tests/helpers/hold-safety-recovery.ts b/packages/ui-server/tests/helpers/hold-safety-recovery.ts new file mode 100644 index 0000000000..6f0aa38186 --- /dev/null +++ b/packages/ui-server/tests/helpers/hold-safety-recovery.ts @@ -0,0 +1,11 @@ +import type { Database } from "bun:sqlite"; +import { safetyQueue } from "../../src/governance/safety-queue"; + +/** Keeps the automatic recorder recovery (#3812) from racing a test that + * drives recovery by hand. It occupies the reconciler's one timer slot. */ +export function holdSafetyRecovery(db: Database): void { + const state = safetyQueue(db).recovery; + if (state.timer) clearTimeout(state.timer); + state.timer = setTimeout(() => {}, 2 ** 31 - 1); + (state.timer as { unref?: () => void }).unref?.(); +} diff --git a/packages/ui-server/tests/safety-containment.test.ts b/packages/ui-server/tests/safety-containment.test.ts new file mode 100644 index 0000000000..5e996683f8 --- /dev/null +++ b/packages/ui-server/tests/safety-containment.test.ts @@ -0,0 +1,299 @@ +/** A safety-recording failure restricts what it puts at risk, never more, and + * recovers by itself when recovery needs no judgment (#3812, #3810). */ +import { afterEach, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createUiDb } from "../src/db/client"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { attemptSafetyRecovery, createGovernanceWrites } from "../src/governance/event-writes"; +import { createSafetyCollector } from "../src/governance/safety-collector"; +import { latchSafety, safetyCatalogCreated, safetyFailureCause, SafetyCapacityExhausted, safetyFailureReason, + SafetyRecordingUnavailable } from "../src/governance/safety-store"; +import { emitTurnError } from "../src/ws/bridge-capabilities/turn-error"; + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); + +function open(path: string) { + const db = createUiDb(path), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); + return { db, writer, writes, async close() { await writer.close(); db.close(); } }; +} +function fixture() { + const root = mkdtempSync(join(tmpdir(), "odysseus-safety-containment-")); roots.push(root); + const path = join(root, "ui.db"); + return { path, ...open(path) }; +} +type F = ReturnType; +/** A first turn that creates `sessionId`, with complete collection. */ +async function chat(f: F, turnId: string, sessionId: string) { + const bindingId = crypto.randomUUID(); + await f.writes.safetyBegin({ turnId, bindingId, sessionId: null, principalId: "odysseus", backendId: "pi", at: 0 }); + f.db.query("INSERT INTO sessions(id,created_at,last_active_at) VALUES(?,0,0)").run(sessionId); + f.db.query("INSERT INTO chat_session_owners VALUES(?,'odysseus',0)").run(sessionId); + safetyCatalogCreated(f.db, sessionId, "odysseus", turnId); await f.writes.bind(turnId, sessionId); + const controller = new AbortController(); + const collector = createSafetyCollector(f.db, f.writes, { turnId, bindingId, sessionId: () => sessionId, backendId: "pi", + shellProxied: () => false, signal: controller.signal, stop: () => controller.abort() }); + await collector.ready("pi", 1); + return { bindingId, collector, controller }; +} +/** A later turn in an existing chat, as turn admission begins it. */ +async function next(f: F, turnId: string, sessionId: string | null) { + await f.writes.safetyBegin({ turnId, bindingId: crypto.randomUUID(), sessionId, principalId: "odysseus", backendId: "pi", at: 1 }); + await f.writes.safetyReady(turnId, "pi", 1); +} +const failed = (f: F) => (f.db.query("SELECT failed FROM safety_meta").get() as { failed: number }).failed; +function captureStderr() { + const lines: string[] = [], descriptor = Object.getOwnPropertyDescriptor(process.stderr, "write")!; + Object.defineProperty(process.stderr, "write", { ...descriptor, value: (chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; } }); + return { lines: () => lines.flatMap(l => l.split("\n")).filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return { raw: l }; } }), + restore: () => Object.defineProperty(process.stderr, "write", descriptor) }; +} +async function until(check: () => boolean, ms = 10000) { + const end = Date.now() + ms; + while (!check()) { if (Date.now() > end) throw new Error("condition not reached"); await Bun.sleep(25); } +} + +test("a failed safetyBegin refuses only that turn: the same chat and another chat still run", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); + f.db.exec("CREATE TRIGGER break_begin BEFORE INSERT ON safety_collections WHEN NEW.turn_id='storm' BEGIN SELECT RAISE(ABORT,'forced begin failure'); END"); + const refused = await f.writes.safetyBegin({ turnId: "storm", bindingId: crypto.randomUUID(), sessionId: "ithaca", principalId: "odysseus", backendId: "pi", at: 1 }) + .then(() => null, error => error); + expect(refused, "SAFETY_BEGIN_FAILURE_IS_A_RETRYABLE_REFUSAL").toBeInstanceOf(SafetyRecordingUnavailable); + expect((refused as SafetyRecordingUnavailable).paused).toBe(false); + expect(failed(f), "SAFETY_BEGIN_FAILURE_NEVER_LATCHES_THE_BRAIN").toBe(0); + await next(f, "homecoming", "ithaca"); + expect(f.writes.recordingAvailable("homecoming", "ithaca"), "SAFETY_BEGIN_FAILURE_LEAVES_ITS_CHAT_USABLE").toBe(true); + expect(f.writes.safety("homecoming", "ithaca").restriction).toBe("normal"); + await next(f, "siege", null); + expect(f.writes.recordingAvailable("siege", null), "SAFETY_BEGIN_FAILURE_LEAVES_OTHER_CHATS_USABLE").toBe(true); + } finally { await f.close(); } +}); + +test("a lost post-delivery occurrence restricts its chat permanently and leaves another chat normal", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); await chat(f, "siege", "troy"); + await f.writes.safetyFail("voyage", new Error("exposure transition lost after delivery")); + expect(failed(f), "SAFETY_CHAT_LOSS_NEVER_LATCHES_THE_BRAIN").toBe(0); + expect(f.writes.recordingAvailable("voyage", "ithaca"), "SAFETY_LOSS_STOPS_ITS_PRODUCER").toBe(false); + expect(f.writes.recordingAvailable("siege", "troy"), "SAFETY_LOSS_LEAVES_OTHER_CHAT_PRODUCERS").toBe(true); + await f.writes.safetyEnd("voyage"); await f.writes.safetyEnd("siege"); + const lost = f.writes.safety(null, "ithaca"); + expect(lost.restriction, "SAFETY_LOSS_RESTRICTS_ITS_CHAT").toBe("restricted"); + expect(lost.coverage.state).toBe("incomplete"); + expect(lost.coverage.epochs.find(e => e.reason === "recording_failed"), "SAFETY_LOSS_GAP_PROJECTS_AS_RECORDING_FAILED").toBeDefined(); + expect(f.writes.safety(null, "troy").restriction, "SAFETY_LOSS_LEAVES_OTHER_CHAT_NORMAL").toBe("normal"); + await next(f, "homecoming", "ithaca"); await next(f, "wooden-horse", "troy"); + expect(f.writes.recordingAvailable("homecoming", "ithaca"), "SAFETY_LOSS_CHAT_RUNS_RESTRICTED_NOT_REFUSED").toBe(true); + expect(f.writes.safety("homecoming", "ithaca").restriction, "SAFETY_LOSS_GAP_IS_PERMANENT").toBe("restricted"); + expect(f.writes.safety("wooden-horse", "troy").restriction).toBe("normal"); + const cause = JSON.parse((f.db.query("SELECT failure_cause FROM safety_collections WHERE turn_id='voyage'").get() as { failure_cause: string }).failure_cause); + expect(cause, "SAFETY_CHAT_FAILURE_KEEPS_ITS_CAUSE").toMatchObject({ site: "safetyFail", turnId: "voyage", message: "exposure transition lost after delivery" }); + } finally { await f.close(); } +}); + +test("an unwritable evidence store restricts the brain, new turns run restricted, and it clears itself", async () => { + const f = fixture(); const log = captureStderr(); try { + const voyage = await chat(f, "voyage", "ithaca"); + // Nothing the loss notice needs can commit: not the chat fact, not the + // brain latch, not any evidence. + f.db.exec(`CREATE TRIGGER no_chat_fact BEFORE UPDATE OF failure ON safety_collections BEGIN SELECT RAISE(ABORT,'disk I/O error'); END; + CREATE TRIGGER no_brain_fact BEFORE UPDATE OF failed ON safety_meta WHEN NEW.failed=1 BEGIN SELECT RAISE(ABORT,'disk I/O error'); END; + CREATE TRIGGER no_evidence BEFORE INSERT ON safety_records BEGIN SELECT RAISE(ABORT,'disk I/O error'); END;`); + expect(await f.writes.safetyFail("voyage", new Error("lost")).then(() => "committed", () => "refused")).toBe("refused"); + expect(f.writes.recordingStatus(), "SAFETY_UNRECORDED_LOSS_RESTRICTS_THE_BRAIN").toMatchObject({ latched: true, retained: true }); + expect(f.writes.recordingAvailable("voyage", "ithaca")).toBe(false); + // A new chat still starts: restricted, never refused. + await next(f, "siege", null); + expect(f.writes.recordingAvailable("siege", null), "SAFETY_BRAIN_RESTRICTION_RUNS_NEW_TURNS").toBe(true); + expect(f.writes.safety("siege", null).restriction, "SAFETY_BRAIN_RESTRICTION_USES_TAINTED_POLICY").toBe("restricted"); + expect(f.writes.taint("siege", null), "SAFETY_BRAIN_RESTRICTION_TAINTS_NEW_TURNS").not.toBeNull(); + // Its own evidence cannot be written either; its permanent gap covers that. + expect(await f.writes.firstTaint({ kind: "taint", turnId: "siege", sessionId: null, actor: "interactive", model: null, profile: null, + payload: { source: "web_fetch", tool: "WebFetch", detail: null } }), "SAFETY_RESTRICTED_TURN_SURVIVES_UNWRITABLE_EVIDENCE").toBe(false); + voyage.controller.abort(); + f.db.exec("DROP TRIGGER no_chat_fact; DROP TRIGGER no_brain_fact; DROP TRIGGER no_evidence;"); + await f.writes.safetyEnd("voyage"); + await until(() => !f.writes.recordingStatus().latched); + expect(failed(f)).toBe(0); + const gaps = Object.fromEntries((f.db.query("SELECT turn_id,gap FROM safety_collections WHERE turn_id IN ('voyage','siege')").all() as { turn_id: string; gap: string }[]).map(r => [r.turn_id, r.gap])); + expect(gaps, "SAFETY_AUTOMATIC_RECOVERY_KEEPS_AFFECTED_GAPS").toEqual({ voyage: "recording_failed_recovered", siege: "recording_failed" }); + expect(f.writes.safety(null, "ithaca").restriction).toBe("restricted"); + await next(f, "homecoming", null); + expect(f.writes.safety("homecoming", null).restriction, "SAFETY_AUTOMATIC_RECOVERY_RESTORES_NORMAL_NEW_CHATS").toBe("normal"); + const audit = f.db.query("SELECT trigger,actor,scope,cause,gapped,at FROM safety_recoveries").all() as { trigger: string; scope: string; cause: string; at: number }[]; + expect(audit.length, "SAFETY_AUTOMATIC_RECOVERY_IS_AUDITED").toBe(1); + expect(audit[0]).toMatchObject({ trigger: "automatic", actor: "host", scope: "brain" }); + expect(audit[0]!.at).toBeGreaterThan(0); + expect(JSON.parse(audit[0]!.cause)).toMatchObject({ site: "retained" }); + expect(log.lines().filter(l => l.body === "safety recording recovered for the brain").length, "SAFETY_AUTOMATIC_RECOVERY_LOGS_ONE_LINE").toBe(1); + } finally { log.restore(); await f.close(); } +}); + +test("a durable brain latch keeps its first cause, counts later ones and clears without a restart", async () => { + const f = fixture(); const log = captureStderr(); try { + await chat(f, "voyage", "ithaca"); + // The chat fact fails; the emergency reserve takes the brain latch. + f.db.exec("CREATE TRIGGER no_chat_fact BEFORE UPDATE OF failure_cause ON safety_collections WHEN NEW.turn_id='voyage' AND (SELECT failed FROM safety_meta)=0 BEGIN SELECT RAISE(ABORT,'database or disk is full'); END"); + await f.writes.safetyFail("voyage", new TypeError("ledger write failed")); + expect(failed(f), "SAFETY_UNWRITABLE_CHAT_FACT_LATCHES_THE_BRAIN").toBe(1); + const first = f.db.query("SELECT * FROM safety_latch").get() as Record; + expect(first, "SAFETY_LATCH_KEEPS_ITS_FIRST_CAUSE").toMatchObject({ reason: "recording_failed", site: "safetyFail", turn_id: "voyage", error_class: "TypeError", count: 1 }); + expect(String(first.message)).toContain("ledger write failed"); + expect(first.since).toBeGreaterThan(0); + // The worker's latch logs on its own thread; this one runs here. + const before = log.lines().length; + latchSafety(f.db, null, "capacity", safetyFailureCause(new SafetyCapacityExhausted("Safety ledger capacity exhausted"), "record", null)); + expect(f.db.query("SELECT site,turn_id,error_class,count FROM safety_latch").get(), "SAFETY_LATER_LATCH_ONLY_COUNTS") + .toEqual({ site: "safetyFail", turn_id: "voyage", error_class: "TypeError", count: 2 }); + const latches = log.lines().slice(before); + expect(latches.length, "SAFETY_EACH_LATCH_LOGS_ONE_LINE").toBe(1); + expect(latches[0]).toMatchObject({ body: "safety recording latched for the brain", + attributes: { "safety.site": "record", "safety.reason": "capacity", "error.message": "Safety ledger capacity exhausted" } }); + const status = f.writes.recordingStatus(); + expect(status, "SAFETY_STATUS_REPORTS_THE_LATCH").toMatchObject({ latched: true, reason: "capacity", cause: { site: "safetyFail", turnId: "voyage", count: 2 } }); + expect(status.since).toBe(first.since as number); + // New turns run restricted while the brain is latched. + await next(f, "siege", null); + expect(f.writes.recordingAvailable("siege", null)).toBe(true); + f.db.exec("DROP TRIGGER no_chat_fact"); + await f.writes.safetyEnd("voyage"); + await until(() => failed(f) === 0); + expect(f.writes.recordingStatus()).toMatchObject({ latched: false, cause: null, lastRecovery: { trigger: "automatic", cause: { site: "safetyFail", count: 2 } } }); + expect(f.db.query("SELECT COUNT(*) n FROM safety_latch").get()).toEqual({ n: 0 }); + } finally { log.restore(); await f.close(); } +}); + +test("the incident state boots, recovers automatically and admits turns", async () => { + const f = fixture(); + await chat(f, "voyage", "ithaca"); await f.writes.safetyEnd("voyage"); + // Exactly the incident: failed=1, reason='capacity', no pending rows, no open collections. + f.db.exec(`UPDATE safety_meta SET failed=1,reason='capacity'; UPDATE safety_collections SET failure='capacity',gap='host_restart_unknown' WHERE turn_id='voyage'`); + expect(f.db.query("SELECT (SELECT COUNT(*) FROM safety_pending) pending,(SELECT COUNT(*) FROM safety_collections WHERE ended=0) open").get()).toEqual({ pending: 0, open: 0 }); + await f.close(); + const g = open(f.path); try { + expect((g.db.query("SELECT failed FROM safety_meta").get() as { failed: number }).failed, "SAFETY_INCIDENT_STATE_RECOVERS_AT_BOOT").toBe(0); + expect(g.db.query("SELECT trigger,actor FROM safety_recoveries").all()).toEqual([{ trigger: "boot", actor: "host" }]); + await g.writes.safetyBegin({ turnId: "homecoming", bindingId: crypto.randomUUID(), sessionId: "ithaca", principalId: "odysseus", backendId: "pi", at: 2 }); + await g.writes.safetyReady("homecoming", "pi", 1); + expect(g.writes.recordingAvailable("homecoming", "ithaca"), "SAFETY_INCIDENT_STATE_ADMITS_TURNS_AFTER_BOOT").toBe(true); + expect(g.writes.safety("homecoming", "ithaca").restriction, "SAFETY_INCIDENT_CHAT_KEEPS_ITS_GAP").toBe("restricted"); + } finally { await g.close(); } +}); + +test("a turn is refused outright only when even its restricted begin cannot commit", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); + latchSafety(f.db, "voyage", "recording_failed", safetyFailureCause(new Error("disk I/O error"), "safetyCommit", "voyage")); + f.db.exec("CREATE TRIGGER no_collections BEFORE INSERT ON safety_collections BEGIN SELECT RAISE(ABORT,'disk I/O error'); END"); + const refused = await f.writes.safetyBegin({ turnId: "siege", bindingId: crypto.randomUUID(), sessionId: null, principalId: "odysseus", backendId: "pi", at: 1 }) + .then(() => null, error => error); + expect(refused, "SAFETY_UNENFORCEABLE_RESTRICTION_REFUSES").toBeInstanceOf(SafetyRecordingUnavailable); + expect((refused as SafetyRecordingUnavailable).paused, "SAFETY_PAUSED_REFUSAL_IS_DISTINCT").toBe(true); + const frames: unknown[] = [], failures: unknown[] = []; + emitTurnError({ sendToClients: (frame: unknown) => frames.push(frame), reportTurnFailed: (...args: unknown[]) => failures.push(args) } as never, + { requestId: "request-siege", turnId: "siege", sessionId: undefined } as never, refused); + expect(frames[0], "SAFETY_REFUSAL_HAS_A_DEDICATED_ERROR_CODE").toMatchObject({ type: "error", code: "SAFETY_RECORDING_UNAVAILABLE", requestId: "request-siege", + failure: { errorClass: "safety_recording_paused" } }); + expect(failures[0]).toEqual(["SAFETY_RECORDING_UNAVAILABLE", expect.anything(), refused.message]); + } finally { await f.close(); } +}); + +test("a refused reservation before delivery stops only the turn; its chat keeps no gap", async () => { + const f = fixture(); try { + const voyage = await chat(f, "voyage", "ithaca"); + f.db.exec("CREATE TRIGGER no_reservation BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced reservation failure'); END"); + const refused = await voyage.collector.begin("scout", "WebFetch", { url: "https://ithaca.invalid/" }).then(() => null, error => error); + expect(refused, "SAFETY_PRE_DELIVERY_RESERVATION_IS_RETRYABLE").toBeInstanceOf(SafetyRecordingUnavailable); + expect(voyage.controller.signal.aborted, "SAFETY_PRE_DELIVERY_RESERVATION_STOPS_THE_TURN").toBe(true); + expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(), "SAFETY_PRE_DELIVERY_RESERVATION_KEEPS_NO_GAP").toEqual({ failure: null }); + expect(failed(f)).toBe(0); + f.db.exec("DROP TRIGGER no_reservation"); + await f.writes.safetyEnd("voyage"); await next(f, "homecoming", "ithaca"); + expect(f.writes.safety("homecoming", "ithaca").restriction).toBe("normal"); + } finally { await f.close(); } +}); + +test("owner recovery clears an idle latch, refuses while a producer is open, and records who did it", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); + latchSafety(f.db, "voyage", "recording_failed", safetyFailureCause(new Error("disk I/O error"), "safetyCommit", "voyage")); + // The reconciler would race this test; the owner route is the fallback under test. + expect(() => f.writes.recoverRecording("penelope"), "SAFETY_OWNER_RECOVERY_REFUSES_WITH_OPEN_PRODUCER").toThrow("Stop all safety producers"); + expect(failed(f), "SAFETY_REFUSED_RECOVERY_CHANGES_NOTHING").toBe(1); + expect(f.db.query("SELECT COUNT(*) n FROM safety_recoveries").get()).toEqual({ n: 0 }); + await f.writes.safetyEnd("voyage"); + const recovery = f.writes.recoverRecording("penelope"); + expect(recovery, "SAFETY_OWNER_RECOVERY_RECORDS_ACTOR_AND_CAUSE").toMatchObject({ recovered: true, trigger: "owner", actor: "penelope", cause: { site: "safetyCommit", turnId: "voyage" } }); + expect(f.db.query("SELECT trigger,actor FROM safety_recoveries").get()).toEqual({ trigger: "owner", actor: "penelope" }); + await next(f, "siege", null); + expect(f.writes.recordingAvailable("siege", null), "SAFETY_OWNER_RECOVERY_ADMITS_TURNS_WITHOUT_RESTART").toBe(true); + expect(f.writes.safety("siege", null).restriction).toBe("normal"); + } finally { await f.close(); } +}); + +test("only a capacity check classifies a failure as capacity", () => { + expect(safetyFailureReason(new SafetyCapacityExhausted("Safety pending capacity exhausted"))).toBe("capacity"); + for (const error of [new Error("SQLITE_IOERR"), new TypeError("bug"), new (class SafetyUnavailable extends Error {})("Invalid bounded safety identity")]) + expect(safetyFailureReason(error), "SAFETY_NON_CAPACITY_ERRORS_ARE_RECORDING_FAILED").toBe("recording_failed"); +}); + +test("a non-capacity reservation error marks its chat recording_failed, not capacity", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); + f.db.exec("CREATE TRIGGER no_reservation BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced reservation failure'); END"); + // A producer that does not hold its input: the reservation may follow delivery. + await f.writes.firstTaint({ kind: "taint", turnId: "voyage", sessionId: "ithaca", actor: "interactive", model: null, profile: null, + payload: { source: "web_fetch", tool: "WebFetch", detail: null } }).catch(() => {}); + expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(), "SAFETY_RESERVE_ERROR_IS_RECORDING_FAILED").toEqual({ failure: "recording_failed" }); + expect(f.db.query("SELECT failed,reason FROM safety_meta").get()).toEqual({ failed: 0, reason: null }); + } finally { await f.close(); } +}); + +test("a legacy row that cannot migrate gaps its own turn instead of latching capacity", async () => { + const f = fixture(); + await chat(f, "voyage", "ithaca"); + await f.writes.safetyEnd("voyage"); + f.db.query(`INSERT INTO governance_events(session_id,turn_id,at,kind,payload,schema_version,actor,model,profile,dedupe_key) + VALUES('ithaca','legacy-turn',0,'taint',?,1,'interactive',NULL,NULL,NULL)`).run(JSON.stringify({ source: "web_fetch", tool: "WebFetch", detail: null })); + f.db.exec("CREATE TRIGGER no_legacy_record BEFORE INSERT ON safety_records BEGIN SELECT RAISE(ABORT,'forced migration failure'); END"); + await f.close(); + const g = open(f.path); try { + expect(g.db.query("SELECT failed FROM safety_meta").get(), "SAFETY_MIGRATION_FAILURE_NEVER_LATCHES_CAPACITY").toEqual({ failed: 0 }); + const row = g.db.query("SELECT failure,ended,failure_cause FROM safety_collections WHERE turn_id='legacy-turn'").get() as { failure: string; ended: number; failure_cause: string }; + expect(row.failure, "SAFETY_MIGRATION_FAILURE_IS_RECORDING_FAILED").toBe("recording_failed"); + expect(JSON.parse(row.failure_cause)).toMatchObject({ site: "migrate", message: "forced migration failure" }); + expect(g.writes.safety(null, "ithaca").restriction, "SAFETY_MIGRATION_FAILURE_RESTRICTS_ITS_CHAT").toBe("restricted"); + } finally { await g.close(); } +}); + +test("the status route shows the recorder to the owner only, and recovery requires the owner", async () => { + const { createStatusRoutes } = await import("../src/routes/health"); + const { Hono } = await import("hono"); + const recovered: string[] = []; + const latched = { latched: true, since: 7, reason: "recording_failed", cause: null, retained: false, lastRecovery: null }; + const app = (kind?: string) => new Hono().use(async (c, nextHandler) => { if (kind) (c as unknown as { set(k: string, v: unknown): void }).set("principal", { id: `${kind}-id`, kind }); await nextHandler(); }) + .route("/api", createStatusRoutes({ sourceCommit: "dev", getCronStatus: () => [], isTurnActive: () => false, + getSafetyRecording: () => latched as never, recoverSafetyRecording: actor => { recovered.push(actor); return { recovered: true } as never; } }) as never); + expect((await (await app("owner").request("/api/status")).json()).safetyRecording, "SAFETY_STATUS_VISIBLE_TO_OWNER").toEqual(latched); + for (const kind of ["delegate", undefined]) + expect((await (await app(kind).request("/api/status")).json()).safetyRecording, "SAFETY_STATUS_HIDDEN_FROM_OTHERS").toBeUndefined(); + const post = (kind?: string) => app(kind).request("/api/status/safety-recording/recover", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }); + expect((await post("delegate")).status, "SAFETY_RECOVERY_REQUIRES_OWNER").toBe(403); + expect((await post("owner")).status).toBe(200); + expect(recovered).toEqual(["owner-id"]); +}); + +test("automatic recovery waits for an uncovered producer to drain", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); + latchSafety(f.db, null, "recording_failed", safetyFailureCause(new Error("disk I/O error"), "record", null)); + expect(attemptSafetyRecovery(f.db), "SAFETY_AUTOMATIC_RECOVERY_WAITS_FOR_UNCOVERED_PRODUCERS").toBe(false); + expect(failed(f)).toBe(1); + await f.writes.safetyEnd("voyage"); + expect(attemptSafetyRecovery(f.db)).toBe(true); + expect(failed(f)).toBe(0); + } finally { await f.close(); } +}); diff --git a/packages/ui-server/tests/safety-history-loss.test.ts b/packages/ui-server/tests/safety-history-loss.test.ts index a8262d2dc8..938b2673bf 100644 --- a/packages/ui-server/tests/safety-history-loss.test.ts +++ b/packages/ui-server/tests/safety-history-loss.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test"; import { safetyHistoryFixture } from "./helpers/safety-history-fixture"; +import { holdSafetyRecovery } from "./helpers/hold-safety-recovery"; import { createSafetyStore } from "../../ui-react/src/stores/safety-state"; import type { SafetyPage, SafetyUpdate, SafetyUnavailable } from "@schlessera/brain-ui-sdk/protocol"; @@ -20,7 +21,9 @@ async function subscribe(f: Fixture, page: SafetyPage, send: (value: SafetyUpdat await flush(f, () => f.history.subscribe({}, f.principal, page.identity, page.highWater, page.snapshotId, () => true, send)); } function injectLossCommitFailure(f: Fixture) { - f.db.exec("CREATE TABLE loss_commit_probe(id TEXT REFERENCES safety_records(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_loss_notice AFTER UPDATE OF failed ON safety_meta WHEN NEW.failed=1 BEGIN INSERT INTO loss_commit_probe VALUES('missing-raft'); END"); + // The retained loss is under test; the automatic reconciler must not clear it meanwhile. + holdSafetyRecovery(f.db); + f.db.exec("CREATE TABLE loss_commit_probe(id TEXT REFERENCES safety_records(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_loss_notice AFTER UPDATE OF failed ON safety_meta WHEN NEW.failed=1 BEGIN INSERT INTO loss_commit_probe VALUES('missing-raft'); END; CREATE TRIGGER fail_loss_notice_chat AFTER UPDATE OF failure ON safety_collections WHEN NEW.failure IS NOT NULL AND EXISTS(SELECT 1 FROM sqlite_master WHERE type='trigger' AND name='fail_loss_notice') BEGIN INSERT INTO loss_commit_probe VALUES('missing-raft'); END"); } async function lose(f: Fixture) { const error = await f.writes.safetyFail("voyage").then(() => null, error => error); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 3529f78946..3f0f65c0a7 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -66,7 +66,8 @@ test("real upgrade classifies old sessions both with and without first-taint row for(const {name} of triggers)f.db.exec(`DROP TRIGGER ${name}`); const tables=f.db.query("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'safety_%'").all() as {name:string}[]; for(const {name} of tables)f.db.exec(`DROP TABLE ${name}`); - f.db.query("DELETE FROM _migrations WHERE filename='081_session_safety.sql'").run(); + // 085 extends the safety tables 081 recreates, so it replays with them. + f.db.query("DELETE FROM _migrations WHERE filename IN ('081_session_safety.sql','085_safety_recording_containment.sql')").run(); f.db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('legacy-clean',0,0),('legacy-tainted',0,0); INSERT INTO dialogue_owners VALUES('legacy-provisional','odysseus',NULL,1,'complete',0)"); f.db.query("INSERT INTO governance_events(session_id,turn_id,at,kind,schema_version,actor,payload) VALUES('legacy-tainted','old-turn',0,'taint',1,'interactive',?)") .run(JSON.stringify({source:"web_fetch",tool:"WebFetch",detail:null})); @@ -82,25 +83,33 @@ test("real upgrade classifies old sessions both with and without first-taint row }finally{await replayWriter.close();restored.close();} }finally{rmSync(f.root,{recursive:true,force:true});}}); -test("an admitted reservation survives real writer restart and fences a new facade and new chat",async()=>{ +test("an admitted reservation survives real writer restart as a permanent gap on its chat; a new chat runs",async()=>{ const f=fixture();try{await fresh(f); const row=governanceEventRow({kind:"taint",turnId:"voyage",sessionId:"ithaca",actor:"interactive",model:null,profile:null,payload:{source:"web_fetch",tool:"WebFetch",detail:null}}); const channel=f.writer.channel(procedures,undefined);await channel.call("safetyReserve",row,"pending-restart",128); expect(f.writes.safety(null,"ithaca").pendingCount).toBe(1); await f.writer.close();f.db.close();const db=createUiDb(f.path),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); - try{const state=writes.safety(null,"ithaca");expect(state.restriction,"SAFETY_PENDING_RESTART_NEVER_APPEARS_NORMAL").toBe("restricted");expect(state.reasons).toContain("recording_failed"); - await expectRejection(writes.safetyBegin({turnId:"new-chat",bindingId:crypto.randomUUID(),sessionId:null,principalId:"odysseus",backendId:"claude",at:1}),"recovery"); + try{const state=writes.safety(null,"ithaca");expect(state.restriction,"SAFETY_PENDING_RESTART_NEVER_APPEARS_NORMAL").toBe("restricted"); + // Boot resolves the reservation itself (#3812): the gap is durable, the latch is not. + expect(state.coverage.epochs.map(e=>e.reason),"SAFETY_PENDING_RESTART_KEEPS_A_PERMANENT_GAP").toContain("host_restart_unknown"); + expect(db.query("SELECT COUNT(*) n FROM safety_pending").get()).toEqual({n:0}); + expect(db.query("SELECT failed FROM safety_meta").get(),"SAFETY_PENDING_RESTART_RECOVERS_AT_BOOT").toEqual({failed:0}); + await writes.safetyBegin({turnId:"new-chat",bindingId:crypto.randomUUID(),sessionId:null,principalId:"odysseus",backendId:"claude",at:1});await writes.safetyReady("new-chat","claude",1); + expect(writes.safety("new-chat",null).restriction,"SAFETY_PENDING_RESTART_LEAVES_NEW_CHATS_NORMAL").toBe("normal"); }finally{await writer.close();db.close();} }finally{rmSync(f.root,{recursive:true,force:true});}}); -test("brain row capacity uses a preallocated durable failure cell and refuses another chat",async()=>{ +test("brain row capacity refuses before delivery, keeps the emergency cell, and refuses another chat",async()=>{ const f=fixture();try{const {collector}=await fresh(f); f.db.query("UPDATE safety_meta SET used_rows=999999").run(); const refused=await collector.begin("overflow","WebFetch",{url:"https://ithaca.invalid"}).then(()=>null,error=>error); expect(String(refused),"SAFETY_CAPACITY_REFUSAL").toContain("capacity"); - expect(f.db.query("SELECT length(padding) n FROM safety_emergency_reserve").get(),"SAFETY_EMERGENCY_CELL_PREALLOCATED").toEqual({n:0}); - const another=createGovernanceWrites(f.db,f.writer);expect(another.safety(null,"ithaca").restriction).toBe("restricted"); - await expectRejection(another.safetyBegin({turnId:"new-chat",bindingId:crypto.randomUUID(),sessionId:null,principalId:"odysseus",backendId:"claude",at:1}),"recovery"); + // Nothing was delivered, so nothing latched: the emergency cell stays allocated for a real loss notice. + expect(f.db.query("SELECT length(padding) n FROM safety_emergency_reserve").get(),"SAFETY_EMERGENCY_CELL_PREALLOCATED").toEqual({n:65536}); + expect(f.db.query("SELECT failed FROM safety_meta").get()).toEqual({failed:0}); + const another=createGovernanceWrites(f.db,f.writer); + // A full brain still refuses every new chat: starting one never bypasses capacity. + await expectRejection(another.safetyBegin({turnId:"new-chat",bindingId:crypto.randomUUID(),sessionId:null,principalId:"odysseus",backendId:"claude",at:1}),"capacity"); }finally{await f.close();}}); test("backend change and resume retain epochs; inherited fork restrictions and coverage never reset",async()=>{ @@ -225,13 +234,13 @@ test("reserved terminal evidence commits at a full brain ledger while new ingest expect(f.writes.safety(null,"ithaca").restriction).toBe("restricted"); }finally{await f.close();}}); -test("byte exhaustion and revision exhaustion persist failure without accepting an exposure",async()=>{ +test("byte exhaustion and revision exhaustion refuse an exposure before delivery without latching",async()=>{ for(const exhausted of ["bytes","revision"]){const f=fixture();try{const {collector}=await fresh(f); if(exhausted==="bytes")f.db.exec("UPDATE safety_meta SET used_bytes=536870912-scope_bytes"); else f.db.exec("UPDATE safety_meta SET revision='18446744073709551615'"); await expectRejection(collector.begin("refused","WebFetch",{url:"https://ithaca.invalid"}),exhausted==="bytes"?"capacity":"revision exhausted"); expect(triggers(f),"SAFETY_OVERFLOW_REFUSES_BEFORE_DELIVERY").toHaveLength(0); - expect(f.writes.safety(null,"ithaca").restriction).toBe("restricted"); + expect(f.db.query("SELECT failed FROM safety_meta").get(),"SAFETY_PRE_DELIVERY_OVERFLOW_NEVER_LATCHES").toEqual({failed:0}); if(exhausted==="revision")expect(f.writes.safety(null,"ithaca").evidenceRevision).toBe("18446744073709551615"); }finally{await f.close();}} }); @@ -286,7 +295,7 @@ test("Claude delivery hooks await real SQLite commits before tool contact and re expect(refused,"SAFETY_BACKEND_REFUSES_UNRECORDED_INPUT").toMatchObject({hookSpecificOutput:{permissionDecision:"deny"}}); }finally{origin.stop(true);await f.close();}}); -test("independent SQLite connections share the durable pending ceiling and failure fence",async()=>{ +test("independent SQLite connections share the durable pending ceiling; the failure fences only its chat",async()=>{ const f=fixture();const {Database}=await import("bun:sqlite");let peer:InstanceType|undefined,peerWriter:ReturnType|undefined; try{const {bindingId}=await fresh(f); f.db.query(`WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<255) @@ -298,7 +307,10 @@ test("independent SQLite connections share the durable pending ceiling and failu expect(results.map(r=>r.status).sort(),"SAFETY_CROSS_CONNECTION_CAPACITY_SERIALIZES").toEqual(["fulfilled","rejected"]); expect(f.db.query("SELECT COUNT(*) n FROM safety_pending").get()).toEqual({n:256}); expect(createGovernanceWrites(peer,peerWriter).safety(null,"ithaca").restriction).toBe("restricted"); - await expectRejection(createGovernanceWrites(peer,peerWriter).safetyBegin({turnId:"other",bindingId:crypto.randomUUID(),sessionId:null,principalId:"odysseus",backendId:"claude",at:1}),"recovery"); + expect(createGovernanceWrites(peer,peerWriter).recordingAvailable("voyage","ithaca"),"SAFETY_CROSS_CONNECTION_FAILURE_STOPS_ITS_PRODUCER").toBe(false); + const peerWrites=createGovernanceWrites(peer,peerWriter); + await peerWrites.safetyBegin({turnId:"other",bindingId:crypto.randomUUID(),sessionId:null,principalId:"odysseus",backendId:"claude",at:1}); + expect(peerWrites.recordingAvailable("other",null),"SAFETY_CROSS_CONNECTION_FAILURE_LEAVES_OTHER_CHATS").toBe(true); }finally{await peerWriter?.close();peer?.close();await f.close();}}); test("128 retained epochs fence a 129th resume without dropping earlier facts",async()=>{ @@ -308,7 +320,7 @@ test("128 retained epochs fence a 129th resume without dropping earlier facts",a SELECT 'epoch_'||x,'turn_'||x,session_id,history_owner_id,generation,'claude',0,1,acknowledged,'0','0' FROM n,safety_collections WHERE id=?`).run(bindingId); await expectRejection(f.writes.safetyBegin({turnId:"too-many",bindingId:crypto.randomUUID(),sessionId:"ithaca",principalId:"odysseus",backendId:"pi",at:1}),"coverage capacity"); expect(f.writes.safety(null,"ithaca").coverage.epochs).toHaveLength(128); - expect(f.writes.safety(null,"ithaca").restriction).toBe("restricted"); + expect(f.db.query("SELECT failed FROM safety_meta").get(),"SAFETY_EPOCH_CAPACITY_REFUSES_ONLY_THE_TURN").toEqual({failed:0}); }finally{await f.close();}}); test("a clean search input cannot suppress mixed JSON paths, an explicit mark or a truncated remainder",async()=>{ @@ -378,9 +390,8 @@ for(const boundary of ["rows","bytes"] as const)for(const admission of ["collect await f.writes.safetyBegin({turnId:"after-scope-recovery",bindingId:crypto.randomUUID(),sessionId:null,principalId:"odysseus",backendId:"claude",at:2}); }finally{await peerWriter?.close();peer?.close();await f.close();}}); -test("a genuine failed event commit recovers existing and fresh facades only after quiescence",async()=>{ +test("a genuine failed event commit fences its chat permanently and leaves the brain usable",async()=>{ const f=fixture();try{await fresh(f); - const {recoverSafetyRecording}=await import("../src/governance/safety-store"); // The deferred FK is checked by COMMIT, after safetyCommit has inserted // its evidence and consumed the reservation inside the real worker. f.db.exec("CREATE TABLE safety_commit_probe(occurrence_id TEXT REFERENCES safety_records(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_safety_commit AFTER INSERT ON safety_records BEGIN INSERT INTO safety_commit_probe VALUES('missing-raft-occurrence'); END"); @@ -388,25 +399,20 @@ test("a genuine failed event commit recovers existing and fresh facades only aft expect(f.db.query("SELECT COUNT(*) n FROM safety_pending").get()).toEqual({n:1}); expect(f.db.query("SELECT COUNT(*) n FROM safety_records").get(),"SAFETY_FAILED_COMMIT_ROLLS_BACK_EVIDENCE_AND_CONSUMPTION").toEqual({n:0}); expect(f.db.query("SELECT COUNT(*) n FROM safety_commit_probe").get()).toEqual({n:0}); - expect(f.db.query("SELECT failed FROM safety_meta").get()).toEqual({failed:1}); - expect(()=>recoverSafetyRecording(f.db)).toThrow("Stop all safety producers"); + expect(f.db.query("SELECT failed FROM safety_meta").get(),"SAFETY_FAILED_COMMIT_NEVER_LATCHES_THE_BRAIN").toEqual({failed:0}); + expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_FAILED_COMMIT_FENCES_ITS_CHAT").toEqual({failure:"recording_failed"}); + for(const writes of [f.writes,createGovernanceWrites(f.db,f.writer)]) + expect(writes.recordingAvailable("voyage","ithaca"),"SAFETY_FAILED_COMMIT_STOPS_ITS_PRODUCER").toBe(false); f.db.exec("DROP TRIGGER fail_safety_commit");await f.writes.safetyEnd("voyage"); - const pendingFailure=f.writes.safetyFail("voyage"); - expect(()=>recoverSafetyRecording(f.db),"SAFETY_RECOVERY_REFUSES_LOCAL_WORK_BEFORE_DURABLE_ADMISSION").toThrow("Stop all safety producers");await pendingFailure; - f.db.exec("CREATE TRIGGER refuse_recovery AFTER UPDATE ON safety_meta WHEN NEW.failed=0 AND OLD.failed=1 BEGIN INSERT INTO safety_commit_probe VALUES('missing-recovery-occurrence'); END"); - expect(()=>recoverSafetyRecording(f.db)).toThrow("FOREIGN KEY constraint failed"); - expect(f.writes.recordingAvailable("voyage","ithaca")).toBe(false); - expect(createGovernanceWrites(f.db,f.writer).recordingAvailable("voyage","ithaca")).toBe(false); - f.db.exec("DROP TRIGGER refuse_recovery");recoverSafetyRecording(f.db); const freshFacade=createGovernanceWrites(f.db,f.writer); for(const [index,writes] of [f.writes,freshFacade].entries()){ const turnId=`recovered-${index}`;await writes.safetyBegin({turnId,bindingId:crypto.randomUUID(),sessionId:"ithaca",principalId:"odysseus",backendId:"claude",at:1});await writes.safetyReady(turnId,"claude",1); - expect(writes.recordingAvailable(turnId,"ithaca"),"SAFETY_VALIDATED_RECOVERY_REARMS_EXISTING_SESSION").toBe(true); - expect(writes.safety(turnId,"ithaca").coverage.state,"SAFETY_RECOVERY_NEVER_RECONSTRUCTS_LOST_INPUT").toBe("incomplete"); + expect(writes.recordingAvailable(turnId,"ithaca"),"SAFETY_FAILED_COMMIT_CHAT_RUNS_RESTRICTED").toBe(true); + expect(writes.safety(turnId,"ithaca").coverage.state,"SAFETY_FAILED_COMMIT_NEVER_RECONSTRUCTS_LOST_INPUT").toBe("incomplete"); expect(writes.safety(turnId,"ithaca").reasons).not.toContain("recording_failed"); await writes.firstTaint({kind:"taint",turnId,sessionId:"ithaca",actor:"interactive",model:null,profile:null,payload:{source:"web_fetch",tool:"WebFetch",detail:null}}); } - expect(f.writes.safety(null,"ithaca").restriction,"SAFETY_RECOVERY_PRESERVES_OLD_GAP").toBe("restricted"); + expect(f.writes.safety(null,"ithaca").restriction,"SAFETY_FAILED_COMMIT_GAP_IS_PERMANENT").toBe("restricted"); }finally{await f.close();}}); for(const boundary of ["count","bytes"] as const)for(const race of [false,true])test(`binding enforces the merged session pending ${boundary} ceiling${race?" across independent connections":""}`,async()=>{ diff --git a/packages/ui-server/tests/safety-loss-recovery.test.ts b/packages/ui-server/tests/safety-loss-recovery.test.ts index 2ab40aec43..5653462951 100644 --- a/packages/ui-server/tests/safety-loss-recovery.test.ts +++ b/packages/ui-server/tests/safety-loss-recovery.test.ts @@ -7,10 +7,13 @@ import {createUiDb} from "../src/db/client"; import {openSqliteWriter} from "../src/db/write-worker"; import {createGovernanceWrites} from "../src/governance/event-writes"; import {createSafetyCollector} from "../src/governance/safety-collector"; +import {holdSafetyRecovery} from "./helpers/hold-safety-recovery"; import {recoverSafetyRecording,safetyCatalogCreated,endSafetyCollection} from "../src/governance/safety-store"; async function fixture(stopThrows=false){ const root=mkdtempSync(join(tmpdir(),"odysseus-loss-recovery-")),path=join(root,"ui.db"),db=createUiDb(path),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); + // These tests drive recovery by hand; the automatic reconciler must not race them. + holdSafetyRecovery(db); const controller=new AbortController(),bindingId=crypto.randomUUID(); await writes.safetyBegin({turnId:"voyage",bindingId,sessionId:null,principalId:"odysseus",backendId:"pi",at:0}); db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); @@ -18,7 +21,7 @@ async function fixture(stopThrows=false){ const collector=createSafetyCollector(db,writes,{turnId:"voyage",bindingId,sessionId:()=>"ithaca",backendId:"pi",shellProxied:()=>false,signal:controller.signal,stop:()=>{controller.abort();if(stopThrows)throw new Error("Producer stop failed");}});await collector.ready("pi",1); // This real deferred FK fails at COMMIT after the loss flag was written, // rolling back the complete notice transaction on the FULL writer. - db.exec("CREATE TABLE loss_commit_probe(id TEXT REFERENCES safety_records(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_loss_notice AFTER UPDATE OF failed ON safety_meta WHEN NEW.failed=1 BEGIN INSERT INTO loss_commit_probe VALUES('missing-raft'); END"); + db.exec("CREATE TABLE loss_commit_probe(id TEXT REFERENCES safety_records(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_loss_notice AFTER UPDATE OF failed ON safety_meta WHEN NEW.failed=1 BEGIN INSERT INTO loss_commit_probe VALUES('missing-raft'); END; CREATE TRIGGER fail_loss_notice_chat AFTER UPDATE OF failure ON safety_collections WHEN NEW.failure IS NOT NULL AND EXISTS(SELECT 1 FROM sqlite_master WHERE type='trigger' AND name='fail_loss_notice') BEGIN INSERT INTO loss_commit_probe VALUES('missing-raft'); END"); return {root,path,db,writer,writes,collector,async close(){await writer.close();db.close();rmSync(root,{recursive:true,force:true});}}; } @@ -31,12 +34,15 @@ test("a failed collector-loss COMMIT fences every facade, completion and later c expect(f.db.query("SELECT failed FROM safety_meta").get(),"SAFETY_LOSS_NOTICE_ACTUALLY_ROLLED_BACK").toEqual({failed:0}); expect(f.db.query("SELECT COUNT(*) n FROM loss_commit_probe").get()).toEqual({n:0}); expect(immediate,"SAFETY_LOSS_RESTRICTS_BEFORE_NOTICE_COMMIT").toBe(false); - for(const writes of [f.writes,createGovernanceWrites(f.db,f.writer)]){ + for(const [index,writes] of [f.writes,createGovernanceWrites(f.db,f.writer)].entries()){ expect(writes.recordingAvailable("voyage","ithaca"),"SAFETY_FAILED_LOSS_NOTICE_REMAINS_UNAVAILABLE").toBe(false); expect(writes.safety(null,"ithaca").restriction).toBe("restricted"); expect(writes.safety(null,"ithaca").coverage.state,"SAFETY_FAILED_NOTICE_NEVER_ADVERTISES_COMPLETE_COVERAGE").toBe("incomplete"); - const begin=await writes.safetyBegin({turnId:"next",bindingId:crypto.randomUUID(),sessionId:"ithaca",principalId:"odysseus",backendId:"pi",at:1}).then(()=>null,error=>error); - expect(String(begin),"SAFETY_FAILED_LOSS_NOTICE_REFUSES_NEW_COLLECTION").toContain("recovery"); + // A later turn runs restricted (#3812): its permanent gap commits before any delivery. + const turnId=`next-${index}`; + await writes.safetyBegin({turnId,bindingId:crypto.randomUUID(),sessionId:"ithaca",principalId:"odysseus",backendId:"pi",at:1}); + expect(f.db.query("SELECT restricted_begin,gap FROM safety_collections WHERE turn_id=?").get(turnId),"SAFETY_FAILED_LOSS_NOTICE_BEGINS_RESTRICTED").toEqual({restricted_begin:1,gap:"recording_failed"}); + expect(writes.safety(turnId,"ithaca").restriction,"SAFETY_FAILED_LOSS_NOTICE_NEW_TURN_IS_RESTRICTED").toBe("restricted"); } const end=await f.writes.safetyEnd("voyage").then(()=>null,error=>error); expect(String(end),"SAFETY_CANNOT_SEAL_HISTORY_WITHOUT_LOSS_FACT").toContain("FOREIGN KEY constraint failed"); diff --git a/packages/ui-server/tests/safety-pi-delivery.test.ts b/packages/ui-server/tests/safety-pi-delivery.test.ts index f3abfeb3b8..f06cffedc9 100644 --- a/packages/ui-server/tests/safety-pi-delivery.test.ts +++ b/packages/ui-server/tests/safety-pi-delivery.test.ts @@ -18,6 +18,7 @@ import {createUiDb} from "../src/db/client"; import {openSqliteWriter} from "../src/db/write-worker"; import {createGovernanceWrites} from "../src/governance/event-writes"; import {createSafetyCollector} from "../src/governance/safety-collector"; +import {holdSafetyRecovery} from "./helpers/hold-safety-recovery"; import {recoverSafetyRecording,safetyCatalogCreated,safetyRecords} from "../src/governance/safety-store"; const injected="workspaces/voyage/raft.md:1: External instructions"; @@ -31,6 +32,7 @@ async function fixture(mode:Mode="normal",acknowledge=true,durable=false) { writeFileSync(join(root,"docs/decisions/provider-history.md"),"Odysseus records an unchanged voyage.\n"); mkdirSync(join(root,"workspaces/voyage"),{recursive:true});writeFileSync(join(root,"workspaces/voyage/raft.md"),"Odysseus repairs the raft.\n"); const db=createUiDb(durable?join(root,"ui.db"):":memory:"),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer),controller=new AbortController(); + holdSafetyRecovery(db); const requests:string[]=[],events:string[]=[];let executed=0,notices=0,finalBeforeRequest=false,manager:SessionManager|undefined; const sessions:AgentSession[]=[]; const origin=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(request){ @@ -142,7 +144,9 @@ for(const mode of ["normal","error","blocked","writer-loss"] as const)test(`inst expect(f.executed,"SAFETY_PI_REAL_INSTALLED_TOOL_EXECUTED").toBe(mode==="blocked"?0:1); if(mode==="writer-loss"){ expect(f.requests,"SAFETY_PI_RECORDING_LOSS_STOPS_NEXT_PROVIDER_REQUEST").toHaveLength(1); - expect(f.writes.recordingAvailable("voyage","ithaca")).toBe(false);return; + // The result was refused before delivery and its producer stopped: the + // turn ends, and nothing it never delivered becomes a gap (#3812). + expect(f.controller.signal.aborted,"SAFETY_PI_RECORDING_LOSS_STOPS_THE_TURN").toBe(true);return; } expect(f.requests).toHaveLength(2); if(mode!=="blocked")expect(f.events.indexOf("permission")).toBeLessThan(f.events.indexOf("execute")); @@ -223,7 +227,7 @@ test("Pi initialization refusal waits for host loss retention before acquisition for(const point of ["startup","during-tool"] as const)test(`installed Pi ${point} refusal survives a real loss-notice COMMIT failure`,async()=>{ const f=await fixture("normal",true,true),ran={value:false}; try{ - f.db.exec("CREATE TABLE pi_loss_probe(id TEXT REFERENCES safety_records(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_pi_loss AFTER UPDATE OF failed ON safety_meta WHEN NEW.failed=1 BEGIN INSERT INTO pi_loss_probe VALUES('missing-raft'); END"); + f.db.exec("CREATE TABLE pi_loss_probe(id TEXT REFERENCES safety_records(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_pi_loss AFTER UPDATE OF failed ON safety_meta WHEN NEW.failed=1 BEGIN INSERT INTO pi_loss_probe VALUES('missing-raft'); END; CREATE TRIGGER fail_pi_loss_chat AFTER UPDATE OF failure ON safety_collections WHEN NEW.failure IS NOT NULL AND EXISTS(SELECT 1 FROM sqlite_master WHERE type='trigger' AND name='fail_pi_loss') BEGIN INSERT INTO pi_loss_probe VALUES('missing-raft'); END"); if(point==="startup")await f.configure([attack("custom-message",ran)]); else f.duringTool(()=>f.configure([attack("custom-message",ran)])); try{const session=await f.open();await session.prompt("Inspect the raft.");}catch{} diff --git a/packages/ui-server/tests/safety-reviews.test.ts b/packages/ui-server/tests/safety-reviews.test.ts index 443d492a53..5fdb973a2b 100644 --- a/packages/ui-server/tests/safety-reviews.test.ts +++ b/packages/ui-server/tests/safety-reviews.test.ts @@ -1,4 +1,5 @@ /** Real FULL writer, immutable occurrences and host-only individual verdicts. */ +import { holdSafetyRecovery } from "./helpers/hold-safety-recovery"; import { expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -275,8 +276,11 @@ test("failed new recording cannot be hidden by resolving previously retained evi test("a loss notice whose COMMIT rolls back still refuses verdicts through the shared local failure marker", async () => { const f = await fixture(); try { const a = await f.add("A"), value = f.body(a), prepared = await f.writes.safetyPrepareReview(value, f.actor); + holdSafetyRecovery(f.db); f.db.exec(`CREATE TABLE loss_commit_probe(id TEXT REFERENCES safety_records(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_loss_commit AFTER UPDATE OF failed ON safety_meta WHEN NEW.failed=1 + BEGIN INSERT INTO loss_commit_probe VALUES('missing-raft'); END; + CREATE TRIGGER fail_loss_chat AFTER UPDATE OF failure ON safety_collections WHEN NEW.failure IS NOT NULL BEGIN INSERT INTO loss_commit_probe VALUES('missing-raft'); END`); await expectRejection(f.writes.safetyFail("voyage"), "FOREIGN KEY constraint failed"); expect(f.db.query("SELECT failed FROM safety_meta").get()).toEqual({ failed: 0 }); diff --git a/packages/ui-server/tests/session-safety-boundaries.test.ts b/packages/ui-server/tests/session-safety-boundaries.test.ts index 69bf78864d..bed9e1059c 100644 --- a/packages/ui-server/tests/session-safety-boundaries.test.ts +++ b/packages/ui-server/tests/session-safety-boundaries.test.ts @@ -46,7 +46,7 @@ function providerRequest(socketPath: string, origin: string): Promise<{ status: }); } -for (const mode of ["healthy", "other-turn-recording-loss", "cancelled"] as const) { +for (const mode of ["healthy", "own-turn-recording-loss", "other-chat-recording-loss", "cancelled"] as const) { test(`final provider admission rechecks ${mode} after the budget wait`, async () => { const f = fixture(), controller = new AbortController(); let requests = 0, admissions = 0; @@ -75,18 +75,23 @@ for (const mode of ["healthy", "other-turn-recording-loss", "cancelled"] as cons await prepareRelayedEgress(run, { emit() {}, requestPermission: async () => ({ behavior: "allow" }) }, budget); const response = providerRequest(run.held.providerRelay!.socketPath, upstream.url.origin); await waiting.promise; - if (mode === "other-turn-recording-loss") { - // A different turn latches the shared recorder, leaving this turn's signal live. - await f.writes.safetyFail("other-turn"); - expect(controller.signal.aborted, "SAFETY_OTHER_TURN_LOSS_LEAVES_REQUEST_SIGNAL_LIVE").toBe(false); + if (mode === "own-turn-recording-loss") { + // The loss notice lands during the wait, leaving this turn's signal live. + await f.writes.safetyFail("requesting-turn"); + expect(controller.signal.aborted, "SAFETY_LOSS_LEAVES_REQUEST_SIGNAL_LIVE").toBe(false); expect(f.writes.recordingAvailable("requesting-turn", null)).toBe(false); + } else if (mode === "other-chat-recording-loss") { + // Another chat's loss restricts that chat, not this request (#3812). + await f.writes.safetyFail("other-turn"); + expect(f.writes.recordingAvailable("requesting-turn", null), "SAFETY_OTHER_CHAT_LOSS_LEAVES_THIS_TURN").toBe(true); } else if (mode === "cancelled") controller.abort(); release.resolve(); const result = await response; expect(admissions, "SAFETY_TEST_REACHES_FINAL_BUDGET_WAIT").toBe(2); - expect(requests, "SAFETY_LOSS_DURING_FINAL_WAIT_NEVER_REACHES_UPSTREAM").toBe(mode === "healthy" ? 1 : 0); - expect(result.status).toBe(mode === "healthy" ? 200 : 403); - if (mode !== "healthy") expect(result.body).toContain("Input recording is unavailable"); + const passes = mode === "healthy" || mode === "other-chat-recording-loss"; + expect(requests, "SAFETY_LOSS_DURING_FINAL_WAIT_NEVER_REACHES_UPSTREAM").toBe(passes ? 1 : 0); + expect(result.status).toBe(passes ? 200 : 403); + if (!passes) expect(result.body).toContain("Input recording is unavailable"); } finally { release.resolve(); await run.held.providerRelay?.stop(); From 349af4e44003bff4bf266758c697cd35abc03945 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 05:12:41 +0100 Subject: [PATCH 02/24] CONTRACT: feat(ui-server): show the owner the safety recorder and an owner recovery fallback (#3810) Owner GET /api/status gains safetyRecording: whether the brain-wide recorder is latched, since when, its reason and first cause, whether only this process retains the loss, and the last recovery. Other principals never see it. POST /api/status/safety-recording/recover gives recoverSafetyRecording a production caller as the owner's fallback to automatic recovery: it refuses with 409 producers_open, changing nothing, while a producer is open, and records the owner as the actor. Contract: additive status field and route (docs/integration-contract/http.md#safety-recording-status-additive-3810). Co-Authored-By: Claude Opus 5.5 --- docs/http-api-coverage.md | 1 + docs/http-api.md | 6 ++++ docs/integration-contract/http.md | 32 +++++++++++++++++++ packages/ui-server/src/app.ts | 2 ++ packages/ui-server/src/routes/health.ts | 30 +++++++++++++++-- .../tests/http-supported-mounts.test.ts | 1 + 6 files changed, 70 insertions(+), 2 deletions(-) diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index dee3dbcdf9..53f14fb8de 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -139,6 +139,7 @@ row's real mounting check. They do not establish mounting by themselves. | `POST /api/schedules/proposals/:id/approve` | `mounted supported handler: POST /api/schedules/proposals/:id/approve` | K | | `POST /api/share` | `mounted supported handler: POST /api/share` | J, Q | | `GET /api/status` | `mounted supported handler: GET /api/status` | T | +| `POST /api/status/safety-recording/recover` | `mounted supported handler: POST /api/status/safety-recording/recover` | T | | `POST /api/status/worker-host` | `mounted supported handler: POST /api/status/worker-host` | T | | `GET /api/voice/keyterms` | `mounted supported handler: GET /api/voice/keyterms` | N | | `GET /api/voice/overrides` | `mounted supported handler: GET /api/voice/overrides` | N | diff --git a/docs/http-api.md b/docs/http-api.md index a19e02ffd7..06ec1ff8d5 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -179,6 +179,7 @@ client code has a gap. Source owners are listed after the table. | POST | `/api/skills/install/github` | I | Install skills from GitHub and sync | React skill settings; integration directories and UI editor transport are internal. CLI/module/skill formats retain their own guarantees. | | POST | `/api/skills/install/zip` | I | Install uploaded skill archive and sync | React skill settings; integration directories and UI editor transport are internal. CLI/module/skill formats retain their own guarantees. | | GET | `/api/status` | S | Read protected operational/runtime status | Independent monitoring and React status; preserve release/runtime/subscription promises. | +| POST | `/api/status/safety-recording/recover` | S | Owner fallback: clear a latched safety recorder whose producers have stopped | Owner tooling when automatic recovery cannot run; additive #3810 ([contract](integration-contract/http.md#safety-recording-status-additive-3810)). Refuses with 409 `producers_open`, changing nothing, while any safety producer is open. | | POST | `/api/status/worker-host` | S | Re-run the agent worker host probe and return what it recorded | React "Check again" and independent monitoring; additive #1632 ([contract](integration-contract/http.md#worker-host-status-additive-1632)). Admits no turn. | | POST | `/api/track-upload` | I | Validate and stage composer track originals | Paired React composer transport; the published file-reference wire/block behavior remains its own contract. | | GET | `/api/tracks` | I | Resolve canonical imported-track evidence | Paired React track-block/export transport; no independent retrieval API selected. | @@ -385,6 +386,11 @@ re-records the mode it probed. It never admits or refuses a turn: each turn runs its own probe. **POST /api/status/worker-host** is protected, accepts no body, re-runs the boot's probes and returns the same `workerHost` object ([contract](integration-contract/http.md#worker-host-status-additive-1632)). +For the owner only, `safetyRecording` reports the brain-wide safety recorder +(#3810): `{ latched, since, reason, cause, retained, lastRecovery }`. A latch +is normally cleared by the host itself (#3812); **POST +/api/status/safety-recording/recover** is the owner's fallback +([contract](integration-contract/http.md#safety-recording-status-additive-3810)). While the server runs as uid 0, `workerHost` also carries `rootServer: { warning }` (#1638): the boot log's warning that its workers can read root-owned files and connect to root-owned and abstract Unix sockets. diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 95ee486290..3a63b65081 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -252,6 +252,38 @@ recorded setup step there. The probe's own requirement is unchanged ([additive, #3664](../integration-contract.md#setup-timeouts-name-their-step-additive-0450-3664)). Clients must tolerate either mode being absent. + + +### Safety recording status and owner recovery (additive, #3810, #3812) + +For an owner principal, authenticated `GET /api/status` gains optional +`safetyRecording`: `{ latched, since, reason, cause, retained, lastRecovery }`. +`latched` is true while the brain-wide safety recorder is failed. `since` is +the Unix-millisecond time of the first latch; `reason` is `recording_failed` +or `capacity`, and `capacity` only when a capacity check refused the write. +`cause` is the first latch's `{ reason, site, turnId, errorClass, message, +stack, since, count }`: identifiers and error text only, never message +content; later latches only increase `count`. `retained` is true when only +this process holds the loss because its durable notice could not commit. +`lastRecovery` is the latest `{ trigger, actor, at, gapped, cause }`, where +`trigger` is `boot`, `automatic` or `owner`. Other principals never receive +the field. + +A brain-wide latch is the exception, not the rule. A failure before delivery +refuses its one turn; lost evidence after delivery restricts its chat with a +permanent gap; only an evidence store that cannot take a scoped fact latches +the brain. While latched, new turns run under their tainted policy with a +permanent pre-delivery gap, and the host clears the latch by itself once the +gap facts are durable and the producers that predate it have drained +([proportionate containment](../decisions/proportionate-containment.md)). + +Owner-only `POST /api/status/safety-recording/recover` takes a JSON body +(ignored), runs the same recovery and answers 200 with `{ recovery, +safetyRecording }`. It refuses with 409 `{ code: "producers_open", message, +retryable: true }`, changing nothing, while any safety producer or collection +is open. Each recovery is recorded with its trigger, actor, time and the cause +it cleared. Affected chats keep their gaps. + ### Root server warning (additive, #1638) diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 41780621c1..25d977b9a0 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1088,6 +1088,8 @@ export async function createApp(options: CreateAppOptions = {}): Promise activity.governanceWrites.recordingStatus(), + recoverSafetyRecording: actor => activity.governanceWrites.recoverRecording(actor), }) ); // Host readers of the index wait for application updates queued before them (#2835). diff --git a/packages/ui-server/src/routes/health.ts b/packages/ui-server/src/routes/health.ts index c2bbbc2f70..f99c560982 100644 --- a/packages/ui-server/src/routes/health.ts +++ b/packages/ui-server/src/routes/health.ts @@ -5,8 +5,12 @@ import type { Database } from "bun:sqlite"; import type { ContentRendererDeclaration } from "@schlessera/brain-ui-sdk"; import type { WorkerHostStatus } from "@schlessera/brain-ui-sdk/protocol"; +import type { AppEnv } from "../app-env.js"; import type { RuntimeStatusSnapshot } from "../activity/runtime-status.js"; import type { BackendBootFailure } from "../agent/backend.js"; +import type { SafetyRecordingStatus, SafetyRecovery } from "../governance/safety-store.js"; +import { requireJson } from "../middleware/origin.js"; +import { requireOwner } from "../middleware/require-owner.js"; import type { SubscriptionStatus } from "../agent/subscription.js"; import type { MetricSnapshot } from "../observability/index.js"; @@ -56,15 +60,24 @@ interface StatusDeps { getSubscription?(): Promise; /** Re-runs the boot's worker host probes and returns what they recorded (#1632). */ checkWorkerHost?(): WorkerHostStatus | Promise; + /** The brain-wide safety recorder: latched, since, reason, first cause (#3810). Owner only. */ + getSafetyRecording?(): SafetyRecordingStatus; + /** Owner fallback for automatic safety-recording recovery (#3810). */ + recoverSafetyRecording?(actor: string): SafetyRecovery; } // Operational status. Registered BEHIND the auth guard: it exposes the git SHA, // cron job errors (raw stderr with filesystem paths), and whether a turn is // active — none of which should be readable unauthenticated. -export function createStatusRoutes(deps: StatusDeps): Hono { - return new Hono().get("/status", async (c) => { +export function createStatusRoutes(deps: StatusDeps): Hono { + return new Hono().get("/status", async (c) => { const backendAvailability = deps.getBackendAvailability?.(); const subscription = deps.getSubscription ? await deps.getSubscription() : undefined; + // The cause names a turn and an error's text: the owner's, not every principal's. + let safetyRecording: SafetyRecordingStatus | undefined; + if (deps.getSafetyRecording && c.get("principal")?.kind === "owner") { + try { safetyRecording = deps.getSafetyRecording(); } catch { safetyRecording = undefined; } + } const contentRenderers = await deps.getContentRenderers?.(c.req.raw.signal).catch(() => undefined); return c.json({ ...(contentRenderers !== undefined ? { contentRenderers } : {}), @@ -85,6 +98,7 @@ export function createStatusRoutes(deps: StatusDeps): Hono { // Whether the subscription token is set, when it expires, when it last // worked, and what to do about the last auth failure. Never the token. ...(subscription ? { subscription } : {}), + ...(safetyRecording ? { safetyRecording } : {}), }); }).post("/status/worker-host", async (c) => { // "Check again" (#1632): re-runs the real probes the boot ran and answers @@ -93,5 +107,17 @@ export function createStatusRoutes(deps: StatusDeps): Hono { // every turn still runs its own probe. if (!deps.checkWorkerHost) return c.json({ error: "Not found" }, 404); return c.json(await deps.checkWorkerHost()); + }).post("/status/safety-recording/recover", requireOwner(), requireJson(), (c) => { + // Runs the same recovery the host runs by itself, with its preconditions: + // it refuses, changing nothing, while any safety producer is open. + if (!deps.recoverSafetyRecording) return c.json({ error: "Not found" }, 404); + c.header("Cache-Control", "no-store"); + try { + const recovery = deps.recoverSafetyRecording(c.get("principal")!.id); + return c.json({ recovery, safetyRecording: deps.getSafetyRecording?.() }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return c.json({ code: /producers/.test(message) ? "producers_open" : "unavailable", message, retryable: true }, 409); + } }); } diff --git a/packages/ui-server/tests/http-supported-mounts.test.ts b/packages/ui-server/tests/http-supported-mounts.test.ts index 5434c4cbd8..6745c5fad6 100644 --- a/packages/ui-server/tests/http-supported-mounts.test.ts +++ b/packages/ui-server/tests/http-supported-mounts.test.ts @@ -52,6 +52,7 @@ const checks: Record = { "GET /api/hygiene/review/details/:itemId": { path: "/api/hygiene/review/details/missing", body: { status: "gone" }, verify: async (r) => { expect(r.headers.get("cache-control")).toBe("no-store"); } }, "POST /api/hygiene/review/preview": { init: json("POST", { itemId: "missing", optionId: "link-note", expectedVersion: 1, input: "notes/arrival.md" }), status: 409, body: { error: "preview_refused" } }, "GET /api/status": { body: { healthy: true, version: "dev", software: { sourceCommit: "dev" } } }, + "POST /api/status/safety-recording/recover": { init: json("POST", {}), verify: async (r) => { const b = await r.json(); expect(b.recovery).toMatchObject({ recovered: false, trigger: "owner" }); expect(b.safetyRecording.latched).toBe(false); } }, "POST /api/status/worker-host": { init: { method: "POST" }, verify: async (r) => { const b = await r.json(); expect(b.ordinary).toMatchObject({ trigger: "check" }); expect(typeof b.ordinary.available).toBe("boolean"); } }, "POST /api/auth/login": { init: json("POST", { password: "wrong-fixture-password" }), status: 401, body: { error: "Invalid credentials" } }, "POST /api/auth/logout": { init: { method: "POST" }, body: { ok: true } }, From 8e575ff7e1f8169e7b7cf782d8f7d5a87e4ae5f1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 05:12:41 +0100 Subject: [PATCH 03/24] feat(ui-react): say a message was refused because safety recording failed (#3810) A message refused with SAFETY_RECORDING_UNAVAILABLE now returns with copy that says safety recording failed or is paused and that nothing was sent, instead of "The brain refused this message." A failed turn with the new failure classes reads the same way. Co-Authored-By: Claude Opus 5.5 --- packages/ui-react/src/lib/draft-client.ts | 4 ++-- packages/ui-react/src/lib/turn-failure.ts | 22 +++++++++++++++++++ packages/ui-react/src/stores/draft-state.ts | 8 +++---- packages/ui-react/src/ws-client/inbound.ts | 3 ++- .../browser/outgoing-snapshots.offline.tsx | 22 +++++++++++++++++++ 5 files changed, 52 insertions(+), 7 deletions(-) diff --git a/packages/ui-react/src/lib/draft-client.ts b/packages/ui-react/src/lib/draft-client.ts index 85f3fcee57..b63a836be7 100644 --- a/packages/ui-react/src/lib/draft-client.ts +++ b/packages/ui-react/src/lib/draft-client.ts @@ -730,7 +730,7 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt }, /** A host frame that names a chat request: it accepted or refused exactly that one. */ - receipt(requestId: string, state: "accepted" | "refused", sessionId: string | undefined): boolean { + receipt(requestId: string, state: "accepted" | "refused", sessionId: string | undefined, reason?: string): boolean { const send = drafts.getState().sends[requestId]; if (!send) return false; if (state === "accepted") { @@ -743,7 +743,7 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt // Accepted after all: its rows come back before the turn's frames do. if (send.state === "unconfirmed") restoreRows(send, sessionId ?? send.sessionId); } else { - drafts.getState().refused(requestId); + drafts.getState().refused(requestId, reason); // Its bubble says it was not sent: the transcript does not say it twice. if (send.snapshotId) withdraw(send); } diff --git a/packages/ui-react/src/lib/turn-failure.ts b/packages/ui-react/src/lib/turn-failure.ts index 88ac292af3..a089e3aedb 100644 --- a/packages/ui-react/src/lib/turn-failure.ts +++ b/packages/ui-react/src/lib/turn-failure.ts @@ -14,8 +14,30 @@ const HEADLINES: Record = { worker_resource_limit: "The agent hit this server's resource limit and was stopped.", }; +/** + * What a returned message says when the host refused it before any turn ran. + * Undefined keeps the generic refusal copy. + */ +export function refusalReason(frame: { code?: string; failure?: { errorClass?: string } }): string | undefined { + if (frame.code !== "SAFETY_RECORDING_UNAVAILABLE") return undefined; + return frame.failure?.errorClass === "safety_recording_paused" + ? "Safety recording is paused on this server. Nothing was sent; try again in a minute." + : "Safety recording failed before this was sent. Nothing ran; try again."; +} + /** Class-driven copy; a class never establishes whether tools already ran. */ export function failurePresentation(failure: TurnFailure) { + // Refused before delivery (#3812, #3810): nothing reached the model. + if (failure.errorClass === "safety_recording_unavailable") return { + headline: "Safety recording failed before this message was sent.", + explanation: "Nothing ran. Try again.", + operator: false, tone: "gold" as const, retry: true, report: false, + }; + if (failure.errorClass === "safety_recording_paused") return { + headline: "Safety recording is paused on this server.", + explanation: "Nothing was sent. The server is recovering it by itself; try again in a minute.", + operator: true, tone: "gold" as const, retry: true, report: false, + }; if (failure.errorClass === "budget_unavailable") return { headline:"Inference budget accounting became unavailable.",explanation:failure.message, operator:true,tone:"red" as const,retry:false,report:true, diff --git a/packages/ui-react/src/stores/draft-state.ts b/packages/ui-react/src/stores/draft-state.ts index a5b70fb116..c8650b5d79 100644 --- a/packages/ui-react/src/stores/draft-state.ts +++ b/packages/ui-react/src/stores/draft-state.ts @@ -337,8 +337,8 @@ export interface DraftStoreState { /** The frame never left: the content goes back where it was. */ sendFailed(requestId: string): void; accepted(requestId: string, sessionId: string | undefined): void; - /** The host refused it: nothing was consumed, so the content goes back. */ - refused(requestId: string): void; + /** The host refused it: nothing was consumed, so the content goes back. `reason` replaces the generic copy. */ + refused(requestId: string, reason?: string): void; unconfirmed(reason: "disconnected" | "uncorrelated"): string[]; /** Edit (the review block): the text and images go back into the draft. */ editSend(requestId: string): void; @@ -891,7 +891,7 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s }, - refused(requestId) { + refused(requestId, reason) { const send = get().sends[requestId]; if (!send || send.state === "accepted" || send.state === "refused") return; if (send.snapshotId) { @@ -899,7 +899,7 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s const owned = snapshotOf(send); set((st) => ({ sends: { ...st.sends, [requestId]: { ...send, state: "refused" } } })); if (owned) withSnapshots(owned.d.draftId, (list) => list.map((x) => x.snapshotId === send.snapshotId - ? { ...x, state: "returned", dispatch: undefined, why: { kind: "refused", reason: "The brain refused this message." } } : x)); + ? { ...x, state: "returned", dispatch: undefined, why: { kind: "refused", reason: reason ?? "The brain refused this message." } } : x)); return; } // The refused message stays in the transcript, its images with it. diff --git a/packages/ui-react/src/ws-client/inbound.ts b/packages/ui-react/src/ws-client/inbound.ts index 862c4b9be3..91c53fe30d 100644 --- a/packages/ui-react/src/ws-client/inbound.ts +++ b/packages/ui-react/src/ws-client/inbound.ts @@ -10,6 +10,7 @@ import type { ReconnectHealing } from "./reconnect.js"; import type { RestorationDriver } from "./restoration.js"; import type { TurnRetries } from "./turn-retry.js"; import type { FollowUpPlacement } from "./follow-ups.js"; +import { refusalReason } from "../lib/turn-failure.js"; import type { AccountServices } from "./account.js"; import type { createConversationClient } from "../voice/conversation-client.js"; @@ -236,7 +237,7 @@ export function createInbound(root: BrainUiServices, deps: InboundDeps) { // A turn-scoped error in a session means the request ran there: it was // accepted, then failed. One with no session left nothing to return to, // so its words come back to the draft, as a refusal's do. - if (deps.services.drafts.receipt(msg.requestId, msg.turnId && msg.sessionId ? "accepted" : "refused", msg.sessionId)) state.clearChatReceipt(msg.requestId); + if (deps.services.drafts.receipt(msg.requestId, msg.turnId && msg.sessionId ? "accepted" : "refused", msg.sessionId, refusalReason(msg))) state.clearChatReceipt(msg.requestId); root.stores.handoff.getState().noteRefusal(msg.requestId, msg.message); // A refused follow-up was never pending; the composer keeps its draft. // A turn-scoped error is not a refusal: the follow-up's turn started diff --git a/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx b/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx index 3b9b45d34b..3ea53bd48e 100644 --- a/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx +++ b/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx @@ -430,3 +430,25 @@ test("case 28: Delete… on a returned snapshot drops its references; the host k // No bubble, no transcript node: the last message stays the column's last row (#1013). expect(s.host.querySelector("[data-transcript]")!.children, "nothing left in the transcript").toHaveLength(0); }); + +test("a message refused because safety recording failed says so, not that the brain refused it (#3810, #3812)", async () => { + const fixture = snapshotHost(); + const s = await mount(fixture); + const refuse = async (text: string, frame: Record) => { + await typed(s, text); + s.sendButton().click(); + await expect.poll(() => s.messages().some((m) => m.text === text), { timeout: 5_000 }).toBe(true); + const sent = s.messages().find((m) => m.text === text)!; + s.socket.deliver({ type: "error", requestId: sent.requestId, ...frame }); + await expect.poll(() => s.bubble(text)?.querySelector("[data-snapshot-why]")?.textContent ?? null, { timeout: 5_000 }).not.toBeNull(); + return s.bubble(text)!.querySelector("[data-snapshot-why]")!.textContent; + }; + expect(await refuse("Sail past the sirens.", { code: "SAFETY_RECORDING_UNAVAILABLE", message: "paused", + failure: { errorClass: "safety_recording_paused", message: "paused" } }), "the paused recorder is named") + .toBe("Safety recording is paused on this server. Nothing was sent; try again in a minute."); + expect(await refuse("Bind me to the mast.", { code: "SAFETY_RECORDING_UNAVAILABLE", message: "failed", + failure: { errorClass: "safety_recording_unavailable", message: "failed" } }), "a one-turn recording failure is retryable") + .toBe("Safety recording failed before this was sent. Nothing ran; try again."); + expect(await refuse("Steer for Ithaca.", { code: "BACKEND_ERROR", message: "refused" }), "other refusals keep their copy") + .toBe("The brain refused this message."); +}); From 8cc0688b9fda22b0a3711085ddb5189a23962357 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 06:10:46 +0100 Subject: [PATCH 04/24] fix(ui-server): schedule recovery from any latch and keep in-flight reservations Self-review and the affected suites found four gaps in the containment change: - A brain latch raised inside a worker call that does not report its scope (a loss at safetyEnd, a peer process) never scheduled automatic recovery. Every call now checks for a latch when it settles. - Construction checked the latch unguarded and threw on a broken store. - An in-process-only brain restriction logged nothing; it now logs one line. - Automatic recovery deleted every pending reservation, including those of open collections it had just gapped, so their commits failed. It now removes only reservations of ended collections; an open one is resolved by its own end. Also registers the recovery route in the mounted-route lifetime audit. Co-Authored-By: Claude Opus 5.5 --- .../ui-server/src/governance/event-writes.ts | 16 ++++++++++++---- .../ui-server/src/governance/safety-store.ts | 4 +++- .../tests/helpers/http-mount-lifetimes.ts | 1 + 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index 2b42f5e4ef..2f688fb5bf 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -136,9 +136,17 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov // nothing it loses can make its chat look complete, so it keeps running. const covered=(turnId:string|null)=>turnId!==null&&!!db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND restricted_begin=1").get(turnId); const retired=(turnId:string)=>!!db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(turnId); + // Any worker write can latch the brain (a failed end, a commit, a peer): + // whichever does, recovery is scheduled from here. + const watchLatch=()=>{try{if(!shared.recovery.timer&&brainFailed())scheduleSafetyRecovery(db);}catch{/* A closed or broken store schedules nothing. */}}; const call:typeof invoke=(name:string,...args:unknown[])=>{ shared.inflight++; - return invoke(name,...args).finally(()=>{shared.inflight--;notifySafetyChanged(db);}); + return invoke(name,...args).finally(()=>{shared.inflight--;watchLatch();notifySafetyChanged(db);}); + }; + const retainedForBrain=(turnId:string|null,notice:unknown)=>{ + retainSafetyLoss(db,turnId,true);scheduleSafetyRecovery(db); + logSafetyRecording("safety recording retained in process for the brain",{"safety.scope":"brain","safety.reason":"recording_failed", + "safety.site":"retained","safety.turn_id":turnId,"error.message":notice instanceof Error?notice.message:String(notice)}); }; const safetyFail=(turnId:string|null,cause?:unknown):Promise=>{ const counted=!turnId||!retired(turnId); @@ -154,7 +162,7 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov },notice=>{ // Neither the chat nor the brain fact committed: the store cannot take // a write. Restrict the brain in-process until recovery commits one. - if(counted){retainSafetyLoss(db,turnId,true);scheduleSafetyRecovery(db);} + if(counted)retainedForBrain(turnId,notice); throw notice; }); }; @@ -162,7 +170,7 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov const scope=(error as {safetyScope?:string}|null)?.safetyScope; if(scope==="chat")return; if(scope==="brain"){scheduleSafetyRecovery(db);return;} - retainSafetyLoss(db,turnId,true);scheduleSafetyRecovery(db); + retainedForBrain(turnId,error); }; const record = (input: GovernanceEventInput, options: { beforeDelivery?: boolean } = {}): Promise<{ id: number; recorded: boolean }> => { const row = governanceEventRow(input); @@ -196,7 +204,7 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov throw error; }).finally(() => { pendingTaints.delete(pending); shared.bytes -= bytes; notifySafetyChanged(db); }); }; - if(brainFailed())scheduleSafetyRecovery(db); + watchLatch(); return { record, safetyPrepareReview: (body,actor)=>call("safetyPrepareReview",body,actor), diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index dca2c68d4f..7752f44e35 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -531,7 +531,9 @@ export function recoverSafetyRecording(db:Database,options:{trigger?:SafetyRecov if(local.unscopedLoss)gap("1=1"); else for(const turnId of local.lostTurns)gap("turn_id=?",turnId); gap("id IN (SELECT collection_id FROM safety_pending) OR failure IS NOT NULL"); - db.query("DELETE FROM safety_pending").run(); + // An open collection's reservation may still commit: it is already + // gapped, and its own end resolves whatever stays pending. + db.query("DELETE FROM safety_pending WHERE collection_id IN (SELECT id FROM safety_collections WHERE ended=1)").run(); db.query("UPDATE safety_emergency_reserve SET padding=zeroblob(65536) WHERE singleton=1").run(); db.query("UPDATE safety_meta SET failed=0,reason=NULL WHERE singleton=1").run(); db.query("DELETE FROM safety_latch").run(); diff --git a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts index 9acb8c595b..4e8d9f8b55 100644 --- a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts +++ b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts @@ -31,6 +31,7 @@ export const mountLifetimes: Record Date: Tue, 10 Nov 2026 06:21:56 +0100 Subject: [PATCH 05/24] fix(ui-server): never let recovery clear a loss that named no chat (#3812) An independent review found two paths where automatic recovery could clear the brain latch with a possibly delivered input left ungapped: - A producer refused early under a latch (or after its own chat failed) retained nothing. A producer that does not hold its input now records its chat's loss before the refusal returns; one that holds it gets the retryable before-delivery refusal. - A loss with no collection of its own latched the brain with no scope, so recovery gapped nothing. A known chat now takes a failed epoch of its own without latching the brain; a loss that names no chat marks the latch `unscoped`, durably, and recovery then gaps every collection, also after a restart. Also from the review: a capacity cause keeps its class across the write worker, the queue-capacity refusal is classified as capacity, a loss only this process retained keeps its original cause for the recovery audit, and two assertions that could pass on a broken tree now check the durable fact. Co-Authored-By: Claude Opus 5.5 --- .../085_safety_recording_containment.sql | 4 +- .../ui-server/src/governance/event-writes.ts | 31 +++++++---- .../ui-server/src/governance/safety-queue.ts | 6 ++- .../ui-server/src/governance/safety-store.ts | 46 +++++++++++----- .../tests/safety-containment.test.ts | 53 +++++++++++++++++-- .../ui-server/tests/safety-ledger.test.ts | 2 + 6 files changed, 112 insertions(+), 30 deletions(-) diff --git a/packages/ui-server/migrations/085_safety_recording_containment.sql b/packages/ui-server/migrations/085_safety_recording_containment.sql index 5d054c2300..e6ca9be702 100644 --- a/packages/ui-server/migrations/085_safety_recording_containment.sql +++ b/packages/ui-server/migrations/085_safety_recording_containment.sql @@ -11,7 +11,9 @@ ALTER TABLE safety_collections ADD COLUMN failure_cause TEXT; CREATE TABLE safety_latch ( singleton INTEGER PRIMARY KEY CHECK(singleton=1), since INTEGER NOT NULL, reason TEXT NOT NULL, site TEXT NOT NULL, turn_id TEXT, - error_class TEXT NOT NULL, message TEXT NOT NULL, stack TEXT, count INTEGER NOT NULL DEFAULT 1 + error_class TEXT NOT NULL, message TEXT NOT NULL, stack TEXT, count INTEGER NOT NULL DEFAULT 1, + -- Some latched loss named no chat: recovery must gap every collection. + unscoped INTEGER NOT NULL DEFAULT 0 ); -- A latch already set before this migration has no recorded cause. INSERT INTO safety_latch(singleton,since,reason,site,turn_id,error_class,message,stack) diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index 2f688fb5bf..3d4e6264b0 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -10,7 +10,7 @@ import { retainSafetyLoss, safetyQueue, notifySafetyChanged } from "./safety-que import { prepareSafetyReview, commitSafetyReview, type SafetyReviewBody, type SafetyReviewer, type SafetyReviewReceipt } from "./safety-reviews.js"; import { beginSafetyCollection, acknowledgeSafety, endSafetyCollection, safetyProjection, reserveSafetyWrite, releaseSafetyWrite, ensureSafetyEventCollection, recordSafetyFailure, recoverSafetyRecording, migrateSafetyHistory, logSafetyRecording, safetyRecordingStatus, - SafetyRecordingUnavailable, SafetyUnavailable, safetyScopeTurns, type SafetyCollectionInput, type SafetyProjection, + SafetyCapacityExhausted, SafetyRecordingUnavailable, SafetyUnavailable, safetyScopeTurns, type SafetyCollectionInput, type SafetyProjection, type SafetyFailureSite, type SafetyRecovery, type SafetyRecordingStatus } from "./safety-store.js"; import { Database } from "bun:sqlite"; import {assertLive,ChatRetiredError} from "../ws/chat-lifecycle.js"; @@ -28,16 +28,16 @@ export function setup(db: Database): WriteProcedures { const retired=(turnId:string)=>!!db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(turnId); // Writes the failure at the narrowest scope that takes it and tells the app // side which one did, on the error itself: `chat`, `brain`, or `unrecorded`. - const contain=(error:unknown,turnId:string|null,site:SafetyFailureSite)=>{ + const contain=(error:unknown,turnId:string|null,site:SafetyFailureSite,sessionId:string|null=null)=>{ let scope:string; - try{scope=recordSafetyFailure(db,turnId,error,site);}catch{scope="unrecorded";} + try{scope=recordSafetyFailure(db,turnId,error,site,sessionId);}catch{scope="unrecorded";} if(error instanceof Error)try{Object.defineProperty(error,"safetyScope",{value:scope,enumerable:true,configurable:true});}catch{/* frozen: treated as unrecorded */} }; return { safetyPrepareReview: (body:SafetyReviewBody,actor:SafetyReviewer) => prepareSafetyReview(db,body,actor), safetyCommitReview: (id:string,body:SafetyReviewBody,actor:SafetyReviewer,pending:boolean,failed:boolean=false) => commitSafetyReview(db,id,body,actor,pending,failed), record: (row: GovernanceEventRow) => { - try { return insertGovernanceEvent(db,row); } catch(error) { if(!(error instanceof ChatRetiredError)&&(row.kind==="taint"||row.kind==="taint_exposure"))contain(error,row.turnId,"record"); throw error; } + try { return insertGovernanceEvent(db,row); } catch(error) { if(!(error instanceof ChatRetiredError)&&(row.kind==="taint"||row.kind==="taint_exposure"))contain(error,row.turnId,"record",row.sessionId); throw error; } }, // A failed begin is before any delivery: it refuses that turn alone and // latches nothing (#3812). The app side names the retryable refusal. @@ -58,11 +58,11 @@ export function setup(db: Database): WriteProcedures { // until the event commits, a refused reservation delivered nothing. safetyReserve: (row:GovernanceEventRow,id:string,bytes:number,beforeDelivery=false) => { try {const turnId=ensureSafetyEventCollection(db,row);reserveSafetyWrite(db,turnId,id,bytes,row.kind==="taint_exposure"?JSON.parse(row.payload).occurrenceId:undefined);} - catch(error){if(!(error instanceof ChatRetiredError)&&!beforeDelivery)contain(error,row.turnId,"safetyReserve");throw error;} + catch(error){if(!(error instanceof ChatRetiredError)&&!beforeDelivery)contain(error,row.turnId,"safetyReserve",row.sessionId);throw error;} }, safetyCommit: (row:GovernanceEventRow,id:string) => { try{return db.transaction(()=>{assertLive(db,[["session",row.sessionId]]);if(row.turnId&&db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(row.turnId))throw new ChatRetiredError();if(!db.query("SELECT 1 FROM safety_pending WHERE id=?").get(id))throw new SafetyUnavailable("Safety reservation absent");releaseSafetyWrite(db,id);return insertGovernanceEvent(db,row,true);}).immediate();} - catch(error){if(!(error instanceof ChatRetiredError))contain(error,row.turnId,"safetyCommit");throw error;} + catch(error){if(!(error instanceof ChatRetiredError))contain(error,row.turnId,"safetyCommit",row.sessionId);throw error;} }, bind: (turnId: string, sessionId: string) => bindTurnEvents(db, turnId, sessionId), // Classification reads the turn's earlier events on the same connection, @@ -143,7 +143,10 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov shared.inflight++; return invoke(name,...args).finally(()=>{shared.inflight--;watchLatch();notifySafetyChanged(db);}); }; - const retainedForBrain=(turnId:string|null,notice:unknown)=>{ + const retainedForBrain=(turnId:string|null,notice:unknown,cause?:unknown)=>{ + const original=cause??notice; + shared.lossCause=shared.lossCause?{...shared.lossCause,count:shared.lossCause.count+1}:{errorClass:original instanceof Error?(original.constructor?.name&&original.constructor.name!=="Error"?original.constructor.name:original.name):"Error", + message:(original instanceof Error?original.message:String(original)).slice(0,512),site:"retained",turnId,at:Date.now(),count:1}; retainSafetyLoss(db,turnId,true);scheduleSafetyRecovery(db); logSafetyRecording("safety recording retained in process for the brain",{"safety.scope":"brain","safety.reason":"recording_failed", "safety.site":"retained","safety.turn_id":turnId,"error.message":notice instanceof Error?notice.message:String(notice)}); @@ -162,7 +165,7 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov },notice=>{ // Neither the chat nor the brain fact committed: the store cannot take // a write. Restrict the brain in-process until recovery commits one. - if(counted)retainedForBrain(turnId,notice); + if(counted)retainedForBrain(turnId,notice,cause); throw notice; }); }; @@ -178,14 +181,20 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov const restricted=covered(row.turnId); // A stopped producer stays stopped: its chat, or the brain, holds the failure. if (!restricted&&input.kind!=="taint_exposure"&&(brainFailed()||(row.turnId!==null&&(shared.lostTurns.has(row.turnId) - ||!!db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND failure IS NOT NULL AND ended=0").get(row.turnId))))) - throw new Error("Safety occurrence writer requires recovery"); + ||!!db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND failure IS NOT NULL AND ended=0").get(row.turnId))))) { + // A producer that holds its input delivered nothing. Any other may + // already have: its chat keeps the loss before this refusal returns. + if (options.beforeDelivery) throw new SafetyRecordingUnavailable(brainFailed()); + const refused = new Error("Safety occurrence writer requires recovery"); + void safetyFail(row.turnId, refused).catch(() => {}); + throw refused; + } const bytes = Buffer.byteLength(JSON.stringify(row))+1024; const session = snapshot(()=>row.turnId===null&&row.sessionId===null ? [...pendingTaints].filter(p=>p.turnId===null&&p.sessionId===null) : pendingInScope(row.turnId,row.sessionId)); if (pendingTaints.size >= 4096 || shared.bytes + bytes > 16777216 || session.length >= 256 || session.reduce((sum, p) => sum + p.bytes, 0) + bytes > 1048576) { - void safetyFail(row.turnId,new Error("Safety occurrence write capacity exceeded")).catch(()=>{}); + void safetyFail(row.turnId,new SafetyCapacityExhausted("Safety occurrence write capacity exceeded")).catch(()=>{}); throw new Error("Safety occurrence write capacity exceeded; ingestion must stop"); } const pending = { turnId: row.turnId, sessionId: row.sessionId, source: input.kind==="taint"?(input as GovernanceEventInput<"taint">).payload.source:"legacy_unknown" as const, bytes }; diff --git a/packages/ui-server/src/governance/safety-queue.ts b/packages/ui-server/src/governance/safety-queue.ts index 29a667de37..23ad481219 100644 --- a/packages/ui-server/src/governance/safety-queue.ts +++ b/packages/ui-server/src/governance/safety-queue.ts @@ -3,10 +3,12 @@ import type { Database } from "bun:sqlite"; import type { SessionTaint } from "./session-taint.js"; type PendingSafety = {turnId:string|null;sessionId:string|null;source:SessionTaint["source"];bytes:number}; const queues=new WeakMap;bytes:number;failed:boolean;inflight:number; - lostTurns:Set;unscopedLoss:boolean;listeners:Set<()=>void>;recovery:{timer:ReturnType|null;attempt:number}}>(); + lostTurns:Set;unscopedLoss:boolean;listeners:Set<()=>void>;recovery:{timer:ReturnType|null;attempt:number}; + /** First cause of a loss only this process holds, kept for the recovery audit. */ + lossCause:{errorClass:string;message:string;site:string;turnId:string|null;at:number;count:number}|null}>(); export function safetyQueue(db:Database){ let queue=queues.get(db); - if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,lostTurns:new Set(),unscopedLoss:false,listeners:new Set(),recovery:{timer:null,attempt:0}};queues.set(db,queue);} + if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,lostTurns:new Set(),unscopedLoss:false,listeners:new Set(),recovery:{timer:null,attempt:0},lossCause:null};queues.set(db,queue);} return queue; } diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index 7752f44e35..20ea65bab8 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -73,7 +73,8 @@ export function safetyFailureCause(error:unknown,site:SafetyFailureSite,turnId:s } /** Honest classification: `capacity` only when a capacity check refused the write. */ export function safetyFailureReason(error:unknown):SafetyFailureReason { - return error instanceof SafetyCapacityExhausted?"capacity":"recording_failed"; + // The name survives the write worker's boundary; only this module's class carries it. + return error instanceof SafetyCapacityExhausted||(error as {name?:unknown}|null)?.name==="SafetyCapacityExhausted"?"capacity":"recording_failed"; } /** One structured stderr line per latch, restriction or recovery. */ export function logSafetyRecording(body:string,attributes:Record):void { @@ -97,12 +98,12 @@ export function failSafetyCollection(db:Database,turnId:string,reason:SafetyFail /** Brain scope: the evidence store could not take a scoped fact. Uses the * emergency cells allocated before ingestion, never appended at overflow. * The first cause is kept; later latches only count. */ -export function latchSafety(db:Database,turnId:string|null,reason:SafetyFailureReason,cause:SafetyFailureCause=safetyFailureCause(new Error("Safety recording latched"),"safetyFail",turnId)):void { +export function latchSafety(db:Database,turnId:string|null,reason:SafetyFailureReason,cause:SafetyFailureCause=safetyFailureCause(new Error("Safety recording latched"),"safetyFail",turnId),unscoped=false):void { db.transaction(()=>{ db.query("UPDATE safety_emergency_reserve SET padding=zeroblob(0) WHERE singleton=1").run(); db.query("UPDATE safety_meta SET failed=1,reason=CASE WHEN reason='capacity' THEN reason ELSE ? END WHERE singleton=1").run(reason); - db.query(`INSERT INTO safety_latch(singleton,since,reason,site,turn_id,error_class,message,stack) VALUES(1,?,?,?,?,?,?,?) - ON CONFLICT(singleton) DO UPDATE SET count=count+1`).run(cause.at,reason,cause.site,cause.turnId,cause.errorClass,cause.message,cause.stack); + db.query(`INSERT INTO safety_latch(singleton,since,reason,site,turn_id,error_class,message,stack,unscoped) VALUES(1,?,?,?,?,?,?,?,?) + ON CONFLICT(singleton) DO UPDATE SET count=count+1,unscoped=MAX(unscoped,excluded.unscoped)`).run(cause.at,reason,cause.site,cause.turnId,cause.errorClass,cause.message,cause.stack,unscoped?1:0); if(turnId) db.query("UPDATE safety_collections SET failure=CASE WHEN failure='capacity' THEN failure ELSE ? END,failure_cause=COALESCE(failure_cause,?) WHERE turn_id=?").run(reason,JSON.stringify(cause),turnId); if(BigInt(meta(db).revision){ + if(!db.query("SELECT 1 FROM sessions WHERE id=?").get(sessionId))return false; + const owned=turnId??`lost_${crypto.randomUUID().replaceAll("-","")}`; + ensureSafetyEventCollection(db,{sessionId,turnId:owned,at:cause.at} as GovernanceEventRow); + if(!failSafetyCollection(db,owned,reason,cause))return false; + if(!turnId)db.query("UPDATE safety_collections SET ended=1,end_revision=COALESCE(end_revision,?) WHERE turn_id=?").run(advance(db),owned); + return true; + }).immediate(); +} function live(db:Database,c:Collection,reserved=false):void { assertLive(db,[["session",c.session_id],["dialogue_owner",c.history_owner_id]]); const owner=c.history_owner_id?one<{generation:number}|null>(db,"SELECT generation FROM dialogue_owners WHERE id=?",c.history_owner_id):null; @@ -445,7 +462,7 @@ export function migrateSafetyHistory(db:Database):boolean { catch(scoped){ if(scoped instanceof ChatRetiredError){after=r.id;continue;} complete=false; - try{latchSafety(db,r.turn_id,reason,cause);}catch{/* The unmigrated row is retried; the next boot latches again. */} + try{latchSafety(db,r.turn_id,reason,cause,true);}catch{/* The unmigrated row is retried; the next boot latches again. */} return complete; } } @@ -523,12 +540,15 @@ export function recoverSafetyRecording(db:Database,options:{trigger?:SafetyRecov const totals=meta(db); if(!totals.failed&&!local.failed&&!one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_pending").n)return; if(totals.used_rows+totals.scope_rows>=SAFETY_LIMITS.brainRows||totals.used_bytes+totals.scope_bytes>=SAFETY_LIMITS.brainBytes)throw new SafetyCapacityExhausted("Safety capacity must be recovered first"); - cause=latchCause(db)??(local.failed?{reason:"recording_failed",site:"retained",turnId:null,errorClass:"SafetyUnavailable", - message:"Only this process retained the loss; its durable notice could not commit.",stack:null,since:at,count:1}:null); + const lost=local.lossCause; + cause=latchCause(db)??(local.failed?{reason:"recording_failed",site:lost?.site??"retained",turnId:lost?.turnId??null,errorClass:lost?.errorClass??"SafetyUnavailable", + message:lost?`${lost.message} (retained in process; its durable notice could not commit)`:"Only this process retained the loss; its durable notice could not commit.", + stack:null,since:lost?.at??at,count:lost?.count??1}:null); + const unscoped=local.unscopedLoss||!!one<{unscoped:number}|null>(db,"SELECT unscoped FROM safety_latch WHERE singleton=1")?.unscoped; const gap=(sql:string,...args:string[])=>{gapped+=db.query(`UPDATE safety_collections SET gap=COALESCE(gap,'recording_failed_recovered') WHERE gap IS NULL AND (${sql})`).run(...args).changes;}; // Reservations on ended epochs could never have released input: the event // and reservation consumption commit together. Retain the historical gap. - if(local.unscopedLoss)gap("1=1"); + if(unscoped)gap("1=1"); else for(const turnId of local.lostTurns)gap("turn_id=?",turnId); gap("id IN (SELECT collection_id FROM safety_pending) OR failure IS NOT NULL"); // An open collection's reservation may still commit: it is already @@ -542,7 +562,7 @@ export function recoverSafetyRecording(db:Database,options:{trigger?:SafetyRecov advance(db);recovered=true; }).immediate(); if(recovered){ - local.failed=false;local.lostTurns.clear();local.unscopedLoss=false; + local.failed=false;local.lostTurns.clear();local.unscopedLoss=false;local.lossCause=null; const c=cause as SafetyLatchCause|null; logSafetyRecording("safety recording recovered for the brain",{"safety.scope":"brain","safety.trigger":trigger,"safety.actor":actor,"safety.gapped":gapped, "safety.reason":c?.reason??null,"safety.site":c?.site??null,"error.class":c?.errorClass??null,"error.message":c?.message??null}); diff --git a/packages/ui-server/tests/safety-containment.test.ts b/packages/ui-server/tests/safety-containment.test.ts index 5e996683f8..1ddec1de5c 100644 --- a/packages/ui-server/tests/safety-containment.test.ts +++ b/packages/ui-server/tests/safety-containment.test.ts @@ -9,7 +9,7 @@ import { openSqliteWriter } from "../src/db/write-worker"; import { attemptSafetyRecovery, createGovernanceWrites } from "../src/governance/event-writes"; import { createSafetyCollector } from "../src/governance/safety-collector"; import { latchSafety, safetyCatalogCreated, safetyFailureCause, SafetyCapacityExhausted, safetyFailureReason, - SafetyRecordingUnavailable } from "../src/governance/safety-store"; + SafetyRecordingUnavailable, SafetyUnavailable } from "../src/governance/safety-store"; import { emitTurnError } from "../src/ws/bridge-capabilities/turn-error"; const roots: string[] = []; @@ -127,7 +127,8 @@ test("an unwritable evidence store restricts the brain, new turns run restricted expect(audit.length, "SAFETY_AUTOMATIC_RECOVERY_IS_AUDITED").toBe(1); expect(audit[0]).toMatchObject({ trigger: "automatic", actor: "host", scope: "brain" }); expect(audit[0]!.at).toBeGreaterThan(0); - expect(JSON.parse(audit[0]!.cause)).toMatchObject({ site: "retained" }); + expect(JSON.parse(audit[0]!.cause), "SAFETY_RETAINED_LOSS_KEEPS_ITS_ORIGINAL_CAUSE").toMatchObject({ site: "retained", turnId: "voyage", errorClass: "Error", + message: expect.stringContaining("lost") }); expect(log.lines().filter(l => l.body === "safety recording recovered for the brain").length, "SAFETY_AUTOMATIC_RECOVERY_LOGS_ONE_LINE").toBe(1); } finally { log.restore(); await f.close(); } }); @@ -236,7 +237,7 @@ test("owner recovery clears an idle latch, refuses while a producer is open, and test("only a capacity check classifies a failure as capacity", () => { expect(safetyFailureReason(new SafetyCapacityExhausted("Safety pending capacity exhausted"))).toBe("capacity"); - for (const error of [new Error("SQLITE_IOERR"), new TypeError("bug"), new (class SafetyUnavailable extends Error {})("Invalid bounded safety identity")]) + for (const error of [new Error("SQLITE_IOERR"), new TypeError("bug"), new SafetyUnavailable("Invalid bounded safety identity")]) expect(safetyFailureReason(error), "SAFETY_NON_CAPACITY_ERRORS_ARE_RECORDING_FAILED").toBe("recording_failed"); }); @@ -297,3 +298,49 @@ test("automatic recovery waits for an uncovered producer to drain", async () => expect(failed(f)).toBe(0); } finally { await f.close(); } }); + +const occurrence = (turnId: string | null, sessionId: string | null) => ({ kind: "taint" as const, turnId, sessionId, actor: "interactive" as const, + model: null, profile: null, payload: { source: "web_fetch" as const, tool: "WebFetch", detail: null } }); + +test("a producer refused under a brain latch still leaves its own chat a durable gap", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); + latchSafety(f.db, null, "recording_failed", safetyFailureCause(new Error("disk I/O error"), "record", null)); + // Not a producer that holds its input: what it refuses may already be delivered. + expect(() => f.writes.firstTaint(occurrence("voyage", "ithaca"))).toThrow("requires recovery"); + await until(() => !!(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get() as { failure: string | null }).failure); + await f.writes.safetyEnd("voyage"); + expect(attemptSafetyRecovery(f.db)).toBe(true); + expect(f.writes.safety(null, "ithaca").restriction, "SAFETY_REFUSED_PRODUCER_UNDER_LATCH_KEEPS_ITS_GAP").toBe("restricted"); + } finally { await f.close(); } +}); + +test("a loss with no collection is kept on its named chat, or gaps every chat when none is named", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); await f.writes.safetyEnd("voyage"); + await chat(f, "siege", "troy"); await f.writes.safetyEnd("siege"); + // The compatibility producer's own collection cannot be created. + f.db.exec("CREATE TRIGGER no_unbound BEFORE INSERT ON safety_collections WHEN NEW.turn_id LIKE 'unbound_%' BEGIN SELECT RAISE(ABORT,'forced compatibility failure'); END"); + await f.writes.firstTaint(occurrence(null, "ithaca")).catch(() => {}); + expect(failed(f), "SAFETY_SESSION_LOSS_NEVER_LATCHES_THE_BRAIN").toBe(0); + expect(f.writes.safety(null, "ithaca").restriction, "SAFETY_SESSION_LOSS_GAPS_ITS_NAMED_CHAT").toBe("restricted"); + expect(f.writes.safety(null, "troy").restriction).toBe("normal"); + await f.writes.firstTaint(occurrence(null, null)).catch(() => {}); + expect(f.db.query("SELECT unscoped FROM safety_latch").get(), "SAFETY_UNNAMED_LOSS_IS_DURABLY_UNSCOPED").toEqual({ unscoped: 1 }); + f.db.exec("DROP TRIGGER no_unbound"); + // Recovery from a fresh process, which retains nothing in memory. + await f.close(); + const g = open(f.path); try { + expect((g.db.query("SELECT failed FROM safety_meta").get() as { failed: number }).failed).toBe(0); + expect(g.writes.safety(null, "troy").restriction, "SAFETY_UNSCOPED_RECOVERY_GAPS_EVERY_CHAT").toBe("restricted"); + } finally { await g.close(); } + } catch (error) { await f.close().catch(() => {}); throw error; } +}); + +test("a capacity cause passed through the write worker stays capacity", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); + await f.writes.safetyFail("voyage", new SafetyCapacityExhausted("Safety occurrence write capacity exceeded")); + expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(), "SAFETY_CAPACITY_SURVIVES_THE_WORKER").toEqual({ failure: "capacity" }); + } finally { await f.close(); } +}); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 3f0f65c0a7..801c973fc8 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -307,6 +307,8 @@ test("independent SQLite connections share the durable pending ceiling; the fail expect(results.map(r=>r.status).sort(),"SAFETY_CROSS_CONNECTION_CAPACITY_SERIALIZES").toEqual(["fulfilled","rejected"]); expect(f.db.query("SELECT COUNT(*) n FROM safety_pending").get()).toEqual({n:256}); expect(createGovernanceWrites(peer,peerWriter).safety(null,"ithaca").restriction).toBe("restricted"); + // The refused reservation's own durable failure, not the 256 pending rows, fences the chat. + expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_CROSS_CONNECTION_FAILURE_IS_DURABLE_CAPACITY").toEqual({failure:"capacity"}); expect(createGovernanceWrites(peer,peerWriter).recordingAvailable("voyage","ithaca"),"SAFETY_CROSS_CONNECTION_FAILURE_STOPS_ITS_PRODUCER").toBe(false); const peerWrites=createGovernanceWrites(peer,peerWriter); await peerWrites.safetyBegin({turnId:"other",bindingId:crypto.randomUUID(),sessionId:null,principalId:"odysseus",backendId:"claude",at:1}); From 88e5805b77ab822b72f51452be274f59ea99c392 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 06:27:00 +0100 Subject: [PATCH 06/24] docs: regenerate the ui-sdk API report and cover the safety status route (#3810) Co-Authored-By: Claude Opus 5.5 --- api-report/ui-sdk.txt | 2 +- docs/http-api-coverage.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index d237edc006..17d557a4f9 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -7664,7 +7664,7 @@ signatures (every public export and the types it is made of) entries: FileEntry[]; } FirstPartyFailureClass (packages/ui-sdk/src/protocol.ts) - type FirstPartyFailureClass = "authentication_failed" | "oauth_org_not_allowed" | "account_on_hold" | "verification_required" | "billing_error" | "subscription_required" | "auth_failure" | "rate_limit" | "overloaded" | "server_error" | "invalid_request" | "model_not_found" | "max_output_tokens" | "cloud_credential_error" | "worker_host_unsupported" | "session_too_large" | "worker_resource_limit" | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "unknown"; + type FirstPartyFailureClass = "authentication_failed" | "oauth_org_not_allowed" | "account_on_hold" | "verification_required" | "billing_error" | "subscription_required" | "auth_failure" | "rate_limit" | "overloaded" | "server_error" | "invalid_request" | "model_not_found" | "max_output_tokens" | "cloud_credential_error" | "worker_host_unsupported" | "session_too_large" | "worker_resource_limit" | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "safety_recording_unavailable" | "safety_recording_paused" | "unknown"; FirstRequestCacheUsage (packages/ui-sdk/src/protocol.ts) export interface FirstRequestCacheUsage { inputTokens: number | null; diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index 53f14fb8de..c5df61a5c4 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -199,6 +199,7 @@ cover start refusal, mid-turn partial work, overlapping observations and leases. - `a failing host boots anyway, logs the named requirement once, and /api/status reports it` ([source](../packages/ui-server/tests/worker-host-status.test.ts)), (`a failing host boots anyway, logs the named requirement once, and /api/status reports it`, `packages/ui-server/tests/worker-host-status.test.ts:66-83`) - `re-runs the real probe and records what it found, in both directions` ([source](../packages/ui-server/tests/worker-host-status.test.ts)), (`re-runs the real probe and records what it found, in both directions`, `packages/ui-server/tests/worker-host-status.test.ts:160-176`) - `is behind the auth guard` ([source](../packages/ui-server/tests/worker-host-status.test.ts)), (`is behind the auth guard`, `packages/ui-server/tests/worker-host-status.test.ts:178-187`) +- `the status route shows the recorder to the owner only, and recovery requires the owner` ([source](../packages/ui-server/tests/safety-containment.test.ts)), (`the status route shows the recorder to the owner only, and recovery requires the owner`, `packages/ui-server/tests/safety-containment.test.ts:273-288`) - `boots, warns once in the log, and keeps the warning on /api/status and through Check again` ([source](../packages/ui-server/tests/worker-host-status.test.ts)), (`boots, warns once in the log, and keeps the warning on /api/status and through Check again`, `packages/ui-server/tests/worker-host-status.test.ts:214-231`) **A — Password access and revocation.** From b354226a43d7a3dfdc060e62a66d205a3cbaab81 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 07:52:15 +0100 Subject: [PATCH 07/24] fix(ui-server): keep a refused tool result's loss with its chat (#3812) A tool result already exists when its safety record is written, and a runtime may keep it in its own session: the installed Claude runtime replays a result whose PostToolUse hook stopped the turn on the next resumed request. Treating a refused result reservation as "before delivery" therefore left the chat normal and complete while the model had seen the untrusted output. Only begin(), which the backend awaits before the tool runs, may now take the pre-delivery shortcut. Result records are no longer tagged beforeDelivery, so a failed reservation is contained at chat scope by the writer and the collector records the loss on the chat as well. The new installed-Claude test proves the replay and the permanent gap; the Pi writer-loss test again requires the loss to stay with its chat. Co-Authored-By: Claude Opus 5.5 --- .../src/governance/safety-collector.ts | 22 +++-- .../tests/safety-pi-delivery.test.ts | 9 +- .../tests/safety-result-retention.test.ts | 89 +++++++++++++++++++ 3 files changed, 108 insertions(+), 12 deletions(-) create mode 100644 packages/ui-server/tests/safety-result-retention.test.ts diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index dfa2f46bd3..c9cb728694 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -14,13 +14,16 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option const marked=(path:string)=>isMarkedUntrusted(db,path); const hash=(value:string)=>new Bun.CryptoHasher("sha256").update(value).digest("hex"); const assertLive=()=>{if(options.signal.aborted)throw new Error("Safety input collection cancelled");}; - const fail=async(error:unknown)=>{ + // `held`: the failure came from begin(), which the backend awaits before it + // runs the tool. A refused reservation there, with a producer that did stop, + // delivered nothing: only this turn is refused, its chat keeps no gap (#3812). + // A result already exists when result() records it, and the runtime may keep + // it in its own session (the Claude runtime replays it on resume), so every + // failure there is a loss after delivery and the chat keeps a permanent gap. + const fail=async(error:unknown,held=false)=>{ const failures=[error]; try{options.stop?.(error instanceof Error?error:new Error(String(error)));}catch(stop){failures.push(stop);} - // Every record here commits before the backend releases its input. A - // refused reservation with a producer that did stop delivered nothing: - // only this turn is refused, and its chat keeps no gap (#3812). - if(failures.length===1&&error instanceof SafetyRecordingUnavailable&&error.beforeDelivery)throw error; + if(held&&failures.length===1&&error instanceof SafetyRecordingUnavailable&&error.beforeDelivery)throw error; try{await writes.safetyFail(options.turnId,error);} catch(notice){throw new AggregateError([...failures,notice],`Safety input refused: ${String(error)}; failure notice could not commit`);} if(failures.length>1)throw new AggregateError(failures,`Safety input refused: ${String(error)}`); @@ -53,7 +56,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option op.occurrences.push(item.id);op.signals.push(signal); } assertLive(); - }catch(error){return fail(error);} + }catch(error){return fail(error,true);} });}, result(toolUseId,tool,output,finalized,segments){return serial(toolUseId,async()=>{ assertLive(); @@ -65,12 +68,13 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option // Each separately delivered external result segment has its own exposure. for(const _segment of (segments??[]).slice(1))for(const signal of op.signals.filter(signal=>["compute_input","external_mcp_input","attachment_input","tool_web_input"].includes(signal.detector))){ const item=occurrence(options.bindingId,signal.detector,op.id,"open");item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; - await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}},{beforeDelivery:true});op.occurrences.push(item.id); + await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); } - // Record output independently, before the backend releases any of its bytes. + // Record output independently, before the backend releases it to the + // model. Its bytes already exist, so a refusal here is never "before delivery". for(const signal of outputTaintSignals(tool,output,options.brainPath,marked)){ const item=occurrence(options.bindingId,signal.detector,op.id,"open");item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; - await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}},{beforeDelivery:true});op.occurrences.push(item.id); + await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); } const state=finalized&&!['Bash','bash'].includes(tool)?"finalized":"interrupted_unknown"; for(const id of op.occurrences)await writes.record({...base(),kind:"taint_exposure",dedupeKey:id,payload:{occurrenceId:id,state}}); diff --git a/packages/ui-server/tests/safety-pi-delivery.test.ts b/packages/ui-server/tests/safety-pi-delivery.test.ts index f06cffedc9..1508f0e092 100644 --- a/packages/ui-server/tests/safety-pi-delivery.test.ts +++ b/packages/ui-server/tests/safety-pi-delivery.test.ts @@ -144,9 +144,12 @@ for(const mode of ["normal","error","blocked","writer-loss"] as const)test(`inst expect(f.executed,"SAFETY_PI_REAL_INSTALLED_TOOL_EXECUTED").toBe(mode==="blocked"?0:1); if(mode==="writer-loss"){ expect(f.requests,"SAFETY_PI_RECORDING_LOSS_STOPS_NEXT_PROVIDER_REQUEST").toHaveLength(1); - // The result was refused before delivery and its producer stopped: the - // turn ends, and nothing it never delivered becomes a gap (#3812). - expect(f.controller.signal.aborted,"SAFETY_PI_RECORDING_LOSS_STOPS_THE_TURN").toBe(true);return; + expect(f.controller.signal.aborted,"SAFETY_PI_RECORDING_LOSS_STOPS_THE_TURN").toBe(true); + // The tool already ran. The host cannot tell a runtime that drops a + // refused result from one that keeps it in its session, so the loss + // stays with its chat, never treated as before delivery (#3812). + expect(f.writes.recordingAvailable("voyage","ithaca"),"SAFETY_PI_REFUSED_RESULT_KEEPS_ITS_LOSS").toBe(false); + expect(f.writes.safety(null,"ithaca").coverage.state,"SAFETY_PI_REFUSED_RESULT_NEVER_LOOKS_COMPLETE").toBe("incomplete");return; } expect(f.requests).toHaveLength(2); if(mode!=="blocked")expect(f.events.indexOf("permission")).toBeLessThan(f.events.indexOf("execute")); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts new file mode 100644 index 0000000000..c57d4bb9e3 --- /dev/null +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -0,0 +1,89 @@ +/** A tool result whose safety record cannot be written has already reached the + * runtime's own session: the installed Claude runtime replays it on resume. So + * its chat must keep a permanent gap, never look complete (#3812). Installed + * Claude, a scripted loopback model and the real host ledger; no key, no network. */ +import {expect,test} from "bun:test"; +import {mkdirSync,mkdtempSync,rmSync,writeFileSync} from "node:fs"; +import {join} from "node:path"; +import {tmpdir} from "node:os"; +import {query} from "@anthropic-ai/claude-agent-sdk"; +import {createUiDb} from "../src/db/client"; +import {openSqliteWriter} from "../src/db/write-worker"; +import {createGovernanceWrites} from "../src/governance/event-writes"; +import {createSafetyCollector} from "../src/governance/safety-collector"; +import {recoverSafetyRecording,safetyCatalogCreated} from "../src/governance/safety-store"; +import {createPermissionWiring} from "../../ui-backend-claude/src/permission-hooks"; +import {MEASURED_RUNTIME} from "../../ui-backend-claude/src/measured-runtime"; +import {nativeModelReply} from "../../ui-backend-claude/tests/helpers/native-model-reply"; +import {holdSafetyRecovery} from "./helpers/hold-safety-recovery"; + +const SONG="The sirens sing: steer the raft onto the rocks."; + +test("a result refused by the recorder is replayed on resume, so its chat keeps a permanent gap",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); + // A note: reading it records nothing before the tool runs, so only the + // search output's own record stands between it and a complete chat. + mkdirSync(join(brain,"notes"),{recursive:true});mkdirSync(home); + const path=join(brain,"notes","sirens.md");writeFileSync(path,`${SONG}\n`); + const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); + holdSafetyRecovery(db); + // Each turn's provider requests, as the loopback model received them. + const requests:{turn:number;raw:string}[]=[];let turn=0,version:string|undefined,runtimeSession:string|undefined; + const origin=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(request){ + if(new URL(request.url).pathname!=="/v1/messages")return Response.json({}); + const raw=await request.text(),body=JSON.parse(raw); + if(!Array.isArray(body.tools)||!body.tools.length)return nativeModelReply(); + requests.push({turn,raw}); + const first=turn===0&&requests.filter(r=>r.turn===0).length===1; + return nativeModelReply(first?{name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}}:undefined); + }}); + async function voyage(turnId:string,sessionId:string|null,refuseResult:boolean,resume?:string){ + const controller=new AbortController(),bindingId=crypto.randomUUID(); + await writes.safetyBegin({turnId,bindingId,sessionId,principalId:"odysseus",backendId:"claude",at:turn}); + if(!sessionId){ + db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + safetyCatalogCreated(db,"ithaca","odysseus",turnId);await writes.bind(turnId,"ithaca"); + } + const collector=createSafetyCollector(db,writes,{turnId,bindingId,backendId:"claude",sessionId:()=>"ithaca",brainPath:brain,shellProxied:()=>false,signal:controller.signal,stop:error=>controller.abort(error)}); + await collector.ready("claude",1); + const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:"allow"}),inputSafety:collector}},allowedTools:["Grep"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); + let results=0; + if(refuseResult){ + // The Grep result exists and the runtime holds it; only its record fails. + const group=wiring.hooks!.PostToolUse!.find(group=>!group.matcher)!,record=group.hooks[0]!; + group.hooks=[async(...args)=>{results++;db.exec("CREATE TRIGGER refuse_result BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced result reservation failure'); END");return record(...args);}]; + } + const timer=setTimeout(()=>controller.abort(),20000); + try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:["Grep"],...wiring,abortController:controller, + ...(resume?{resume}:{}), + env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),PATH:process.env.PATH??"/usr/bin:/bin",ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ + if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; + if("session_id" in message&&typeof message.session_id==="string")runtimeSession=message.session_id; + }}catch{/* The refused turn is stopped by its collector. */} + finally{clearTimeout(timer);db.exec("DROP TRIGGER IF EXISTS refuse_result");await writes.safetyEnd(turnId);} + return {results,aborted:controller.signal.aborted}; + } + try{ + const first=await voyage("voyage",null,true); + expect(version,"SAFETY_ACTUAL_INSTALLED_RUNTIME").toBe(MEASURED_RUNTIME.claudeCode); + expect(first.results,"SAFETY_ACTUAL_RESULT_HOOK_EXECUTED").toBe(1); + expect(first.aborted,"SAFETY_REFUSED_RESULT_STOPS_ITS_TURN").toBe(true); + expect(runtimeSession,"SAFETY_RUNTIME_SESSION_TO_RESUME").toBeDefined(); + turn=1; + await voyage("homeward","ithaca",false,runtimeSession); + const resumed=requests.filter(r=>r.turn===1); + expect(resumed.length,"SAFETY_ACTUAL_NATIVE_RESUME").toBeGreaterThan(0); + // The premise: refusing the record did not keep the result out of the model's context. + expect(resumed.some(r=>r.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_REFUSED_RESULT").toBe(true); + const chat=writes.safety("homeward","ithaca"); + expect(chat.restriction,"SAFETY_REFUSED_RESULT_RESTRICTS_ITS_CHAT").toBe("restricted"); + expect(chat.coverage.state,"SAFETY_REFUSED_RESULT_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + expect(chat.coverage.epochs.find(e=>e.reason==="recording_failed"),"SAFETY_REFUSED_RESULT_IS_A_RECORDING_GAP").toBeDefined(); + expect(db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_REFUSED_RESULT_GAP_IS_DURABLE").toEqual({failure:"recording_failed"}); + // Contained to its chat: the brain-wide recorder is untouched, and a + // recovery has nothing to clear, so the gap stays. + expect(db.query("SELECT failed FROM safety_meta").get(),"SAFETY_REFUSED_RESULT_NEVER_LATCHES_THE_BRAIN").toEqual({failed:0}); + recoverSafetyRecording(db,{trigger:"owner",actor:"penelope"}); + expect(writes.safety(null,"ithaca").restriction,"SAFETY_REFUSED_RESULT_GAP_SURVIVES_RECOVERY").toBe("restricted"); + }finally{origin.stop(true);await writer.close();db.close();rmSync(root,{recursive:true,force:true});} +},60000); From ed5a0272e256313a9efd62cb8ce98e11a2d6fa84 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 07:52:16 +0100 Subject: [PATCH 08/24] CONTRACT: fix(ui-server): drain pre-latch producers, show the retained cause, and say what frees spent room (#3812, #3810) - Automatic recovery now waits until every producer that predates the latch has ended, failed or not. Only turns begun restricted run beside it; a failed producer's durable or in-memory loss no longer exempts it from the drain. - /api/status `safetyRecording.cause` falls back to the cause this process holds while its notice cannot commit, marked `durable: false`; a committed latch cause carries `durable: true`. - Every capacity refusal names what it spent (`turn`, `chat` or `brain`). A turn refused for spent chat or brain room ends with the additive failure classes `safety_recording_chat_full` (start a new chat) or `safety_recording_brain_full` (retrying won't help), and the PWA no longer asks the owner to try again. Additive: one optional field on the status cause and two failure classes, documented in docs/integration-contract/http.md and wire.md. Co-Authored-By: Claude Opus 5.5 --- .../3812-safety-recording-containment.md | 10 +- api-report/ui-sdk.txt | 2 +- docs/decisions/proportionate-containment.md | 4 +- docs/decisions/session-safety-reviews.md | 16 ++- docs/http-api-coverage.md | 2 +- docs/integration-contract/http.md | 10 +- docs/integration-contract/wire.md | 7 +- docs/plans/reviewable-session-safety.md | 2 +- packages/ui-react/src/lib/turn-failure.ts | 21 +++- packages/ui-sdk/src/protocol.ts | 4 +- .../ui-server/src/governance/event-writes.ts | 8 +- .../ui-server/src/governance/safety-store.ts | 80 +++++++++----- .../src/ws/bridge-capabilities/turn-error.ts | 9 +- .../tests/safety-containment.test.ts | 103 +++++++++++++++++- 14 files changed, 215 insertions(+), 63 deletions(-) diff --git a/.changeset/3812-safety-recording-containment.md b/.changeset/3812-safety-recording-containment.md index e85542691c..e0ec1f5603 100644 --- a/.changeset/3812-safety-recording-containment.md +++ b/.changeset/3812-safety-recording-containment.md @@ -6,10 +6,10 @@ A safety-recording failure now restricts only what it puts at risk, and the host recovers by itself (#3812, #3810). -- **One turn, before delivery.** A failed safety begin, or a refused reservation that delivered nothing, refuses only that turn with the new retryable `SAFETY_RECORDING_UNAVAILABLE` error. The chat and the brain stay usable. -- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. It keeps running under its tainted policy; other chats are untouched. -- **The brain, only when the evidence store cannot take a scoped fact.** New turns still run, restricted, each with a permanent gap written before anything is sent. The server keeps retrying and clears the latch itself once the gaps are durable. A turn is refused only if even its restricted start cannot be written (`safety_recording_paused`). +- **One turn, before delivery.** A failed safety begin, or a refused record of a tool's input before the tool runs, refuses only that turn with the new `SAFETY_RECORDING_UNAVAILABLE` error. The chat and the brain stay usable. When the refusal is for spent room, it says what to do: start a new chat (`safety_recording_chat_full`), or that retrying won't help (`safety_recording_brain_full`). +- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails: the runtime may already keep it in its session. The chat keeps running under its tainted policy; other chats are untouched. +- **The brain, only when the evidence store cannot take a scoped fact.** New turns still run, restricted, each with a permanent gap written before anything is sent. The server keeps retrying and clears the latch itself once the gaps are durable and every turn that predates the latch has ended. A turn is refused only if even its restricted start cannot be written (`safety_recording_paused`). - **Boot** resolves a set latch and pending reservations automatically instead of refusing every turn. -- **Diagnosable.** Each latch keeps its first cause and a count in the database, logs one structured line, and is shown to the owner as `safetyRecording` on `/api/status`. Errors are no longer all labelled `capacity`. Every recovery is recorded with who or what ran it. +- **Diagnosable.** Each latch keeps its first cause and a count in the database, logs one structured line, and is shown to the owner as `safetyRecording` on `/api/status`, also while only the server process holds it (`cause.durable: false`). Errors are no longer all labelled `capacity`. Every recovery is recorded with who or what ran it. - **Owner fallback.** `POST /api/status/safety-recording/recover` runs the same recovery when nothing is open. -- **PWA.** A message refused this way says that safety recording failed or is paused, instead of "The brain refused this message." +- **PWA.** A message refused this way says that safety recording failed, is paused, or has no room left and what to do, instead of "The brain refused this message." diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 17d557a4f9..577962d377 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -7664,7 +7664,7 @@ signatures (every public export and the types it is made of) entries: FileEntry[]; } FirstPartyFailureClass (packages/ui-sdk/src/protocol.ts) - type FirstPartyFailureClass = "authentication_failed" | "oauth_org_not_allowed" | "account_on_hold" | "verification_required" | "billing_error" | "subscription_required" | "auth_failure" | "rate_limit" | "overloaded" | "server_error" | "invalid_request" | "model_not_found" | "max_output_tokens" | "cloud_credential_error" | "worker_host_unsupported" | "session_too_large" | "worker_resource_limit" | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "safety_recording_unavailable" | "safety_recording_paused" | "unknown"; + type FirstPartyFailureClass = "authentication_failed" | "oauth_org_not_allowed" | "account_on_hold" | "verification_required" | "billing_error" | "subscription_required" | "auth_failure" | "rate_limit" | "overloaded" | "server_error" | "invalid_request" | "model_not_found" | "max_output_tokens" | "cloud_credential_error" | "worker_host_unsupported" | "session_too_large" | "worker_resource_limit" | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "safety_recording_unavailable" | "safety_recording_paused" | "safety_recording_chat_full" | "safety_recording_brain_full" | "unknown"; FirstRequestCacheUsage (packages/ui-sdk/src/protocol.ts) export interface FirstRequestCacheUsage { inputTokens: number | null; diff --git a/docs/decisions/proportionate-containment.md b/docs/decisions/proportionate-containment.md index 54fe965703..d17583df3c 100644 --- a/docs/decisions/proportionate-containment.md +++ b/docs/decisions/proportionate-containment.md @@ -12,10 +12,10 @@ Ruled by the maintainer on 2026-11-09 (#3812). Tracked under #3813. A hosted instance refused every turn in every chat. One turn's safety-recording write had failed, and the guard reacted by setting one durable flag for the whole brain (`latchSafety`, -`packages/ui-server/src/governance/safety-store.ts:37-44`). From then on, turn +`packages/ui-server/src/governance/safety-store.ts:115-125`). From then on, turn admission threw for every chat, including new chats that had never seen untrusted input (`beginSafetyCollection`, -`packages/ui-server/src/governance/safety-store.ts:70-76`). The error that +`packages/ui-server/src/governance/safety-store.ts:183-192`). The error that set the flag was recorded as "capacity" while the store was at a fraction of a percent of its limits, and its real cause was never stored. The only way back was to stop the server and run `recoverSafetyRecording` from a script, a diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index e75a33ca43..1df1d6b1b5 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -78,9 +78,15 @@ Ruled by the maintainer on 2026-11-09, under [proportionate containment](proportionate-containment.md). "Restricted" means running under the tainted policy, not refusing. -- **Before delivery** (a failed collection begin, or a refused reservation - whose producer holds its input until the event commits): the one turn is - refused with a retryable `SAFETY_RECORDING_UNAVAILABLE`. Nothing latches. +- **Before delivery** (a failed collection begin, or a refused record of a + tool's input, which the backend awaits before the tool runs): the one turn + is refused with `SAFETY_RECORDING_UNAVAILABLE`. Nothing latches. A tool's + result is never before delivery: its bytes exist when it is recorded, and a + runtime may keep them in its own session (the Claude runtime replays them + on resume), so a result that cannot be recorded is lost after delivery. + A refusal for spent room says what frees it: a full chat needs a new chat + (`safety_recording_chat_full`), and a full brain cannot be helped by a + retry (`safety_recording_brain_full`). - **Lost after delivery**: the turn's own collection takes the failure and its first cause, so its chat keeps a permanent gap projected as `recording_failed` and that producer stops. Other chats are unaffected. A @@ -92,14 +98,14 @@ running under the tainted policy, not refusing. is refused only when that restricted begin itself cannot commit (`safety_recording_paused`). The host keeps retrying, backing off to once a minute, and clears the latch itself with `recoverSafetyRecording` semantics - once the producers that predate it have drained. + once every producer that predates it has ended, failed or not. - **Boot** resolves a set latch and pending reservations after restart classification, gaps first. A legacy row that cannot migrate gaps its own turn. The server never boots into refusing every turn. Every latch keeps its first cause (class, message, bounded stack, call site, turn, time) and a count, logs one structured line, and is visible to the owner -on `/api/status`. Every recovery is recorded with its trigger, actor, time and +on `/api/status`, also while only the host process holds it. Every recovery is recorded with its trigger, actor, time and cleared cause. The owner route (#3810) is a fallback with the strict quiescence precondition. Only a capacity check classifies a failure as `capacity`. No gap ever clears, and nothing here lets an unrecorded input diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index c5df61a5c4..103e419e42 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -199,7 +199,7 @@ cover start refusal, mid-turn partial work, overlapping observations and leases. - `a failing host boots anyway, logs the named requirement once, and /api/status reports it` ([source](../packages/ui-server/tests/worker-host-status.test.ts)), (`a failing host boots anyway, logs the named requirement once, and /api/status reports it`, `packages/ui-server/tests/worker-host-status.test.ts:66-83`) - `re-runs the real probe and records what it found, in both directions` ([source](../packages/ui-server/tests/worker-host-status.test.ts)), (`re-runs the real probe and records what it found, in both directions`, `packages/ui-server/tests/worker-host-status.test.ts:160-176`) - `is behind the auth guard` ([source](../packages/ui-server/tests/worker-host-status.test.ts)), (`is behind the auth guard`, `packages/ui-server/tests/worker-host-status.test.ts:178-187`) -- `the status route shows the recorder to the owner only, and recovery requires the owner` ([source](../packages/ui-server/tests/safety-containment.test.ts)), (`the status route shows the recorder to the owner only, and recovery requires the owner`, `packages/ui-server/tests/safety-containment.test.ts:273-288`) +- `the status route shows the recorder to the owner only, and recovery requires the owner` ([source](../packages/ui-server/tests/safety-containment.test.ts)), (`the status route shows the recorder to the owner only, and recovery requires the owner`, `packages/ui-server/tests/safety-containment.test.ts:275-290`) - `boots, warns once in the log, and keeps the warning on /api/status and through Check again` ([source](../packages/ui-server/tests/worker-host-status.test.ts)), (`boots, warns once in the log, and keeps the warning on /api/status and through Check again`, `packages/ui-server/tests/worker-host-status.test.ts:214-231`) **A — Password access and revocation.** diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 3a63b65081..3de2bd7738 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -262,9 +262,10 @@ For an owner principal, authenticated `GET /api/status` gains optional the Unix-millisecond time of the first latch; `reason` is `recording_failed` or `capacity`, and `capacity` only when a capacity check refused the write. `cause` is the first latch's `{ reason, site, turnId, errorClass, message, -stack, since, count }`: identifiers and error text only, never message -content; later latches only increase `count`. `retained` is true when only -this process holds the loss because its durable notice could not commit. +stack, since, count, durable }`: identifiers and error text only, never +message content; later latches only increase `count`. `retained` is true when +only this process holds the loss because its durable notice could not commit; +`cause` is then the cause this process holds, with `durable: false`. `lastRecovery` is the latest `{ trigger, actor, at, gapped, cause }`, where `trigger` is `boot`, `automatic` or `owner`. Other principals never receive the field. @@ -274,7 +275,8 @@ refuses its one turn; lost evidence after delivery restricts its chat with a permanent gap; only an evidence store that cannot take a scoped fact latches the brain. While latched, new turns run under their tainted policy with a permanent pre-delivery gap, and the host clears the latch by itself once the -gap facts are durable and the producers that predate it have drained +gap facts are durable and every producer that predates it has ended, failed or +not ([proportionate containment](../decisions/proportionate-containment.md)). Owner-only `POST /api/status/safety-recording/recover` takes a JSON body diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 881d8ff4a8..321d9b9511 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -178,8 +178,11 @@ additive error code `SAFETY_RECORDING_UNAVAILABLE` (#3810, #3812) and the additive failure classes `safety_recording_unavailable` (a one-turn failure before delivery; retry) and `safety_recording_paused` (the brain-wide recorder is failed and even the turn's restricted start could not commit; the host -recovers it by itself). Nothing reached the model in either case. A client -says so instead of reporting a refusal by the brain. +recovers it by itself). Two more classes name spent room that no retry or +recovery frees: `safety_recording_chat_full` (this chat has no room left; +start a new chat) and `safety_recording_brain_full` (the server has no room +left; a new chat does not help). Nothing reached the model in any of these +cases. A client says so instead of reporting a refusal by the brain. `budget_exceeded` and `budget_unavailable` are additive host failure classes. The former names a turn/session/day `budgetScope`; a day stop carries diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 5ab84d402c..2e8d10774e 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -25,7 +25,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. - Taint recording retains every independently observed signal and reads a durable revisioned aggregate, including pending/failure and explicit unknown coverage (`safetyProjection`, - `packages/ui-server/src/governance/safety-store.ts:232-237`). Legacy rows prove + `packages/ui-server/src/governance/safety-store.ts:357-362`). Legacy rows prove their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, diff --git a/packages/ui-react/src/lib/turn-failure.ts b/packages/ui-react/src/lib/turn-failure.ts index a089e3aedb..bd0b21bc30 100644 --- a/packages/ui-react/src/lib/turn-failure.ts +++ b/packages/ui-react/src/lib/turn-failure.ts @@ -20,9 +20,13 @@ const HEADLINES: Record = { */ export function refusalReason(frame: { code?: string; failure?: { errorClass?: string } }): string | undefined { if (frame.code !== "SAFETY_RECORDING_UNAVAILABLE") return undefined; - return frame.failure?.errorClass === "safety_recording_paused" - ? "Safety recording is paused on this server. Nothing was sent; try again in a minute." - : "Safety recording failed before this was sent. Nothing ran; try again."; + switch (frame.failure?.errorClass) { + case "safety_recording_paused": return "Safety recording is paused on this server. Nothing was sent; try again in a minute."; + // Spent room: retrying cannot free it (#3812). + case "safety_recording_chat_full": return "This chat has no room left for safety records. Nothing was sent; start a new chat to continue."; + case "safety_recording_brain_full": return "This server has no room left for safety records. Nothing was sent, and retrying won't help."; + default: return "Safety recording failed before this was sent. Nothing ran; try again."; + } } /** Class-driven copy; a class never establishes whether tools already ran. */ @@ -33,6 +37,17 @@ export function failurePresentation(failure: TurnFailure) { explanation: "Nothing ran. Try again.", operator: false, tone: "gold" as const, retry: true, report: false, }; + // Spent room is not retryable: recovery cannot free it either. + if (failure.errorClass === "safety_recording_chat_full") return { + headline: "This chat has no room left for safety records.", + explanation: "Nothing was sent. Start a new chat to continue.", + operator: false, tone: "gold" as const, retry: false, report: false, + }; + if (failure.errorClass === "safety_recording_brain_full") return { + headline: "This server has no room left for safety records.", + explanation: "Nothing was sent. Retrying or starting a new chat won't help. Report this so the limit can be raised.", + operator: true, tone: "red" as const, retry: false, report: true, + }; if (failure.errorClass === "safety_recording_paused") return { headline: "Safety recording is paused on this server.", explanation: "Nothing was sent. The server is recovering it by itself; try again in a minute.", diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 0030aba2ba..df019502f1 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -1366,7 +1366,7 @@ type FirstPartyFailureClass = | "auth_failure" | "rate_limit" | "overloaded" | "server_error" | "invalid_request" | "model_not_found" | "max_output_tokens" | "cloud_credential_error" | "worker_host_unsupported" | "session_too_large" | "worker_resource_limit" - | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "safety_recording_unavailable" | "safety_recording_paused" | "unknown"; + | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "safety_recording_unavailable" | "safety_recording_paused" | "safety_recording_chat_full" | "safety_recording_brain_full" | "unknown"; /** * First-party failure classes, shared by emitters and reviewed diagnostics. @@ -1402,6 +1402,8 @@ export const FIRST_PARTY_FAILURE_CLASSES: Readonly<{ [Class in FirstPartyFailure input_safety_unavailable: "input_safety_unavailable", safety_recording_unavailable: "safety_recording_unavailable", safety_recording_paused: "safety_recording_paused", + safety_recording_chat_full: "safety_recording_chat_full", + safety_recording_brain_full: "safety_recording_brain_full", unknown: "unknown", }); diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index 3d4e6264b0..14cd33afee 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -92,8 +92,10 @@ export interface GovernanceWrites { */ record(input: GovernanceEventInput): Promise<{ id: number; recorded: boolean }>; /** Stores every distinct occurrence; only the exact host key deduplicates. Historical internal method name. */ - /** `beforeDelivery`: the producer holds the input until this settles, so a - * refused reservation delivered nothing and refuses only the turn. */ + /** `beforeDelivery`: a tool's input, recorded before the tool runs, which + * the producer holds until this settles; a refused reservation delivered + * nothing and refuses only the turn. Never for a result: its bytes already + * exist and a runtime may keep them in its session (#3812). */ firstTaint(input: GovernanceEventInput<"taint">, options?: { beforeDelivery?: boolean }): Promise; /** The brain-wide recorder state the owner sees on `/api/status` (#3810). */ recordingStatus(): SafetyRecordingStatus; @@ -194,7 +196,7 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov ? [...pendingTaints].filter(p=>p.turnId===null&&p.sessionId===null) : pendingInScope(row.turnId,row.sessionId)); if (pendingTaints.size >= 4096 || shared.bytes + bytes > 16777216 || session.length >= 256 || session.reduce((sum, p) => sum + p.bytes, 0) + bytes > 1048576) { - void safetyFail(row.turnId,new SafetyCapacityExhausted("Safety occurrence write capacity exceeded")).catch(()=>{}); + void safetyFail(row.turnId,new SafetyCapacityExhausted("Safety occurrence write capacity exceeded","turn")).catch(()=>{}); throw new Error("Safety occurrence write capacity exceeded; ingestion must stop"); } const pending = { turnId: row.turnId, sessionId: row.sessionId, source: input.kind==="taint"?(input as GovernanceEventInput<"taint">).payload.source:"legacy_unknown" as const, bytes }; diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index 20ea65bab8..e6042d63fd 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -27,8 +27,14 @@ interface Collection { id: string; turn_id: string; session_id: string | null; p interface Session { session_id: string; history_owner_id: string; generation: string; principal_id: string | null; classification: string; origin_turn: string | null; backend_id: string | null } export class SafetyUnavailable extends Error { constructor(message: string) { super(message); } } +/** What a capacity refusal spent, so a refusal can say what frees it: `turn` + * room frees itself (pending writes settle, or only this one record is too + * big); `chat` room is that chat's for good; `brain` room is the server's. */ +export type SafetyCapacityScope = "turn"|"chat"|"brain"; /** A capacity check refused the write. Only this class latches as `capacity`. */ -export class SafetyCapacityExhausted extends SafetyUnavailable {} +export class SafetyCapacityExhausted extends SafetyUnavailable { + constructor(message: string, readonly scope: SafetyCapacityScope) { super(message); } +} /** * A turn refused before any of its input reached the model, because its * safety record could not be written. Nothing ran and nothing is latched, so @@ -41,13 +47,21 @@ export class SafetyRecordingUnavailable extends Error { readonly beforeDelivery = true; /** A capacity check refused it: retrying waits for room, not for luck. */ readonly capacity: boolean; + /** Room retrying can never free: this chat's, or the whole brain's. It + * outranks `paused`: recovery cannot make room either. */ + readonly full: "chat"|"brain"|null; constructor(readonly paused: boolean, cause?: unknown) { const capacity = cause instanceof SafetyCapacityExhausted || (cause as { name?: string } | null)?.name === "SafetyCapacityExhausted"; - super(paused - ? "Safety recording is paused on this server, so this turn could not start. Nothing was sent. The server recovers it automatically." - : capacity ? `Safety recording has no room left (${(cause as Error).message}). Nothing was sent.` + // The scope is an own field, so it survives the write worker's boundary. + const scope = capacity ? (cause as { scope?: unknown }).scope : undefined; + const full = scope === "chat" || scope === "brain" ? scope : null; + super(full === "chat" ? `This chat has no room left for safety records (${(cause as Error).message}), so this turn could not start. Nothing was sent. Start a new chat to continue.` + : full === "brain" ? `This server has no room left for safety records (${(cause as Error).message}), so this turn could not start. Nothing was sent, and retrying or a new chat won't help.` + : paused ? "Safety recording is paused on this server, so this turn could not start. Nothing was sent. The server recovers it automatically." + : capacity ? `Safety recording has no room left (${(cause as Error).message}). Nothing was sent; try again shortly.` : "Safety recording failed before anything was sent. Nothing ran; try again.", { cause }); this.capacity = capacity; + this.full = full; } } const one = (db: Database, sql: string, ...args: (string | number | null)[]) => db.query(sql).get(...args) as T; @@ -55,7 +69,7 @@ const collection = (db: Database, turn: string) => one(db,"SE const meta = (db: Database) => one<{revision:string;failed:number;reason:string|null;used_rows:number;used_bytes:number;scope_rows:number;scope_bytes:number}>(db,"SELECT * FROM safety_meta WHERE singleton=1"); export function advance(db: Database): string { const old=BigInt(meta(db).revision); - if(old>=MAX_REVISION) throw new SafetyCapacityExhausted("Safety revision exhausted"); + if(old>=MAX_REVISION) throw new SafetyCapacityExhausted("Safety revision exhausted","brain"); const next=String(old+1n); db.query("UPDATE safety_meta SET revision=? WHERE singleton=1").run(next); return next; } @@ -151,13 +165,18 @@ function capacity(db:Database,c:Collection,rows:number,bytes:number):void { const pending=one<{rows:number;bytes:number}>(db,`SELECT COALESCE(SUM(p.rows),0) rows,COALESCE(SUM(p.reserved_bytes),0) bytes FROM safety_pending p`); const localPending=one<{rows:number;bytes:number}>(db,`SELECT COALESCE(SUM(p.rows),0) rows,COALESCE(SUM(p.reserved_bytes),0) bytes FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE ${scope}`,...args); + // Room held only by pending writes frees itself as they settle. + if(all.used_rows+all.scope_rows+rows>SAFETY_LIMITS.brainRows||all.used_bytes+all.scope_bytes+bytes>SAFETY_LIMITS.brainBytes) + throw new SafetyCapacityExhausted("Safety ledger capacity exhausted","brain"); + if(used.rows+rows>SAFETY_LIMITS.sessionRows||used.bytes+bytes>SAFETY_LIMITS.sessionBytes) + throw new SafetyCapacityExhausted("Safety ledger capacity exhausted","chat"); if(all.used_rows+all.scope_rows+pending.rows+rows>SAFETY_LIMITS.brainRows||all.used_bytes+all.scope_bytes+pending.bytes+bytes>SAFETY_LIMITS.brainBytes ||used.rows+localPending.rows+rows>SAFETY_LIMITS.sessionRows||used.bytes+localPending.bytes+bytes>SAFETY_LIMITS.sessionBytes) - throw new SafetyCapacityExhausted("Safety ledger capacity exhausted"); + throw new SafetyCapacityExhausted("Safety ledger capacity exhausted","turn"); if(c.session_id===null){ const unbound=one<{bytes:number}>(db,`SELECT COALESCE(SUM(r.reserved_bytes),0) bytes FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.session_id IS NULL`); - if(unbound.bytes+pending.bytes+bytes+one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL").n*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted"); + if(unbound.bytes+pending.bytes+bytes+one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL").n*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted","brain"); } } /** Must commit before any first-turn bytes or tool execution. Callbacks cannot create a session. */ @@ -188,15 +207,16 @@ export function beginSafetyCollection(db:Database,input:SafetyCollectionInput):s assertLive(db,[["dialogue_owner",owner]]); if(session?.principal_id&&session.principal_id!==input.principalId)throw new SafetyUnavailable("Safety principal mismatch"); const n=one<{n:number}>(db, input.sessionId?"SELECT COUNT(*) n FROM safety_collections WHERE session_id=?":"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL",...(input.sessionId?[input.sessionId]:[])); - if(n.n>=(input.sessionId?SAFETY_LIMITS.epochs:SAFETY_LIMITS.unbound))throw new SafetyCapacityExhausted("Safety coverage capacity exhausted"); + if(n.n>=(input.sessionId?SAFETY_LIMITS.epochs:SAFETY_LIMITS.unbound))throw new SafetyCapacityExhausted("Safety coverage capacity exhausted",input.sessionId?"chat":"brain"); if(input.sessionId===null){ const unbound=one<{bytes:number}>(db,`SELECT COALESCE(SUM(r.reserved_bytes),0) bytes FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.session_id IS NULL`); const pending=one<{bytes:number}>(db,`SELECT COALESCE(SUM(p.reserved_bytes),0) bytes FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE c.session_id IS NULL`); - if(unbound.bytes+pending.bytes+(n.n+1)*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted"); + if(unbound.bytes+pending.bytes+(n.n+1)*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted","brain"); } const ledger=meta(db),pending=one<{rows:number;bytes:number}>(db,"SELECT COALESCE(SUM(rows),0) rows,COALESCE(SUM(reserved_bytes),0) bytes FROM safety_pending"); - if(ledger.used_rows+ledger.scope_rows+pending.rows+1>SAFETY_LIMITS.brainRows||ledger.used_bytes+ledger.scope_bytes+pending.bytes+2048>SAFETY_LIMITS.brainBytes)throw new SafetyCapacityExhausted("Safety identity capacity exhausted"); - if(owner&&one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE history_owner_id=? AND generation=?",owner,generation).n>=128)throw new SafetyCapacityExhausted("Safety coverage capacity exhausted"); + if(ledger.used_rows+ledger.scope_rows+pending.rows+1>SAFETY_LIMITS.brainRows||ledger.used_bytes+ledger.scope_bytes+pending.bytes+2048>SAFETY_LIMITS.brainBytes) + throw new SafetyCapacityExhausted("Safety identity capacity exhausted",ledger.used_rows+ledger.scope_rows+1>SAFETY_LIMITS.brainRows||ledger.used_bytes+ledger.scope_bytes+2048>SAFETY_LIMITS.brainBytes?"brain":"turn"); + if(owner&&one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE history_owner_id=? AND generation=?",owner,generation).n>=128)throw new SafetyCapacityExhausted("Safety coverage capacity exhausted","chat"); if(input.policyHash!==undefined&&input.policyHash!==null&&!/^[a-f0-9]{64}$/.test(input.policyHash))throw new SafetyUnavailable("Invalid safety policy hash"); const gap=restricted?"recording_failed":uncollectedOwner?"missing_history_owner_collection":input.sessionId&&!session?.principal_id?"unknown_history_owner":session?.backend_id&&session.backend_id!==input.backendId?"backend_history_not_reconstructed":null; db.query(`INSERT INTO safety_collections(id,turn_id,session_id,principal_id,history_owner_id,generation,backend_id,started_at,gap,start_revision) @@ -248,14 +268,15 @@ export function bindSafetyCollection(db:Database,turnId:string,sessionId:string) assertLive(db,[["session",sessionId],["dialogue_owner",owner]]); const {scope,args}=safetyScope(db,turnId,sessionId); const epochs=one<{n:number}>(db,`SELECT COUNT(*) n FROM safety_collections c WHERE ${scope}`,...args); - if(epochs.n>128)throw new SafetyCapacityExhausted("Safety binding coverage capacity exhausted"); + if(epochs.n>128)throw new SafetyCapacityExhausted("Safety binding coverage capacity exhausted","chat"); const totals=one<{rows:number;bytes:number}>(db,`SELECT COALESCE(SUM(r.reserved_rows),0) rows,COALESCE(SUM(r.reserved_bytes),0) bytes FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE ${scope}`,...args); const pending=one<{rows:number;bytes:number;count:number;serializedBytes:number}>(db,`SELECT COALESCE(SUM(p.rows),0) rows,COALESCE(SUM(p.reserved_bytes),0) bytes, COUNT(*) count,COALESCE(SUM(p.bytes),0) serializedBytes FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE ${scope}`,...args); - if(totals.rows+pending.rows>SAFETY_LIMITS.sessionRows||totals.bytes+pending.bytes>SAFETY_LIMITS.sessionBytes)throw new SafetyCapacityExhausted("Safety binding capacity exhausted"); - if(pending.count>SAFETY_LIMITS.sessionPending||pending.serializedBytes>SAFETY_LIMITS.sessionPendingBytes)throw new SafetyCapacityExhausted("Safety binding pending capacity exhausted"); + if(totals.rows+pending.rows>SAFETY_LIMITS.sessionRows||totals.bytes+pending.bytes>SAFETY_LIMITS.sessionBytes) + throw new SafetyCapacityExhausted("Safety binding capacity exhausted",totals.rows>SAFETY_LIMITS.sessionRows||totals.bytes>SAFETY_LIMITS.sessionBytes?"chat":"turn"); + if(pending.count>SAFETY_LIMITS.sessionPending||pending.serializedBytes>SAFETY_LIMITS.sessionPendingBytes)throw new SafetyCapacityExhausted("Safety binding pending capacity exhausted","turn"); const previous=one<{session_id:string;history_owner_id:string;generation:string}|null>(db,"SELECT * FROM safety_bindings WHERE turn_id=?",turnId); if(previous&&(previous.session_id!==sessionId||previous.history_owner_id!==owner||previous.generation!==gen))throw new SafetyUnavailable("Safety SessionKey binding changed"); db.query("INSERT INTO safety_bindings VALUES(?,?,?,?,?,?) ON CONFLICT DO NOTHING").run(c.id,turnId,sessionId,owner,gen,advance(db)); @@ -275,12 +296,12 @@ function appendRecord(db:Database,c:Collection,id:string,kind:"occurrence"|"expo const json=JSON.stringify(payload),bytes=Buffer.byteLength(JSON.stringify({id,collectionId:c.id,turnId:c.turn_id, session:{sessionId:c.session_id,historyOwnerId:c.history_owner_id,historyGeneration:c.generation},sequence:"18446744073709551615",observedAt:at, kind,occurrenceId,source,detector,state,payload})); - if(bytes>SAFETY_LIMITS.occurrenceBytes)throw new SafetyCapacityExhausted("Safety occurrence byte limit exceeded"); + if(bytes>SAFETY_LIMITS.occurrenceBytes)throw new SafetyCapacityExhausted("Safety occurrence byte limit exceeded","turn"); const previous=one(db,"SELECT * FROM safety_records WHERE id=?",id); if(previous){if(previous.collection_id!==c.id||(previous.detail_pruned ? previous.payload!==JSON.stringify({sha256:new Bun.CryptoHasher("sha256").update(json).digest("hex")}) : previous.payload!==json))throw new SafetyUnavailable("Conflicting safety occurrence identity");return;} const rows=kind==="occurrence"?(state==="finalized"?2:4):0, reserved=kind==="occurrence"?bytes+VERDICT_BYTES+(state==="finalized"?0:2*TERMINAL_BYTES):0; - if(kind==="exposure"&&bytes>TERMINAL_BYTES)throw new SafetyCapacityExhausted("Safety terminal reserve exceeded"); + if(kind==="exposure"&&bytes>TERMINAL_BYTES)throw new SafetyCapacityExhausted("Safety terminal reserve exceeded","turn"); capacity(db,c,rows,reserved); db.query("INSERT INTO safety_records VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,0)").run(id,c.id,advance(db),at,kind,occurrenceId,source,detector,state,json,bytes,rows,reserved); db.query("UPDATE safety_meta SET used_rows=used_rows+?,used_bytes=used_bytes+? WHERE singleton=1").run(rows,reserved); @@ -429,7 +450,7 @@ export function reserveSafetyWrite(db:Database,turnId:string,requestId:string,by const local=one<{n:number;bytes:number}>(db,`SELECT COUNT(*) n,COALESCE(SUM(p.bytes),0) bytes FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE ${scope}`,...args); if(global.n>=SAFETY_LIMITS.brainPending||global.bytes+bytes>SAFETY_LIMITS.brainPendingBytes||local.n>=SAFETY_LIMITS.sessionPending||local.bytes+bytes>SAFETY_LIMITS.sessionPendingBytes) - throw new SafetyCapacityExhausted("Safety pending capacity exhausted"); + throw new SafetyCapacityExhausted("Safety pending capacity exhausted","turn"); const rows=terminalOccurrenceId?0:4,reserved=terminalOccurrenceId?0:bytes+VERDICT_BYTES+2*TERMINAL_BYTES; capacity(db,c,rows,reserved); db.query("INSERT INTO safety_pending VALUES(?,?,?,?,?)").run(requestId,c.id,bytes,rows,reserved);advance(db); @@ -503,11 +524,14 @@ const latchCause=(db:Database):SafetyLatchCause|null=>{ const row=one<{since:number;reason:string;site:string;turn_id:string|null;error_class:string;message:string;stack:string|null;count:number}|null>(db,"SELECT * FROM safety_latch WHERE singleton=1"); return row?{reason:row.reason,site:row.site,turnId:row.turn_id,errorClass:row.error_class,message:row.message,stack:row.stack,since:row.since,count:row.count}:null; }; -/** What the owner sees about the brain-wide recorder (#3810). */ -export interface SafetyRecordingStatus { latched:boolean; since:number|null; reason:string|null; cause:SafetyLatchCause|null; retained:boolean; lastRecovery:Omit|null } +/** What the owner sees about the brain-wide recorder (#3810). `cause.durable` + * is false while only this process holds it, its notice not yet committed. */ +export interface SafetyRecordingStatus { latched:boolean; since:number|null; reason:string|null; cause:(SafetyLatchCause&{durable:boolean})|null; retained:boolean; lastRecovery:Omit|null } export function safetyRecordingStatus(db:Database):SafetyRecordingStatus { return Database.prototype.transaction.call(db,()=>{ - const m=meta(db),local=safetyQueue(db),cause=latchCause(db); + const m=meta(db),local=safetyQueue(db),durable=latchCause(db),lost=local.lossCause; + const cause=durable?{...durable,durable:true}:local.failed&&lost?{reason:"recording_failed",site:lost.site,turnId:lost.turnId, + errorClass:lost.errorClass,message:lost.message,stack:null,since:lost.at,count:lost.count,durable:false}:null; const last=one<{at:number;trigger:SafetyRecoveryTrigger;actor:string;cause:string|null;gapped:number}|null>(db,"SELECT * FROM safety_recoveries ORDER BY id DESC LIMIT 1"); return {latched:!!m.failed||local.failed,since:cause?.since??null,reason:m.failed?(m.reason??"recording_failed"):local.failed?"recording_failed":null,cause, retained:local.failed&&!m.failed, @@ -522,24 +546,24 @@ export function safetyRecordingStatus(db:Database):SafetyRecordingStatus { * gap, so its chat stays restricted until reviewed. * * `owner` and `boot` recovery require every producer to have stopped. - * `automatic` recovery runs beside turns begun restricted: their collections - * already carry a permanent gap, so it waits only for producers whose - * evidence could still be in flight (#3812). + * `automatic` recovery runs beside turns begun restricted: they began after + * the latch, each with a permanent gap. Every other producer was in flight + * when the latch was set, failed or not, and must end first (#3812). */ export function recoverSafetyRecording(db:Database,options:{trigger?:SafetyRecoveryTrigger;actor?:string}={}):SafetyRecovery { const local=safetyQueue(db),trigger=options.trigger??"owner",actor=options.actor??"host",at=Date.now(); const automatic=trigger==="automatic"; - const covered=(turnId:string|null)=>turnId!==null&&!!db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND (restricted_begin=1 OR failure IS NOT NULL)").get(turnId); - if(automatic?[...local.pending].some(p=>!local.unscopedLoss&&!covered(p.turnId)&&!(p.turnId!==null&&local.lostTurns.has(p.turnId))):(local.pending.size||local.inflight)) + const begunRestricted=(turnId:string|null)=>turnId!==null&&!!db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND restricted_begin=1").get(turnId); + if(automatic?[...local.pending].some(p=>!begunRestricted(p.turnId)):(local.pending.size||local.inflight)) throw new SafetyUnavailable("Stop all safety producers before recovery"); let cause:SafetyLatchCause|null=null,gapped=0,recovered=false; db.transaction(()=>{ - const open=db.query<{turn_id:string;restricted_begin:number;failure:string|null},[]>("SELECT turn_id,restricted_begin,failure FROM safety_collections WHERE ended=0").all(); - if(automatic?open.some(c=>!local.unscopedLoss&&!c.restricted_begin&&!c.failure&&!local.lostTurns.has(c.turn_id)):open.length) + const open=db.query<{restricted_begin:number},[]>("SELECT restricted_begin FROM safety_collections WHERE ended=0").all(); + if(automatic?open.some(c=>!c.restricted_begin):open.length) throw new SafetyUnavailable("Stop all safety producers before recovery"); const totals=meta(db); if(!totals.failed&&!local.failed&&!one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_pending").n)return; - if(totals.used_rows+totals.scope_rows>=SAFETY_LIMITS.brainRows||totals.used_bytes+totals.scope_bytes>=SAFETY_LIMITS.brainBytes)throw new SafetyCapacityExhausted("Safety capacity must be recovered first"); + if(totals.used_rows+totals.scope_rows>=SAFETY_LIMITS.brainRows||totals.used_bytes+totals.scope_bytes>=SAFETY_LIMITS.brainBytes)throw new SafetyCapacityExhausted("Safety capacity must be recovered first","brain"); const lost=local.lossCause; cause=latchCause(db)??(local.failed?{reason:"recording_failed",site:lost?.site??"retained",turnId:lost?.turnId??null,errorClass:lost?.errorClass??"SafetyUnavailable", message:lost?`${lost.message} (retained in process; its durable notice could not commit)`:"Only this process retained the loss; its durable notice could not commit.", diff --git a/packages/ui-server/src/ws/bridge-capabilities/turn-error.ts b/packages/ui-server/src/ws/bridge-capabilities/turn-error.ts index 5e32fce511..e9dca08287 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/turn-error.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/turn-error.ts @@ -31,9 +31,12 @@ export function emitTurnError(host: WsHost, turn: RunningTurn, err: unknown): vo host.sendToClients(withTurnScope({ type: "error", code: errorClass.toUpperCase(), message, failure: { errorClass, message }, ...correlation }, turn)); } else if (err instanceof SafetyRecordingUnavailable) { - // Refused before delivery (#3812): retryable, and distinct from a refusal - // by the brain, so the client can say what happened (#3810). - const errorClass = err.paused ? "safety_recording_paused" : "safety_recording_unavailable"; + // Refused before delivery (#3812), and distinct from a refusal by the + // brain, so the client can say what happened and what to do (#3810). + // Spent room is not retryable: a full chat needs a new chat, a full + // brain needs its limit raised; recovery frees neither. + const errorClass = err.full === "chat" ? "safety_recording_chat_full" : err.full === "brain" ? "safety_recording_brain_full" + : err.paused ? "safety_recording_paused" : "safety_recording_unavailable"; host.reportTurnFailed("SAFETY_RECORDING_UNAVAILABLE", turn, err.message); host.sendToClients(withTurnScope({ type: "error", code: "SAFETY_RECORDING_UNAVAILABLE", message: err.message, failure: { errorClass, message: err.message }, ...correlation }, turn)); diff --git a/packages/ui-server/tests/safety-containment.test.ts b/packages/ui-server/tests/safety-containment.test.ts index 1ddec1de5c..d9d3414edb 100644 --- a/packages/ui-server/tests/safety-containment.test.ts +++ b/packages/ui-server/tests/safety-containment.test.ts @@ -11,6 +11,8 @@ import { createSafetyCollector } from "../src/governance/safety-collector"; import { latchSafety, safetyCatalogCreated, safetyFailureCause, SafetyCapacityExhausted, safetyFailureReason, SafetyRecordingUnavailable, SafetyUnavailable } from "../src/governance/safety-store"; import { emitTurnError } from "../src/ws/bridge-capabilities/turn-error"; +import { holdSafetyRecovery } from "./helpers/hold-safety-recovery"; +import { failurePresentation, refusalReason } from "../../ui-react/src/lib/turn-failure"; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); @@ -146,7 +148,7 @@ test("a durable brain latch keeps its first cause, counts later ones and clears expect(first.since).toBeGreaterThan(0); // The worker's latch logs on its own thread; this one runs here. const before = log.lines().length; - latchSafety(f.db, null, "capacity", safetyFailureCause(new SafetyCapacityExhausted("Safety ledger capacity exhausted"), "record", null)); + latchSafety(f.db, null, "capacity", safetyFailureCause(new SafetyCapacityExhausted("Safety ledger capacity exhausted", "brain"), "record", null)); expect(f.db.query("SELECT site,turn_id,error_class,count FROM safety_latch").get(), "SAFETY_LATER_LATCH_ONLY_COUNTS") .toEqual({ site: "safetyFail", turn_id: "voyage", error_class: "TypeError", count: 2 }); const latches = log.lines().slice(before); @@ -154,7 +156,7 @@ test("a durable brain latch keeps its first cause, counts later ones and clears expect(latches[0]).toMatchObject({ body: "safety recording latched for the brain", attributes: { "safety.site": "record", "safety.reason": "capacity", "error.message": "Safety ledger capacity exhausted" } }); const status = f.writes.recordingStatus(); - expect(status, "SAFETY_STATUS_REPORTS_THE_LATCH").toMatchObject({ latched: true, reason: "capacity", cause: { site: "safetyFail", turnId: "voyage", count: 2 } }); + expect(status, "SAFETY_STATUS_REPORTS_THE_LATCH").toMatchObject({ latched: true, reason: "capacity", cause: { site: "safetyFail", turnId: "voyage", count: 2, durable: true } }); expect(status.since).toBe(first.since as number); // New turns run restricted while the brain is latched. await next(f, "siege", null); @@ -236,7 +238,7 @@ test("owner recovery clears an idle latch, refuses while a producer is open, and }); test("only a capacity check classifies a failure as capacity", () => { - expect(safetyFailureReason(new SafetyCapacityExhausted("Safety pending capacity exhausted"))).toBe("capacity"); + expect(safetyFailureReason(new SafetyCapacityExhausted("Safety pending capacity exhausted", "turn"))).toBe("capacity"); for (const error of [new Error("SQLITE_IOERR"), new TypeError("bug"), new SafetyUnavailable("Invalid bounded safety identity")]) expect(safetyFailureReason(error), "SAFETY_NON_CAPACITY_ERRORS_ARE_RECORDING_FAILED").toBe("recording_failed"); }); @@ -340,7 +342,100 @@ test("a loss with no collection is kept on its named chat, or gaps every chat wh test("a capacity cause passed through the write worker stays capacity", async () => { const f = fixture(); try { await chat(f, "voyage", "ithaca"); - await f.writes.safetyFail("voyage", new SafetyCapacityExhausted("Safety occurrence write capacity exceeded")); + await f.writes.safetyFail("voyage", new SafetyCapacityExhausted("Safety occurrence write capacity exceeded", "turn")); expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(), "SAFETY_CAPACITY_SURVIVES_THE_WORKER").toEqual({ failure: "capacity" }); } finally { await f.close(); } }); + +/** Neither the chat fact nor the brain latch can commit: only this process holds the loss. */ +function refuseLossNotices(f: F) { + f.db.exec(`CREATE TRIGGER no_chat_fact BEFORE UPDATE OF failure ON safety_collections BEGIN SELECT RAISE(ABORT,'disk I/O error'); END; + CREATE TRIGGER no_brain_fact BEFORE UPDATE OF failed ON safety_meta WHEN NEW.failed=1 BEGIN SELECT RAISE(ABORT,'disk I/O error'); END;`); +} + +for (const loss of ["retained", "durable"] as const) test(`automatic recovery waits for every producer that predates the latch, even a failed one: ${loss}`, async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); + holdSafetyRecovery(f.db); + if (loss === "retained") { + // Only this process holds the producer's loss; writes then work again. + refuseLossNotices(f); + await f.writes.safetyFail("voyage", new Error("exposure transition lost")).catch(() => {}); + f.db.exec("DROP TRIGGER no_chat_fact; DROP TRIGGER no_brain_fact"); + } else { + // Its chat holds the loss durably, and something else latched the brain. + await f.writes.safetyFail("voyage", new Error("exposure transition lost")); + latchSafety(f.db, null, "recording_failed", safetyFailureCause(new Error("disk I/O error"), "record", null)); + } + // The failed producer is still running. + expect(f.db.query("SELECT ended FROM safety_collections WHERE turn_id='voyage'").get()).toEqual({ ended: 0 }); + expect(attemptSafetyRecovery(f.db), "SAFETY_AUTOMATIC_RECOVERY_DRAINS_FAILED_PRODUCERS").toBe(false); + expect(f.writes.recordingStatus().latched, "SAFETY_UNDRAINED_RECOVERY_KEEPS_THE_LATCH").toBe(true); + // A turn begun under the latch never holds recovery back. + await next(f, "siege", null); + await f.writes.safetyEnd("voyage"); + expect(attemptSafetyRecovery(f.db), "SAFETY_AUTOMATIC_RECOVERY_RUNS_BESIDE_RESTRICTED_TURNS").toBe(true); + expect(f.writes.recordingStatus().latched).toBe(false); + expect(f.writes.safety(null, "ithaca").restriction, "SAFETY_DRAINED_RECOVERY_KEEPS_THE_GAP").toBe("restricted"); + } finally { await f.close(); } +}); + +test("status shows the cause this process holds while its loss notice cannot commit", async () => { + const f = fixture(); try { + await chat(f, "voyage", "ithaca"); + holdSafetyRecovery(f.db); + refuseLossNotices(f); + await f.writes.safetyFail("voyage", new TypeError("exposure transition lost")).catch(() => {}); + const status = f.writes.recordingStatus(); + expect(status).toMatchObject({ latched: true, retained: true }); + expect(status.cause, "SAFETY_STATUS_SHOWS_THE_RETAINED_CAUSE").toMatchObject({ errorClass: "TypeError", message: "exposure transition lost", + turnId: "voyage", count: 1, durable: false }); + expect(status.since, "SAFETY_STATUS_DATES_THE_RETAINED_CAUSE").toBe(status.cause!.since); + expect(status.since).toBeGreaterThan(0); + } finally { await f.close(); } +}); + +test("spent safety room says what to do instead of asking for a retry", async () => { + const f = fixture(); try { + const { bindingId } = await chat(f, "voyage", "ithaca"); await f.writes.safetyEnd("voyage"); + // The chat has used all 128 of its coverage epochs; nothing frees them. + f.db.query(`WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<127) + INSERT INTO safety_collections(id,turn_id,session_id,history_owner_id,generation,backend_id,started_at,ended,acknowledged,start_revision,end_revision) + SELECT 'epoch_'||x,'turn_'||x,session_id,history_owner_id,generation,'pi',0,1,acknowledged,'0','0' FROM n,safety_collections WHERE id=?`).run(bindingId); + const refuse = async (turnId: string, sessionId: string | null) => { + const refused = await f.writes.safetyBegin({ turnId, bindingId: crypto.randomUUID(), sessionId, principalId: "odysseus", backendId: "pi", at: 1 }) + .then(() => null, error => error) as SafetyRecordingUnavailable; + const frames: { code: string; failure: { errorClass: string; message: string } }[] = []; + emitTurnError({ sendToClients: (frame: never) => frames.push(frame), reportTurnFailed() {} } as never, { turnId, requestId: `request-${turnId}` } as never, refused); + return { refused, frame: frames[0]! }; + }; + for (const turnId of ["homecoming", "homecoming-again"]) { + const { refused, frame } = await refuse(turnId, "ithaca"); + expect(refused.full, "SAFETY_EPOCH_CEILING_IS_A_FULL_CHAT").toBe("chat"); + expect(frame.failure.errorClass).toBe("safety_recording_chat_full"); + expect(refusalReason(frame), "SAFETY_FULL_CHAT_SAYS_START_A_NEW_CHAT").toBe("This chat has no room left for safety records. Nothing was sent; start a new chat to continue."); + expect(failurePresentation(frame.failure as never), "SAFETY_FULL_CHAT_IS_NOT_RETRYABLE").toMatchObject({ retry: false, explanation: "Nothing was sent. Start a new chat to continue." }); + } + // A new chat still starts. + await next(f, "siege", null); + expect(f.writes.recordingAvailable("siege", null), "SAFETY_FULL_CHAT_LEAVES_NEW_CHATS").toBe(true); + await f.writes.safetyEnd("siege"); + // The brain's room for first turns not yet in a chat is spent: a new chat cannot help. + f.db.query(`WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<1024) + INSERT INTO safety_collections(id,turn_id,session_id,history_owner_id,generation,backend_id,started_at,ended,acknowledged,start_revision,end_revision) + SELECT 'unbound_'||x,'unbound_turn_'||x,NULL,NULL,'1','pi',0,1,'[]','0','0' FROM n`).run(); + const { refused, frame } = await refuse("wooden-horse", null); + expect(refused.full, "SAFETY_UNBOUND_CEILING_IS_A_FULL_BRAIN").toBe("brain"); + expect(frame.failure.errorClass).toBe("safety_recording_brain_full"); + expect(refusalReason(frame), "SAFETY_FULL_BRAIN_SAYS_RETRY_WONT_HELP").toBe("This server has no room left for safety records. Nothing was sent, and retrying won't help."); + expect(failurePresentation(frame.failure as never), "SAFETY_FULL_BRAIN_IS_NOT_RETRYABLE").toMatchObject({ retry: false, report: true }); + } finally { await f.close(); } +}); + +test("room held only by pending writes stays a retryable refusal", () => { + const refused = new SafetyRecordingUnavailable(false, new SafetyCapacityExhausted("Safety pending capacity exhausted", "turn")); + expect(refused, "SAFETY_PENDING_ROOM_IS_RETRYABLE").toMatchObject({ capacity: true, full: null }); + // Across the write worker the class arrives as a name and its own fields. + const revived = Object.assign(new Error("Safety coverage capacity exhausted"), { name: "SafetyCapacityExhausted", scope: "chat" }); + expect(new SafetyRecordingUnavailable(true, revived).full, "SAFETY_FULL_OUTRANKS_PAUSED").toBe("chat"); +}); From 8e426bfc1b30fc91acda148ed020e56f537a6bb8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 07:52:16 +0100 Subject: [PATCH 09/24] test(ui-react): a second chat stays usable beside a recording gap, in the pinned browser (#3812) The real Chat page in the pinned Chromium talks to the real app and its own safety recorder. The first chat's search result reaches the runtime and its record is refused, so that chat keeps a permanent recording gap; a second chat, started from the page's New chat, sends twice and is answered under normal policy, and the brain never latches. Co-Authored-By: Claude Opus 5.5 --- packages/ui-kit/vitest.config.ts | 3 +- .../browser/outgoing-snapshots.offline.tsx | 3 + .../tests/browser/safety-gap-command.ts | 85 +++++++++++++++++ .../tests/browser/safety-gap-scene.tsx | 18 ++++ .../tests/browser/safety-gap.layout.tsx | 26 ++++++ .../fixtures/safety-gap-browser-server.ts | 91 +++++++++++++++++++ 6 files changed, 225 insertions(+), 1 deletion(-) create mode 100644 packages/ui-react/tests/browser/safety-gap-command.ts create mode 100644 packages/ui-react/tests/browser/safety-gap-scene.tsx create mode 100644 packages/ui-react/tests/browser/safety-gap.layout.tsx create mode 100644 packages/ui-react/tests/fixtures/safety-gap-browser-server.ts diff --git a/packages/ui-kit/vitest.config.ts b/packages/ui-kit/vitest.config.ts index d23e179e11..1624a728b6 100644 --- a/packages/ui-kit/vitest.config.ts +++ b/packages/ui-kit/vitest.config.ts @@ -12,6 +12,7 @@ import { hygieneLifecycleFailures } from "../ui-react/tests/browser/hygiene-life import { hygieneContextLifecycle, hygieneLifecycle, hygieneLifecycleCleanup } from "../ui-react/tests/browser/hygiene-lifecycle-command.ts"; import { hygieneServer } from "../ui-react/tests/browser/hygiene-server-command.ts"; import { dispatchActions } from "../ui-react/tests/browser/dispatch-actions-command.ts"; +import { safetyGapChats } from "../ui-react/tests/browser/safety-gap-command.ts"; import { transcriptionHttp } from "../ui-react/tests/browser/offline/transcription-http.ts"; import path from "node:path"; import { MeasuredBrowserSequencer } from "../../scripts/browser-sequencer.ts"; @@ -172,7 +173,7 @@ export default mergeConfig( browser: { enabled: true, screenshotFailures: false, - commands: { recordingProof, rankTap, conversationServer, mermaidMedia, mermaidOutput, mermaidScreenComparison, buttonCapture, overlayMouse, dictationMotion, policyServer, storageServer, hygieneLoop, hygieneServer, hygieneLifecycle, hygieneContextLifecycle, hygieneLifecycleCleanup, hygieneLifecycleFailures, dispatchActions, sheetInput, focusCapture, formViewport, formConsumerStyles, rankFooterFonts, codeHighlightFailure, codeHighlightFailureCount, offlineScene, coldCapture, shareReview, transcriptionHttp, startRequestLog, requestLog, grantMicrophone }, + commands: { recordingProof, rankTap, conversationServer, mermaidMedia, mermaidOutput, mermaidScreenComparison, buttonCapture, overlayMouse, dictationMotion, policyServer, storageServer, hygieneLoop, hygieneServer, hygieneLifecycle, hygieneContextLifecycle, hygieneLifecycleCleanup, hygieneLifecycleFailures, dispatchActions, safetyGapChats, sheetInput, focusCapture, formViewport, formConsumerStyles, rankFooterFonts, codeHighlightFailure, codeHighlightFailureCount, offlineScene, coldCapture, shareReview, transcriptionHttp, startRequestLog, requestLog, grantMicrophone }, // The fake microphone plays the generated 10-second fixture // (#1016). Chromium reads the file at launch, so it is written // when this config loads; the fake UI grants the permission. diff --git a/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx b/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx index 3ea53bd48e..ca57cbb06e 100644 --- a/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx +++ b/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx @@ -449,6 +449,9 @@ test("a message refused because safety recording failed says so, not that the br expect(await refuse("Bind me to the mast.", { code: "SAFETY_RECORDING_UNAVAILABLE", message: "failed", failure: { errorClass: "safety_recording_unavailable", message: "failed" } }), "a one-turn recording failure is retryable") .toBe("Safety recording failed before this was sent. Nothing ran; try again."); + expect(await refuse("Ask the sirens again.", { code: "SAFETY_RECORDING_UNAVAILABLE", message: "full", + failure: { errorClass: "safety_recording_chat_full", message: "full" } }), "a full chat says what to do, not to retry") + .toBe("This chat has no room left for safety records. Nothing was sent; start a new chat to continue."); expect(await refuse("Steer for Ithaca.", { code: "BACKEND_ERROR", message: "refused" }), "other refusals keep their copy") .toBe("The brain refused this message."); }); diff --git a/packages/ui-react/tests/browser/safety-gap-command.ts b/packages/ui-react/tests/browser/safety-gap-command.ts new file mode 100644 index 0000000000..7ea2936ad9 --- /dev/null +++ b/packages/ui-react/tests/browser/safety-gap-command.ts @@ -0,0 +1,85 @@ +/// +/** + * #3812: one chat carries a permanent safety-recording gap, and a second + * chat stays usable beside it. The real Chat page in Chromium talks to the + * real app (its own WebSocket, draft routes and safety recorder) served by + * `../fixtures/safety-gap-browser-server.ts`. Server and Chromium both run + * inside the network-disabled browser container. + */ +import { spawn } from "node:child_process"; +import { resolve } from "node:path"; +import type { BrowserCommand } from "vitest/node"; + +interface Chat { restriction: string; coverage: string; gap: boolean; available: boolean } +interface State { turns: Array<{ sessionId: string; prompt: string; outcome: string }>; brainLatched: boolean; chats: Record } +/** The host's state after the gap and after the second chat, and what the page showed. */ +export interface SafetyGapChats { gapped: State; after: State; refusalCopy: boolean; composerDisabled: string | null; diagnostics: string[] } + +export const safetyGapChats: BrowserCommand<[], SafetyGapChats> = async (ctx) => { + const origin = new URL(ctx.page.url()).origin; + const child = spawn(process.env.BUN_BIN ?? "bun", + ["--preload", resolve("../../scripts/test-network-child-preload.ts"), resolve("../ui-react/tests/fixtures/safety-gap-browser-server.ts"), origin], + { cwd: resolve("../.."), env: process.env, stdio: ["ignore", "pipe", "pipe"] }); + let stderr = "", stdout = ""; + child.stderr!.on("data", (b) => { stderr += String(b); }); + const url = await new Promise((res, reject) => { + const timer = setTimeout(() => { child.kill(); reject(new Error(`fixture timeout: ${stderr}`)); }, 20_000); + child.once("exit", (code) => { clearTimeout(timer); reject(new Error(`fixture exited ${code}: ${stderr}`)); }); + child.stdout!.on("data", (b) => { + stdout += String(b); + if (stdout.includes("\n")) { clearTimeout(timer); try { res(JSON.parse(stdout.split("\n")[0]!).url); } catch (e) { reject(e); } } + }); + }); + const state = async () => await (await fetch(`${url}/fixture`)).json() as State; + // Below 1280 the Chat page draws its own New chat disc. + const context = await ctx.context.browser()!.newContext({ viewport: { width: 1024, height: 800 }, reducedMotion: "reduce" }); + // The pinned Chromium requires this origin-scoped permission for loopback sockets. + await context.grantPermissions(["local-network-access"], { origin }); + // Vitest's browser transform routes each dynamic import through its + // runner; this page is not the runner's, so the Chat page's lazy imports + // load directly. + const html = `
`; + const diagnostics: string[] = []; + context.on("page", (page) => { + page.on("pageerror", (e) => diagnostics.push(e.message)); + page.on("console", (m) => { if (m.type() === "error") diagnostics.push(m.text()); }); + }); + try { + const app = new URL(url).origin; + await context.route("**/*", async (route) => { + const target = new URL(route.request().url()); + if (target.origin !== origin && target.origin !== app) { await route.abort(); return; } + if (target.origin === origin && target.pathname === "/safety-gap") { await route.fulfill({ contentType: "text/html", body: html }); return; } + await route.continue(); + }); + const page = await context.newPage(); + await page.goto(`${origin}/safety-gap`); + const field = page.locator("[data-composer] textarea"); + const send = async (text: string, answer: string) => { + await field.waitFor({ timeout: 10_000 }); + await page.waitForFunction(() => document.querySelector("[data-composer] textarea")?.getAttribute("placeholder") !== "Connecting...", undefined, { timeout: 10_000 }); + await field.fill(text); + await page.locator('[data-composer] [aria-label^="Send"]').click(); + await page.getByText(answer, { exact: false }).first().waitFor({ timeout: 10_000 }); + }; + // The first chat's search result reaches the runtime; its record is refused. + await send("Listen for the sirens.", "The wax is in the crew's ears."); + const gapped = await state(); + // A second chat, from the page's own New chat. + await page.getByRole("button", { name: "New chat" }).click(); + await page.waitForFunction(() => !document.body.innerText.includes("The wax is in the crew's ears."), undefined, { timeout: 10_000 }); + await send("Steer for Ithaca.", "The crew rows on: Steer for Ithaca."); + await send("Row past Scylla.", "The crew rows on: Row past Scylla."); + const after = await state(); + const body = await page.locator("body").innerText(); + return { gapped, after, refusalCopy: /Safety recording|brain refused/i.test(body), + composerDisabled: await page.locator('[data-composer] [aria-label^="Send"]').getAttribute("aria-disabled"), diagnostics }; + } catch (error) { + for (const page of context.pages()) diagnostics.push((await page.locator("body").innerText()).slice(0, 1500)); + throw new Error(`${String(error)}\n${diagnostics.join("\n")}\n${stderr.slice(-2000)}`); + } finally { + await context.close(); + child.kill(); + } +}; +declare module "vitest/browser" { interface BrowserCommands { safetyGapChats: () => Promise } } diff --git a/packages/ui-react/tests/browser/safety-gap-scene.tsx b/packages/ui-react/tests/browser/safety-gap-scene.tsx new file mode 100644 index 0000000000..b069cf2fbc --- /dev/null +++ b/packages/ui-react/tests/browser/safety-gap-scene.tsx @@ -0,0 +1,18 @@ +/** #3812: the real Chat page against the real app's WebSocket and routes, split topology. */ +import { useEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { createBrainUiRoot } from "../../src/root.js"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { ChatPage } from "../../src/components/chat/chat-page.js"; +import "../../../ui-kit/dist/styles.css"; +import "../../dist/styles.css"; + +const url = (window as unknown as { __safetyGapUrl: string }).__safetyGapUrl; +const ui = createBrainUiRoot({ storage: null, config: { backendUrl: url, appName: "Odysseus’s notebook", assistantName: "Brain" } }); + +function Scene() { + useEffect(() => ui.connection.connect(), []); + return ; +} + +createRoot(document.getElementById("scene")!).render(); diff --git a/packages/ui-react/tests/browser/safety-gap.layout.tsx b/packages/ui-react/tests/browser/safety-gap.layout.tsx new file mode 100644 index 0000000000..e55e8d6f23 --- /dev/null +++ b/packages/ui-react/tests/browser/safety-gap.layout.tsx @@ -0,0 +1,26 @@ +/** + * #3812: a safety-recording failure restricts what it puts at risk, never + * more. One chat keeps a permanent recording gap, written by the real host + * when its search result's record was refused; a second chat, started from + * the real Chat page, sends, is answered and keeps sending, under normal + * policy. The brain-wide recorder never latches. + */ +import { expect, test } from "vitest"; +import { commands } from "vitest/browser"; + +test("a second chat stays usable while one chat carries a recording gap", async () => { + const r = await commands.safetyGapChats(); + const gapped = r.gapped.turns[0]!.sessionId; + expect(r.gapped.chats[gapped], "BROWSER_FIRST_CHAT_KEEPS_A_RECORDING_GAP").toEqual({ restriction: "restricted", coverage: "incomplete", gap: true, available: true }); + expect(r.gapped.brainLatched, "BROWSER_CHAT_GAP_NEVER_LATCHES_THE_BRAIN").toBe(false); + const second = r.after.turns.filter(t => t.sessionId !== gapped); + expect(second.map(t => [t.prompt, t.outcome]), "BROWSER_SECOND_CHAT_RUNS_EVERY_TURN") + .toEqual([["Steer for Ithaca.", "success"], ["Row past Scylla.", "success"]]); + expect(new Set(second.map(t => t.sessionId)).size, "BROWSER_SECOND_CHAT_IS_ONE_CHAT").toBe(1); + expect(r.after.chats[second[0]!.sessionId], "BROWSER_SECOND_CHAT_STAYS_NORMAL").toEqual({ restriction: "normal", coverage: "complete", gap: false, available: true }); + expect(r.after.chats[gapped], "BROWSER_FIRST_CHAT_GAP_IS_PERMANENT").toMatchObject({ restriction: "restricted", gap: true }); + expect(r.after.brainLatched).toBe(false); + expect(r.refusalCopy, "BROWSER_SECOND_CHAT_SHOWS_NO_REFUSAL").toBe(false); + expect(r.composerDisabled, "BROWSER_SECOND_CHAT_COMPOSER_STAYS_ENABLED").not.toBe("true"); + expect(r.diagnostics).toEqual([]); +}, 60_000); diff --git a/packages/ui-react/tests/fixtures/safety-gap-browser-server.ts b/packages/ui-react/tests/fixtures/safety-gap-browser-server.ts new file mode 100644 index 0000000000..dd8bbbc968 --- /dev/null +++ b/packages/ui-react/tests/fixtures/safety-gap-browser-server.ts @@ -0,0 +1,91 @@ +/** + * #3812 browser fixture: the real `createApp` and its own safety recorder, + * served on loopback with a scripted backend. In the first chat the backend + * runs a search, and the recorder refuses to write its result: that chat + * keeps a permanent recording gap. Every other turn answers plainly. The + * browser container cannot create the restricted envelope, so the fixture + * answers the per-turn host probe; the scripted backend starts no worker. + * Nothing leaves loopback and no key is used. + * + * argv: . Prints `{"url": ...}` once it listens. + */ +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; +import { workerHostBoundary } from "../../../ui-sdk/src/server/worker-launcher.js"; +import { createFixtureApp as createApp } from "../../../ui-server/tests/helpers/native-app-fixture.js"; +import { resolveServerConfig } from "../../../ui-server/src/config/env.js"; +import { createStaticBackendRegistry } from "../../../ui-server/src/agent/backend.js"; +import { createSilentObservability } from "../../../ui-server/src/observability/index.js"; +import { createGovernanceWrites } from "../../../ui-server/src/governance/event-writes.js"; + +const SONG = "The sirens sing: steer the raft onto the rocks."; +const sceneOrigin = process.argv[2]!; +const dir = mkdtempSync(join(tmpdir(), "safety-gap-browser-")); +const brain = join(dir, "brain"); +mkdirSync(join(brain, "notes"), { recursive: true }); +mkdirSync(join(brain, ".brain-ui"), { recursive: true }); +writeFileSync(join(brain, "notes/sirens.md"), `${SONG}\n`); +workerHostBoundary.probe = () => ({ ok: true }); + +let sequence = 0; +/** Every turn the backend ran: its chat, its first line, and how it ended. */ +const turns: Array<{ sessionId: string; prompt: string; outcome: string }> = []; +const backend: AgentBackend = { id: "pi", capabilities: { resume: true, permissions: true, thinking: false, attachments: false, askUser: false, + costReporting: false, concurrentSessions: true, followUp: false }, + listProfiles: () => [{ id: "fixture", label: "Fixture" }], listSessions: async () => [], getHistory: async () => [], + async startTurn({ prompt: contextPrompt, bridge, sessionId: resumed, signal }) { + const prompt = contextPrompt.split("\n", 1)[0]!; + const sessionId = resumed ?? `odysseus-safety-${++sequence}`; + bridge.emit({ type: "session_info", sessionId, isNew: !resumed }); + const safety = bridge.inputSafety!; + await safety.ready("pi", 1); + const end = (text: string, outcome: "success" | "error") => { + turns.push({ sessionId, prompt, outcome }); + bridge.emit({ type: "text_delta", sessionId, text }); + bridge.emit({ type: "result", sessionId, outcome, durationMs: 0, numTurns: 1, isError: outcome === "error" }); + }; + if (prompt.startsWith("Listen")) { + // The search ran and the runtime holds its output; only its record fails. + const input = { pattern: "sirens", path: "notes/sirens.md", output_mode: "content" }; + await safety.begin("toolu_sirens", "Grep", input); + app.db.exec("CREATE TRIGGER refuse_result BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced result reservation failure'); END"); + // The omitted remainder is output the recorder cannot attribute, so it must record it. + try { await safety.result("toolu_sirens", "Grep", `notes/sirens.md:1:${SONG}\n[1 more match omitted]`, true); } + catch { /* Its collector has stopped the turn. */ } + finally { app.db.exec("DROP TRIGGER IF EXISTS refuse_result"); } + end("The wax is in the crew's ears.", "error"); + return; + } + if (signal.aborted) return; + end(`The crew rows on: ${prompt}`, "success"); + } }; +const app = await createApp({ + config: resolveServerConfig({ AUTH_MODE: "none", HOST: "127.0.0.1", NODE_ENV: "test", DB_PATH: join(dir, "ui.sqlite"), BRAIN_PATH: brain, + BRAIN_UI_MODEL_DISCOVERY: "0", BRAIN_UI_PRICING_DISCOVERY: "0", ALLOWED_ORIGINS: sceneOrigin }), + observability: createSilentObservability(), + registry: createStaticBackendRegistry([backend], backend.id), +}); +// Reads only: every projection the host would admit or restrict a turn by. +const reader = createGovernanceWrites(app.db); +function state() { + const sessions = [...new Set(turns.map(t => t.sessionId))]; + return { + turns, + brainLatched: (app.db.query("SELECT failed FROM safety_meta").get() as { failed: number }).failed === 1, + chats: Object.fromEntries(sessions.map(id => { + const projection = reader.safety(null, id); + return [id, { restriction: projection.restriction, coverage: projection.coverage.state, + gap: projection.coverage.epochs.some(e => e.reason === "recording_failed"), available: reader.recordingAvailable(null, id) }]; + })), + }; +} + +const server = Bun.serve({ hostname: "127.0.0.1", port: 0, websocket: app.websocket, + async fetch(request, srv) { + const url = new URL(request.url); + if (url.pathname === "/fixture") return Response.json(state(), { headers: { "access-control-allow-origin": sceneOrigin } }); + return app.fetch(request, srv); + } }); +process.stdout.write(JSON.stringify({ url: `http://127.0.0.1:${server.port}` }) + "\n"); From e162f73fefd56eee28f5ad646bffd41c9c7e226b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 09:01:34 +0100 Subject: [PATCH 10/24] fix(ui-server): record a stopped turn's tool result, and gap every result the host cannot record (#3812) Second review of #3827 at 511e94a23. P1: result() checked the turn's liveness before its try, so a turn stopped as its result arrived skipped both the record and safetyFail(), while the installed Claude runtime replays that result on resume. A result that reaches the host is now recorded whatever happened to the turn: stopping refuses new tools, never the record of one that ran. Any failure while recording still leaves the chat a permanent gap. Audit of every exit between a tool running and its result's record, in both backends. Also fixed: - a result queued behind a failed begin() inherited its refusal; - a result for a call whose begin() failed partway recorded nothing for the unrecorded input (the call is now not admitted: gap); - the Pi host refused a stopped turn's safetyResult before recording it (now recorded, then the post-record live check refuses the worker); - a malformed or replayed Pi safetyResult left no gap (new internal inputSafety.lost); - the Pi worker skipped the report when the session's own afterToolCall failed. P2a: a latch records the safety revision it was set at (durable and in process). Automatic recovery exempts only turns begun restricted after it; one begun restricted under an earlier latch drains first. P2c: unbound room (count and both byte checks) is brain-full only when ended unbound collections alone fill it; room an open first turn or a pending write holds is a retryable refusal. Co-Authored-By: Claude Opus 5.5 --- .../3812-safety-recording-containment.md | 6 +- docs/decisions/session-safety-reviews.md | 13 +- packages/ui-backend-pi/src/tool-safety.ts | 13 +- packages/ui-backend-pi/src/worker-rpc.ts | 28 +++- packages/ui-sdk/src/server/backend.ts | 4 + .../085_safety_recording_containment.sql | 10 +- .../src/governance/safety-collector.ts | 33 +++-- .../ui-server/src/governance/safety-queue.ts | 8 +- .../ui-server/src/governance/safety-store.ts | 46 ++++-- .../tests/safety-containment.test.ts | 79 +++++++++++ .../tests/safety-result-exits.test.ts | 131 ++++++++++++++++++ .../tests/safety-result-retention.test.ts | 71 +++++++--- 12 files changed, 378 insertions(+), 64 deletions(-) create mode 100644 packages/ui-server/tests/safety-result-exits.test.ts diff --git a/.changeset/3812-safety-recording-containment.md b/.changeset/3812-safety-recording-containment.md index e0ec1f5603..3c2d83c589 100644 --- a/.changeset/3812-safety-recording-containment.md +++ b/.changeset/3812-safety-recording-containment.md @@ -6,9 +6,9 @@ A safety-recording failure now restricts only what it puts at risk, and the host recovers by itself (#3812, #3810). -- **One turn, before delivery.** A failed safety begin, or a refused record of a tool's input before the tool runs, refuses only that turn with the new `SAFETY_RECORDING_UNAVAILABLE` error. The chat and the brain stay usable. When the refusal is for spent room, it says what to do: start a new chat (`safety_recording_chat_full`), or that retrying won't help (`safety_recording_brain_full`). -- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails: the runtime may already keep it in its session. The chat keeps running under its tainted policy; other chats are untouched. -- **The brain, only when the evidence store cannot take a scoped fact.** New turns still run, restricted, each with a permanent gap written before anything is sent. The server keeps retrying and clears the latch itself once the gaps are durable and every turn that predates the latch has ended. A turn is refused only if even its restricted start cannot be written (`safety_recording_paused`). +- **One turn, before delivery.** A failed safety begin, or a refused record of a tool's input before the tool runs, refuses only that turn with the new `SAFETY_RECORDING_UNAVAILABLE` error. The chat and the brain stay usable. When the refusal is for spent room, it says what to do: start a new chat (`safety_recording_chat_full`), or that retrying won't help (`safety_recording_brain_full`). Room that running turns or pending writes still hold is a plain retryable refusal. +- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails or whose report the host refuses: the runtime may already keep it in its session. Stopping a turn while a tool runs still records that tool's result. The chat keeps running under its tainted policy; other chats are untouched. +- **The brain, only when the evidence store cannot take a scoped fact.** New turns still run, restricted, each with a permanent gap written before anything is sent. The server keeps retrying and clears the latch itself once the gaps are durable and every turn that predates the latch has ended, including one begun restricted under an earlier latch. A turn is refused only if even its restricted start cannot be written (`safety_recording_paused`). - **Boot** resolves a set latch and pending reservations automatically instead of refusing every turn. - **Diagnosable.** Each latch keeps its first cause and a count in the database, logs one structured line, and is shown to the owner as `safetyRecording` on `/api/status`, also while only the server process holds it (`cause.durable: false`). Errors are no longer all labelled `capacity`. Every recovery is recorded with who or what ran it. - **Owner fallback.** `POST /api/status/safety-recording/recover` runs the same recovery when nothing is open. diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index 1df1d6b1b5..43d62fa242 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -86,11 +86,19 @@ running under the tainted policy, not refusing. on resume), so a result that cannot be recorded is lost after delivery. A refusal for spent room says what frees it: a full chat needs a new chat (`safety_recording_chat_full`), and a full brain cannot be helped by a - retry (`safety_recording_brain_full`). + retry (`safety_recording_brain_full`). The room for first turns not yet in + a chat is full only when ended collections alone fill it; room that a + running turn or a pending write holds frees itself, so that refusal is a + plain retry. - **Lost after delivery**: the turn's own collection takes the failure and its first cause, so its chat keeps a permanent gap projected as `recording_failed` and that producer stops. Other chats are unaffected. A reservation still open when its collection ends becomes the same gap. + Between a tool running and its result's record, nothing may skip both: a + stopped turn still records the result (stopping refuses new tools, never a + record), a report the host refuses before its record (a malformed or + replayed Pi report) and a result for a call whose input record failed both + leave the gap. - **Evidence store unwritable** (the chat fact cannot commit): the brain latches through the emergency reserve, or, when even that fails, in the host process. New turns still begin, each with a permanent @@ -98,7 +106,8 @@ running under the tainted policy, not refusing. is refused only when that restricted begin itself cannot commit (`safety_recording_paused`). The host keeps retrying, backing off to once a minute, and clears the latch itself with `recoverSafetyRecording` semantics - once every producer that predates it has ended, failed or not. + once every producer that predates it has ended, failed or not; only turns + begun restricted after that latch run beside it. - **Boot** resolves a set latch and pending reservations after restart classification, gaps first. A legacy row that cannot migrate gaps its own turn. The server never boots into refusing every turn. diff --git a/packages/ui-backend-pi/src/tool-safety.ts b/packages/ui-backend-pi/src/tool-safety.ts index 7c91c32a0c..6b586f95a4 100644 --- a/packages/ui-backend-pi/src/tool-safety.ts +++ b/packages/ui-backend-pi/src/tool-safety.ts @@ -61,10 +61,13 @@ export function installPiToolSafety(agent:Agent,safety:PiToolSafety,hasUnqualifi }catch(error){stop();throw error;} }; agent.afterToolCall=async(context,signal)=>{ - try{ - const final=await after?.(context,signal); - await safety.result(context.toolCall.name,context.toolCall.id,final?.content??context.result.content); - return final; - }catch(error){stop();throw error;} + // The tool already ran: its result is reported even when the session's own + // hook failed, so the host records it or keeps its chat's gap (#3812). + let final:Awaited>>,failure:{error:unknown}|undefined; + try{final=await after?.(context,signal);}catch(error){failure={error};} + try{await safety.result(context.toolCall.name,context.toolCall.id,final?.content??context.result.content);} + catch(error){stop();throw error;} + if(failure){stop();throw failure.error;} + return final; }; } diff --git a/packages/ui-backend-pi/src/worker-rpc.ts b/packages/ui-backend-pi/src/worker-rpc.ts index 86f0e5e78a..a5d749213e 100644 --- a/packages/ui-backend-pi/src/worker-rpc.ts +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -258,7 +258,7 @@ export const PI_WORKER_RPC_HANDLERS: Readonly{ - if(Object.keys(msg.input).some(key=>!["output","segments"].includes(key))||typeof msg.input.output!=="string"||msg.input.segments!==undefined&&(!Array.isArray(msg.input.segments)||(msg.input.segments as unknown[]).some(v=>typeof v!=="string")))throw new Error("Malformed safety result"); + if(Object.keys(msg.input).some(key=>!["output","segments"].includes(key))||typeof msg.input.output!=="string"||msg.input.segments!==undefined&&(!Array.isArray(msg.input.segments)||(msg.input.segments as unknown[]).some(v=>typeof v!=="string")))throw resultLoss(new Error("Malformed safety result")); const execution=context.executed(msg); const bounded=execution.name===msg.toolName&&context.canFinalizeSafety?.(msg.toolName,msg.toolCallId)===true; await bridge.inputSafety?.result(msg.toolCallId,msg.toolName,msg.input.output,bounded,msg.input.segments as string[]|undefined); @@ -273,14 +273,32 @@ export const PI_WORKER_RPC_HANDLERS: Readonly Promise { let lastRpcId = 0; return msg => { + // A tool already ran when its result arrives, and recording it only + // restricts: a stopped turn still records it, then the post-record live + // check refuses the worker. A report refused before it reaches the + // collector leaves its chat a permanent gap instead (#3812). + const result = msg.method === "safetyResult", safety = context.turn.bridge?.inputSafety; try { - context.live(); - if (msg.id <= lastRpcId) throw new Error("Replayed pi worker RPC"); + if (!result || !safety) context.live(); + if (msg.id <= lastRpcId) throw resultLoss(new Error("Replayed pi worker RPC")); lastRpcId = msg.id; const bridge = context.turn.bridge!; const handler = Object.hasOwn(PI_WORKER_RPC_HANDLERS, msg.method) ? PI_WORKER_RPC_HANDLERS[msg.method] : undefined; if (!handler) throw new Error(`Unknown pi worker RPC method: ${String(msg.method)}`); - return handler(msg, bridge, context); - } catch (error) { return Promise.reject(error); } + const answer = handler(msg, bridge, context); + return result && safety ? answer.catch(error => keepResultLoss(safety, msg, error)) : answer; + } catch (error) { return result && safety ? keepResultLoss(safety, msg, error) : Promise.reject(error); } }; } + +/** Marks a result report refused before the collector saw it. A rejection + * from the collector itself already left its own gap. */ +const LOST = Symbol("pi safety result refused before its record"); +function resultLoss(error: Error): Error { return Object.assign(error, { [LOST]: true }); } +async function keepResultLoss(safety: NonNullable, msg: PiWorkerRpc, error: unknown): Promise { + if ((error as { [LOST]?: boolean } | null)?.[LOST]) { + // A loss notice that cannot commit is held by the host; the report is refused either way. + try { await safety.lost?.(msg.toolCallId, msg.toolName, error); } catch { /* The host retains it in process. */ } + } + throw error; +} diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index de8a6c9cfd..29cf407327 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -185,6 +185,10 @@ export interface BackendBridge { unavailable?(): Promise; begin(toolUseId: string, toolName: string, input: Readonly>): Promise; result(toolUseId: string, toolName: string, output: string, finalized: boolean, segments?: readonly string[]): Promise; + /** @internal A tool ran, but its result report was refused before `result` + * could record it: the turn's chat keeps a permanent gap. Resolves once + * that gap is durable. */ + lost?(toolUseId: string, toolName: string, cause: unknown): Promise; }; /** Validated, exact-base policy proposal; the server owns its explicit approval and write. */ proposePolicyChange?(requestId: string, input: import("../tool-contracts/policy.js").PolicyChangeInput): Promise; diff --git a/packages/ui-server/migrations/085_safety_recording_containment.sql b/packages/ui-server/migrations/085_safety_recording_containment.sql index e6ca9be702..f717716a78 100644 --- a/packages/ui-server/migrations/085_safety_recording_containment.sql +++ b/packages/ui-server/migrations/085_safety_recording_containment.sql @@ -13,11 +13,15 @@ CREATE TABLE safety_latch ( since INTEGER NOT NULL, reason TEXT NOT NULL, site TEXT NOT NULL, turn_id TEXT, error_class TEXT NOT NULL, message TEXT NOT NULL, stack TEXT, count INTEGER NOT NULL DEFAULT 1, -- Some latched loss named no chat: recovery must gap every collection. - unscoped INTEGER NOT NULL DEFAULT 0 + unscoped INTEGER NOT NULL DEFAULT 0, + -- The safety revision when this latch was set. Only a collection begun + -- restricted after it may run beside its automatic recovery; every earlier + -- producer, even one begun restricted under an earlier latch, drains first. + revision TEXT NOT NULL DEFAULT '0' ); -- A latch already set before this migration has no recorded cause. -INSERT INTO safety_latch(singleton,since,reason,site,turn_id,error_class,message,stack) - SELECT 1,0,COALESCE(reason,'recording_failed'),'unknown',NULL,'unknown','The latch predates cause recording.',NULL +INSERT INTO safety_latch(singleton,since,reason,site,turn_id,error_class,message,stack,revision) + SELECT 1,0,COALESCE(reason,'recording_failed'),'unknown',NULL,'unknown','The latch predates cause recording.',NULL,revision FROM safety_meta WHERE singleton=1 AND failed=1; -- Every recovery: who or what cleared the latch, when, and the cause it cleared. CREATE TABLE safety_recoveries ( diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index c9cb728694..87b260342d 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -9,7 +9,9 @@ import { SafetyRecordingUnavailable } from "./safety-store.js"; export function createSafetyCollector(db:Database,writes:GovernanceWrites,options:{turnId:string;bindingId:string;backendId:string; sessionId:()=>string|null;actor?:"interactive"|"voice";brainPath?:string;shellProxied:()=>boolean;signal:AbortSignal;onReady?:()=>void;stop?:(error:Error)=>void;policyHash?:string|null}):NonNullable { - const operations=new Map;id:string;occurrences:string[];done:boolean;signals:IngestionSignal[];outputHash?:string}>(); + // `admitted`: every input signal of its latest begin() is recorded. A result + // for a call whose begin() failed partway cannot be recorded faithfully. + const operations=new Map;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string}>(); const base=()=>({turnId:options.turnId,sessionId:options.sessionId(),actor:options.actor??"interactive" as const,model:null,profile:null}); const marked=(path:string)=>isMarkedUntrusted(db,path); const hash=(value:string)=>new Bun.CryptoHasher("sha256").update(value).digest("hex"); @@ -30,10 +32,13 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option throw error; }; const tails=new Map>();let queued=0; - const serial=(id:string,work:()=>Promise):Promise=>{ + const serial=(id:string,work:()=>Promise,afterFailure=false):Promise=>{ if(queued>=256)return fail(new Error("Safety collection queue capacity exceeded")); queued++; - const result=(tails.get(id)??Promise.resolve()).then(work);tails.set(id,result); + // A result runs even after its call's begin() failed: that refusal must not + // become the result's, which would skip both its record and its gap. + const prior=tails.get(id)??Promise.resolve(); + const result=(afterFailure?prior.catch(()=>{}):prior).then(work);tails.set(id,result); void result.finally(()=>{queued--;if(tails.get(id)===result)tails.delete(id);}).catch(()=>{}); return result; }; @@ -46,23 +51,27 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option const inputHash=hash(JSON.stringify(input)),previous=operations.get(toolUseId); if(previous&&(previous.tool!==tool||previous.done))throw new Error("Safety operation identity already completed or changed tool"); if(!previous&&operations.size>=2000)throw new Error("Safety tool operation capacity exceeded"); - const op=previous??{tool,inputHashes:new Set(),id:crypto.randomUUID(),occurrences:[] as string[],done:false,signals:[] as IngestionSignal[]}; + const op=previous??{tool,inputHashes:new Set(),id:crypto.randomUUID(),occurrences:[] as string[],done:false,admitted:false,signals:[] as IngestionSignal[]}; if(!op.inputHashes.has(inputHash)&&op.inputHashes.size>=16)throw new Error("Safety input revision capacity exceeded"); - op.inputHashes.add(inputHash);operations.set(toolUseId,op); + op.inputHashes.add(inputHash);op.admitted=false;operations.set(toolUseId,op); for(const signal of inputTaintSignals(tool,input,options.brainPath,marked,options.shellProxied())){ if(op.signals.some(prior=>prior.detector===signal.detector&&prior.key===signal.key))continue; const item=occurrence(options.bindingId,signal.detector,op.id,"open");item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}},{beforeDelivery:true}); op.occurrences.push(item.id);op.signals.push(signal); } + op.admitted=true; assertLive(); }catch(error){return fail(error,true);} });}, + // A result already exists when it reaches the host, and the runtime may keep + // it in its session. So nothing between the tool running and its record + // may skip both: a stopped turn still records it (stopping refuses new + // tools, never a record), and any failure leaves its chat a permanent gap. result(toolUseId,tool,output,finalized,segments){return serial(toolUseId,async()=>{ - assertLive(); try{ if(segments&&segments.length>256)throw new Error("Safety result segment capacity exceeded"); - const op=operations.get(toolUseId);if(!op||op.tool!==tool)throw new Error("Safety result has no admitted operation"); + const op=operations.get(toolUseId);if(!op||op.tool!==tool||!op.admitted)throw new Error("Safety result has no admitted operation"); const outputHash=hash(JSON.stringify([output,finalized,segments??null])); if(op.done){if(op.outputHash!==outputHash)throw new Error("Conflicting safety result delivery");return;} // Each separately delivered external result segment has its own exposure. @@ -78,8 +87,14 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option } const state=finalized&&!['Bash','bash'].includes(tool)?"finalized":"interrupted_unknown"; for(const id of op.occurrences)await writes.record({...base(),kind:"taint_exposure",dedupeKey:id,payload:{occurrenceId:id,state}}); - op.done=true;op.outputHash=outputHash;assertLive(); + op.done=true;op.outputHash=outputHash; }catch(error){return fail(error);} - });}, + },true);}, + // A result the backend could not hand over (a refused or malformed report): + // its chat keeps a permanent gap. Resolves once that gap is durable. + async lost(toolUseId,tool,cause){ + const loss=new Error(`Safety result for ${tool} (${toolUseId}) was not recorded: ${cause instanceof Error?cause.message:String(cause)}`); + try{await fail(loss);}catch(error){if(error!==loss)throw error;} + }, }; } diff --git a/packages/ui-server/src/governance/safety-queue.ts b/packages/ui-server/src/governance/safety-queue.ts index 23ad481219..c013e5c144 100644 --- a/packages/ui-server/src/governance/safety-queue.ts +++ b/packages/ui-server/src/governance/safety-queue.ts @@ -3,12 +3,14 @@ import type { Database } from "bun:sqlite"; import type { SessionTaint } from "./session-taint.js"; type PendingSafety = {turnId:string|null;sessionId:string|null;source:SessionTaint["source"];bytes:number}; const queues=new WeakMap;bytes:number;failed:boolean;inflight:number; + /** The safety revision when this process latched in memory; null when unreadable. */ + latchRevision:string|null; lostTurns:Set;unscopedLoss:boolean;listeners:Set<()=>void>;recovery:{timer:ReturnType|null;attempt:number}; /** First cause of a loss only this process holds, kept for the recovery audit. */ lossCause:{errorClass:string;message:string;site:string;turnId:string|null;at:number;count:number}|null}>(); export function safetyQueue(db:Database){ let queue=queues.get(db); - if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,lostTurns:new Set(),unscopedLoss:false,listeners:new Set(),recovery:{timer:null,attempt:0},lossCause:null};queues.set(db,queue);} + if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,latchRevision:null,lostTurns:new Set(),unscopedLoss:false,listeners:new Set(),recovery:{timer:null,attempt:0},lossCause:null};queues.set(db,queue);} return queue; } @@ -23,9 +25,11 @@ export function notifySafetyChanged(db:Database):void { * or a notice that could not commit at all (`brainWide`), restricts the brain * until automatic recovery commits conservative gaps for every affected epoch. */ export function retainSafetyLoss(db:Database,turnId:string|null,brainWide=false):void { - const queue=safetyQueue(db); + const queue=safetyQueue(db),was=queue.failed; if(turnId===null||(!queue.lostTurns.has(turnId)&&queue.lostTurns.size>=4096)){queue.unscopedLoss=true;queue.failed=true;} else queue.lostTurns.add(turnId); if(brainWide)queue.failed=true; + // Unreadable: recovery then treats every open producer as predating it. + if(queue.failed&&!was){try{queue.latchRevision=(db.query("SELECT revision FROM safety_meta WHERE singleton=1").get() as {revision:string}|null)?.revision??null;}catch{queue.latchRevision=null;}} notifySafetyChanged(db); } diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index e6042d63fd..0cc540a443 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -116,8 +116,8 @@ export function latchSafety(db:Database,turnId:string|null,reason:SafetyFailureR db.transaction(()=>{ db.query("UPDATE safety_emergency_reserve SET padding=zeroblob(0) WHERE singleton=1").run(); db.query("UPDATE safety_meta SET failed=1,reason=CASE WHEN reason='capacity' THEN reason ELSE ? END WHERE singleton=1").run(reason); - db.query(`INSERT INTO safety_latch(singleton,since,reason,site,turn_id,error_class,message,stack,unscoped) VALUES(1,?,?,?,?,?,?,?,?) - ON CONFLICT(singleton) DO UPDATE SET count=count+1,unscoped=MAX(unscoped,excluded.unscoped)`).run(cause.at,reason,cause.site,cause.turnId,cause.errorClass,cause.message,cause.stack,unscoped?1:0); + db.query(`INSERT INTO safety_latch(singleton,since,reason,site,turn_id,error_class,message,stack,unscoped,revision) VALUES(1,?,?,?,?,?,?,?,?,?) + ON CONFLICT(singleton) DO UPDATE SET count=count+1,unscoped=MAX(unscoped,excluded.unscoped)`).run(cause.at,reason,cause.site,cause.turnId,cause.errorClass,cause.message,cause.stack,unscoped?1:0,meta(db).revision); if(turnId) db.query("UPDATE safety_collections SET failure=CASE WHEN failure='capacity' THEN failure ELSE ? END,failure_cause=COALESCE(failure_cause,?) WHERE turn_id=?").run(reason,JSON.stringify(cause),turnId); if(BigInt(meta(db).revision)(db,`SELECT COUNT(*) n,COALESCE((SELECT SUM(r.reserved_bytes) FROM safety_records r + JOIN safety_collections c ON c.id=r.collection_id WHERE c.session_id IS NULL AND c.ended=1),0) bytes + FROM safety_collections WHERE session_id IS NULL AND ended=1`); + return ended.n>=SAFETY_LIMITS.unbound||ended.bytes+(ended.n+1)*2048>SAFETY_LIMITS.unboundBytes?"brain":"turn"; +} function capacity(db:Database,c:Collection,rows:number,bytes:number):void { const all=meta(db); const {scope,args}=safetyScope(db,c.turn_id,c.session_id); @@ -176,7 +186,7 @@ function capacity(db:Database,c:Collection,rows:number,bytes:number):void { if(c.session_id===null){ const unbound=one<{bytes:number}>(db,`SELECT COALESCE(SUM(r.reserved_bytes),0) bytes FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.session_id IS NULL`); - if(unbound.bytes+pending.bytes+bytes+one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL").n*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted","brain"); + if(unbound.bytes+pending.bytes+bytes+one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL").n*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted",unboundScope(db)); } } /** Must commit before any first-turn bytes or tool execution. Callbacks cannot create a session. */ @@ -207,11 +217,11 @@ export function beginSafetyCollection(db:Database,input:SafetyCollectionInput):s assertLive(db,[["dialogue_owner",owner]]); if(session?.principal_id&&session.principal_id!==input.principalId)throw new SafetyUnavailable("Safety principal mismatch"); const n=one<{n:number}>(db, input.sessionId?"SELECT COUNT(*) n FROM safety_collections WHERE session_id=?":"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL",...(input.sessionId?[input.sessionId]:[])); - if(n.n>=(input.sessionId?SAFETY_LIMITS.epochs:SAFETY_LIMITS.unbound))throw new SafetyCapacityExhausted("Safety coverage capacity exhausted",input.sessionId?"chat":"brain"); + if(n.n>=(input.sessionId?SAFETY_LIMITS.epochs:SAFETY_LIMITS.unbound))throw new SafetyCapacityExhausted("Safety coverage capacity exhausted",input.sessionId?"chat":unboundScope(db)); if(input.sessionId===null){ const unbound=one<{bytes:number}>(db,`SELECT COALESCE(SUM(r.reserved_bytes),0) bytes FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.session_id IS NULL`); const pending=one<{bytes:number}>(db,`SELECT COALESCE(SUM(p.reserved_bytes),0) bytes FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE c.session_id IS NULL`); - if(unbound.bytes+pending.bytes+(n.n+1)*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted","brain"); + if(unbound.bytes+pending.bytes+(n.n+1)*2048>SAFETY_LIMITS.unboundBytes)throw new SafetyCapacityExhausted("Safety unbound byte capacity exhausted",unboundScope(db)); } const ledger=meta(db),pending=one<{rows:number;bytes:number}>(db,"SELECT COALESCE(SUM(rows),0) rows,COALESCE(SUM(reserved_bytes),0) bytes FROM safety_pending"); if(ledger.used_rows+ledger.scope_rows+pending.rows+1>SAFETY_LIMITS.brainRows||ledger.used_bytes+ledger.scope_bytes+pending.bytes+2048>SAFETY_LIMITS.brainBytes) @@ -546,20 +556,30 @@ export function safetyRecordingStatus(db:Database):SafetyRecordingStatus { * gap, so its chat stays restricted until reviewed. * * `owner` and `boot` recovery require every producer to have stopped. - * `automatic` recovery runs beside turns begun restricted: they began after - * the latch, each with a permanent gap. Every other producer was in flight - * when the latch was set, failed or not, and must end first (#3812). + * `automatic` recovery runs beside turns begun restricted after the latch it + * clears, each with a permanent gap. Every other producer was in flight when + * that latch was set, failed or not, or begun restricted under an earlier + * latch, and must end first (#3812). */ export function recoverSafetyRecording(db:Database,options:{trigger?:SafetyRecoveryTrigger;actor?:string}={}):SafetyRecovery { const local=safetyQueue(db),trigger=options.trigger??"owner",actor=options.actor??"host",at=Date.now(); const automatic=trigger==="automatic"; - const begunRestricted=(turnId:string|null)=>turnId!==null&&!!db.query("SELECT 1 FROM safety_collections WHERE turn_id=? AND restricted_begin=1").get(turnId); - if(automatic?[...local.pending].some(p=>!begunRestricted(p.turnId)):(local.pending.size||local.inflight)) + // The earliest latch still set, durable or in process. A producer begun + // restricted under an earlier, recovered latch predates this one. + const since=()=>{ + const durable=one<{revision:string}|null>(db,"SELECT revision FROM safety_latch WHERE singleton=1")?.revision; + const marks=[durable,local.failed?local.latchRevision??MAX_REVISION.toString():undefined].filter((r):r is string=>r!==undefined).map(r=>BigInt(r)); + return marks.length?marks.reduce((a,b)=>a!!c?.restricted_begin&&(latch===null||BigInt(c.start_revision)>latch); + const collectionOf=(turnId:string|null)=>turnId===null?null:one<{restricted_begin:number;start_revision:string}|null>(db,"SELECT restricted_begin,start_revision FROM safety_collections WHERE turn_id=?",turnId); + if(automatic?(()=>{const latch=since();return [...local.pending].some(p=>!begunRestricted(collectionOf(p.turnId),latch));})():(local.pending.size||local.inflight)) throw new SafetyUnavailable("Stop all safety producers before recovery"); let cause:SafetyLatchCause|null=null,gapped=0,recovered=false; db.transaction(()=>{ - const open=db.query<{restricted_begin:number},[]>("SELECT restricted_begin FROM safety_collections WHERE ended=0").all(); - if(automatic?open.some(c=>!c.restricted_begin):open.length) + const open=db.query<{restricted_begin:number;start_revision:string},[]>("SELECT restricted_begin,start_revision FROM safety_collections WHERE ended=0").all(); + const latch=since(); + if(automatic?open.some(c=>!begunRestricted(c,latch)):open.length) throw new SafetyUnavailable("Stop all safety producers before recovery"); const totals=meta(db); if(!totals.failed&&!local.failed&&!one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_pending").n)return; @@ -586,7 +606,7 @@ export function recoverSafetyRecording(db:Database,options:{trigger?:SafetyRecov advance(db);recovered=true; }).immediate(); if(recovered){ - local.failed=false;local.lostTurns.clear();local.unscopedLoss=false;local.lossCause=null; + local.failed=false;local.latchRevision=null;local.lostTurns.clear();local.unscopedLoss=false;local.lossCause=null; const c=cause as SafetyLatchCause|null; logSafetyRecording("safety recording recovered for the brain",{"safety.scope":"brain","safety.trigger":trigger,"safety.actor":actor,"safety.gapped":gapped, "safety.reason":c?.reason??null,"safety.site":c?.site??null,"error.class":c?.errorClass??null,"error.message":c?.message??null}); diff --git a/packages/ui-server/tests/safety-containment.test.ts b/packages/ui-server/tests/safety-containment.test.ts index d9d3414edb..caf92bc3ef 100644 --- a/packages/ui-server/tests/safety-containment.test.ts +++ b/packages/ui-server/tests/safety-containment.test.ts @@ -380,6 +380,35 @@ for (const loss of ["retained", "durable"] as const) test(`automatic recovery wa } finally { await f.close(); } }); +for (const loss of ["retained", "durable"] as const) test(`a turn begun restricted under an earlier latch drains before a later latch clears: ${loss}`, async () => { + const f = fixture(); try { + holdSafetyRecovery(f.db); + latchSafety(f.db, null, "recording_failed", safetyFailureCause(new Error("the first storm"), "record", null)); + // Begun restricted under the first latch, and still sailing when it clears. + await next(f, "still-sailing", null); + expect(attemptSafetyRecovery(f.db), "SAFETY_LATCH_CLEARS_BESIDE_ITS_OWN_RESTRICTED_TURN").toBe(true); + expect(f.writes.recordingStatus().latched).toBe(false); + // A second latch while that turn is still open: it predates this one. + if (loss === "retained") { + refuseLossNotices(f); + await f.writes.safetyFail(null as never, new Error("the second storm")).catch(() => {}); + f.db.exec("DROP TRIGGER no_chat_fact; DROP TRIGGER no_brain_fact"); + } else latchSafety(f.db, null, "recording_failed", safetyFailureCause(new Error("the second storm"), "record", null)); + expect(f.writes.recordingStatus().latched).toBe(true); + expect(f.db.query("SELECT ended FROM safety_collections WHERE turn_id='still-sailing'").get()).toEqual({ ended: 0 }); + expect(attemptSafetyRecovery(f.db), "SAFETY_LATER_LATCH_DRAINS_AN_EARLIER_RESTRICTED_TURN").toBe(false); + expect(f.writes.recordingStatus().latched, "SAFETY_UNDRAINED_LATER_LATCH_STAYS_SET").toBe(true); + // A turn begun under the second latch never holds it back. + await next(f, "new-voyage", null); + await f.writes.safetyEnd("still-sailing"); + expect(attemptSafetyRecovery(f.db), "SAFETY_LATER_LATCH_CLEARS_BESIDE_ITS_OWN_RESTRICTED_TURN").toBe(true); + expect(f.writes.recordingStatus().latched).toBe(false); + // Neither restricted turn's gap is cleared. + expect(f.db.query("SELECT turn_id,gap FROM safety_collections WHERE turn_id IN ('still-sailing','new-voyage') ORDER BY turn_id").all()) + .toEqual([{ turn_id: "new-voyage", gap: "recording_failed" }, { turn_id: "still-sailing", gap: "recording_failed" }]); + } finally { await f.close(); } +}); + test("status shows the cause this process holds while its loss notice cannot commit", async () => { const f = fixture(); try { await chat(f, "voyage", "ithaca"); @@ -432,6 +461,56 @@ test("spent safety room says what to do instead of asking for a retry", async () } finally { await f.close(); } }); +test("room for turns not yet in a chat is spent for good only when nothing can free it", async () => { + const f = fixture(); try { + holdSafetyRecovery(f.db); + // One first turn is still running, not yet in its chat. + await next(f, "landfall", null); + const fill = (from: number, to: number) => f.db.query(`WITH RECURSIVE n(x) AS (VALUES(${from}) UNION ALL SELECT x+1 FROM n WHERE x<${to}) + INSERT INTO safety_collections(id,turn_id,session_id,history_owner_id,generation,backend_id,started_at,ended,acknowledged,start_revision,end_revision) + SELECT 'unbound_'||x,'unbound_turn_'||x,NULL,NULL,'1','pi',0,1,'[]','0','0' FROM n`).run(); + const begin = (turnId: string) => f.writes.safetyBegin({ turnId, bindingId: crypto.randomUUID(), sessionId: null, principalId: "odysseus", backendId: "pi", at: 1 }) + .then(() => null, error => error as SafetyRecordingUnavailable); + // Ended unbound collections plus the running one fill the pool. + fill(1, 1023); + const waiting = await begin("waiting"); + expect(waiting, "SAFETY_UNBOUND_CEILING_REFUSES").toBeInstanceOf(SafetyRecordingUnavailable); + expect(waiting, "SAFETY_UNBOUND_ROOM_A_RUNNING_TURN_FREES_IS_RETRYABLE").toMatchObject({ capacity: true, full: null }); + // That turn joins its chat; the same retry now starts, with no limit raised. + f.db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + safetyCatalogCreated(f.db, "ithaca", "odysseus", "landfall"); await f.writes.bind("landfall", "ithaca"); + expect(await begin("waiting"), "SAFETY_UNBOUND_RETRY_STARTS_ONCE_ROOM_FREES").toBeNull(); + // Once only ended unbound collections remain, retrying can never help. + await f.writes.safetyEnd("waiting"); await f.writes.safetyEnd("landfall"); + fill(1024, 1025); + expect(await begin("wooden-horse"), "SAFETY_UNBOUND_ROOM_NOTHING_FREES_IS_A_FULL_BRAIN").toMatchObject({ capacity: true, full: "brain" }); + } finally { await f.close(); } +}); + +test("unbound byte room a running first turn holds is retryable; ballast that ended is not", async () => { + const f = fixture(); try { + holdSafetyRecovery(f.db); + await next(f, "landfall", null); + const unbound = (turnId: string) => (f.db.query("SELECT id FROM safety_collections WHERE turn_id=?").get(turnId) as { id: string }).id; + const ballast = (id: string, collection: string, bytes: number) => f.db.query(`INSERT INTO safety_records(id,collection_id,sequence,observed_at,kind,occurrence_id, + source,detector,state,payload,bytes,reserved_rows,reserved_bytes,detail_pruned) VALUES(?,?,'ballast_'||?,0,'occurrence',?,NULL,NULL,'finalized','{}',2,0,?,0)`).run(id, collection, id, id, bytes); + f.db.query(`INSERT INTO safety_collections(id,turn_id,session_id,history_owner_id,generation,backend_id,started_at,ended,acknowledged,start_revision,end_revision) + VALUES('hold','hold_turn',NULL,NULL,'1','pi',0,1,'[]','0','0')`).run(); + // The running first turn's own records fill the unbound byte room. + ballast("cargo", unbound("landfall"), 4194304); ballast("hold_cargo", "hold", 4190000); + const begin = (turnId: string) => f.writes.safetyBegin({ turnId, bindingId: crypto.randomUUID(), sessionId: null, principalId: "odysseus", backendId: "pi", at: 1 }) + .then(() => null, error => error as SafetyRecordingUnavailable); + expect(await begin("waiting"), "SAFETY_UNBOUND_BYTES_A_RUNNING_TURN_HOLDS_ARE_RETRYABLE").toMatchObject({ capacity: true, full: null }); + f.db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + safetyCatalogCreated(f.db, "ithaca", "odysseus", "landfall"); await f.writes.bind("landfall", "ithaca"); + expect(await begin("waiting"), "SAFETY_UNBOUND_BYTE_RETRY_STARTS_ONCE_ROOM_FREES").toBeNull(); + // Ended ballast alone leaves no room: retrying can never help. + await f.writes.safetyEnd("waiting"); + ballast("more_cargo", "hold", 8388608); + expect(await begin("wooden-horse"), "SAFETY_ENDED_UNBOUND_BYTES_ARE_A_FULL_BRAIN").toMatchObject({ capacity: true, full: "brain" }); + } finally { await f.close(); } +}); + test("room held only by pending writes stays a retryable refusal", () => { const refused = new SafetyRecordingUnavailable(false, new SafetyCapacityExhausted("Safety pending capacity exhausted", "turn")); expect(refused, "SAFETY_PENDING_ROOM_IS_RETRYABLE").toMatchObject({ capacity: true, full: null }); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts new file mode 100644 index 0000000000..806b5003b0 --- /dev/null +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -0,0 +1,131 @@ +/** Every exit between a tool running and its result's record either records + * the result or leaves its chat a permanent gap, in both backends (#3812). + * The installed Claude runtime's replay of a stopped turn's result is proved + * in `safety-result-retention.test.ts`; these drive the remaining exits + * against the real host ledger. Keyless and offline. */ +import { afterEach, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Agent } from "@earendil-works/pi-agent-core"; +import { createUiDb } from "../src/db/client"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createGovernanceWrites } from "../src/governance/event-writes"; +import { createSafetyCollector } from "../src/governance/safety-collector"; +import { safetyCatalogCreated } from "../src/governance/safety-store"; +import { createPiWorkerRpcDispatcher, type PiWorkerRpc, type PiWorkerRpcContext } from "../../ui-backend-pi/src/worker-rpc"; +import { installPiToolSafety } from "../../ui-backend-pi/src/tool-safety"; +import { holdSafetyRecovery } from "./helpers/hold-safety-recovery"; + +/** A search that names a workspace note: only its result's record carries the taint. */ +const SEARCH = "workspaces/voyage/raft.md:1: Sail past the sirens."; + +/** Settles `work` on the normal event loop: a pending `expect().rejects` waits + * synchronously and never sees the write worker's reply. */ +const refusal = (work: Promise) => work.then(() => null, (error: unknown) => error as Error); + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); + +async function voyage() { + const root = mkdtempSync(join(tmpdir(), "odysseus-safety-exits-")); roots.push(root); + const brain = join(root, "brain"); mkdirSync(join(brain, "workspaces/voyage"), { recursive: true }); + writeFileSync(join(brain, "workspaces/voyage/raft.md"), "Sail past the sirens.\n"); + const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); + holdSafetyRecovery(db); + const bindingId = crypto.randomUUID(), controller = new AbortController(); + await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: "odysseus", backendId: "pi", at: 0 }); + db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + safetyCatalogCreated(db, "ithaca", "odysseus", "voyage"); await writes.bind("voyage", "ithaca"); + const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, backendId: "pi", sessionId: () => "ithaca", brainPath: brain, + shellProxied: () => false, signal: controller.signal, stop: error => controller.abort(error) }); + await collector.ready("pi", 1); + return { db, writes, collector, controller, + failure: () => (db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get() as { failure: string | null }).failure, + recorded: () => db.query(`SELECT r.detector FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id + WHERE c.turn_id='voyage' AND r.kind='occurrence'`).all(), + chat: () => writes.safety(null, "ithaca"), + async close() { await writer.close(); db.close(); } }; +} +type Voyage = Awaited>; + +/** The host side of a Pi worker whose turn has stopped. */ +function dispatcher(f: Voyage) { + return createPiWorkerRpcDispatcher({ turn: { bridge: { inputSafety: f.collector } }, + live() { if (f.controller.signal.aborted) throw new Error("Pi worker RPC refused: turn is inactive, cancelled or revoked."); }, + executed: (msg: PiWorkerRpc) => ({ name: msg.toolName, host: false, lock: false, phases: new Set() }), + canFinalizeSafety: () => false } as unknown as PiWorkerRpcContext); +} +const report = (id: number, toolCallId: string, input: Record): PiWorkerRpc => + ({ type: "rpc", id, method: "safetyResult", toolName: "grep", toolCallId, input }) as PiWorkerRpc; + +test("a result reaching a turn that stopped and ended leaves its chat a permanent gap", async () => { + const f = await voyage(); try { + await f.collector.begin("toolu_raft", "Grep", { pattern: "sirens" }); + // Odysseus stops the turn; it ends before the runtime reports the search. + f.controller.abort(new Error("Odysseus stopped the turn")); + await f.writes.safetyEnd("voyage"); + expect(await refusal(f.collector.result("toolu_raft", "Grep", SEARCH, true)), "SAFETY_LATE_RESULT_IS_REFUSED").toBeInstanceOf(Error); + expect(f.failure(), "SAFETY_LATE_RESULT_IS_A_DURABLE_GAP").toBe("recording_failed"); + expect(f.chat().restriction, "SAFETY_LATE_RESULT_RESTRICTS_ITS_CHAT").toBe("restricted"); + expect(f.chat().coverage.state, "SAFETY_LATE_RESULT_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + } finally { await f.close(); } +}); + +for (const timing of ["after", "queued"] as const) test(`a result whose call was refused before delivery is never let through unrecorded: ${timing}`, async () => { + const f = await voyage(); try { + // The web input's record is refused before the tool runs: that refusal alone leaves no gap. + f.db.exec("CREATE TRIGGER refuse_input BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced input reservation failure'); END"); + const begun = refusal(f.collector.begin("toolu_aeolus", "WebFetch", { url: "https://example.com/aeolus" })); + // A runtime that ran the call anyway reports its result, at once or later: + // it cannot be recorded against an input that never was. + const reported = timing === "queued" ? refusal(f.collector.result("toolu_aeolus", "WebFetch", "The bag of winds is open.", true)) : undefined; + expect(await begun).toBeInstanceOf(Error); + f.db.exec("DROP TRIGGER refuse_input"); + if (timing === "after") expect(f.failure(), "SAFETY_REFUSED_INPUT_LEAVES_NO_GAP").toBeNull(); + const result = await (reported ?? refusal(f.collector.result("toolu_aeolus", "WebFetch", "The bag of winds is open.", true))); + expect(f.failure(), "SAFETY_RESULT_AFTER_REFUSED_BEGIN_IS_A_GAP").toBe("recording_failed"); + expect(result?.message).toContain("no admitted operation"); + expect(f.chat().coverage.state).toBe("incomplete"); + } finally { await f.close(); } +}); + +test("a Pi result reaching a stopped turn is still recorded", async () => { + const f = await voyage(); try { + await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + f.controller.abort(new Error("Odysseus stopped the turn")); + // The worker is refused once the result is recorded, so it stops. + expect((await refusal(dispatcher(f)(report(1, "call_raft", { output: SEARCH, segments: [SEARCH] }))))?.message).toContain("inactive, cancelled or revoked"); + expect(f.recorded(), "SAFETY_PI_STOPPED_RESULT_IS_RECORDED").toEqual([{ detector: "tool_search_output" }]); + expect(f.chat().restriction, "SAFETY_PI_STOPPED_RESULT_RESTRICTS_ITS_CHAT").toBe("restricted"); + } finally { await f.close(); } +}); + +for (const kind of ["malformed", "replayed"] as const) test(`a Pi result report refused before its record leaves its chat a permanent gap: ${kind}`, async () => { + const f = await voyage(); try { + await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + const dispatch = dispatcher(f); + if (kind === "malformed") expect((await refusal(dispatch(report(1, "call_raft", { output: 7 }))))?.message).toBe("Malformed safety result"); + else { + await f.collector.begin("call_raft_again", "grep", { pattern: "rocks" }); + expect(await dispatch(report(2, "call_raft_again", { output: "" }))).toEqual({ ok: true }); + expect((await refusal(dispatch(report(2, "call_raft", { output: SEARCH }))))?.message).toBe("Replayed pi worker RPC"); + } + expect(f.failure(), "SAFETY_PI_REFUSED_REPORT_IS_A_DURABLE_GAP").toBe("recording_failed"); + expect(f.chat().coverage.state, "SAFETY_PI_REFUSED_REPORT_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + } finally { await f.close(); } +}); + +test("a Pi result is still reported when the session's own after-hook fails", async () => { + const f = await voyage(); try { + await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + let stopped = 0; + const agent = { afterToolCall: async () => { throw new Error("the session's after-hook failed"); }, abort() {} } as unknown as Agent; + installPiToolSafety(agent, { permission: async () => ({ behavior: "allow" }), stop: () => { stopped++; }, + result: (name, id, content) => f.collector.result(id, name, content.filter(p => p.type === "text").map(p => (p as { text: string }).text).join("\n"), true) }, () => false); + expect((await refusal(agent.afterToolCall!({ toolCall: { name: "grep", id: "call_raft" }, result: { content: [{ type: "text", text: SEARCH }] } } as never, undefined)))?.message) + .toBe("the session's after-hook failed"); + expect(f.recorded(), "SAFETY_PI_RESULT_SURVIVES_A_FAILED_AFTER_HOOK").toEqual([{ detector: "tool_search_output" }]); + expect(stopped, "SAFETY_PI_FAILED_AFTER_HOOK_STOPS_THE_WORKER").toBe(1); + } finally { await f.close(); } +}); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index c57d4bb9e3..3e77cb7bc5 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -1,7 +1,9 @@ -/** A tool result whose safety record cannot be written has already reached the - * runtime's own session: the installed Claude runtime replays it on resume. So - * its chat must keep a permanent gap, never look complete (#3812). Installed - * Claude, a scripted loopback model and the real host ledger; no key, no network. */ +/** A tool result that reaches the host already exists in the runtime's own + * session: the installed Claude runtime replays it on resume. So its record + * must be written whatever happened to the turn, and a record that cannot be + * written leaves its chat a permanent gap; the chat never looks clean + * (#3812). Installed Claude, a scripted loopback model and the real host + * ledger; no key, no network. */ import {expect,test} from "bun:test"; import {mkdirSync,mkdtempSync,rmSync,writeFileSync} from "node:fs"; import {join} from "node:path"; @@ -19,7 +21,9 @@ import {holdSafetyRecovery} from "./helpers/hold-safety-recovery"; const SONG="The sirens sing: steer the raft onto the rocks."; -test("a result refused by the recorder is replayed on resume, so its chat keeps a permanent gap",async()=>{ +/** `refused`: the result's reservation fails. `cancelled`: the turn is + * stopped after the tool ran, just before its result is recorded. */ +async function voyageHome(interruption:"refused"|"cancelled",check:(f:{db:ReturnType;writes:ReturnType})=>void){ const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); // A note: reading it records nothing before the tool runs, so only the // search output's own record stands between it and a complete chat. @@ -37,7 +41,7 @@ test("a result refused by the recorder is replayed on resume, so its chat keeps const first=turn===0&&requests.filter(r=>r.turn===0).length===1; return nativeModelReply(first?{name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}}:undefined); }}); - async function voyage(turnId:string,sessionId:string|null,refuseResult:boolean,resume?:string){ + async function voyage(turnId:string,sessionId:string|null,interrupt:boolean,resume?:string){ const controller=new AbortController(),bindingId=crypto.randomUUID(); await writes.safetyBegin({turnId,bindingId,sessionId,principalId:"odysseus",backendId:"claude",at:turn}); if(!sessionId){ @@ -48,10 +52,15 @@ test("a result refused by the recorder is replayed on resume, so its chat keeps await collector.ready("claude",1); const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:"allow"}),inputSafety:collector}},allowedTools:["Grep"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); let results=0; - if(refuseResult){ - // The Grep result exists and the runtime holds it; only its record fails. + if(interrupt){ + // The Grep result exists and the runtime holds it; only its record is at risk. const group=wiring.hooks!.PostToolUse!.find(group=>!group.matcher)!,record=group.hooks[0]!; - group.hooks=[async(...args)=>{results++;db.exec("CREATE TRIGGER refuse_result BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced result reservation failure'); END");return record(...args);}]; + group.hooks=[async(...args)=>{ + results++; + if(interruption==="refused")db.exec("CREATE TRIGGER refuse_result BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced result reservation failure'); END"); + else controller.abort(new Error("Odysseus stopped the turn as the result arrived")); + return record(...args); + }]; } const timer=setTimeout(()=>controller.abort(),20000); try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:["Grep"],...wiring,abortController:controller, @@ -59,7 +68,7 @@ test("a result refused by the recorder is replayed on resume, so its chat keeps env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),PATH:process.env.PATH??"/usr/bin:/bin",ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; if("session_id" in message&&typeof message.session_id==="string")runtimeSession=message.session_id; - }}catch{/* The refused turn is stopped by its collector. */} + }}catch{/* The interrupted turn is stopped. */} finally{clearTimeout(timer);db.exec("DROP TRIGGER IF EXISTS refuse_result");await writes.safetyEnd(turnId);} return {results,aborted:controller.signal.aborted}; } @@ -67,23 +76,41 @@ test("a result refused by the recorder is replayed on resume, so its chat keeps const first=await voyage("voyage",null,true); expect(version,"SAFETY_ACTUAL_INSTALLED_RUNTIME").toBe(MEASURED_RUNTIME.claudeCode); expect(first.results,"SAFETY_ACTUAL_RESULT_HOOK_EXECUTED").toBe(1); - expect(first.aborted,"SAFETY_REFUSED_RESULT_STOPS_ITS_TURN").toBe(true); + expect(first.aborted,"SAFETY_INTERRUPTED_RESULT_STOPS_ITS_TURN").toBe(true); expect(runtimeSession,"SAFETY_RUNTIME_SESSION_TO_RESUME").toBeDefined(); turn=1; await voyage("homeward","ithaca",false,runtimeSession); const resumed=requests.filter(r=>r.turn===1); expect(resumed.length,"SAFETY_ACTUAL_NATIVE_RESUME").toBeGreaterThan(0); - // The premise: refusing the record did not keep the result out of the model's context. - expect(resumed.some(r=>r.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_REFUSED_RESULT").toBe(true); - const chat=writes.safety("homeward","ithaca"); - expect(chat.restriction,"SAFETY_REFUSED_RESULT_RESTRICTS_ITS_CHAT").toBe("restricted"); - expect(chat.coverage.state,"SAFETY_REFUSED_RESULT_NEVER_LOOKS_COMPLETE").toBe("incomplete"); - expect(chat.coverage.epochs.find(e=>e.reason==="recording_failed"),"SAFETY_REFUSED_RESULT_IS_A_RECORDING_GAP").toBeDefined(); - expect(db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_REFUSED_RESULT_GAP_IS_DURABLE").toEqual({failure:"recording_failed"}); + // The premise: interrupting the record did not keep the result out of the model's context. + expect(resumed.some(r=>r.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT").toBe(true); + check({db,writes}); // Contained to its chat: the brain-wide recorder is untouched, and a - // recovery has nothing to clear, so the gap stays. - expect(db.query("SELECT failed FROM safety_meta").get(),"SAFETY_REFUSED_RESULT_NEVER_LATCHES_THE_BRAIN").toEqual({failed:0}); + // recovery has nothing to clear, so the chat stays restricted. + expect(db.query("SELECT failed FROM safety_meta").get(),"SAFETY_INTERRUPTED_RESULT_NEVER_LATCHES_THE_BRAIN").toEqual({failed:0}); recoverSafetyRecording(db,{trigger:"owner",actor:"penelope"}); - expect(writes.safety(null,"ithaca").restriction,"SAFETY_REFUSED_RESULT_GAP_SURVIVES_RECOVERY").toBe("restricted"); + expect(writes.safety(null,"ithaca").restriction,"SAFETY_INTERRUPTED_RESULT_SURVIVES_RECOVERY").toBe("restricted"); }finally{origin.stop(true);await writer.close();db.close();rmSync(root,{recursive:true,force:true});} -},60000); +} + +test("a result refused by the recorder is replayed on resume, so its chat keeps a permanent gap",()=>voyageHome("refused",({db,writes})=>{ + const chat=writes.safety("homeward","ithaca"); + expect(chat.restriction,"SAFETY_REFUSED_RESULT_RESTRICTS_ITS_CHAT").toBe("restricted"); + expect(chat.coverage.state,"SAFETY_REFUSED_RESULT_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + expect(chat.coverage.epochs.find(e=>e.reason==="recording_failed"),"SAFETY_REFUSED_RESULT_IS_A_RECORDING_GAP").toBeDefined(); + expect(db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_REFUSED_RESULT_GAP_IS_DURABLE").toEqual({failure:"recording_failed"}); +}),60000); + +test("a turn stopped as its result arrives still records the result the runtime replays",()=>voyageHome("cancelled",({db,writes})=>{ + // Stopping a turn stops new tools, never the record of one that already ran. + const recorded=db.query(`SELECT r.detector FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id + WHERE c.turn_id='voyage' AND r.kind='occurrence'`).all(); + expect(recorded,"SAFETY_CANCELLED_RESULT_IS_RECORDED").toEqual([{detector:"tool_search_output"}]); + const chat=writes.safety("homeward","ithaca"); + expect(chat.restriction,"SAFETY_CANCELLED_RESULT_RESTRICTS_ITS_CHAT").toBe("restricted"); + expect(chat.unresolvedCount,"SAFETY_CANCELLED_RESULT_IS_UNRESOLVED").toBe(1); + expect(chat.reasons,"SAFETY_CANCELLED_RESULT_AWAITS_REVIEW").toContain("unresolved"); + // Recorded, so reviewable: the stop leaves no permanent gap of its own. + expect(db.query("SELECT failure,gap FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_CANCELLED_RECORDED_RESULT_IS_NO_GAP").toEqual({failure:null,gap:null}); + expect(chat.coverage.state,"SAFETY_CANCELLED_RECORDED_RESULT_KEEPS_COVERAGE").toBe("complete"); +}),60000); From 688e03999c75587e04742c79ffd0c073a8fa3080 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 10:07:32 +0100 Subject: [PATCH 11/24] fix(ui-server): gap every admitted tool call whose result is never recorded (#3812) A turn stopped while a tool runs reaches neither Claude result hook, yet the runtime keeps the call in its session and may replay its output on resume. The collector only gapped a chat when a delivered hook failed, so a Grep stopped mid-run left its chat normal and complete. Every call `begin()` admits is now an obligation, recorded before the tool runs (`safety_obligations`, migration 085). It is discharged only when its result is durably recorded, or when the backend refuses the call, which proves it never ran: a rejected `begin()`, a Claude PreToolUse or `canUseTool` deny, or a Pi permission answer other than allow. A collection that ends owing one, however it ended, and an obligation still open at boot, give the chat a permanent `recording_failed` gap naming the call. Nothing depends on the runtime delivering a hook. A fully observed result of a stopped turn is still recorded as an occurrence, with no gap. A refused call stays refused, so a parallel hook cannot reopen it. Co-Authored-By: Claude Opus 5.5 --- .../3812-safety-recording-containment.md | 2 +- .../decisions/claude-2.1.287-compatibility.md | 2 +- docs/decisions/session-safety-reviews.md | 9 +- .../ui-backend-claude/src/permission-hooks.ts | 19 +++- .../tests/permission-wiring-units.test.ts | 36 +++++++ packages/ui-backend-pi/src/permission-gate.ts | 10 +- packages/ui-backend-pi/src/worker-rpc.ts | 10 +- .../tests/tools-permission.test.ts | 12 +++ .../ui-backend-pi/tests/worker-rpc.test.ts | 17 ++++ packages/ui-sdk/src/server/backend.ts | 6 ++ .../085_safety_recording_containment.sql | 10 ++ .../ui-server/src/governance/event-writes.ts | 24 ++++- .../src/governance/safety-collector.ts | 46 ++++++++- .../ui-server/src/governance/safety-store.ts | 59 +++++++++++- .../tests/live-safety-admission.test.ts | 9 +- .../tests/safety-result-exits.test.ts | 96 ++++++++++++++++++- .../tests/safety-result-retention.test.ts | 84 +++++++++++++--- 17 files changed, 411 insertions(+), 40 deletions(-) diff --git a/.changeset/3812-safety-recording-containment.md b/.changeset/3812-safety-recording-containment.md index 3c2d83c589..a0ff208a15 100644 --- a/.changeset/3812-safety-recording-containment.md +++ b/.changeset/3812-safety-recording-containment.md @@ -7,7 +7,7 @@ A safety-recording failure now restricts only what it puts at risk, and the host recovers by itself (#3812, #3810). - **One turn, before delivery.** A failed safety begin, or a refused record of a tool's input before the tool runs, refuses only that turn with the new `SAFETY_RECORDING_UNAVAILABLE` error. The chat and the brain stay usable. When the refusal is for spent room, it says what to do: start a new chat (`safety_recording_chat_full`), or that retrying won't help (`safety_recording_brain_full`). Room that running turns or pending writes still hold is a plain retryable refusal. -- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails or whose report the host refuses: the runtime may already keep it in its session. Stopping a turn while a tool runs still records that tool's result. The chat keeps running under its tainted policy; other chats are untouched. +- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails or whose report the host refuses: the runtime may already keep it in its session. Stopping a turn while a tool runs still records that tool's result. Every tool call the host admits owes its result's record until that record is written or the call is refused, so a call whose result never arrives (a turn stopped before the runtime reported it, or a server that died mid-tool) also leaves the gap. The chat keeps running under its tainted policy; other chats are untouched. - **The brain, only when the evidence store cannot take a scoped fact.** New turns still run, restricted, each with a permanent gap written before anything is sent. The server keeps retrying and clears the latch itself once the gaps are durable and every turn that predates the latch has ended, including one begun restricted under an earlier latch. A turn is refused only if even its restricted start cannot be written (`safety_recording_paused`). - **Boot** resolves a set latch and pending reservations automatically instead of refusing every turn. - **Diagnosable.** Each latch keeps its first cause and a count in the database, logs one structured line, and is shown to the owner as `safetyRecording` on `/api/status`, also while only the server process holds it (`cause.durable: false`). Errors are no longer all labelled `capacity`. Every recovery is recorded with who or what ran it. diff --git a/docs/decisions/claude-2.1.287-compatibility.md b/docs/decisions/claude-2.1.287-compatibility.md index c1a650722f..a1508c4272 100644 --- a/docs/decisions/claude-2.1.287-compatibility.md +++ b/docs/decisions/claude-2.1.287-compatibility.md @@ -126,7 +126,7 @@ The backend builds the actual turn options and production permission handlers The explicit ask lives in (`enforcementHookFor`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`) and is registered under enforcement in -(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:715-718`). +(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:730-733`). `scripts/measure-claude-enforcement.ts` runs `createClaudeBackend().startTurn()` and forwards to the SDK resolved from that backend. Its query wrapper only diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index 43d62fa242..a8769b2c84 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -98,7 +98,14 @@ running under the tainted policy, not refusing. stopped turn still records the result (stopping refuses new tools, never a record), a report the host refuses before its record (a malformed or replayed Pi report) and a result for a call whose input record failed both - leave the gap. + leave the gap. The host does not rely on the runtime to report a result: + the Claude runtime dispatches neither result hook for a turn stopped while + a tool runs, and still keeps that call in its session. So every call + `begin()` admits is an obligation, recorded before the tool runs, until its + result is durably recorded or the backend refuses the call (a refusal, or + a rejected `begin()`, proves it never ran). A collection that ends owing + one, however it ended, and an obligation still open at boot, leave the + same permanent gap. - **Evidence store unwritable** (the chat fact cannot commit): the brain latches through the emergency reserve, or, when even that fails, in the host process. New turns still begin, each with a permanent diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts index 792397c9d5..2b1df57915 100644 --- a/packages/ui-backend-claude/src/permission-hooks.ts +++ b/packages/ui-backend-claude/src/permission-hooks.ts @@ -666,13 +666,28 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick { if (toolUseId) await req.bridge.inputSafety?.refused?.(toolUseId).catch(() => {}); }; + const decideToolUse = canUseToolFor(ctx); + const canUseTool: typeof decideToolUse = async (toolName, input, opts) => { + const result = await decideToolUse(toolName, input, opts); + if (result?.behavior === "deny") await refuse(opts.toolUseID); + return result; + }; const mutatingHook = mutatingHookFor(ctx); const { agentHook, rtkHook } = createRewriteHooks(ctx, options); // Claude runs matching hooks in parallel. Every hook, including a read // observation or rewrite that finishes last, must fence its own final wait. // Outward gates still recompute standing/per-use authority in their bodies. const fence: (hook: HookCallback) => HookCallback = hook => async (...args) => { + const output = await fenced(hook, args); + if (args[0].hook_event_name === "PreToolUse" && "hookSpecificOutput" in output && output.hookSpecificOutput?.hookEventName === "PreToolUse" + && output.hookSpecificOutput.permissionDecision === "deny") await refuse(args[0].tool_use_id); + return output; + }; + async function fenced(hook: HookCallback, args: Parameters): Promise>> { let snapshot: AdmissionSafetySnapshot | undefined; let output: Awaited>; try { @@ -690,7 +705,7 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick { if((input.hook_event_name==="PostToolUse"||input.hook_event_name==="PostToolUseFailure")&&req.bridge.inputSafety){ const response=input.hook_event_name==="PostToolUse"?input.tool_response:input.error; diff --git a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts index 80a9ab0b0c..84f600c953 100644 --- a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts +++ b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts @@ -14,6 +14,7 @@ import { mutatingHookFor, createNativeFileGuards, createPermissionContext, + createPermissionWiring, outsideEnforcedAllowlist, reusablePerUseDecision, type PermissionWiringOptions, @@ -114,3 +115,38 @@ describe("the extracted callbacks", () => { expect(locks).toEqual(["oar-1"]); }); }); + +describe("refusals owe no result", () => { + // A deny this backend returns is final: the runtime never runs the call, + // so the host's collector stops waiting for its result (#3812). + function wiring(signal: AbortSignal) { + const refused: string[] = []; + const { canUseTool, hooks } = createPermissionWiring({ + req: { prompt: "Count the suitors in the hall", signal, + bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "allow" }), + inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); } } } } as never, + allowedTools: ["Read"], confirmPatterns: [], brainPath: "/srv/odysseus-brain", + turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool() {} } as never, childEnv: {}, log: () => {}, + }); + const preToolUse = hooks!.PreToolUse!.find(group => !group.matcher)!.hooks[0]!; + return { canUseTool: canUseTool!, preToolUse, refused }; + } + + test("a call the backend denies tells the collector it never runs", async () => { + const stopped = new AbortController(); stopped.abort(); + const { canUseTool, preToolUse, refused } = wiring(stopped.signal); + expect((await canUseTool("Glob", { pattern: "ithaca/*.md" }, { toolUseID: "oar-1", signal: stopped.signal } as never))?.behavior).toBe("deny"); + const [input, , options] = hookCall("Grep", { pattern: "suitors" }); + const output = await preToolUse({ ...(input as object), tool_use_id: "oar-2" } as never, "oar-2", options); + expect((output as { hookSpecificOutput?: { permissionDecision?: string } }).hookSpecificOutput?.permissionDecision).toBe("deny"); + expect(refused, "CLAUDE_DENY_REFUSES_THE_CALL").toEqual(["oar-1", "oar-2"]); + }); + + test("a call the backend lets run stays owed", async () => { + const live = new AbortController(); + const { canUseTool, preToolUse, refused } = wiring(live.signal); + expect((await canUseTool("Glob", { pattern: "ithaca/*.md" }, { toolUseID: "oar-1", signal: live.signal } as never))?.behavior).toBe("allow"); + await preToolUse(...hookCall("Read", { file_path: "/srv/odysseus-brain/notes/ithaca.md" })); + expect(refused, "CLAUDE_ALLOW_LEAVES_THE_CALL_OWED").toEqual([]); + }); +}); diff --git a/packages/ui-backend-pi/src/permission-gate.ts b/packages/ui-backend-pi/src/permission-gate.ts index 0a745a56b9..c4ca0ad8af 100644 --- a/packages/ui-backend-pi/src/permission-gate.ts +++ b/packages/ui-backend-pi/src/permission-gate.ts @@ -33,7 +33,7 @@ * executes. */ -import type { InlineExtension } from "@earendil-works/pi-coding-agent"; +import type { InlineExtension, ToolCallEvent, ToolCallEventResult } from "@earendil-works/pi-coding-agent"; import { APIFY_TOOL_NAMES, WEB_TOOL_NAME_LIST, @@ -108,6 +108,12 @@ export function createPermissionGate(options: PermissionGateOptions): InlineExte name: "brain-permission-gate", factory: (pi) => { pi.on("tool_call", async (event) => { + const answer = await admit(event); + // A blocked call never runs, so it owes no result record (#3812). + if (answer?.block) await turn.bridge?.inputSafety?.refused?.(event.toolCallId); + return answer; + }); + async function admit(event: ToolCallEvent): Promise { if (turn.signal?.aborted) return { block: true, reason: "Turn cancelled before tool admission." }; if (isCompletedAutonomousToolCall(turn.autonomous, event.toolName, event.input)) return { block: true, reason: "This call already completed before yielding; inspect its retained result instead of replaying it." }; @@ -135,7 +141,7 @@ export function createPermissionGate(options: PermissionGateOptions): InlineExte Object.assign(target, decision.updatedInput); } return undefined; - }); + } }, }; } diff --git a/packages/ui-backend-pi/src/worker-rpc.ts b/packages/ui-backend-pi/src/worker-rpc.ts index a5d749213e..f22b5102a9 100644 --- a/packages/ui-backend-pi/src/worker-rpc.ts +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -278,6 +278,12 @@ export function createPiWorkerRpcDispatcher(context: PiWorkerRpcContext): (msg: // check refuses the worker. A report refused before it reaches the // collector leaves its chat a permanent gap instead (#3812). const result = msg.method === "safetyResult", safety = context.turn.bridge?.inputSafety; + // Pi runs a call only on an "allow" answer: a denial or a rejection + // blocks it before it executes, so the call owes no result (#3812). + const permission = msg.method === "permission" && safety?.refused ? safety : undefined; + const refuse = (outcome: Promise): Promise => !permission ? outcome : outcome.then( + async answer => { if ((answer as { behavior?: string } | null)?.behavior !== "allow") await permission.refused!(msg.toolCallId); return answer; }, + async error => { await permission.refused!(msg.toolCallId); throw error; }); try { if (!result || !safety) context.live(); if (msg.id <= lastRpcId) throw resultLoss(new Error("Replayed pi worker RPC")); @@ -286,8 +292,8 @@ export function createPiWorkerRpcDispatcher(context: PiWorkerRpcContext): (msg: const handler = Object.hasOwn(PI_WORKER_RPC_HANDLERS, msg.method) ? PI_WORKER_RPC_HANDLERS[msg.method] : undefined; if (!handler) throw new Error(`Unknown pi worker RPC method: ${String(msg.method)}`); const answer = handler(msg, bridge, context); - return result && safety ? answer.catch(error => keepResultLoss(safety, msg, error)) : answer; - } catch (error) { return result && safety ? keepResultLoss(safety, msg, error) : Promise.reject(error); } + return result && safety ? answer.catch(error => keepResultLoss(safety, msg, error)) : refuse(answer); + } catch (error) { return result && safety ? keepResultLoss(safety, msg, error) : refuse(Promise.reject(error)); } }; } diff --git a/packages/ui-backend-pi/tests/tools-permission.test.ts b/packages/ui-backend-pi/tests/tools-permission.test.ts index 101758bd30..65251b1734 100644 --- a/packages/ui-backend-pi/tests/tools-permission.test.ts +++ b/packages/ui-backend-pi/tests/tools-permission.test.ts @@ -80,6 +80,18 @@ describe("approval policy (approvalReason)", () => { }); describe("tool_call permission gate", () => { + test("a call the gate blocks tells the collector it never runs", async () => { + // A blocked call never executes, so it owes no result record (#3812). + const refused: string[] = []; + const turn = createTurnContext(); + const mock = makeMockBridge({ decision: { behavior: "deny", message: "Penelope declines" } }); + turn.bridge = { ...mock.bridge, inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); } } }; + const handler = gateHandler({ turn, allowedTools: ALLOWED, confirmPatterns: CONFIRM }); + expect(await handler({ toolName: "write_file", toolCallId: "allowed", input: { path: "a.md", content: "x" } })).toBeUndefined(); + expect(await handler({ toolName: "brain_archive", toolCallId: "declined", input: { path: "notes/suitors.md" } })).toMatchObject({ block: true }); + expect(refused, "PI_GATE_BLOCK_REFUSES_THE_CALL").toEqual(["declined"]); + }); + test("default brain_read_base executes in-process without an approval card", async () => { const brain = makeEmptyBrain(); try { diff --git a/packages/ui-backend-pi/tests/worker-rpc.test.ts b/packages/ui-backend-pi/tests/worker-rpc.test.ts index 50f5311632..ed58081015 100644 --- a/packages/ui-backend-pi/tests/worker-rpc.test.ts +++ b/packages/ui-backend-pi/tests/worker-rpc.test.ts @@ -211,3 +211,20 @@ test("an unavailable collector notice awaits durable failure and carries no tool await Promise.resolve();expect(returned,"PI_SAFETY_UNAVAILABLE_WAITS_FOR_COMMIT").toBe(false); expect(called).toBe(1);release();expect(String(await result)).toContain("Unqualified Pi input transformations"); }); + +test("every permission answer but allow tells the collector the call never runs", async () => { + // Pi runs a call only on "allow": a denial or a rejection blocks it before + // it executes, so the call owes no result record (#3812). + const refused: string[] = []; + const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); } }; + const routed = harness({}, { applyBrain: async () => ({ ok: true }) as never, inputSafety }); + expect(await routed.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-allowed"))).toEqual({ behavior: "allow" }); + const unrouted = harness({}, { inputSafety }); + expect(await unrouted.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-denied"))).toMatchObject({ behavior: "deny" }); + // Stopped after admission, before its answer: the worker blocks the call. + let checks = 0; + const stopped = harness({ live: () => { if (++checks > 1) throw new Error("Pi worker RPC refused: turn is inactive, cancelled or revoked."); } }, + { applyBrain: async () => ({ ok: true }) as never, inputSafety }); + await expect(stopped.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-stopped"))).rejects.toThrow("turn is inactive"); + expect(refused, "PI_NON_ALLOW_PERMISSION_REFUSES_THE_CALL").toEqual(["call-denied", "call-stopped"]); +}); diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index 29cf407327..d5fc3623d0 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -189,6 +189,12 @@ export interface BackendBridge { * could record it: the turn's chat keeps a permanent gap. Resolves once * that gap is durable. */ lost?(toolUseId: string, toolName: string, cause: unknown): Promise; + /** @internal The backend refused this call, so the runtime never runs it. + * Every call `begin` admits owes its `result` until one is recorded or + * this says it never ran; still owed when the turn ends, it leaves the + * turn's chat a permanent gap. Call it for every refusal the backend + * returns, before returning it. Never rejects. */ + refused?(toolUseId: string): Promise; }; /** Validated, exact-base policy proposal; the server owns its explicit approval and write. */ proposePolicyChange?(requestId: string, input: import("../tool-contracts/policy.js").PolicyChangeInput): Promise; diff --git a/packages/ui-server/migrations/085_safety_recording_containment.sql b/packages/ui-server/migrations/085_safety_recording_containment.sql index f717716a78..789454fc91 100644 --- a/packages/ui-server/migrations/085_safety_recording_containment.sql +++ b/packages/ui-server/migrations/085_safety_recording_containment.sql @@ -29,3 +29,13 @@ CREATE TABLE safety_recoveries ( trigger TEXT NOT NULL CHECK(trigger IN ('boot','automatic','owner')), actor TEXT NOT NULL, scope TEXT NOT NULL, cause TEXT, gapped INTEGER NOT NULL ); +-- A tool call admitted before it runs owes its result's record. Its row is +-- the obligation: it goes when that record is durable, or when the backend +-- refuses the call, which proves it never ran. A row still here when its +-- collection ends, or at boot, leaves that chat a permanent gap. +CREATE TABLE safety_obligations ( + id TEXT PRIMARY KEY, + collection_id TEXT NOT NULL REFERENCES safety_collections(id) ON DELETE CASCADE, + tool_use_id TEXT NOT NULL, tool TEXT NOT NULL, opened_at INTEGER NOT NULL +); +CREATE INDEX safety_obligations_collection ON safety_obligations(collection_id); diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index 14cd33afee..cb76ab5cdc 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -8,7 +8,7 @@ */ import { retainSafetyLoss, safetyQueue, notifySafetyChanged } from "./safety-queue.js"; import { prepareSafetyReview, commitSafetyReview, type SafetyReviewBody, type SafetyReviewer, type SafetyReviewReceipt } from "./safety-reviews.js"; -import { beginSafetyCollection, acknowledgeSafety, endSafetyCollection, safetyProjection, reserveSafetyWrite, releaseSafetyWrite, +import { beginSafetyCollection, acknowledgeSafety, endSafetyCollection, safetyProjection, reserveSafetyWrite, releaseSafetyWrite, openSafetyObligation, dischargeSafetyObligation, ensureSafetyEventCollection, recordSafetyFailure, recoverSafetyRecording, migrateSafetyHistory, logSafetyRecording, safetyRecordingStatus, SafetyCapacityExhausted, SafetyRecordingUnavailable, SafetyUnavailable, safetyScopeTurns, type SafetyCollectionInput, type SafetyProjection, type SafetyFailureSite, type SafetyRecovery, type SafetyRecordingStatus } from "./safety-store.js"; @@ -43,6 +43,8 @@ export function setup(db: Database): WriteProcedures { // latches nothing (#3812). The app side names the retryable refusal. safetyBegin: (input:SafetyCollectionInput) => beginSafetyCollection(db,input), safetyReady: (turnId:string,backendId:string,version:number) => acknowledgeSafety(db,turnId,backendId,version), + safetyOblige: (turnId:string,id:string,toolUseId:string,tool:string) => openSafetyObligation(db,turnId,id,toolUseId,tool), + safetyDischarge: (turnId:string,id:string) => dischargeSafetyObligation(db,turnId,id), safetyEnd: (turnId:string,loss=false) => { // Never seal an apparently complete epoch if its loss notice rolled // back. A failed retry leaves it open for restart classification. @@ -79,6 +81,15 @@ export interface GovernanceWrites { /** Refuses with `SafetyRecordingUnavailable` when the collection cannot commit; nothing is latched. */ safetyBegin(input:SafetyCollectionInput):Promise; safetyReady(turnId:string,backendId:string,version:number):Promise; + /** A tool call admitted before it runs owes its result's record from now + * until `safetyDischarge`; still owed when its collection ends, or at boot, + * it leaves its chat a permanent gap (#3812). Refuses with + * `SafetyRecordingUnavailable`: the call has not run, and the backend + * refuses it. */ + safetyOblige(turnId:string,obligationId:string,toolUseId:string,tool:string):Promise; + /** The call's result is durably recorded, or the backend refused the call + * and it never ran. A failure leaves the obligation, and so the gap. */ + safetyDischarge(turnId:string,obligationId:string):Promise; safetyEnd(turnId:string):Promise; /** Marks the turn's chat failed (`cause` is error text only); the brain only when that cannot commit. */ safetyFail(turnId:string,cause?:unknown):Promise; @@ -239,6 +250,17 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov } }, safetyReady: (turnId,backendId,version)=>call("safetyReady",turnId,backendId,version), + async safetyOblige(turnId,obligationId,toolUseId,tool){ + try{await call("safetyOblige",turnId,obligationId,toolUseId,tool);} + catch(error){ + if((error as {code?:string})?.code==="chat_retired")throw error; + // Before the call runs: the backend refuses it, and nothing latches. + logSafetyRecording("safety recording refused one tool call before it ran",{"safety.scope":"turn","safety.site":"safetyOblige","safety.turn_id":turnId, + "error.class":error instanceof Error?error.constructor?.name??error.name:"Error","error.message":error instanceof Error?error.message:String(error)}); + throw new SafetyRecordingUnavailable(brainFailed(),error); + } + }, + safetyDischarge: (turnId,obligationId)=>call("safetyDischarge",turnId,obligationId), safetyEnd: turnId=>call("safetyEnd",turnId,shared.unscopedLoss||shared.lostTurns.has(turnId)), safetyFail, safety: (turnId,sessionId)=>snapshot(()=>{ diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index 87b260342d..650bdf0b0c 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -9,9 +9,13 @@ import { SafetyRecordingUnavailable } from "./safety-store.js"; export function createSafetyCollector(db:Database,writes:GovernanceWrites,options:{turnId:string;bindingId:string;backendId:string; sessionId:()=>string|null;actor?:"interactive"|"voice";brainPath?:string;shellProxied:()=>boolean;signal:AbortSignal;onReady?:()=>void;stop?:(error:Error)=>void;policyHash?:string|null}):NonNullable { - // `admitted`: every input signal of its latest begin() is recorded. A result - // for a call whose begin() failed partway cannot be recorded faithfully. - const operations=new Map;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string}>(); + // `admitted`: every input signal of its latest begin() is recorded, and the + // call owes its result. A result for a call whose begin() failed partway + // cannot be recorded faithfully. `owed`: its obligation is durable (#3812). + // `refused`: the backend refused the call, so it never runs. + type Operation={tool:string;inputHashes:Set;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string;owed:boolean;refused:boolean}; + const operations=new Map(); + const operation=(tool:string):Operation=>({tool,inputHashes:new Set(),id:crypto.randomUUID(),occurrences:[],done:false,admitted:false,signals:[],owed:false,refused:false}); const base=()=>({turnId:options.turnId,sessionId:options.sessionId(),actor:options.actor??"interactive" as const,model:null,profile:null}); const marked=(path:string)=>isMarkedUntrusted(db,path); const hash=(value:string)=>new Bun.CryptoHasher("sha256").update(value).digest("hex"); @@ -31,6 +35,12 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(failures.length>1)throw new AggregateError(failures,`Safety input refused: ${String(error)}`); throw error; }; + // A call that never runs owes nothing. A discharge that cannot commit + // leaves the obligation, and so its chat's gap when the collection ends. + const discharge=async(op:Operation)=>{ + if(!op.owed)return; + try{await writes.safetyDischarge(options.turnId,op.id);op.owed=false;}catch{/* Still owed: the end gaps it. */} + }; const tails=new Map>();let queued=0; const serial=(id:string,work:()=>Promise,afterFailure=false):Promise=>{ if(queued>=256)return fail(new Error("Safety collection queue capacity exceeded")); @@ -45,13 +55,22 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option return { async ready(backend,version){assertLive();await writes.safetyReady(options.turnId,backend,version);options.onReady?.();}, async unavailable(){return fail(new Error("Input collection is not qualified for this runtime configuration"));}, + // Every call begin() admits owes its result's record until that record is + // durable or the backend refuses the call. A rejected begin() is such a + // refusal: the backend awaits it before running the tool, and runs nothing + // on rejection. The obligation is the host's own record, so it holds + // whatever the runtime delivers: cancellation, abort, a result hook the + // runtime skips, or process death all leave the gap (#3812). begin(toolUseId,tool,input){return serial(toolUseId,async()=>{ assertLive(); + // Refused: the runtime never runs it, and refusing again is no failure. + if(operations.get(toolUseId)?.refused)throw new Error("Safety operation was refused; the call does not run"); + let op:Operation|undefined; try{ const inputHash=hash(JSON.stringify(input)),previous=operations.get(toolUseId); if(previous&&(previous.tool!==tool||previous.done))throw new Error("Safety operation identity already completed or changed tool"); if(!previous&&operations.size>=2000)throw new Error("Safety tool operation capacity exceeded"); - const op=previous??{tool,inputHashes:new Set(),id:crypto.randomUUID(),occurrences:[] as string[],done:false,admitted:false,signals:[] as IngestionSignal[]}; + op=previous??operation(tool); if(!op.inputHashes.has(inputHash)&&op.inputHashes.size>=16)throw new Error("Safety input revision capacity exceeded"); op.inputHashes.add(inputHash);op.admitted=false;operations.set(toolUseId,op); for(const signal of inputTaintSignals(tool,input,options.brainPath,marked,options.shellProxied())){ @@ -60,9 +79,14 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}},{beforeDelivery:true}); op.occurrences.push(item.id);op.signals.push(signal); } + if(!op.owed){await writes.safetyOblige(options.turnId,op.id,toolUseId,tool);op.owed=true;} op.admitted=true; assertLive(); - }catch(error){return fail(error,true);} + }catch(error){ + // The backend refuses the call, so it never runs and owes nothing. + if(op)await discharge(op); + return fail(error,true); + } });}, // A result already exists when it reaches the host, and the runtime may keep // it in its session. So nothing between the tool running and its record @@ -88,8 +112,20 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option const state=finalized&&!['Bash','bash'].includes(tool)?"finalized":"interrupted_unknown"; for(const id of op.occurrences)await writes.record({...base(),kind:"taint_exposure",dedupeKey:id,payload:{occurrenceId:id,state}}); op.done=true;op.outputHash=outputHash; + // Recorded: the call owes nothing. A discharge that cannot commit stays + // owed, which only gaps the chat; it is no loss of this record. + await discharge(op); }catch(error){return fail(error);} },true);}, + // The backend refused this call, which proves it never runs: it owes no + // result. Never rejects; an obligation it cannot discharge stays a gap. + // A later begin() for it is refused too, so a parallel hook cannot reopen it. + refused(toolUseId){return serial(toolUseId,async()=>{ + const op=operations.get(toolUseId); + if(!op){if(operations.size<2000)operations.set(toolUseId,{...operation(""),refused:true});return;} + op.refused=true; + if(!op.done)await discharge(op); + },true).catch(()=>{});}, // A result the backend could not hand over (a refused or malformed report): // its chat keeps a permanent gap. Resolves once that gap is durable. async lost(toolUseId,tool,cause){ diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index 0cc540a443..0c56af57a4 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -74,7 +74,7 @@ export function advance(db: Database): string { } /** Where a safety-recording failure was raised. */ -export type SafetyFailureSite = "safetyBegin"|"safetyReserve"|"safetyCommit"|"record"|"safetyFail"|"safetyEnd"|"migrate"|"boot-pending"; +export type SafetyFailureSite = "safetyBegin"|"safetyReserve"|"safetyCommit"|"record"|"safetyFail"|"safetyEnd"|"migrate"|"boot-pending"|"boot-obligation"; export type SafetyFailureReason = "recording_failed"|"capacity"; /** A failure's cause: identifiers and error text only, never message content. */ export interface SafetyFailureCause { errorClass:string; message:string; stack:string|null; site:SafetyFailureSite; turnId:string|null; at:number } @@ -347,8 +347,50 @@ export function appendSafetyEvent(db:Database,row:GovernanceEventRow,reserved=fa return null; } } +/** A collection may hold this many calls that still owe their results. */ +const OBLIGATIONS = 2048; +const clipText=(text:string)=>clip(text.replace(/[\u0000-\u001f\u007f]/g," "),128); +/** + * A tool call admitted before it runs owes its result's record (#3812). It + * is owed until that record is durable, or until the backend refuses the + * call, which proves it never ran. Owing it is restrictive only: it needs no + * healthy recorder, only an open collection to gap if the result never comes. + */ +export function openSafetyObligation(db:Database,turnId:string,id:string,toolUseId:string,tool:string,at=Date.now()):void { + db.transaction(()=>{ + if(!/^[A-Za-z0-9_-]{1,128}$/.test(id))throw new SafetyUnavailable("Invalid safety obligation identity"); + const c=collection(db,turnId);if(!c)throw new SafetyUnavailable("Safety obligation requires a collection"); + live(db,c,true); + const prior=one<{collection_id:string}|null>(db,"SELECT collection_id FROM safety_obligations WHERE id=?",id); + if(prior){if(prior.collection_id!==c.id)throw new SafetyUnavailable("Conflicting safety obligation");return;} + if(one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_obligations WHERE collection_id=?",c.id).n>=OBLIGATIONS) + throw new SafetyCapacityExhausted("Safety obligation capacity exhausted","turn"); + db.query("INSERT INTO safety_obligations(id,collection_id,tool_use_id,tool,opened_at) VALUES(?,?,?,?,?)").run(id,c.id,clipText(toolUseId),clipText(tool),at); + }).immediate(); +} +/** Its result is durably recorded, or the call was refused and never ran. + * Once the collection ended the call's gap is already committed: nothing to do. */ +export function dischargeSafetyObligation(db:Database,turnId:string,id:string):void { + db.query("DELETE FROM safety_obligations WHERE id=? AND collection_id=(SELECT id FROM safety_collections WHERE turn_id=? AND ended=0)").run(id,turnId); +} +/** Every call still owing its result in these collections becomes their + * chats' permanent gap, naming the first such call. Returns the causes. */ +function gapOwedResults(db:Database,collectionId:string|null,site:SafetyFailureSite):SafetyFailureCause[] { + // With one MIN(), SQLite takes the bare columns from that first-opened row. + const owed=db.query<{collection_id:string;turn_id:string;n:number;tool:string;tool_use_id:string},[string|null,string|null]>(`SELECT o.collection_id,c.turn_id,COUNT(*) n,MIN(o.rowid) first,o.tool,o.tool_use_id + FROM safety_obligations o JOIN safety_collections c ON c.id=o.collection_id WHERE ? IS NULL OR o.collection_id=? GROUP BY o.collection_id`).all(collectionId,collectionId); + const causes:SafetyFailureCause[]=[]; + for(const row of owed){ + const cause=safetyFailureCause(new SafetyUnavailable(`A tool result was never recorded: ${row.tool} (${row.tool_use_id})${row.n>1?` and ${row.n-1} more`:""}`),site,row.turn_id); + db.query("UPDATE safety_collections SET failure=COALESCE(failure,'recording_failed'),failure_cause=COALESCE(failure_cause,?) WHERE id=?").run(JSON.stringify(cause),row.collection_id); + db.query("DELETE FROM safety_obligations WHERE collection_id=?").run(row.collection_id); + causes.push(cause); + } + return causes; +} +const logOwed=(causes:SafetyFailureCause[])=>{for(const cause of causes)logSafetyRecording("safety recording failed for one chat",causeAttributes("chat","recording_failed",cause));}; export function endSafetyCollection(db:Database,turnId:string):void { - db.transaction(()=>{const c=collection(db,turnId);if(!c||c.ended)return; + const owed=db.transaction(()=>{const c=collection(db,turnId);if(!c||c.ended)return []; // Lost/incomplete hooks leave exposures open and therefore unresolved. db.query("UPDATE safety_collections SET ended=1,end_revision=? WHERE id=?").run(advance(db),c.id); // A reservation still open at the end can never commit: an ended epoch @@ -358,7 +400,12 @@ export function endSafetyCollection(db:Database,turnId:string):void { db.query("UPDATE safety_collections SET failure=COALESCE(failure,'recording_failed'),gap=COALESCE(gap,'recording_failed_recovered') WHERE id=?").run(c.id); db.query("DELETE FROM safety_pending WHERE collection_id=?").run(c.id); } + // A call that still owes its result may have run, and the runtime may keep + // its output in its session, whether the turn was cancelled, aborted or + // never got a result hook. Nothing records it now: its chat keeps the gap. + return gapOwedResults(db,c.id,"safetyEnd"); }).immediate(); + logOwed(owed); } export interface SafetyProjection { session:SafetySessionKey|null;evidenceRevision:string;unresolvedCount:number;earliestUnresolvedId:string|null; pendingCount:number;restriction:"normal"|"restricted";reasons:string[]; @@ -433,12 +480,18 @@ function readSafetyProjection(db:Database,turnId:string|null,sessionId:string|nu } /** Explicit detector loss/restart never auto-clears an admitted exposure. */ export function recoverSafetyCollections(db:Database):void { - db.transaction(()=>{ + const owed=db.transaction(()=>{ const n=one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE ended=0").n; if(n){db.query("UPDATE safety_collections SET gap=COALESCE(gap,'host_restart_unknown'),ended=1,end_revision=? WHERE ended=0").run(advance(db));} + // A call that owed its result when the process died may have run: its + // chat keeps the gap, as if its collection had ended with it owed. + const owed=gapOwedResults(db,null,"boot-obligation"); + if(owed.length&&!n)advance(db); if(one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_pending").n) latchSafety(db,null,"recording_failed",safetyFailureCause(new SafetyUnavailable("Safety reservations were pending at restart"),"boot-pending",null)); + return owed; }).immediate(); + logOwed(owed); } /** Prune only display bytes; identity, counts and reserved audit capacity survive. */ export function pruneSafetyDetail(db:Database,before:number):number { diff --git a/packages/ui-server/tests/live-safety-admission.test.ts b/packages/ui-server/tests/live-safety-admission.test.ts index ea876e9872..f37d7e28db 100644 --- a/packages/ui-server/tests/live-safety-admission.test.ts +++ b/packages/ui-server/tests/live-safety-admission.test.ts @@ -394,7 +394,7 @@ test("zero reviewed triggers cannot clear unknown coverage or waive ordinary den for (const last of ["rtk", "agent", "native-read", "index"] as const) { for (const change of ["healthy", "recording-loss", "revoke", "cancel"] as const) { test(`parallel Claude ${last}: final wait fences ${change} before process/file delivery`, async () => { - const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(), siblings = Promise.withResolvers(); const wait = async () => { entered.resolve(); await release.promise; }; const versions = new NativeFileVersions(), begin = versions.beginRead.bind(versions); versions.beginRead = async (...args) => { await begin(...args); await wait(); }; @@ -414,10 +414,13 @@ for (const last of ["rtk", "agent", "native-read", "index"] as const) { const calls = wiring.hooks!.PreToolUse!.filter(group => !group.matcher || new RegExp(group.matcher).test(name)) .flatMap(group => group.hooks).map(hook => hook({ hook_event_name: "PreToolUse", tool_name: name, tool_input: input, tool_use_id: "parallel-admission" } as never, "parallel-admission", { signal: f.controller.signal }) - .then(output => { finished++; return output; })); + .then(output => { if (++finished === calls.length - 1) siblings.resolve(); return output; })); + if (calls.length === 1) siblings.resolve(); try { + // Every other hook has returned (each records its call's admission, + // a write-worker round trip) while the last one waits. await entered.promise; - await new Promise(resolve => setImmediate(resolve)); + await siblings.promise; expect(finished, "PARALLEL_PROBE_REACHES_LAST_HOOK_WAIT").toBe(calls.length - 1); if (change === "recording-loss") await f.writes.safetyFail("another-turn"); if (change === "revoke") f.revoke(); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 806b5003b0..20302be78d 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -1,8 +1,11 @@ /** Every exit between a tool running and its result's record either records * the result or leaves its chat a permanent gap, in both backends (#3812). - * The installed Claude runtime's replay of a stopped turn's result is proved - * in `safety-result-retention.test.ts`; these drive the remaining exits - * against the real host ledger. Keyless and offline. */ + * Every call `begin()` admits owes its result until the record is durable or + * the backend refuses the call; one still owed when its collection ends, or + * at boot, is a gap. The installed Claude runtime's replay of a stopped + * turn's result, and its skipped result hooks, are proved in + * `safety-result-retention.test.ts`; these drive the remaining exits against + * the real host ledger. Keyless and offline. */ import { afterEach, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -40,10 +43,12 @@ async function voyage() { const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, backendId: "pi", sessionId: () => "ithaca", brainPath: brain, shellProxied: () => false, signal: controller.signal, stop: error => controller.abort(error) }); await collector.ready("pi", 1); - return { db, writes, collector, controller, + return { db, writes, collector, controller, path: join(root, "ui.db"), failure: () => (db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get() as { failure: string | null }).failure, recorded: () => db.query(`SELECT r.detector FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.turn_id='voyage' AND r.kind='occurrence'`).all(), + cause: () => JSON.parse((db.query("SELECT failure_cause FROM safety_collections WHERE turn_id='voyage'").get() as { failure_cause: string | null }).failure_cause ?? "null"), + owed: () => (db.query("SELECT COUNT(*) n FROM safety_obligations").get() as { n: number }).n, chat: () => writes.safety(null, "ithaca"), async close() { await writer.close(); db.close(); } }; } @@ -129,3 +134,86 @@ test("a Pi result is still reported when the session's own after-hook fails", as expect(stopped, "SAFETY_PI_FAILED_AFTER_HOOK_STOPS_THE_WORKER").toBe(1); } finally { await f.close(); } }); + +test("a call admitted and never reported leaves its chat a permanent gap when its collection ends", async () => { + const f = await voyage(); try { + // A runtime that ran the search but never reported it: no result hook, + // no worker report. Only the call's admission stands for its result. + await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + expect(f.owed(), "SAFETY_ADMITTED_CALL_OWES_ITS_RESULT").toBe(1); + await f.writes.safetyEnd("voyage"); + expect(f.failure(), "SAFETY_OWED_RESULT_IS_A_DURABLE_GAP").toBe("recording_failed"); + expect(f.cause(), "SAFETY_OWED_RESULT_NAMES_ITS_CALL").toMatchObject({ site: "safetyEnd", turnId: "voyage", message: expect.stringContaining("grep (call_raft)") }); + expect(f.owed(), "SAFETY_ENDED_COLLECTION_OWES_NOTHING_MORE").toBe(0); + expect(f.chat().restriction, "SAFETY_OWED_RESULT_RESTRICTS_ITS_CHAT").toBe("restricted"); + expect(f.chat().coverage.state, "SAFETY_OWED_RESULT_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + } finally { await f.close(); } +}); + +test("a call the backend refuses owes nothing, and a recorded result discharges its call", async () => { + const f = await voyage(); try { + await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + await f.collector.begin("call_oar", "grep", { pattern: "oar" }); + // The gate refuses the first call after admitting it: it never runs. + await f.collector.refused!("call_raft"); + // A refused call stays refused: a parallel admission cannot reopen it. + expect(String((await refusal(f.collector.begin("call_raft", "grep", { pattern: "sirens" })))?.message), "SAFETY_REFUSED_CALL_STAYS_REFUSED").toContain("refused"); + expect(f.controller.signal.aborted, "SAFETY_REFUSED_CALL_DOES_NOT_STOP_ITS_TURN").toBe(false); + await f.collector.result("call_oar", "grep", "", true); + expect(f.owed(), "SAFETY_REFUSED_AND_RECORDED_CALLS_OWE_NOTHING").toBe(0); + await f.writes.safetyEnd("voyage"); + expect(f.failure(), "SAFETY_REFUSED_CALL_LEAVES_NO_GAP").toBeNull(); + expect(f.chat().coverage.state, "SAFETY_DISCHARGED_CALLS_KEEP_COVERAGE").toBe("complete"); + } finally { await f.close(); } +}); + +test("a call refused when its edited input cannot be recorded owes nothing", async () => { + const f = await voyage(); try { + await f.collector.begin("call_aeolus", "WebFetch", { url: "https://example.com/aeolus" }); + expect(f.owed(), "SAFETY_ADMITTED_FETCH_OWES_ITS_RESULT").toBe(1); + // An approval edits the call; recording the edited input is refused, so + // the backend refuses the call, which never runs. + f.db.exec("CREATE TRIGGER refuse_input BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced input reservation failure'); END"); + expect(await refusal(f.collector.begin("call_aeolus", "WebFetch", { url: "https://example.com/zephyr" })), "SAFETY_UNRECORDED_EDIT_REFUSES_THE_CALL").toBeInstanceOf(Error); + f.db.exec("DROP TRIGGER refuse_input"); + expect(f.owed(), "SAFETY_REFUSED_EDIT_OWES_NOTHING").toBe(0); + await f.writes.safetyEnd("voyage"); + expect(f.failure(), "SAFETY_REFUSED_EDIT_LEAVES_NO_GAP").toBeNull(); + } finally { await f.close(); } +}); + +test("a call whose admission cannot be recorded never runs, owes nothing and leaves no gap", async () => { + const f = await voyage(); try { + f.db.exec("CREATE TRIGGER refuse_obligation BEFORE INSERT ON safety_obligations BEGIN SELECT RAISE(ABORT,'forced obligation failure'); END"); + const begun = await refusal(f.collector.begin("call_raft", "grep", { pattern: "sirens" })); + f.db.exec("DROP TRIGGER refuse_obligation"); + // Refused before the tool ran: the backend refuses the call. + expect((begun as { code?: string } | null)?.code, "SAFETY_UNRECORDED_ADMISSION_REFUSES_THE_CALL").toBe("safety_recording_unavailable"); + expect(f.owed(), "SAFETY_UNRECORDED_ADMISSION_OWES_NOTHING").toBe(0); + await f.writes.safetyEnd("voyage"); + expect(f.failure(), "SAFETY_UNRECORDED_ADMISSION_LEAVES_NO_GAP").toBeNull(); + } finally { await f.close(); } +}); + +test("a call still owed when the host dies leaves its chat a permanent gap at boot", async () => { + const f = await voyage(); + await f.collector.begin("call_oar", "grep", { pattern: "oar" }); + await f.collector.result("call_oar", "grep", "", true); + await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + expect(f.owed(), "SAFETY_ONLY_THE_UNREPORTED_CALL_IS_OWED").toBe(1); + // The process dies mid-search: nothing ends the collection. + await f.close(); + const db = createUiDb(f.path), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); + holdSafetyRecovery(db); + try { + const voyage = db.query("SELECT failure,failure_cause,gap FROM safety_collections WHERE turn_id='voyage'").get() as { failure: string | null; failure_cause: string; gap: string | null }; + expect(voyage.failure, "SAFETY_OWED_AT_RESTART_IS_A_DURABLE_GAP").toBe("recording_failed"); + // It names the call still owed, not the one already recorded. + expect(JSON.parse(voyage.failure_cause), "SAFETY_OWED_AT_RESTART_NAMES_ITS_CALL").toMatchObject({ site: "boot-obligation", turnId: "voyage", message: "A tool result was never recorded: grep (call_raft)" }); + expect(voyage.gap, "SAFETY_RESTART_STILL_CLASSIFIES_THE_OPEN_COLLECTION").toBe("host_restart_unknown"); + expect((db.query("SELECT COUNT(*) n FROM safety_obligations").get() as { n: number }).n, "SAFETY_BOOT_LEAVES_NOTHING_OWED").toBe(0); + const chat = writes.safety(null, "ithaca"); + expect(chat.restriction, "SAFETY_OWED_AT_RESTART_RESTRICTS_ITS_CHAT").toBe("restricted"); + expect(chat.coverage.epochs.find(epoch => epoch.reason === "recording_failed"), "SAFETY_OWED_AT_RESTART_IS_A_RECORDING_GAP").toBeDefined(); + } finally { await writer.close(); db.close(); } +}); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 3e77cb7bc5..46e30bedc7 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -2,10 +2,13 @@ * session: the installed Claude runtime replays it on resume. So its record * must be written whatever happened to the turn, and a record that cannot be * written leaves its chat a permanent gap; the chat never looks clean - * (#3812). Installed Claude, a scripted loopback model and the real host - * ledger; no key, no network. */ + * (#3812). A turn stopped while the tool runs reaches neither result hook, + * so a call admitted by `begin()` owes its record until it is written, and + * still owing it when the collection ends is a gap. Installed Claude, a + * scripted loopback model and the real host ledger; no key, no network. */ import {expect,test} from "bun:test"; -import {mkdirSync,mkdtempSync,rmSync,writeFileSync} from "node:fs"; +import {chmodSync,existsSync,mkdirSync,mkdtempSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; +import {createRequire} from "node:module"; import {join} from "node:path"; import {tmpdir} from "node:os"; import {query} from "@anthropic-ai/claude-agent-sdk"; @@ -21,14 +24,37 @@ import {holdSafetyRecovery} from "./helpers/hold-safety-recovery"; const SONG="The sirens sing: steer the raft onto the rocks."; +/** The installed runtime is also its own ripgrep: run as `rg`, the binary + * the SDK spawns searches instead of starting a session. */ +function installedRipgrep(root:string):string { + const sdk=createRequire(createRequire(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk")); + const real=join(root,"runtime-rg");mkdirSync(real); + symlinkSync(sdk.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude"),join(real,"rg")); + return join(real,"rg"); +} + /** `refused`: the result's reservation fails. `cancelled`: the turn is - * stopped after the tool ran, just before its result is recorded. */ -async function voyageHome(interruption:"refused"|"cancelled",check:(f:{db:ReturnType;writes:ReturnType})=>void){ + * stopped after the tool ran, just before its result is recorded. + * `running`: the turn is stopped once the search has printed its matches but + * before its process exits, so the runtime dispatches neither result hook. */ +type Interruption="refused"|"cancelled"|"running"; +async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType;writes:ReturnType; + first:{results:number;failures:number;aborted:boolean};searched:boolean;replayed:string[]})=>void){ const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); // A note: reading it records nothing before the tool runs, so only the // search output's own record stands between it and a complete chat. mkdirSync(join(brain,"notes"),{recursive:true});mkdirSync(home); const path=join(brain,"notes","sirens.md");writeFileSync(path,`${SONG}\n`); + // The runtime searches with the `rg` on its PATH. This one is the + // installed runtime's own ripgrep; it marks when the matches are out and + // then holds its exit, the window a stop lands in. + const bin=join(root,"bin"),searched=join(root,"sirens-heard"),rg=installedRipgrep(root);mkdirSync(bin); + writeFileSync(join(bin,"rg"),`#!/bin/sh +case " $* " in + *" sirens "*) '${rg}' "$@"; code=$?; : > '${searched}'; sleep 3; exit "$code";; + *) exec '${rg}' "$@";; +esac +`);chmodSync(join(bin,"rg"),0o755); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); holdSafetyRecovery(db); // Each turn's provider requests, as the loopback model received them. @@ -51,40 +77,49 @@ async function voyageHome(interruption:"refused"|"cancelled",check:(f:{db:Return const collector=createSafetyCollector(db,writes,{turnId,bindingId,backendId:"claude",sessionId:()=>"ithaca",brainPath:brain,shellProxied:()=>false,signal:controller.signal,stop:error=>controller.abort(error)}); await collector.ready("claude",1); const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:"allow"}),inputSafety:collector}},allowedTools:["Grep"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); - let results=0; + let results=0,failures=0; if(interrupt){ // The Grep result exists and the runtime holds it; only its record is at risk. const group=wiring.hooks!.PostToolUse!.find(group=>!group.matcher)!,record=group.hooks[0]!; group.hooks=[async(...args)=>{ results++; if(interruption==="refused")db.exec("CREATE TRIGGER refuse_result BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced result reservation failure'); END"); - else controller.abort(new Error("Odysseus stopped the turn as the result arrived")); + else if(interruption==="cancelled")controller.abort(new Error("Odysseus stopped the turn as the result arrived")); return record(...args); }]; + const failureGroup=wiring.hooks!.PostToolUseFailure!.find(group=>!group.matcher)!,failed=failureGroup.hooks[0]!; + failureGroup.hooks=[async(...args)=>{failures++;return failed(...args);}]; } + // Stop the turn the moment the search has printed its matches. + const watching=interrupt&&interruption==="running"?setInterval(()=>{if(existsSync(searched))controller.abort(new Error("Odysseus stopped the turn while the search ran"));},5):undefined; const timer=setTimeout(()=>controller.abort(),20000); try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:["Grep"],...wiring,abortController:controller, ...(resume?{resume}:{}), - env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),PATH:process.env.PATH??"/usr/bin:/bin",ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ + env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; if("session_id" in message&&typeof message.session_id==="string")runtimeSession=message.session_id; }}catch{/* The interrupted turn is stopped. */} - finally{clearTimeout(timer);db.exec("DROP TRIGGER IF EXISTS refuse_result");await writes.safetyEnd(turnId);} - return {results,aborted:controller.signal.aborted}; + finally{clearInterval(watching);clearTimeout(timer);db.exec("DROP TRIGGER IF EXISTS refuse_result");await writes.safetyEnd(turnId);} + return {results,failures,aborted:controller.signal.aborted}; } try{ const first=await voyage("voyage",null,true); expect(version,"SAFETY_ACTUAL_INSTALLED_RUNTIME").toBe(MEASURED_RUNTIME.claudeCode); - expect(first.results,"SAFETY_ACTUAL_RESULT_HOOK_EXECUTED").toBe(1); + if(interruption==="running")expect(existsSync(searched),"SAFETY_ACTUAL_SEARCH_RAN").toBe(true); expect(first.aborted,"SAFETY_INTERRUPTED_RESULT_STOPS_ITS_TURN").toBe(true); expect(runtimeSession,"SAFETY_RUNTIME_SESSION_TO_RESUME").toBeDefined(); turn=1; await voyage("homeward","ithaca",false,runtimeSession); const resumed=requests.filter(r=>r.turn===1); expect(resumed.length,"SAFETY_ACTUAL_NATIVE_RESUME").toBeGreaterThan(0); + // What the resumed session carries for the search call: its matches, or + // the runtime's own "interrupted" note when the stop beat its bookkeeping. + const replayed=resumed.flatMap(r=>(JSON.parse(r.raw).messages as {content:unknown}[]).flatMap(m=>Array.isArray(m.content)?m.content as {type?:string;tool_use_id?:string;content?:unknown}[]:[])) + .filter(block=>block.type==="tool_result"&&block.tool_use_id==="toolu_sirens").map(block=>typeof block.content==="string"?block.content:JSON.stringify(block.content)); + expect(replayed.length,"SAFETY_RUNTIME_RESUMES_THE_INTERRUPTED_CALL").toBeGreaterThan(0); // The premise: interrupting the record did not keep the result out of the model's context. - expect(resumed.some(r=>r.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT").toBe(true); - check({db,writes}); + if(interruption!=="running")expect(resumed.some(r=>r.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT").toBe(true); + check({db,writes,first,searched:existsSync(searched),replayed}); // Contained to its chat: the brain-wide recorder is untouched, and a // recovery has nothing to clear, so the chat stays restricted. expect(db.query("SELECT failed FROM safety_meta").get(),"SAFETY_INTERRUPTED_RESULT_NEVER_LATCHES_THE_BRAIN").toEqual({failed:0}); @@ -93,7 +128,8 @@ async function voyageHome(interruption:"refused"|"cancelled",check:(f:{db:Return }finally{origin.stop(true);await writer.close();db.close();rmSync(root,{recursive:true,force:true});} } -test("a result refused by the recorder is replayed on resume, so its chat keeps a permanent gap",()=>voyageHome("refused",({db,writes})=>{ +test("a result refused by the recorder is replayed on resume, so its chat keeps a permanent gap",()=>voyageHome("refused",({db,writes,first})=>{ + expect(first.results,"SAFETY_ACTUAL_RESULT_HOOK_EXECUTED").toBe(1); const chat=writes.safety("homeward","ithaca"); expect(chat.restriction,"SAFETY_REFUSED_RESULT_RESTRICTS_ITS_CHAT").toBe("restricted"); expect(chat.coverage.state,"SAFETY_REFUSED_RESULT_NEVER_LOOKS_COMPLETE").toBe("incomplete"); @@ -101,7 +137,8 @@ test("a result refused by the recorder is replayed on resume, so its chat keeps expect(db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_REFUSED_RESULT_GAP_IS_DURABLE").toEqual({failure:"recording_failed"}); }),60000); -test("a turn stopped as its result arrives still records the result the runtime replays",()=>voyageHome("cancelled",({db,writes})=>{ +test("a turn stopped as its result arrives still records the result the runtime replays",()=>voyageHome("cancelled",({db,writes,first})=>{ + expect(first.results,"SAFETY_ACTUAL_RESULT_HOOK_EXECUTED").toBe(1); // Stopping a turn stops new tools, never the record of one that already ran. const recorded=db.query(`SELECT r.detector FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.turn_id='voyage' AND r.kind='occurrence'`).all(); @@ -114,3 +151,20 @@ test("a turn stopped as its result arrives still records the result the runtime expect(db.query("SELECT failure,gap FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_CANCELLED_RECORDED_RESULT_IS_NO_GAP").toEqual({failure:null,gap:null}); expect(chat.coverage.state,"SAFETY_CANCELLED_RECORDED_RESULT_KEEPS_COVERAGE").toBe("complete"); }),60000); + +test("a turn stopped while its search runs reaches neither result hook, and its chat keeps a permanent gap",()=>voyageHome("running",({db,writes,first,replayed})=>{ + // The runtime skips both result hooks for a stopped turn, so the host never + // sees this result: only the call's admission stands for it. + expect(first.results+first.failures,"SAFETY_RUNTIME_SKIPPED_BOTH_RESULT_HOOKS").toBe(0); + // Whether the session kept the matches or only noted the interruption, the + // call ran and its outcome stayed in the runtime's session. + expect(replayed.every(text=>text.includes(SONG)||/interrupted/i.test(text)),"SAFETY_RUNTIME_KEEPS_THE_CALL_IN_ITS_SESSION").toBe(true); + const chat=writes.safety("homeward","ithaca"); + expect(chat.restriction,"SAFETY_UNRECORDED_RESULT_RESTRICTS_ITS_CHAT").toBe("restricted"); + expect(chat.coverage.state,"SAFETY_UNRECORDED_RESULT_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + expect(chat.coverage.epochs.find(e=>e.reason==="recording_failed"),"SAFETY_UNRECORDED_RESULT_IS_A_RECORDING_GAP").toBeDefined(); + const voyage=db.query("SELECT failure,failure_cause FROM safety_collections WHERE turn_id='voyage'").get() as {failure:string|null;failure_cause:string|null}; + expect(voyage.failure,"SAFETY_UNRECORDED_RESULT_GAP_IS_DURABLE").toBe("recording_failed"); + // The gap names the call that still owed its record. + expect(JSON.parse(voyage.failure_cause??"{}"),"SAFETY_UNRECORDED_RESULT_NAMES_ITS_CALL").toMatchObject({site:"safetyEnd",turnId:"voyage",message:expect.stringContaining("Grep (toolu_sirens)")}); +}),60000); From 6e0c92bf06323264ebffe4bbaef090476fe2ee34 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 11:48:18 +0100 Subject: [PATCH 12/24] fix(ui-server): keep an allowed call owed until its result is recorded, and discharge it with that record (#3812) A refusal proved a call never ran only until the backend let it run. A later permission request for the same Pi call id, rejected as a replay, refused for a stopped turn or denied, discharged the obligation of a call that had already run, and its chat ended normal and complete. Backends now tell the collector when they let a call run (the Pi dispatcher's allow, the Pi gate's pass, Claude's permission callback allow); from then on a refusal or a rejected begin() for that id discharges nothing, and only the call's recorded result does. An allow the collector can no longer note is refused instead. A result's last exposure now commits with its call's discharge in one transaction, so neither a collection's end nor a restart can find the record durable and the call still owed. A collection's end also waits, bounded, for a result record already under way: stopping a turn refuses new tools, never the record of one that ran. Co-Authored-By: Claude Opus 5.5 --- .../ui-backend-claude/src/permission-hooks.ts | 12 ++ .../tests/permission-wiring-units.test.ts | 25 ++- packages/ui-backend-pi/src/permission-gate.ts | 11 +- packages/ui-backend-pi/src/worker-rpc.ts | 17 +- .../tests/tools-permission.test.ts | 17 ++ .../ui-backend-pi/tests/worker-rpc.test.ts | 19 ++- packages/ui-sdk/src/server/backend.ts | 12 +- .../ui-server/src/governance/event-writes.ts | 41 ++++- .../src/governance/safety-collector.ts | 72 +++++++-- .../ui-server/src/governance/safety-queue.ts | 6 +- .../tests/safety-result-exits.test.ts | 148 +++++++++++++++++- 11 files changed, 340 insertions(+), 40 deletions(-) diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts index 2b1df57915..9f0aa51b26 100644 --- a/packages/ui-backend-claude/src/permission-hooks.ts +++ b/packages/ui-backend-claude/src/permission-hooks.ts @@ -671,9 +671,21 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick { if (toolUseId) await req.bridge.inputSafety?.refused?.(toolUseId).catch(() => {}); }; const decideToolUse = canUseToolFor(ctx); + // The callback's allow is the runtime's last gate: the call runs. Noted + // first, so no later deny for the same id discharges a call that may have + // run; one the host can no longer allow is denied instead. A PreToolUse + // hook's allow is no such gate, since a parallel hook's deny wins. const canUseTool: typeof decideToolUse = async (toolName, input, opts) => { const result = await decideToolUse(toolName, input, opts); if (result?.behavior === "deny") await refuse(opts.toolUseID); + else if (result?.behavior === "allow" && req.bridge.inputSafety?.allowed) { + try { await req.bridge.inputSafety.allowed(opts.toolUseID); } + catch (error) { + turnLock.releaseForTool(opts.toolUseID); + await refuse(opts.toolUseID); + return { behavior: "deny", message: error instanceof Error ? error.message : "Safety recording refused this call." }; + } + } return result; }; const mutatingHook = mutatingHookFor(ctx); diff --git a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts index 84f600c953..5210675829 100644 --- a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts +++ b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts @@ -119,17 +119,18 @@ describe("the extracted callbacks", () => { describe("refusals owe no result", () => { // A deny this backend returns is final: the runtime never runs the call, // so the host's collector stops waiting for its result (#3812). - function wiring(signal: AbortSignal) { - const refused: string[] = []; + function wiring(signal: AbortSignal, unnoted?: string) { + const refused: string[] = [], allowed: string[] = [], released: string[] = []; const { canUseTool, hooks } = createPermissionWiring({ req: { prompt: "Count the suitors in the hall", signal, bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "allow" }), - inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); } } } } as never, + inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, + allowed: async (id: string) => { if (id === unnoted) throw new Error("Safety operation was refused or not admitted; the call does not run"); allowed.push(id); } } } } as never, allowedTools: ["Read"], confirmPatterns: [], brainPath: "/srv/odysseus-brain", - turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool() {} } as never, childEnv: {}, log: () => {}, + turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool(id: string) { released.push(id); } } as never, childEnv: {}, log: () => {}, }); const preToolUse = hooks!.PreToolUse!.find(group => !group.matcher)!.hooks[0]!; - return { canUseTool: canUseTool!, preToolUse, refused }; + return { canUseTool: canUseTool!, preToolUse, refused, allowed, released }; } test("a call the backend denies tells the collector it never runs", async () => { @@ -144,9 +145,21 @@ describe("refusals owe no result", () => { test("a call the backend lets run stays owed", async () => { const live = new AbortController(); - const { canUseTool, preToolUse, refused } = wiring(live.signal); + const { canUseTool, preToolUse, refused, allowed } = wiring(live.signal); expect((await canUseTool("Glob", { pattern: "ithaca/*.md" }, { toolUseID: "oar-1", signal: live.signal } as never))?.behavior).toBe("allow"); await preToolUse(...hookCall("Read", { file_path: "/srv/odysseus-brain/notes/ithaca.md" })); expect(refused, "CLAUDE_ALLOW_LEAVES_THE_CALL_OWED").toEqual([]); + // The callback's allow is the runtime's last gate, so it is noted before + // the call runs: no later deny for the same id can discharge it (#3812). + expect(allowed, "CLAUDE_CALLBACK_ALLOW_IS_NOTED").toEqual(["oar-1"]); + }); + + test("a callback allow the collector cannot note is denied instead", async () => { + const live = new AbortController(); + const { canUseTool, refused, released } = wiring(live.signal, "oar-1"); + const answer = await canUseTool("Glob", { pattern: "ithaca/*.md" }, { toolUseID: "oar-1", signal: live.signal } as never); + expect(answer, "CLAUDE_UNNOTED_ALLOW_IS_DENIED").toMatchObject({ behavior: "deny", message: expect.stringContaining("does not run") }); + expect(refused, "CLAUDE_UNNOTED_ALLOW_IS_REFUSED").toEqual(["oar-1"]); + expect(released, "CLAUDE_UNNOTED_ALLOW_RELEASES_ITS_LOCK").toContain("oar-1"); }); }); diff --git a/packages/ui-backend-pi/src/permission-gate.ts b/packages/ui-backend-pi/src/permission-gate.ts index c4ca0ad8af..0b1c6cf128 100644 --- a/packages/ui-backend-pi/src/permission-gate.ts +++ b/packages/ui-backend-pi/src/permission-gate.ts @@ -108,9 +108,16 @@ export function createPermissionGate(options: PermissionGateOptions): InlineExte name: "brain-permission-gate", factory: (pi) => { pi.on("tool_call", async (event) => { - const answer = await admit(event); + const answer = await admit(event), safety = turn.bridge?.inputSafety; // A blocked call never runs, so it owes no result record (#3812). - if (answer?.block) await turn.bridge?.inputSafety?.refused?.(event.toolCallId); + if (answer?.block) { await safety?.refused?.(event.toolCallId); return answer; } + // A call let through may run: from now on only its recorded result + // discharges it. One the host can no longer allow is blocked instead. + try { await safety?.allowed?.(event.toolCallId); } + catch (error) { + await safety?.refused?.(event.toolCallId); + return { block: true, reason: error instanceof Error ? error.message : "Safety recording refused this call." }; + } return answer; }); async function admit(event: ToolCallEvent): Promise { diff --git a/packages/ui-backend-pi/src/worker-rpc.ts b/packages/ui-backend-pi/src/worker-rpc.ts index f22b5102a9..cae0113504 100644 --- a/packages/ui-backend-pi/src/worker-rpc.ts +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -279,10 +279,21 @@ export function createPiWorkerRpcDispatcher(context: PiWorkerRpcContext): (msg: // collector leaves its chat a permanent gap instead (#3812). const result = msg.method === "safetyResult", safety = context.turn.bridge?.inputSafety; // Pi runs a call only on an "allow" answer: a denial or a rejection - // blocks it before it executes, so the call owes no result (#3812). - const permission = msg.method === "permission" && safety?.refused ? safety : undefined; + // blocks it before it executes, so the call owes no result (#3812). An + // allow is noted first, so a later denial, rejection, stopped turn or + // replay of a request for the same call cannot discharge a call that may + // have run; one the host can no longer allow is denied instead. + const permission = msg.method === "permission" && safety?.refused && safety.allowed ? safety : undefined; const refuse = (outcome: Promise): Promise => !permission ? outcome : outcome.then( - async answer => { if ((answer as { behavior?: string } | null)?.behavior !== "allow") await permission.refused!(msg.toolCallId); return answer; }, + async answer => { + if ((answer as { behavior?: string } | null)?.behavior !== "allow") { await permission.refused!(msg.toolCallId); return answer; } + try { await permission.allowed!(msg.toolCallId); return answer; } + catch (error) { + context.grants.delete(msg.toolCallId); + await permission.refused!(msg.toolCallId); + return { behavior: "deny", message: error instanceof Error ? error.message : "Safety recording refused this call." } as T; + } + }, async error => { await permission.refused!(msg.toolCallId); throw error; }); try { if (!result || !safety) context.live(); diff --git a/packages/ui-backend-pi/tests/tools-permission.test.ts b/packages/ui-backend-pi/tests/tools-permission.test.ts index 65251b1734..5daadb52a4 100644 --- a/packages/ui-backend-pi/tests/tools-permission.test.ts +++ b/packages/ui-backend-pi/tests/tools-permission.test.ts @@ -92,6 +92,23 @@ describe("tool_call permission gate", () => { expect(refused, "PI_GATE_BLOCK_REFUSES_THE_CALL").toEqual(["declined"]); }); + test("a call the gate lets through is noted before it runs, and one the collector cannot note is blocked", async () => { + // Noted, a later block for the same call cannot discharge one that may + // have run; not noted, it must not run at all (#3812). + const refused: string[] = [], allowed: string[] = []; + const turn = createTurnContext(); + const mock = makeMockBridge({ decision: { behavior: "allow" } }); + turn.bridge = { ...mock.bridge, inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, + refused: async (id: string) => { refused.push(id); }, + allowed: async (id: string) => { if (id === "unnoted") throw new Error("Safety operation was refused or not admitted; the call does not run"); allowed.push(id); } } }; + const handler = gateHandler({ turn, allowedTools: ALLOWED, confirmPatterns: CONFIRM }); + expect(await handler({ toolName: "write_file", toolCallId: "noted", input: { path: "a.md", content: "x" } }), "PI_GATE_NOTED_CALL_RUNS").toBeUndefined(); + expect(await handler({ toolName: "write_file", toolCallId: "unnoted", input: { path: "b.md", content: "y" } }), "PI_GATE_UNNOTED_CALL_IS_BLOCKED") + .toMatchObject({ block: true, reason: expect.stringContaining("does not run") }); + expect(allowed, "PI_GATE_ALLOW_IS_NOTED").toEqual(["noted"]); + expect(refused, "PI_GATE_UNNOTED_CALL_IS_REFUSED").toEqual(["unnoted"]); + }); + test("default brain_read_base executes in-process without an approval card", async () => { const brain = makeEmptyBrain(); try { diff --git a/packages/ui-backend-pi/tests/worker-rpc.test.ts b/packages/ui-backend-pi/tests/worker-rpc.test.ts index ed58081015..c5ae0b6d06 100644 --- a/packages/ui-backend-pi/tests/worker-rpc.test.ts +++ b/packages/ui-backend-pi/tests/worker-rpc.test.ts @@ -215,8 +215,9 @@ test("an unavailable collector notice awaits durable failure and carries no tool test("every permission answer but allow tells the collector the call never runs", async () => { // Pi runs a call only on "allow": a denial or a rejection blocks it before // it executes, so the call owes no result record (#3812). - const refused: string[] = []; - const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); } }; + const refused: string[] = [], allowed: string[] = []; + const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, + allowed: async (id: string) => { allowed.push(id); } }; const routed = harness({}, { applyBrain: async () => ({ ok: true }) as never, inputSafety }); expect(await routed.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-allowed"))).toEqual({ behavior: "allow" }); const unrouted = harness({}, { inputSafety }); @@ -227,4 +228,18 @@ test("every permission answer but allow tells the collector the call never runs" { applyBrain: async () => ({ ok: true }) as never, inputSafety }); await expect(stopped.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-stopped"))).rejects.toThrow("turn is inactive"); expect(refused, "PI_NON_ALLOW_PERMISSION_REFUSES_THE_CALL").toEqual(["call-denied", "call-stopped"]); + expect(allowed, "PI_ALLOWED_PERMISSION_IS_NOTED_BEFORE_IT_RUNS").toEqual(["call-allowed"]); +}); + +test("an allow the collector can no longer note is denied, and its grant withdrawn", async () => { + // A refusal already discharged this call's obligation: letting it run now + // would leave its result owed to nothing (#3812). + const refused: string[] = []; + const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, + allowed: async () => { throw new Error("Safety operation was refused or not admitted; the call does not run"); } }; + const { context, dispatch } = harness({}, { inputSafety }); + const answer = await dispatch(rpc("permission", "read_file", { path: "notes/ithaca.md" }, "call-refused")); + expect(answer, "PI_UNNOTED_ALLOW_IS_DENIED").toMatchObject({ behavior: "deny", message: expect.stringContaining("does not run") }); + expect(context.grants.has("call-refused"), "PI_UNNOTED_ALLOW_LEAVES_NO_GRANT").toBe(false); + expect(refused, "PI_UNNOTED_ALLOW_IS_REFUSED").toEqual(["call-refused"]); }); diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index d5fc3623d0..9abfc84a98 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -193,8 +193,18 @@ export interface BackendBridge { * Every call `begin` admits owes its `result` until one is recorded or * this says it never ran; still owed when the turn ends, it leaves the * turn's chat a permanent gap. Call it for every refusal the backend - * returns, before returning it. Never rejects. */ + * returns, before returning it. A refusal after `allowed` proves + * nothing about a call that may already have run, and discharges + * nothing. Never rejects. */ refused?(toolUseId: string): Promise; + /** @internal The backend lets this call run. From now on only its + * recorded `result` discharges it: a later refusal, a rejected `begin`, + * a stopped turn or a replayed request for the same id proves nothing + * about a call that may already have run. Call it before returning every + * allow; a backend that calls `refused` must call this too. Rejects when + * the call was refused or its admission did not complete; the backend + * then refuses the call instead. */ + allowed?(toolUseId: string): Promise; }; /** Validated, exact-base policy proposal; the server owns its explicit approval and write. */ proposePolicyChange?(requestId: string, input: import("../tool-contracts/policy.js").PolicyChangeInput): Promise; diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index cb76ab5cdc..daabef976b 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -62,8 +62,15 @@ export function setup(db: Database): WriteProcedures { try {const turnId=ensureSafetyEventCollection(db,row);reserveSafetyWrite(db,turnId,id,bytes,row.kind==="taint_exposure"?JSON.parse(row.payload).occurrenceId:undefined);} catch(error){if(!(error instanceof ChatRetiredError)&&!beforeDelivery)contain(error,row.turnId,"safetyReserve",row.sessionId);throw error;} }, - safetyCommit: (row:GovernanceEventRow,id:string) => { - try{return db.transaction(()=>{assertLive(db,[["session",row.sessionId]]);if(row.turnId&&db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(row.turnId))throw new ChatRetiredError();if(!db.query("SELECT 1 FROM safety_pending WHERE id=?").get(id))throw new SafetyUnavailable("Safety reservation absent");releaseSafetyWrite(db,id);return insertGovernanceEvent(db,row,true);}).immediate();} + // `discharge`: the obligation of the call whose result this row completes. + // It goes in the row's own transaction, so no end or restart finds the + // record durable and the call still owed (#3812). + safetyCommit: (row:GovernanceEventRow,id:string,discharge:string|null=null) => { + try{return db.transaction(()=>{assertLive(db,[["session",row.sessionId]]);if(row.turnId&&db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(row.turnId))throw new ChatRetiredError();if(!db.query("SELECT 1 FROM safety_pending WHERE id=?").get(id))throw new SafetyUnavailable("Safety reservation absent");releaseSafetyWrite(db,id); + const stored=insertGovernanceEvent(db,row,true); + if(discharge===null)return stored; + if(!row.turnId)throw new SafetyUnavailable("Safety discharge requires its turn"); + dischargeSafetyObligation(db,row.turnId,discharge);return {...stored,discharged:true};}).immediate();} catch(error){if(!(error instanceof ChatRetiredError))contain(error,row.turnId,"safetyCommit",row.sessionId);throw error;} }, bind: (turnId: string, sessionId: string) => bindTurnEvents(db, turnId, sessionId), @@ -90,6 +97,7 @@ export interface GovernanceWrites { /** The call's result is durably recorded, or the backend refused the call * and it never ran. A failure leaves the obligation, and so the gap. */ safetyDischarge(turnId:string,obligationId:string):Promise; + /** Ends the turn's collection once its result records under way settle. */ safetyEnd(turnId:string):Promise; /** Marks the turn's chat failed (`cause` is error text only); the brain only when that cannot commit. */ safetyFail(turnId:string,cause?:unknown):Promise; @@ -99,9 +107,11 @@ export interface GovernanceWrites { /** * Validates now, throwing `GovernanceEventError` as the synchronous writer * did; the returned promise settles once the row commits, or with the - * database failure. + * database failure. `discharge`: on a tool result's last record, the + * obligation of the call it completes, discharged in the same transaction; + * `discharged` confirms that it was (#3812). */ - record(input: GovernanceEventInput): Promise<{ id: number; recorded: boolean }>; + record(input: GovernanceEventInput, options?: { discharge?: string }): Promise<{ id: number; recorded: boolean; discharged?: boolean }>; /** Stores every distinct occurrence; only the exact host key deduplicates. Historical internal method name. */ /** `beforeDelivery`: a tool's input, recorded before the tool runs, which * the producer holds until this settles; a refused reservation delivered @@ -127,6 +137,11 @@ export interface GovernanceWrites { replaySteering(): Promise; } +/** How long a collection's end waits for its turn's result records under + * way. Each settles with its writes; the bound only keeps a stuck one from + * holding the turn's teardown. */ +const SAFETY_END_RECORD_WAIT_MS = 10_000; + /** The app side: every write commits on `writer` when there is one, else on `db` at once. */ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): GovernanceWrites { const invoke = procedureCaller(db, { url, setup }, undefined, writer); @@ -188,7 +203,7 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov if(scope==="brain"){scheduleSafetyRecovery(db);return;} retainedForBrain(turnId,error); }; - const record = (input: GovernanceEventInput, options: { beforeDelivery?: boolean } = {}): Promise<{ id: number; recorded: boolean }> => { + const record = (input: GovernanceEventInput, options: { beforeDelivery?: boolean; discharge?: string } = {}): Promise<{ id: number; recorded: boolean; discharged?: boolean }> => { const row = governanceEventRow(input); if (input.kind !== "taint" && input.kind !== "taint_exposure") return call("record", row); const restricted=covered(row.turnId); @@ -215,7 +230,7 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov notifySafetyChanged(db); const reservation=crypto.randomUUID();let reserved=false; const stored = call("safetyReserve",row,reservation,bytes,!!options.beforeDelivery) - .then(()=>{reserved=true;return call<{id:number;recorded:boolean}>("safetyCommit",row,reservation);}); + .then(()=>{reserved=true;return call<{id:number;recorded:boolean;discharged?:boolean}>("safetyCommit",row,reservation,options.discharge??null);}); return stored.catch(error => { if((error as {code?:string})?.code==="chat_retired")throw error; // Already permanently gapped before delivery: this loss changes nothing. @@ -261,7 +276,19 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov } }, safetyDischarge: (turnId,obligationId)=>call("safetyDischarge",turnId,obligationId), - safetyEnd: turnId=>call("safetyEnd",turnId,shared.unscopedLoss||shared.lostTurns.has(turnId)), + async safetyEnd(turnId){ + // A tool result's record already under way finishes first: stopping a + // turn refuses new tools, never the record of one that ran (#3812). + // Bounded: a record still unsettled then is refused by the end, and its + // chat keeps the gap. + const under=shared.recording.get(turnId); + if(under?.size){ + let timer:ReturnType|undefined; + await Promise.race([Promise.allSettled([...under]),new Promise(resolve=>{timer=setTimeout(resolve,SAFETY_END_RECORD_WAIT_MS);(timer as {unref?:()=>void}).unref?.();})]); + clearTimeout(timer); + } + await call("safetyEnd",turnId,shared.unscopedLoss||shared.lostTurns.has(turnId)); + }, safetyFail, safety: (turnId,sessionId)=>snapshot(()=>{ const projection=safetyProjection(db,turnId,sessionId); diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index 650bdf0b0c..173dd17d96 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -6,15 +6,23 @@ import { isMarkedUntrusted } from "../files/untrusted-marks.js"; import { occurrence } from "./occurrence.js"; import type { GovernanceWrites } from "./event-writes.js"; import { SafetyRecordingUnavailable } from "./safety-store.js"; +import { safetyQueue } from "./safety-queue.js"; export function createSafetyCollector(db:Database,writes:GovernanceWrites,options:{turnId:string;bindingId:string;backendId:string; sessionId:()=>string|null;actor?:"interactive"|"voice";brainPath?:string;shellProxied:()=>boolean;signal:AbortSignal;onReady?:()=>void;stop?:(error:Error)=>void;policyHash?:string|null}):NonNullable { // `admitted`: every input signal of its latest begin() is recorded, and the // call owes its result. A result for a call whose begin() failed partway // cannot be recorded faithfully. `owed`: its obligation is durable (#3812). - // `refused`: the backend refused the call, so it never runs. + // `refused`: the backend refused the call; unless it allowed it first, it + // never runs. type Operation={tool:string;inputHashes:Set;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string;owed:boolean;refused:boolean}; const operations=new Map(); + // Calls the backend let run. A refusal proves a call never ran only until + // the backend allowed it: from then on only its recorded result discharges + // it, whatever a later refusal, rejected begin(), stopped turn or replayed + // request for the same id says (#3812). Kept apart from `operations`: an + // allow may precede the begin() a parallel hook has not yet made. + const allowed=new Set(); const operation=(tool:string):Operation=>({tool,inputHashes:new Set(),id:crypto.randomUUID(),occurrences:[],done:false,admitted:false,signals:[],owed:false,refused:false}); const base=()=>({turnId:options.turnId,sessionId:options.sessionId(),actor:options.actor??"interactive" as const,model:null,profile:null}); const marked=(path:string)=>isMarkedUntrusted(db,path); @@ -41,7 +49,17 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(!op.owed)return; try{await writes.safetyDischarge(options.turnId,op.id);op.owed=false;}catch{/* Still owed: the end gaps it. */} }; + // Only a call the backend never let run may be discharged by its refusal. + const dischargeRefused=async(toolUseId:string,op:Operation)=>{if(!allowed.has(toolUseId))await discharge(op);}; const tails=new Map>();let queued=0; + // A result record under way, which the turn's end waits for (#3812). + const recording=(work:Promise):Promise=>{ + const records=safetyQueue(db).recording;let mine=records.get(options.turnId); + if(!mine)records.set(options.turnId,mine=new Set()); + const own=mine;own.add(work); + void work.finally(()=>{own.delete(work);if(!own.size&&records.get(options.turnId)===own)records.delete(options.turnId);}).catch(()=>{}); + return work; + }; const serial=(id:string,work:()=>Promise,afterFailure=false):Promise=>{ if(queued>=256)return fail(new Error("Safety collection queue capacity exceeded")); queued++; @@ -58,9 +76,11 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option // Every call begin() admits owes its result's record until that record is // durable or the backend refuses the call. A rejected begin() is such a // refusal: the backend awaits it before running the tool, and runs nothing - // on rejection. The obligation is the host's own record, so it holds - // whatever the runtime delivers: cancellation, abort, a result hook the - // runtime skips, or process death all leave the gap (#3812). + // on rejection. Once the backend allowed the call it may have run, so a + // rejected later begin() for it discharges nothing. The obligation is the + // host's own record, so it holds whatever the runtime delivers: + // cancellation, abort, a result hook the runtime skips, or process death + // all leave the gap (#3812). begin(toolUseId,tool,input){return serial(toolUseId,async()=>{ assertLive(); // Refused: the runtime never runs it, and refusing again is no failure. @@ -83,16 +103,18 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option op.admitted=true; assertLive(); }catch(error){ - // The backend refuses the call, so it never runs and owes nothing. - if(op)await discharge(op); + // The backend refuses the call: unless it already let it run, the + // call never runs and owes nothing. + if(op)await dischargeRefused(toolUseId,op); return fail(error,true); } });}, // A result already exists when it reaches the host, and the runtime may keep // it in its session. So nothing between the tool running and its record // may skip both: a stopped turn still records it (stopping refuses new - // tools, never a record), and any failure leaves its chat a permanent gap. - result(toolUseId,tool,output,finalized,segments){return serial(toolUseId,async()=>{ + // tools, never a record; the turn's end waits for a record under way), + // and any failure leaves its chat a permanent gap. + result(toolUseId,tool,output,finalized,segments){return recording(serial(toolUseId,async()=>{ try{ if(segments&&segments.length>256)throw new Error("Safety result segment capacity exceeded"); const op=operations.get(toolUseId);if(!op||op.tool!==tool||!op.admitted)throw new Error("Safety result has no admitted operation"); @@ -110,22 +132,40 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); } const state=finalized&&!['Bash','bash'].includes(tool)?"finalized":"interrupted_unknown"; - for(const id of op.occurrences)await writes.record({...base(),kind:"taint_exposure",dedupeKey:id,payload:{occurrenceId:id,state}}); + // The last exposure commits with the call's discharge, in one + // transaction: no end and no restart can find the record durable and + // the call still owed between them, and gap a recorded result. + for(const [index,id] of op.occurrences.entries()){ + const last=index===op.occurrences.length-1&&op.owed; + const stored=await writes.record({...base(),kind:"taint_exposure",dedupeKey:id,payload:{occurrenceId:id,state}},last?{discharge:op.id}:undefined); + if(last&&stored.discharged)op.owed=false; + } op.done=true;op.outputHash=outputHash; - // Recorded: the call owes nothing. A discharge that cannot commit stays - // owed, which only gaps the chat; it is no loss of this record. + // A result with nothing to record is recorded by its discharge alone. A + // discharge that cannot commit stays owed, which only gaps the chat; it + // is no loss of this record. await discharge(op); }catch(error){return fail(error);} - },true);}, - // The backend refused this call, which proves it never runs: it owes no - // result. Never rejects; an obligation it cannot discharge stays a gap. - // A later begin() for it is refused too, so a parallel hook cannot reopen it. + },true));}, + // The backend refused this call, which proves it never runs, unless the + // backend already let it run: then the refusal proves nothing, and only the + // call's recorded result discharges it. Never rejects; an obligation it + // cannot discharge stays a gap. A later begin() or allow for it is refused + // too, so a parallel hook or request cannot reopen it. refused(toolUseId){return serial(toolUseId,async()=>{ const op=operations.get(toolUseId); if(!op){if(operations.size<2000)operations.set(toolUseId,{...operation(""),refused:true});return;} op.refused=true; - if(!op.done)await discharge(op); + if(!op.done)await dischargeRefused(toolUseId,op); },true).catch(()=>{});}, + // The backend lets this call run. A call already refused, or whose latest + // begin() did not complete, must not: the backend refuses it instead. + allowed(toolUseId){return serial(toolUseId,async()=>{ + const op=operations.get(toolUseId); + if(op&&(op.refused||!op.admitted))throw new Error("Safety operation was refused or not admitted; the call does not run"); + if(!allowed.has(toolUseId)&&allowed.size>=2000)throw new Error("Safety allowance capacity exceeded; the call does not run"); + allowed.add(toolUseId); + },true);}, // A result the backend could not hand over (a refused or malformed report): // its chat keeps a permanent gap. Resolves once that gap is durable. async lost(toolUseId,tool,cause){ diff --git a/packages/ui-server/src/governance/safety-queue.ts b/packages/ui-server/src/governance/safety-queue.ts index c013e5c144..5114c982f6 100644 --- a/packages/ui-server/src/governance/safety-queue.ts +++ b/packages/ui-server/src/governance/safety-queue.ts @@ -7,10 +7,12 @@ const queues=new WeakMap;bytes:number;faile latchRevision:string|null; lostTurns:Set;unscopedLoss:boolean;listeners:Set<()=>void>;recovery:{timer:ReturnType|null;attempt:number}; /** First cause of a loss only this process holds, kept for the recovery audit. */ - lossCause:{errorClass:string;message:string;site:string;turnId:string|null;at:number;count:number}|null}>(); + lossCause:{errorClass:string;message:string;site:string;turnId:string|null;at:number;count:number}|null; + /** Each turn's tool-result records under way; its collection's end waits for them. */ + recording:Map>>}>(); export function safetyQueue(db:Database){ let queue=queues.get(db); - if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,latchRevision:null,lostTurns:new Set(),unscopedLoss:false,listeners:new Set(),recovery:{timer:null,attempt:0},lossCause:null};queues.set(db,queue);} + if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,latchRevision:null,lostTurns:new Set(),unscopedLoss:false,listeners:new Set(),recovery:{timer:null,attempt:0},lossCause:null,recording:new Map()};queues.set(db,queue);} return queue; } diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 20302be78d..7e3f96e3f2 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -18,6 +18,11 @@ import { createSafetyCollector } from "../src/governance/safety-collector"; import { safetyCatalogCreated } from "../src/governance/safety-store"; import { createPiWorkerRpcDispatcher, type PiWorkerRpc, type PiWorkerRpcContext } from "../../ui-backend-pi/src/worker-rpc"; import { installPiToolSafety } from "../../ui-backend-pi/src/tool-safety"; +import { createPermissionGate } from "../../ui-backend-pi/src/permission-gate"; +import { createBrainTools } from "../../ui-backend-pi/src/tools"; +import { createBrainAccess } from "../../ui-backend-pi/src/brain-access"; +import { createTurnContext } from "../../ui-backend-pi/src/turn-context"; +import { createPermissionWiring } from "../../ui-backend-claude/src/permission-hooks"; import { holdSafetyRecovery } from "./helpers/hold-safety-recovery"; /** A search that names a workspace note: only its result's record carries the taint. */ @@ -43,7 +48,9 @@ async function voyage() { const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, backendId: "pi", sessionId: () => "ithaca", brainPath: brain, shellProxied: () => false, signal: controller.signal, stop: error => controller.abort(error) }); await collector.ready("pi", 1); - return { db, writes, collector, controller, path: join(root, "ui.db"), + return { db, writes, collector, controller, brain, path: join(root, "ui.db"), + /** Resolves once the writer has applied every write sent before it. */ + idle: () => writer.idle(), failure: () => (db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get() as { failure: string | null }).failure, recorded: () => db.query(`SELECT r.detector FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.turn_id='voyage' AND r.kind='occurrence'`).all(), @@ -217,3 +224,142 @@ test("a call still owed when the host dies leaves its chat a permanent gap at bo expect(chat.coverage.epochs.find(epoch => epoch.reason === "recording_failed"), "SAFETY_OWED_AT_RESTART_IS_A_RECORDING_GAP").toBeDefined(); } finally { await writer.close(); db.close(); } }); + +/** The real curated search, run the way the worker runs it once the host allowed it. */ +async function searchRuns(f: Voyage, toolCallId: string, input: Record): Promise { + const grep = createBrainTools({ brain: createBrainAccess(f.brain), turn: createTurnContext(), exec: {}, + lock: { withKey: async (_key: string, run: () => Promise) => run() } } as never).find(tool => tool.name === "grep")!; + return JSON.stringify((await grep.execute(toolCallId, input as never, f.controller.signal, undefined, undefined as never)).content); +} + +/** What stands for a call that ran and was never reported: its obligation, then its chat's gap. */ +async function stillOwed(f: Voyage, call: string) { + // A search of a note records nothing before it runs: only the obligation is left. + expect(f.chat().unresolvedCount, "SAFETY_UNREPORTED_SEARCH_LEFT_NOTHING_ELSE").toBe(0); + expect(f.owed(), "SAFETY_LATER_REFUSAL_KEEPS_THE_OBLIGATION").toBe(1); + await f.writes.safetyEnd("voyage"); + expect(f.failure(), "SAFETY_ALLOWED_UNREPORTED_CALL_IS_A_DURABLE_GAP").toBe("recording_failed"); + expect(f.cause(), "SAFETY_ALLOWED_UNREPORTED_CALL_NAMES_ITS_CALL").toMatchObject({ site: "safetyEnd", message: expect.stringContaining(call) }); + expect(f.chat().restriction, "SAFETY_ALLOWED_UNREPORTED_CALL_RESTRICTS_ITS_CHAT").toBe("restricted"); + expect(f.chat().coverage.state, "SAFETY_ALLOWED_UNREPORTED_CALL_NEVER_LOOKS_COMPLETE").toBe("incomplete"); +} + +// A refusal proves a call never ran only until the backend let it run. A +// later request for the same call, refused for any reason, proves nothing +// about the search that already ran (#3812). +for (const later of ["replayed", "stopped", "denied", "unrecordable"] as const) test(`a Pi call allowed and run stays owed whatever a later request for it says: ${later}`, async () => { + const f = await voyage(); try { + const allowedTools = new Set(["grep"]); + const turn = { bridge: { inputSafety: f.collector, emit() {}, requestPermission: async () => ({ behavior: "deny", message: "Penelope declines the later request" }) }, + signal: f.controller.signal, enforceAllowedTools: false, noGrantSurface: false }; + const dispatch = createPiWorkerRpcDispatcher({ turn, grants: new Map(), allowedTools, confirmPatterns: [], admitTool() {}, autonomous: false, + live() { if (f.controller.signal.aborted) throw new Error("Pi worker RPC refused: turn is inactive, cancelled or revoked."); } } as unknown as PiWorkerRpcContext); + const ask = { type: "rpc", id: 1, method: "permission", toolName: "grep", toolCallId: "call_raft", input: { pattern: "sirens" } } as PiWorkerRpc; + expect(await dispatch(ask), "SAFETY_PI_CALL_IS_ALLOWED").toEqual({ behavior: "allow" }); + expect(f.owed(), "SAFETY_PI_ALLOWED_CALL_OWES_ITS_RESULT").toBe(1); + // The worker runs the search; its result never reaches the host. + expect(await searchRuns(f, ask.toolCallId, ask.input), "SAFETY_PI_ALLOWED_SEARCH_RAN").toContain("Sail past the sirens"); + if (later === "stopped") f.controller.abort(new Error("Odysseus stopped the turn")); + if (later === "denied") allowedTools.clear(); + // Re-requested with an input whose record is refused: its admission, a + // rejected begin(), fails before delivery and gaps nothing by itself. + if (later === "unrecordable") f.db.exec("CREATE TRIGGER refuse_input BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced input reservation failure'); END"); + const answer = await dispatch({ ...ask, id: later === "replayed" ? 1 : 2, ...(later === "unrecordable" ? { input: { pattern: "sirens", path: "workspaces/voyage" } } : {}) }) + .catch((error: Error) => error); + if (later === "unrecordable") f.db.exec("DROP TRIGGER refuse_input"); + if (later === "denied") expect(answer, "SAFETY_PI_LATER_REQUEST_IS_DENIED").toMatchObject({ behavior: "deny" }); + else expect((answer as Error).message, "SAFETY_PI_LATER_REQUEST_IS_REJECTED").toContain(later === "replayed" ? "Replayed pi worker RPC" : "inactive, cancelled or revoked"); + if (later === "unrecordable") expect(f.failure(), "SAFETY_PI_REFUSED_ADMISSION_GAPS_NOTHING_BY_ITSELF").toBeNull(); + await stillOwed(f, "grep (call_raft)"); + } finally { await f.close(); } +}); + +test("a Pi call the in-process gate let through stays owed when a later admission of it is blocked", async () => { + const f = await voyage(); try { + const turn = createTurnContext(); + turn.bridge = { inputSafety: f.collector, emit() {}, requestPermission: async () => ({ behavior: "allow" }) } as never; + turn.signal = f.controller.signal; + let admit: ((event: { toolName: string; toolCallId: string; input: unknown }) => Promise<{ block: boolean; reason?: string } | undefined>) | undefined; + createPermissionGate({ turn, allowedTools: new Set(["grep"]), confirmPatterns: [] }).factory({ on: (event: string, handler: unknown) => { if (event === "tool_call") admit = handler as typeof admit; } } as never); + const call = { toolName: "grep", toolCallId: "call_raft", input: { pattern: "sirens" } }; + expect(await admit!(call), "SAFETY_PI_GATE_LETS_THE_CALL_RUN").toBeUndefined(); + expect(await searchRuns(f, call.toolCallId, call.input), "SAFETY_PI_GATE_SEARCH_RAN").toContain("Sail past the sirens"); + f.controller.abort(new Error("Odysseus stopped the turn")); + expect(await admit!(call), "SAFETY_PI_GATE_BLOCKS_THE_LATER_ADMISSION").toMatchObject({ block: true }); + await stillOwed(f, "grep (call_raft)"); + } finally { await f.close(); } +}); + +test("a Claude call its callback allowed stays owed whatever a later admission of it says", async () => { + const f = await voyage(); try { + const wiring = createPermissionWiring({ req: { prompt: "Listen for the sirens.", signal: f.controller.signal, + bridge: { emit() {}, requestPermission: async () => ({ behavior: "allow" }), inputSafety: f.collector } } as never, + allowedTools: [], confirmPatterns: [], brainPath: f.brain, childEnv: { PATH: "/usr/bin:/bin" }, log() {}, + turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool() {} } as never }); + const input = { pattern: "sirens", path: f.brain, output_mode: "content" }, options = { toolUseID: "toolu_sirens", signal: new AbortController().signal } as never; + // The callback is the runtime's last gate: on its allow the search runs. + expect((await wiring.canUseTool!("Grep", input, options))?.behavior, "SAFETY_CLAUDE_CALLBACK_ALLOWS_THE_CALL").toBe("allow"); + expect(f.owed(), "SAFETY_CLAUDE_ALLOWED_CALL_OWES_ITS_RESULT").toBe(1); + // The turn stops before either result hook; the call is admitted again and denied. + f.controller.abort(new Error("Odysseus stopped the turn")); + const preToolUse = wiring.hooks!.PreToolUse!.find(group => !group.matcher)!.hooks[0]!; + const hooked = await preToolUse({ hook_event_name: "PreToolUse", tool_name: "Grep", tool_input: input, tool_use_id: "toolu_sirens" } as never, "toolu_sirens", { signal: new AbortController().signal }); + expect((hooked as { hookSpecificOutput?: { permissionDecision?: string } }).hookSpecificOutput?.permissionDecision, "SAFETY_CLAUDE_LATER_HOOK_DENIES").toBe("deny"); + expect((await wiring.canUseTool!("Grep", input, options))?.behavior, "SAFETY_CLAUDE_LATER_CALLBACK_DENIES").toBe("deny"); + await stillOwed(f, "Grep (toolu_sirens)"); + } finally { await f.close(); } +}); + +test("a result's last record discharges its call in the same commit, so a host dying after it owes nothing", async () => { + const f = await voyage(); let release = () => {}, reported: Promise | undefined, open = true; + try { + await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + let committed = () => {}; + const recorded = new Promise(resolve => { committed = resolve; }), hold = new Promise(resolve => { release = resolve; }); + // Hold the collector the moment the result's exposure has committed. + const record = f.writes.record; + f.writes.record = async (...args: Parameters) => { const stored = await record(...args); if (args[0].kind === "taint_exposure") { committed(); await hold; } return stored; }; + reported = refusal(f.collector.result("call_raft", "grep", SEARCH, true)); + await recorded; + expect(f.db.query("SELECT kind,state FROM safety_records ORDER BY rowid").all(), "SAFETY_RESULT_RECORD_IS_DURABLE").toContainEqual({ kind: "exposure", state: "finalized" }); + expect(f.owed(), "SAFETY_RECORDED_RESULT_IS_DISCHARGED_IN_ITS_OWN_COMMIT").toBe(0); + // The host dies here, before the collector returns. + await f.close(); open = false; + const db = createUiDb(f.path), writer = openSqliteWriter(db); + holdSafetyRecovery(db); + try { + const voyage = db.query("SELECT failure,failure_cause FROM safety_collections WHERE turn_id='voyage'").get() as { failure: string | null; failure_cause: string | null }; + expect(voyage, "SAFETY_RECORDED_RESULT_IS_NO_GAP_AT_BOOT").toEqual({ failure: null, failure_cause: null }); + expect(db.query("SELECT r.detector FROM safety_records r WHERE r.kind='occurrence'").all(), "SAFETY_RECORDED_RESULT_SURVIVES_RESTART").toEqual([{ detector: "tool_search_output" }]); + } finally { await writer.close(); db.close(); } + } finally { release(); await reported; if (open) await f.close(); } +}); + +test("a collection's end waits for a stopped turn's result record already under way", async () => { + const f = await voyage(); let release = () => {}, reported: Promise | undefined; + try { + await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + let reached = () => {}; + const midway = new Promise(resolve => { reached = resolve; }), hold = new Promise(resolve => { release = resolve; }); + // Hold the record halfway: its occurrence committed, its exposure not yet. + const record = f.writes.record; + f.writes.record = async (...args: Parameters) => { if (args[0].kind === "taint_exposure") { reached(); await hold; } return record(...args); }; + // Odysseus stops the turn as the result arrives; teardown then ends its collection. + f.controller.abort(new Error("Odysseus stopped the turn as the result arrived")); + reported = refusal(f.collector.result("call_raft", "grep", SEARCH, true)); + await midway; + const ending = f.writes.safetyEnd("voyage"); + // The writer applies its writes in order: had the end been sent, it is applied now. + await f.idle(); + expect(f.db.query("SELECT ended FROM safety_collections WHERE turn_id='voyage'").get(), "SAFETY_END_WAITS_FOR_A_RECORD_UNDER_WAY").toEqual({ ended: 0 }); + release(); + expect(await reported, "SAFETY_RECORD_UNDER_WAY_COMPLETES").toBeNull(); + await ending; + expect(f.db.query("SELECT ended FROM safety_collections WHERE turn_id='voyage'").get(), "SAFETY_END_FOLLOWS_THE_RECORD").toEqual({ ended: 1 }); + expect(f.recorded(), "SAFETY_STOPPED_TURN_RESULT_IS_RECORDED").toEqual([{ detector: "tool_search_output" }]); + // Recorded, so reviewable: the stop leaves no permanent gap of its own. + expect(f.failure(), "SAFETY_RECORD_UNDER_WAY_AT_THE_END_IS_NO_GAP").toBeNull(); + expect(f.chat().unresolvedCount, "SAFETY_RECORD_UNDER_WAY_AWAITS_REVIEW").toBe(1); + expect(f.chat().coverage.state, "SAFETY_RECORD_UNDER_WAY_KEEPS_COVERAGE").toBe("complete"); + } finally { release(); await reported; await f.close(); } +}); From b0f12a4c55c0101286098e9315867cf093ce0228 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 11:55:42 +0100 Subject: [PATCH 13/24] docs: say an allowed call stays owed until its result is recorded, and re-anchor citations into the files it touches (#3812) Co-Authored-By: Claude Opus 5.5 --- .changeset/3812-safety-recording-containment.md | 2 +- docs/decisions/async-collaboration.md | 4 ++-- docs/decisions/claude-2.1.287-compatibility.md | 2 +- docs/decisions/live-conversation.md | 2 +- docs/decisions/session-safety-reviews.md | 14 ++++++++++---- docs/decisions/voice-permission.md | 2 +- .../live-conversation-investigation.md | 4 ++-- docs/plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 4 ++-- docs/plans/chat-history-deletion.md | 2 +- 10 files changed, 22 insertions(+), 16 deletions(-) diff --git a/.changeset/3812-safety-recording-containment.md b/.changeset/3812-safety-recording-containment.md index a0ff208a15..8d63c377c3 100644 --- a/.changeset/3812-safety-recording-containment.md +++ b/.changeset/3812-safety-recording-containment.md @@ -7,7 +7,7 @@ A safety-recording failure now restricts only what it puts at risk, and the host recovers by itself (#3812, #3810). - **One turn, before delivery.** A failed safety begin, or a refused record of a tool's input before the tool runs, refuses only that turn with the new `SAFETY_RECORDING_UNAVAILABLE` error. The chat and the brain stay usable. When the refusal is for spent room, it says what to do: start a new chat (`safety_recording_chat_full`), or that retrying won't help (`safety_recording_brain_full`). Room that running turns or pending writes still hold is a plain retryable refusal. -- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails or whose report the host refuses: the runtime may already keep it in its session. Stopping a turn while a tool runs still records that tool's result. Every tool call the host admits owes its result's record until that record is written or the call is refused, so a call whose result never arrives (a turn stopped before the runtime reported it, or a server that died mid-tool) also leaves the gap. The chat keeps running under its tainted policy; other chats are untouched. +- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails or whose report the host refuses: the runtime may already keep it in its session. Stopping a turn while a tool runs still records that tool's result. Every tool call the host admits owes its result's record until that record is written or the call is refused, so a call whose result never arrives (a turn stopped before the runtime reported it, or a server that died mid-tool) also leaves the gap. Once the host has let a call run, only its recorded result settles it: a later refusal of the same call, such as a replayed or denied permission request, does not. A turn's end waits for a result record already under way, and a result's record and its settlement are written together. The chat keeps running under its tainted policy; other chats are untouched. - **The brain, only when the evidence store cannot take a scoped fact.** New turns still run, restricted, each with a permanent gap written before anything is sent. The server keeps retrying and clears the latch itself once the gaps are durable and every turn that predates the latch has ended, including one begun restricted under an earlier latch. A turn is refused only if even its restricted start cannot be written (`safety_recording_paused`). - **Boot** resolves a set latch and pending reservations automatically instead of refusing every turn. - **Diagnosable.** Each latch keeps its first cause and a count in the database, logs one structured line, and is shown to the owner as `safetyRecording` on `/api/status`, also while only the server process holds it (`cause.durable: false`). Errors are no longer all labelled `capacity`. Every recovery is recorded with who or what ran it. diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index 4d31f70758..d74e09da46 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:642`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:666`). These are permission primitives, +optional inputs are (`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:674`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:698`). These are permission primitives, not a claim of filesystem or network containment. The ordinary Claude assembly loads project settings and appends bridge tools @@ -85,7 +85,7 @@ is historical. Preserve subscription billing and the selected runtime identity. Pi disables built-in tools but currently loads resources and extensions (`createSessionResources`, `packages/ui-backend-pi/src/session-resources.ts:29-149`) and gates extension calls (`createPermissionGate`, -`packages/ui-backend-pi/src/permission-gate.ts:103-134`). Removing four curated +`packages/ui-backend-pi/src/permission-gate.ts:105-154`). Removing four curated tools cannot prove that extensions, MCP, scratch writers or in-process code have no egress or write access. Both first-party runtimes owe executable evidence; the plan's earlier “pi is easy” claim is not a containment result. diff --git a/docs/decisions/claude-2.1.287-compatibility.md b/docs/decisions/claude-2.1.287-compatibility.md index a1508c4272..618c970aba 100644 --- a/docs/decisions/claude-2.1.287-compatibility.md +++ b/docs/decisions/claude-2.1.287-compatibility.md @@ -126,7 +126,7 @@ The backend builds the actual turn options and production permission handlers The explicit ask lives in (`enforcementHookFor`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`) and is registered under enforcement in -(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:730-733`). +(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:742-745`). `scripts/measure-claude-enforcement.ts` runs `createClaudeBackend().startTurn()` and forwards to the SDK resolved from that backend. Its query wrapper only diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index 4cdebecd99..ff95643ed9 100644 --- a/docs/decisions/live-conversation.md +++ b/docs/decisions/live-conversation.md @@ -82,7 +82,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:784-827`); +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:816-872`); 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/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index a8769b2c84..8e4801d829 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -96,16 +96,22 @@ running under the tainted policy, not refusing. reservation still open when its collection ends becomes the same gap. Between a tool running and its result's record, nothing may skip both: a stopped turn still records the result (stopping refuses new tools, never a - record), a report the host refuses before its record (a malformed or + record, and a collection's end waits, bounded, for a record already under + way), a report the host refuses before its record (a malformed or replayed Pi report) and a result for a call whose input record failed both leave the gap. The host does not rely on the runtime to report a result: the Claude runtime dispatches neither result hook for a turn stopped while a tool runs, and still keeps that call in its session. So every call `begin()` admits is an obligation, recorded before the tool runs, until its result is durably recorded or the backend refuses the call (a refusal, or - a rejected `begin()`, proves it never ran). A collection that ends owing - one, however it ended, and an obligation still open at boot, leave the - same permanent gap. + a rejected `begin()`, proves it never ran). That proof holds only until + the backend lets the call run: the Pi dispatcher's allow, the Pi gate's + pass and the Claude permission callback's allow are noted before the call + runs, and from then on a later refusal, rejected `begin()`, stopped turn or + replayed request for the same call discharges nothing; only its recorded + result does. A result's last record and its discharge commit together. A + collection that ends owing one, however it ended, and an obligation still + open at boot, leave the same permanent gap. - **Evidence store unwritable** (the chat fact cannot commit): the brain latches through the emergency reserve, or, when even that fails, in the host process. New turns still begin, each with a permanent diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 79e694bba0..88d0544ddc 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -621,7 +621,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:642`) +(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:674`) — 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 91423df40e..08642c10fa 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:553-650`). +(`export interface StartTurnRequest`, `packages/ui-sdk/src/server/backend.ts:585-721`). 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:784-827`). +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:816-872`). 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 7623cc6016..e3b412701c 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:553-643`); ordinary Claude turns create an SDK session, emit + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:585-721`); 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 f1d94d0471..8d8a401701 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -144,7 +144,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. (`export function createClaudeSdkTurn(`, `packages/ui-backend-claude/src/sdk-options.ts:122-511`). Restricted execution needs narrower credentials/configuration; it does not start from the old full-host-env assumption. - **Pi resources and extension gate:** (`export function createSessionResources(`, `packages/ui-backend-pi/src/session-resources.ts:29-152`) and - (`export function createPermissionGate(`, `packages/ui-backend-pi/src/permission-gate.ts:103-134`). Built-ins are disabled, + (`export function createPermissionGate(`, `packages/ui-backend-pi/src/permission-gate.ts:105-154`). Built-ins are disabled, but ambient resources/extensions and in-process execution still need containment. - **Cost timing:** (`store.rollupRun(runId);`, `packages/ui-server/src/activity/recorder.ts:787`) settles after execution; (`export function sumEffectiveCost(`, `packages/ui-server/src/activity/store.ts:179-194`) explicitly counts unpriced runs. @@ -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:553-643`)) + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:585-721`)) - 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 38f4a08466..fb603a0098 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -148,7 +148,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:9-157`). `AgentBackend` exposes native list/read and read-only storage roots, not deletion -(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:765-808`). A storage root +(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:816-872`). 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 From 9e6802a2660328fb0d217691510e8b934b306b37 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 11:59:37 +0100 Subject: [PATCH 14/24] test(ui-server): resolve the Pi gate's extension factory the way its own tests do Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/safety-result-exits.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 7e3f96e3f2..ad3e0db852 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -280,7 +280,8 @@ test("a Pi call the in-process gate let through stays owed when a later admissio turn.bridge = { inputSafety: f.collector, emit() {}, requestPermission: async () => ({ behavior: "allow" }) } as never; turn.signal = f.controller.signal; let admit: ((event: { toolName: string; toolCallId: string; input: unknown }) => Promise<{ block: boolean; reason?: string } | undefined>) | undefined; - createPermissionGate({ turn, allowedTools: new Set(["grep"]), confirmPatterns: [] }).factory({ on: (event: string, handler: unknown) => { if (event === "tool_call") admit = handler as typeof admit; } } as never); + const gate = createPermissionGate({ turn, allowedTools: new Set(["grep"]), confirmPatterns: [] }); + (typeof gate === "function" ? gate : gate.factory)({ on: (event: string, handler: unknown) => { if (event === "tool_call") admit = handler as typeof admit; } } as never); const call = { toolName: "grep", toolCallId: "call_raft", input: { pattern: "sirens" } }; expect(await admit!(call), "SAFETY_PI_GATE_LETS_THE_CALL_RUN").toBeUndefined(); expect(await searchRuns(f, call.toolCallId, call.input), "SAFETY_PI_GATE_SEARCH_RAN").toContain("Sail past the sirens"); From 862316ac396c8e52c231f0f52c5fb35503de36f1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 13:04:42 +0100 Subject: [PATCH 15/24] docs(http-api): count the safety-recording recovery route among the declared endpoints (#3810) Co-Authored-By: Claude Opus 5.5 --- docs/http-api.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/http-api.md b/docs/http-api.md index b2d1a2b969..8983e6387b 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion and individual safety-review routes mounted by `createApp`: 179 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual safety-review and safety-recording recovery routes mounted by `createApp`: 180 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -213,7 +213,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 179 declared endpoints are mounted regardless of backend, renderer or +All 180 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. From a04ba5d2da26d3cbe9ae2c78ac049ff618965767 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 14:04:27 +0100 Subject: [PATCH 16/24] fix(ui-server): let only a recorded result settle an admitted call, and publish a Pi grant only after its last check (#3812) A refusal could still discharge an admitted call whose allow the backend never saw. The installed Claude runtime admits two calls under one tool-use id, and runs a bare `allowedTools` entry or a rewrite hook's allow without asking the permission callback. When the first of two Grep calls sharing an id ran and the turn was stopped, the second admission's denial discharged the first call's obligation. The chat then ended normal and complete with no gap. Once begin() has made a call's obligation durable, only that call's recorded result discharges it. No refusal does, whether a denial, a rejected later begin(), a stopped turn or a replayed request. A refusal now only refuses later admissions and allows under its id. A begin() rejected before its obligation is durable still owes nothing. This leaves a conservative gap for a call that was denied after its admission and never ran. That cost is accepted. The in-memory allow set is gone: allowed() is now only the collector's last check before a call runs. The Pi dispatcher published a document-base grant before that check resolved. A concurrent readBase could consume the grant while a refusal for the same id was turning the answer into a deny, and real file bytes were returned for a call that both permission answers denied. The grant is now published only after the check passes, followed by a recheck of liveness and standing admission, with no wait between the grant and the answer. Co-Authored-By: Claude Opus 5.5 --- .../3812-safety-recording-containment.md | 2 +- docs/decisions/session-safety-reviews.md | 28 ++++--- .../ui-backend-claude/src/permission-hooks.ts | 17 +++-- .../tests/permission-wiring-units.test.ts | 30 ++++---- packages/ui-backend-pi/src/permission-gate.ts | 8 +- packages/ui-backend-pi/src/worker-rpc.ts | 55 ++++++++------ .../tests/tools-permission.test.ts | 21 +++--- .../ui-backend-pi/tests/worker-rpc.test.ts | 21 +++--- packages/ui-sdk/src/server/backend.ts | 27 ++++--- .../ui-server/src/governance/event-writes.ts | 4 +- .../src/governance/safety-collector.ts | 66 +++++++--------- .../ui-server/src/governance/safety-store.ts | 11 +-- .../tests/safety-result-exits.test.ts | 75 +++++++++++++++---- .../tests/safety-result-retention.test.ts | 71 +++++++++++++++--- 14 files changed, 277 insertions(+), 159 deletions(-) diff --git a/.changeset/3812-safety-recording-containment.md b/.changeset/3812-safety-recording-containment.md index 8d63c377c3..c08deb4678 100644 --- a/.changeset/3812-safety-recording-containment.md +++ b/.changeset/3812-safety-recording-containment.md @@ -7,7 +7,7 @@ A safety-recording failure now restricts only what it puts at risk, and the host recovers by itself (#3812, #3810). - **One turn, before delivery.** A failed safety begin, or a refused record of a tool's input before the tool runs, refuses only that turn with the new `SAFETY_RECORDING_UNAVAILABLE` error. The chat and the brain stay usable. When the refusal is for spent room, it says what to do: start a new chat (`safety_recording_chat_full`), or that retrying won't help (`safety_recording_brain_full`). Room that running turns or pending writes still hold is a plain retryable refusal. -- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails or whose report the host refuses: the runtime may already keep it in its session. Stopping a turn while a tool runs still records that tool's result. Every tool call the host admits owes its result's record until that record is written or the call is refused, so a call whose result never arrives (a turn stopped before the runtime reported it, or a server that died mid-tool) also leaves the gap. Once the host has let a call run, only its recorded result settles it: a later refusal of the same call, such as a replayed or denied permission request, does not. A turn's end waits for a result record already under way, and a result's record and its settlement are written together. The chat keeps running under its tainted policy; other chats are untouched. +- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails or whose report the host refuses: the runtime may already keep it in its session. Stopping a turn while a tool runs still records that tool's result. Every tool call the host admits owes its result's record until that record is written, and nothing else settles it: no refusal proves that an admitted call never ran. So a call whose result never arrives (a turn stopped before the runtime reported it, or a server that died mid-tool) leaves the gap, and so does a call denied after its admission. A permission grant is never usable before the host's last check of the call has passed. A turn's end waits for a result record already under way, and a result's record and its settlement are written together. The chat keeps running under its tainted policy; other chats are untouched. - **The brain, only when the evidence store cannot take a scoped fact.** New turns still run, restricted, each with a permanent gap written before anything is sent. The server keeps retrying and clears the latch itself once the gaps are durable and every turn that predates the latch has ended, including one begun restricted under an earlier latch. A turn is refused only if even its restricted start cannot be written (`safety_recording_paused`). - **Boot** resolves a set latch and pending reservations automatically instead of refusing every turn. - **Diagnosable.** Each latch keeps its first cause and a count in the database, logs one structured line, and is shown to the owner as `safetyRecording` on `/api/status`, also while only the server process holds it (`cause.durable: false`). Errors are no longer all labelled `capacity`. Every recovery is recorded with who or what ran it. diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index 8e4801d829..4b9a369492 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -102,16 +102,24 @@ running under the tainted policy, not refusing. leave the gap. The host does not rely on the runtime to report a result: the Claude runtime dispatches neither result hook for a turn stopped while a tool runs, and still keeps that call in its session. So every call - `begin()` admits is an obligation, recorded before the tool runs, until its - result is durably recorded or the backend refuses the call (a refusal, or - a rejected `begin()`, proves it never ran). That proof holds only until - the backend lets the call run: the Pi dispatcher's allow, the Pi gate's - pass and the Claude permission callback's allow are noted before the call - runs, and from then on a later refusal, rejected `begin()`, stopped turn or - replayed request for the same call discharges nothing; only its recorded - result does. A result's last record and its discharge commit together. A - collection that ends owing one, however it ended, and an obligation still - open at boot, leave the same permanent gap. + `begin()` admits is an obligation, recorded before the tool runs, and only + its durably recorded result discharges it. No refusal does: not a denial, + a rejected later `begin()`, a stopped turn or a replayed request. The host + does not see every allow (the Claude runtime runs a bare `allowedTools` + entry, or a rewrite hook's allow, without asking), and the installed + Claude runtime admits two calls under one id, so a refusal never proves + that an admitted call did not run. A call denied after its admission + therefore also leaves the gap; that false gap is the accepted cost. Only a + `begin()` rejected before its obligation is durable owes nothing, since + the backend runs nothing on that rejection. A refusal still refuses every + later admission and allow under its id. Each backend's allow (the Pi + dispatcher's, the Pi gate's pass, the Claude permission callback's) is + checked by the collector before the call can run, and the Pi dispatcher + publishes a call's grant only after that check, so no concurrent request + can use a grant for a call the check then refuses. A result's last record + and its discharge commit together. A collection that ends owing one, + however it ended, and an obligation still open at boot, leave the same + permanent gap. - **Evidence store unwritable** (the chat fact cannot commit): the brain latches through the emergency reserve, or, when even that fails, in the host process. New turns still begin, each with a permanent diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts index 9f0aa51b26..d7823d4e62 100644 --- a/packages/ui-backend-claude/src/permission-hooks.ts +++ b/packages/ui-backend-claude/src/permission-hooks.ts @@ -666,15 +666,18 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick { if (toolUseId) await req.bridge.inputSafety?.refused?.(toolUseId).catch(() => {}); }; const decideToolUse = canUseToolFor(ctx); - // The callback's allow is the runtime's last gate: the call runs. Noted - // first, so no later deny for the same id discharges a call that may have - // run; one the host can no longer allow is denied instead. A PreToolUse - // hook's allow is no such gate, since a parallel hook's deny wins. + // The callback's allow is the runtime's last gate: the call runs. The + // collector checks it first; one it can no longer let run is denied + // instead. const canUseTool: typeof decideToolUse = async (toolName, input, opts) => { const result = await decideToolUse(toolName, input, opts); if (result?.behavior === "deny") await refuse(opts.toolUseID); diff --git a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts index 5210675829..9b6b0a879d 100644 --- a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts +++ b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts @@ -116,16 +116,18 @@ describe("the extracted callbacks", () => { }); }); -describe("refusals owe no result", () => { - // A deny this backend returns is final: the runtime never runs the call, - // so the host's collector stops waiting for its result (#3812). - function wiring(signal: AbortSignal, unnoted?: string) { +describe("refusals and the collector's last check", () => { + // Every deny this backend returns refuses the call's id at the host's + // collector, so nothing later under that id is admitted or let run. It + // discharges nothing: only a recorded result settles an admitted call + // (#3812). + function wiring(signal: AbortSignal, unchecked?: string) { const refused: string[] = [], allowed: string[] = [], released: string[] = []; const { canUseTool, hooks } = createPermissionWiring({ req: { prompt: "Count the suitors in the hall", signal, bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "allow" }), inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, - allowed: async (id: string) => { if (id === unnoted) throw new Error("Safety operation was refused or not admitted; the call does not run"); allowed.push(id); } } } } as never, + allowed: async (id: string) => { if (id === unchecked) throw new Error("Safety operation was refused or not admitted; the call does not run"); allowed.push(id); } } } } as never, allowedTools: ["Read"], confirmPatterns: [], brainPath: "/srv/odysseus-brain", turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool(id: string) { released.push(id); } } as never, childEnv: {}, log: () => {}, }); @@ -133,7 +135,7 @@ describe("refusals owe no result", () => { return { canUseTool: canUseTool!, preToolUse, refused, allowed, released }; } - test("a call the backend denies tells the collector it never runs", async () => { + test("a call the backend denies is refused at the collector", async () => { const stopped = new AbortController(); stopped.abort(); const { canUseTool, preToolUse, refused } = wiring(stopped.signal); expect((await canUseTool("Glob", { pattern: "ithaca/*.md" }, { toolUseID: "oar-1", signal: stopped.signal } as never))?.behavior).toBe("deny"); @@ -143,23 +145,23 @@ describe("refusals owe no result", () => { expect(refused, "CLAUDE_DENY_REFUSES_THE_CALL").toEqual(["oar-1", "oar-2"]); }); - test("a call the backend lets run stays owed", async () => { + test("a call the backend lets run is checked by the collector and never refused", async () => { const live = new AbortController(); const { canUseTool, preToolUse, refused, allowed } = wiring(live.signal); expect((await canUseTool("Glob", { pattern: "ithaca/*.md" }, { toolUseID: "oar-1", signal: live.signal } as never))?.behavior).toBe("allow"); await preToolUse(...hookCall("Read", { file_path: "/srv/odysseus-brain/notes/ithaca.md" })); expect(refused, "CLAUDE_ALLOW_LEAVES_THE_CALL_OWED").toEqual([]); - // The callback's allow is the runtime's last gate, so it is noted before - // the call runs: no later deny for the same id can discharge it (#3812). - expect(allowed, "CLAUDE_CALLBACK_ALLOW_IS_NOTED").toEqual(["oar-1"]); + // The callback's allow is the runtime's last gate, so the collector + // checks it before the call runs (#3812). + expect(allowed, "CLAUDE_CALLBACK_ALLOW_IS_CHECKED").toEqual(["oar-1"]); }); - test("a callback allow the collector cannot note is denied instead", async () => { + test("a callback allow the collector's check refuses is denied instead", async () => { const live = new AbortController(); const { canUseTool, refused, released } = wiring(live.signal, "oar-1"); const answer = await canUseTool("Glob", { pattern: "ithaca/*.md" }, { toolUseID: "oar-1", signal: live.signal } as never); - expect(answer, "CLAUDE_UNNOTED_ALLOW_IS_DENIED").toMatchObject({ behavior: "deny", message: expect.stringContaining("does not run") }); - expect(refused, "CLAUDE_UNNOTED_ALLOW_IS_REFUSED").toEqual(["oar-1"]); - expect(released, "CLAUDE_UNNOTED_ALLOW_RELEASES_ITS_LOCK").toContain("oar-1"); + expect(answer, "CLAUDE_UNCHECKED_ALLOW_IS_DENIED").toMatchObject({ behavior: "deny", message: expect.stringContaining("does not run") }); + expect(refused, "CLAUDE_UNCHECKED_ALLOW_IS_REFUSED").toEqual(["oar-1"]); + expect(released, "CLAUDE_UNCHECKED_ALLOW_RELEASES_ITS_LOCK").toContain("oar-1"); }); }); diff --git a/packages/ui-backend-pi/src/permission-gate.ts b/packages/ui-backend-pi/src/permission-gate.ts index 0b1c6cf128..00c1361186 100644 --- a/packages/ui-backend-pi/src/permission-gate.ts +++ b/packages/ui-backend-pi/src/permission-gate.ts @@ -109,10 +109,12 @@ export function createPermissionGate(options: PermissionGateOptions): InlineExte factory: (pi) => { pi.on("tool_call", async (event) => { const answer = await admit(event), safety = turn.bridge?.inputSafety; - // A blocked call never runs, so it owes no result record (#3812). + // A blocked call's id is refused at the collector, so nothing later + // under it is admitted or let through. That discharges nothing: only + // a recorded result settles a call `begin()` admitted (#3812). if (answer?.block) { await safety?.refused?.(event.toolCallId); return answer; } - // A call let through may run: from now on only its recorded result - // discharges it. One the host can no longer allow is blocked instead. + // The collector's last check before the call runs: one it can no + // longer let run is blocked instead. try { await safety?.allowed?.(event.toolCallId); } catch (error) { await safety?.refused?.(event.toolCallId); diff --git a/packages/ui-backend-pi/src/worker-rpc.ts b/packages/ui-backend-pi/src/worker-rpc.ts index cae0113504..44a6c30440 100644 --- a/packages/ui-backend-pi/src/worker-rpc.ts +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -146,18 +146,35 @@ async function permission(msg: PiWorkerRpc, bridge: BackendBridge, context: PiWo // Exact application authorization belongs to the server route. await bridge.inputSafety?.begin(msg.toolCallId,msg.toolName,msg.input); live(); - const unavailable = safetyAdmissionRefusal(bridge.admissionSafety); - if (unavailable) return { behavior: "deny", message: unavailable }; - return { behavior: "allow" }; + return permit(msg, bridge, context, { behavior: "allow" }, () => safetyAdmissionRefusal(bridge.admissionSafety)); } grants.delete(msg.toolCallId); const decision = await decidePiToolPermission({ turn: turnContext, allowedTools, confirmPatterns }, msg.toolName, msg.input, msg.toolCallId); live(); - if (decision.behavior === "allow") { - const stale = revalidatePiAdmission(turnContext, msg.toolName, msg.toolCallId, decision.updatedInput ?? msg.input); - if (stale) return { behavior: "deny", message: stale }; - } - if (decision.behavior === "allow") grants.set(msg.toolCallId, { name: msg.toolName, input: JSON.stringify(decision.updatedInput ?? msg.input) }); + if (decision.behavior !== "allow") return decision; + const input = decision.updatedInput ?? msg.input; + return permit(msg, bridge, context, decision, () => revalidatePiAdmission(turnContext, msg.toolName, msg.toolCallId, input), + { name: msg.toolName, input: JSON.stringify(input) }); +} + +/** + * Lets one decided call run. The collector's last check comes first; the + * turn's liveness and the call's standing admission are rechecked after it, + * and the grant is published last, with no wait between it and the answer. + * A grant is usable the moment it exists, by any concurrent RPC for the call + * (a document-base read, a bridge call, a lock, a file observation or a + * final admission), so one published before the collector's check could run + * a call that check then refuses (#3812). A refused check denies the call, + * a stopped turn rejects it, and neither publishes anything. + */ +async function permit(msg: PiWorkerRpc, bridge: BackendBridge, context: PiWorkerRpcContext, decision: unknown, + refusal: () => string | null, grant?: { name: string; input: string }): Promise { + try { await bridge.inputSafety?.allowed?.(msg.toolCallId); } + catch (error) { return { behavior: "deny", message: error instanceof Error ? error.message : "Safety recording refused this call." }; } + context.live(); + const refused = refusal(); + if (refused) return { behavior: "deny", message: refused }; + if (grant) context.grants.set(msg.toolCallId, grant); return decision; } @@ -278,21 +295,17 @@ export function createPiWorkerRpcDispatcher(context: PiWorkerRpcContext): (msg: // check refuses the worker. A report refused before it reaches the // collector leaves its chat a permanent gap instead (#3812). const result = msg.method === "safetyResult", safety = context.turn.bridge?.inputSafety; - // Pi runs a call only on an "allow" answer: a denial or a rejection - // blocks it before it executes, so the call owes no result (#3812). An - // allow is noted first, so a later denial, rejection, stopped turn or - // replay of a request for the same call cannot discharge a call that may - // have run; one the host can no longer allow is denied instead. - const permission = msg.method === "permission" && safety?.refused && safety.allowed ? safety : undefined; + // Pi runs a call only on an "allow" answer, which the permission handler + // gives only once the collector's last check passed (`permit`). Every + // other answer, and every rejection (a replay, a stopped turn), refuses + // the call's id at the collector, so no later request for it is admitted + // or let run. A refusal discharges nothing: it proves nothing about a + // call already admitted under that id (#3812). + const permission = msg.method === "permission" && safety?.refused ? safety : undefined; const refuse = (outcome: Promise): Promise => !permission ? outcome : outcome.then( async answer => { - if ((answer as { behavior?: string } | null)?.behavior !== "allow") { await permission.refused!(msg.toolCallId); return answer; } - try { await permission.allowed!(msg.toolCallId); return answer; } - catch (error) { - context.grants.delete(msg.toolCallId); - await permission.refused!(msg.toolCallId); - return { behavior: "deny", message: error instanceof Error ? error.message : "Safety recording refused this call." } as T; - } + if ((answer as { behavior?: string } | null)?.behavior !== "allow") await permission.refused!(msg.toolCallId); + return answer; }, async error => { await permission.refused!(msg.toolCallId); throw error; }); try { diff --git a/packages/ui-backend-pi/tests/tools-permission.test.ts b/packages/ui-backend-pi/tests/tools-permission.test.ts index 5daadb52a4..2fe3457153 100644 --- a/packages/ui-backend-pi/tests/tools-permission.test.ts +++ b/packages/ui-backend-pi/tests/tools-permission.test.ts @@ -80,8 +80,9 @@ describe("approval policy (approvalReason)", () => { }); describe("tool_call permission gate", () => { - test("a call the gate blocks tells the collector it never runs", async () => { - // A blocked call never executes, so it owes no result record (#3812). + test("a call the gate blocks is refused at the collector", async () => { + // A blocked call's id is refused, so nothing later under it is admitted + // or let through; that discharges nothing (#3812). const refused: string[] = []; const turn = createTurnContext(); const mock = makeMockBridge({ decision: { behavior: "deny", message: "Penelope declines" } }); @@ -92,21 +93,21 @@ describe("tool_call permission gate", () => { expect(refused, "PI_GATE_BLOCK_REFUSES_THE_CALL").toEqual(["declined"]); }); - test("a call the gate lets through is noted before it runs, and one the collector cannot note is blocked", async () => { - // Noted, a later block for the same call cannot discharge one that may - // have run; not noted, it must not run at all (#3812). + test("a call the gate lets through is checked by the collector first, and one the check refuses is blocked", async () => { + // The collector's last check: a call whose id was refused, or whose + // latest admission did not complete, must not run at all (#3812). const refused: string[] = [], allowed: string[] = []; const turn = createTurnContext(); const mock = makeMockBridge({ decision: { behavior: "allow" } }); turn.bridge = { ...mock.bridge, inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, - allowed: async (id: string) => { if (id === "unnoted") throw new Error("Safety operation was refused or not admitted; the call does not run"); allowed.push(id); } } }; + allowed: async (id: string) => { if (id === "unchecked") throw new Error("Safety operation was refused or not admitted; the call does not run"); allowed.push(id); } } }; const handler = gateHandler({ turn, allowedTools: ALLOWED, confirmPatterns: CONFIRM }); - expect(await handler({ toolName: "write_file", toolCallId: "noted", input: { path: "a.md", content: "x" } }), "PI_GATE_NOTED_CALL_RUNS").toBeUndefined(); - expect(await handler({ toolName: "write_file", toolCallId: "unnoted", input: { path: "b.md", content: "y" } }), "PI_GATE_UNNOTED_CALL_IS_BLOCKED") + expect(await handler({ toolName: "write_file", toolCallId: "checked", input: { path: "a.md", content: "x" } }), "PI_GATE_CHECKED_CALL_RUNS").toBeUndefined(); + expect(await handler({ toolName: "write_file", toolCallId: "unchecked", input: { path: "b.md", content: "y" } }), "PI_GATE_REFUSED_CHECK_BLOCKS_THE_CALL") .toMatchObject({ block: true, reason: expect.stringContaining("does not run") }); - expect(allowed, "PI_GATE_ALLOW_IS_NOTED").toEqual(["noted"]); - expect(refused, "PI_GATE_UNNOTED_CALL_IS_REFUSED").toEqual(["unnoted"]); + expect(allowed, "PI_GATE_ALLOW_IS_CHECKED").toEqual(["checked"]); + expect(refused, "PI_GATE_BLOCKED_CALL_IS_REFUSED").toEqual(["unchecked"]); }); test("default brain_read_base executes in-process without an approval card", async () => { diff --git a/packages/ui-backend-pi/tests/worker-rpc.test.ts b/packages/ui-backend-pi/tests/worker-rpc.test.ts index c5ae0b6d06..014cdaea00 100644 --- a/packages/ui-backend-pi/tests/worker-rpc.test.ts +++ b/packages/ui-backend-pi/tests/worker-rpc.test.ts @@ -212,9 +212,10 @@ test("an unavailable collector notice awaits durable failure and carries no tool expect(called).toBe(1);release();expect(String(await result)).toContain("Unqualified Pi input transformations"); }); -test("every permission answer but allow tells the collector the call never runs", async () => { - // Pi runs a call only on "allow": a denial or a rejection blocks it before - // it executes, so the call owes no result record (#3812). +test("every permission answer but allow refuses the call at the collector, and an allow is checked first", async () => { + // Pi runs a call only on "allow". A denial or a rejection refuses the + // call's id, so nothing later under it is admitted or let run; that + // discharges nothing (#3812). const refused: string[] = [], allowed: string[] = []; const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, allowed: async (id: string) => { allowed.push(id); } }; @@ -228,18 +229,18 @@ test("every permission answer but allow tells the collector the call never runs" { applyBrain: async () => ({ ok: true }) as never, inputSafety }); await expect(stopped.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-stopped"))).rejects.toThrow("turn is inactive"); expect(refused, "PI_NON_ALLOW_PERMISSION_REFUSES_THE_CALL").toEqual(["call-denied", "call-stopped"]); - expect(allowed, "PI_ALLOWED_PERMISSION_IS_NOTED_BEFORE_IT_RUNS").toEqual(["call-allowed"]); + expect(allowed, "PI_ALLOWED_PERMISSION_IS_CHECKED_BEFORE_IT_RUNS").toEqual(["call-allowed"]); }); -test("an allow the collector can no longer note is denied, and its grant withdrawn", async () => { - // A refusal already discharged this call's obligation: letting it run now - // would leave its result owed to nothing (#3812). +test("an allow the collector's last check refuses is denied, and its grant never published", async () => { + // The call's id was refused, or its latest admission did not complete: it + // must not run, and nothing it could use may exist (#3812). const refused: string[] = []; const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, allowed: async () => { throw new Error("Safety operation was refused or not admitted; the call does not run"); } }; const { context, dispatch } = harness({}, { inputSafety }); const answer = await dispatch(rpc("permission", "read_file", { path: "notes/ithaca.md" }, "call-refused")); - expect(answer, "PI_UNNOTED_ALLOW_IS_DENIED").toMatchObject({ behavior: "deny", message: expect.stringContaining("does not run") }); - expect(context.grants.has("call-refused"), "PI_UNNOTED_ALLOW_LEAVES_NO_GRANT").toBe(false); - expect(refused, "PI_UNNOTED_ALLOW_IS_REFUSED").toEqual(["call-refused"]); + expect(answer, "PI_UNCHECKED_ALLOW_IS_DENIED").toMatchObject({ behavior: "deny", message: expect.stringContaining("does not run") }); + expect(context.grants.has("call-refused"), "PI_UNCHECKED_ALLOW_LEAVES_NO_GRANT").toBe(false); + expect(refused, "PI_UNCHECKED_ALLOW_IS_REFUSED").toEqual(["call-refused"]); }); diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index 9abfc84a98..03af9e96e8 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -189,21 +189,20 @@ export interface BackendBridge { * could record it: the turn's chat keeps a permanent gap. Resolves once * that gap is durable. */ lost?(toolUseId: string, toolName: string, cause: unknown): Promise; - /** @internal The backend refused this call, so the runtime never runs it. - * Every call `begin` admits owes its `result` until one is recorded or - * this says it never ran; still owed when the turn ends, it leaves the - * turn's chat a permanent gap. Call it for every refusal the backend - * returns, before returning it. A refusal after `allowed` proves - * nothing about a call that may already have run, and discharges - * nothing. Never rejects. */ + /** @internal The backend refused a call with this id. Every call `begin` + * admits owes its `result` from then on, and only a recorded `result` + * discharges it; still owed when the turn ends, it leaves the turn's + * chat a permanent gap. A refusal discharges nothing, since it cannot + * prove that a call admitted under the same id did not run: it refuses + * every later `begin` and `allowed` for the id. Call it for every + * refusal the backend returns, before returning it. Never rejects. */ refused?(toolUseId: string): Promise; - /** @internal The backend lets this call run. From now on only its - * recorded `result` discharges it: a later refusal, a rejected `begin`, - * a stopped turn or a replayed request for the same id proves nothing - * about a call that may already have run. Call it before returning every - * allow; a backend that calls `refused` must call this too. Rejects when - * the call was refused or its admission did not complete; the backend - * then refuses the call instead. */ + /** @internal The backend's last check before it lets this call run. Call + * it before returning every allow, and hand out nothing the call could + * use (a grant, a capability) until it resolves; a backend that calls + * `refused` must call this too. Rejects when the call's id was refused + * or its latest `begin` did not complete; the backend then refuses the + * call instead. */ allowed?(toolUseId: string): Promise; }; /** Validated, exact-base policy proposal; the server owns its explicit approval and write. */ diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index daabef976b..f793a9c8d3 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -94,8 +94,8 @@ export interface GovernanceWrites { * `SafetyRecordingUnavailable`: the call has not run, and the backend * refuses it. */ safetyOblige(turnId:string,obligationId:string,toolUseId:string,tool:string):Promise; - /** The call's result is durably recorded, or the backend refused the call - * and it never ran. A failure leaves the obligation, and so the gap. */ + /** The call's result is durably recorded; nothing else discharges it, a + * refusal included. A failure leaves the obligation, and so the gap. */ safetyDischarge(turnId:string,obligationId:string):Promise; /** Ends the turn's collection once its result records under way settle. */ safetyEnd(turnId:string):Promise; diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index 173dd17d96..d48bd263d1 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -13,16 +13,10 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option // `admitted`: every input signal of its latest begin() is recorded, and the // call owes its result. A result for a call whose begin() failed partway // cannot be recorded faithfully. `owed`: its obligation is durable (#3812). - // `refused`: the backend refused the call; unless it allowed it first, it - // never runs. + // `refused`: the backend refused a call with this id, so nothing more for + // that id is admitted or let run. type Operation={tool:string;inputHashes:Set;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string;owed:boolean;refused:boolean}; const operations=new Map(); - // Calls the backend let run. A refusal proves a call never ran only until - // the backend allowed it: from then on only its recorded result discharges - // it, whatever a later refusal, rejected begin(), stopped turn or replayed - // request for the same id says (#3812). Kept apart from `operations`: an - // allow may precede the begin() a parallel hook has not yet made. - const allowed=new Set(); const operation=(tool:string):Operation=>({tool,inputHashes:new Set(),id:crypto.randomUUID(),occurrences:[],done:false,admitted:false,signals:[],owed:false,refused:false}); const base=()=>({turnId:options.turnId,sessionId:options.sessionId(),actor:options.actor??"interactive" as const,model:null,profile:null}); const marked=(path:string)=>isMarkedUntrusted(db,path); @@ -43,14 +37,12 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(failures.length>1)throw new AggregateError(failures,`Safety input refused: ${String(error)}`); throw error; }; - // A call that never runs owes nothing. A discharge that cannot commit - // leaves the obligation, and so its chat's gap when the collection ends. + // Only a recorded result discharges an obligation. A discharge that cannot + // commit leaves it, and so its chat's gap when the collection ends. const discharge=async(op:Operation)=>{ if(!op.owed)return; try{await writes.safetyDischarge(options.turnId,op.id);op.owed=false;}catch{/* Still owed: the end gaps it. */} }; - // Only a call the backend never let run may be discharged by its refusal. - const dischargeRefused=async(toolUseId:string,op:Operation)=>{if(!allowed.has(toolUseId))await discharge(op);}; const tails=new Map>();let queued=0; // A result record under way, which the turn's end waits for (#3812). const recording=(work:Promise):Promise=>{ @@ -73,24 +65,28 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option return { async ready(backend,version){assertLive();await writes.safetyReady(options.turnId,backend,version);options.onReady?.();}, async unavailable(){return fail(new Error("Input collection is not qualified for this runtime configuration"));}, - // Every call begin() admits owes its result's record until that record is - // durable or the backend refuses the call. A rejected begin() is such a - // refusal: the backend awaits it before running the tool, and runs nothing - // on rejection. Once the backend allowed the call it may have run, so a - // rejected later begin() for it discharges nothing. The obligation is the - // host's own record, so it holds whatever the runtime delivers: + // Every call begin() admits owes its result's record from the moment its + // obligation is durable, and only that record discharges it (#3812). No + // refusal does, not even a rejected later begin() for the same id: the + // host does not see every allow (the Claude runtime runs a bare + // `allowedTools` entry, or a rewrite hook's allow, without asking), and a + // runtime can admit two calls under one id, so no refusal proves an + // admitted call did not run. A call refused before it ran therefore still + // gaps its chat; that false gap is the accepted cost. A begin() rejected + // before its obligation is durable owes nothing: the backend awaits it + // before running the tool, and runs nothing on rejection. The obligation is + // the host's own record, so it holds whatever the runtime delivers: // cancellation, abort, a result hook the runtime skips, or process death - // all leave the gap (#3812). + // all leave the gap. begin(toolUseId,tool,input){return serial(toolUseId,async()=>{ assertLive(); // Refused: the runtime never runs it, and refusing again is no failure. if(operations.get(toolUseId)?.refused)throw new Error("Safety operation was refused; the call does not run"); - let op:Operation|undefined; try{ const inputHash=hash(JSON.stringify(input)),previous=operations.get(toolUseId); if(previous&&(previous.tool!==tool||previous.done))throw new Error("Safety operation identity already completed or changed tool"); if(!previous&&operations.size>=2000)throw new Error("Safety tool operation capacity exceeded"); - op=previous??operation(tool); + const op=previous??operation(tool); if(!op.inputHashes.has(inputHash)&&op.inputHashes.size>=16)throw new Error("Safety input revision capacity exceeded"); op.inputHashes.add(inputHash);op.admitted=false;operations.set(toolUseId,op); for(const signal of inputTaintSignals(tool,input,options.brainPath,marked,options.shellProxied())){ @@ -102,12 +98,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(!op.owed){await writes.safetyOblige(options.turnId,op.id,toolUseId,tool);op.owed=true;} op.admitted=true; assertLive(); - }catch(error){ - // The backend refuses the call: unless it already let it run, the - // call never runs and owes nothing. - if(op)await dischargeRefused(toolUseId,op); - return fail(error,true); - } + }catch(error){return fail(error,true);} });}, // A result already exists when it reaches the host, and the runtime may keep // it in its session. So nothing between the tool running and its record @@ -147,24 +138,21 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option await discharge(op); }catch(error){return fail(error);} },true));}, - // The backend refused this call, which proves it never runs, unless the - // backend already let it run: then the refusal proves nothing, and only the - // call's recorded result discharges it. Never rejects; an obligation it - // cannot discharge stays a gap. A later begin() or allow for it is refused - // too, so a parallel hook or request cannot reopen it. + // The backend refused a call with this id. That proves nothing about a call + // already admitted under the id, so it discharges nothing; it refuses every + // later begin() and allow for the id, so a parallel hook or request cannot + // reopen it. Never rejects. refused(toolUseId){return serial(toolUseId,async()=>{ const op=operations.get(toolUseId); - if(!op){if(operations.size<2000)operations.set(toolUseId,{...operation(""),refused:true});return;} - op.refused=true; - if(!op.done)await dischargeRefused(toolUseId,op); + if(op)op.refused=true;else if(operations.size<2000)operations.set(toolUseId,{...operation(""),refused:true}); },true).catch(()=>{});}, - // The backend lets this call run. A call already refused, or whose latest - // begin() did not complete, must not: the backend refuses it instead. + // The backend's last check before it lets this call run. A call whose id + // was refused, or whose latest begin() did not complete, must not run: the + // backend refuses it instead, and hands out nothing the call could use + // until this resolves. allowed(toolUseId){return serial(toolUseId,async()=>{ const op=operations.get(toolUseId); if(op&&(op.refused||!op.admitted))throw new Error("Safety operation was refused or not admitted; the call does not run"); - if(!allowed.has(toolUseId)&&allowed.size>=2000)throw new Error("Safety allowance capacity exceeded; the call does not run"); - allowed.add(toolUseId); },true);}, // A result the backend could not hand over (a refused or malformed report): // its chat keeps a permanent gap. Resolves once that gap is durable. diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index 0c56af57a4..7c479d43d9 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -352,9 +352,10 @@ const OBLIGATIONS = 2048; const clipText=(text:string)=>clip(text.replace(/[\u0000-\u001f\u007f]/g," "),128); /** * A tool call admitted before it runs owes its result's record (#3812). It - * is owed until that record is durable, or until the backend refuses the - * call, which proves it never ran. Owing it is restrictive only: it needs no - * healthy recorder, only an open collection to gap if the result never comes. + * is owed until that record is durable; no refusal discharges it, since none + * proves an admitted call did not run. Owing it is restrictive only: it needs + * no healthy recorder, only an open collection to gap if the result never + * comes. */ export function openSafetyObligation(db:Database,turnId:string,id:string,toolUseId:string,tool:string,at=Date.now()):void { db.transaction(()=>{ @@ -368,8 +369,8 @@ export function openSafetyObligation(db:Database,turnId:string,id:string,toolUse db.query("INSERT INTO safety_obligations(id,collection_id,tool_use_id,tool,opened_at) VALUES(?,?,?,?,?)").run(id,c.id,clipText(toolUseId),clipText(tool),at); }).immediate(); } -/** Its result is durably recorded, or the call was refused and never ran. - * Once the collection ended the call's gap is already committed: nothing to do. */ +/** Its result is durably recorded. Once the collection ended the call's gap + * is already committed: nothing to do. */ export function dischargeSafetyObligation(db:Database,turnId:string,id:string):void { db.query("DELETE FROM safety_obligations WHERE id=? AND collection_id=(SELECT id FROM safety_collections WHERE turn_id=? AND ended=0)").run(id,turnId); } diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index ad3e0db852..d08a03324e 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -1,7 +1,7 @@ /** Every exit between a tool running and its result's record either records * the result or leaves its chat a permanent gap, in both backends (#3812). - * Every call `begin()` admits owes its result until the record is durable or - * the backend refuses the call; one still owed when its collection ends, or + * Every call `begin()` admits owes its result until the record is durable, + * and no refusal discharges it; one still owed when its collection ends, or * at boot, is a gap. The installed Claude runtime's replay of a stopped * turn's result, and its skipped result hooks, are proved in * `safety-result-retention.test.ts`; these drive the remaining exits against @@ -11,6 +11,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Agent } from "@earendil-works/pi-agent-core"; +import { createEffectiveSafety } from "../src/governance/effective-safety"; import { createUiDb } from "../src/db/client"; import { openSqliteWriter } from "../src/db/write-worker"; import { createGovernanceWrites } from "../src/governance/event-writes"; @@ -157,35 +158,43 @@ test("a call admitted and never reported leaves its chat a permanent gap when it } finally { await f.close(); } }); -test("a call the backend refuses owes nothing, and a recorded result discharges its call", async () => { +// No refusal proves an admitted call never ran: the Claude runtime runs a +// bare `allowedTools` entry without asking and admits two calls under one id +// (`safety-result-retention.test.ts`). So a call refused after its admission +// still gaps its chat; that false gap is the accepted cost (#3812). +test("a call refused after its admission stays owed, and only a recorded result discharges a call", async () => { const f = await voyage(); try { await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); await f.collector.begin("call_oar", "grep", { pattern: "oar" }); - // The gate refuses the first call after admitting it: it never runs. + // The gate refuses the first call after admitting it, with no allow seen. await f.collector.refused!("call_raft"); // A refused call stays refused: a parallel admission cannot reopen it. expect(String((await refusal(f.collector.begin("call_raft", "grep", { pattern: "sirens" })))?.message), "SAFETY_REFUSED_CALL_STAYS_REFUSED").toContain("refused"); expect(f.controller.signal.aborted, "SAFETY_REFUSED_CALL_DOES_NOT_STOP_ITS_TURN").toBe(false); await f.collector.result("call_oar", "grep", "", true); - expect(f.owed(), "SAFETY_REFUSED_AND_RECORDED_CALLS_OWE_NOTHING").toBe(0); + expect(f.db.query("SELECT tool_use_id FROM safety_obligations").all(), "SAFETY_REFUSAL_DISCHARGES_NOTHING_A_RESULT_DOES").toEqual([{ tool_use_id: "call_raft" }]); await f.writes.safetyEnd("voyage"); - expect(f.failure(), "SAFETY_REFUSED_CALL_LEAVES_NO_GAP").toBeNull(); - expect(f.chat().coverage.state, "SAFETY_DISCHARGED_CALLS_KEEP_COVERAGE").toBe("complete"); + expect(f.failure(), "SAFETY_REFUSED_ADMITTED_CALL_IS_A_DURABLE_GAP").toBe("recording_failed"); + expect(f.cause(), "SAFETY_REFUSED_ADMITTED_CALL_NAMES_ITS_CALL").toMatchObject({ site: "safetyEnd", message: expect.stringContaining("grep (call_raft)") }); + expect(f.chat().coverage.state, "SAFETY_REFUSED_ADMITTED_CALL_NEVER_LOOKS_COMPLETE").toBe("incomplete"); } finally { await f.close(); } }); -test("a call refused when its edited input cannot be recorded owes nothing", async () => { +test("a call refused when its edited input cannot be recorded stays owed from its first admission", async () => { const f = await voyage(); try { await f.collector.begin("call_aeolus", "WebFetch", { url: "https://example.com/aeolus" }); expect(f.owed(), "SAFETY_ADMITTED_FETCH_OWES_ITS_RESULT").toBe(1); // An approval edits the call; recording the edited input is refused, so - // the backend refuses the call, which never runs. + // the backend refuses the call. That later begin() proves nothing about + // the call its first admission let through. f.db.exec("CREATE TRIGGER refuse_input BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced input reservation failure'); END"); expect(await refusal(f.collector.begin("call_aeolus", "WebFetch", { url: "https://example.com/zephyr" })), "SAFETY_UNRECORDED_EDIT_REFUSES_THE_CALL").toBeInstanceOf(Error); f.db.exec("DROP TRIGGER refuse_input"); - expect(f.owed(), "SAFETY_REFUSED_EDIT_OWES_NOTHING").toBe(0); + // Refused before the edit could run: that refusal alone gaps nothing. + expect(f.failure(), "SAFETY_REFUSED_EDIT_GAPS_NOTHING_BY_ITSELF").toBeNull(); + expect(f.owed(), "SAFETY_REFUSED_EDIT_KEEPS_THE_FIRST_OBLIGATION").toBe(1); await f.writes.safetyEnd("voyage"); - expect(f.failure(), "SAFETY_REFUSED_EDIT_LEAVES_NO_GAP").toBeNull(); + expect(f.failure(), "SAFETY_REFUSED_EDIT_IS_A_DURABLE_GAP").toBe("recording_failed"); } finally { await f.close(); } }); @@ -244,8 +253,7 @@ async function stillOwed(f: Voyage, call: string) { expect(f.chat().coverage.state, "SAFETY_ALLOWED_UNREPORTED_CALL_NEVER_LOOKS_COMPLETE").toBe("incomplete"); } -// A refusal proves a call never ran only until the backend let it run. A -// later request for the same call, refused for any reason, proves nothing +// A later request for the same call, refused for any reason, proves nothing // about the search that already ran (#3812). for (const later of ["replayed", "stopped", "denied", "unrecordable"] as const) test(`a Pi call allowed and run stays owed whatever a later request for it says: ${later}`, async () => { const f = await voyage(); try { @@ -364,3 +372,44 @@ test("a collection's end waits for a stopped turn's result record already under expect(f.chat().coverage.state, "SAFETY_RECORD_UNDER_WAY_KEEPS_COVERAGE").toBe("complete"); } finally { release(); await reported; await f.close(); } }); + +// A Pi grant is usable the moment it exists, by any concurrent RPC for the +// call. So the dispatcher publishes it only after the collector's last check +// passed: a check that then refuses the call must find nothing used (#3812). +test("a Pi grant is unusable until the collector's last check passes, and a call refused at that check stays owed", async () => { + const f = await voyage(); let release = () => {}; + try { + mkdirSync(join(f.brain, "notes"), { recursive: true }); writeFileSync(join(f.brain, "notes/sirens.md"), "The sirens sing.\n"); + let read = 0, checking = () => {}; + const checked = new Promise(resolve => { checking = resolve; }), hold = new Promise(resolve => { release = resolve; }); + // Hold the collector's last check for the read, once it is reached. + const inputSafety = { ...f.collector, allowed: async (id: string) => { checking(); await hold; return f.collector.allowed!(id); } }; + const admissionSafety = createEffectiveSafety(f.db, { turnId: "voyage", sessionId: () => "ithaca", policyHash: null, writes: f.writes, authority: () => ({ current: true, epoch: "1" }) }); + const turn = { bridge: { inputSafety, admissionSafety, emit() {}, requestPermission: async () => ({ behavior: "deny", message: "Penelope declines the push" }), + readBrainBase: async (path: string) => { read++; return { content: await Bun.file(join(f.brain, path)).text() }; } }, + signal: f.controller.signal, enforceAllowedTools: false, noGrantSurface: false }; + const dispatch = createPiWorkerRpcDispatcher({ turn, grants: new Map(), allowedTools: new Set(["brain_read_base"]), confirmPatterns: [], admitTool() {}, autonomous: false, + live() { if (f.controller.signal.aborted) throw new Error("Pi worker RPC refused: turn is inactive, cancelled or revoked."); }, + executed: () => ({ name: "brain_read_base", host: false, lock: false, phases: new Set() }) } as unknown as PiWorkerRpcContext); + const ask = { type: "rpc", id: 1, method: "permission", toolName: "brain_read_base", toolCallId: "call_sirens", input: { path: "notes/sirens.md" } } as PiWorkerRpc; + // The allowlist lets the read through; only the collector's check remains. + const answer = dispatch(ask); + await checked; + expect(f.owed(), "SAFETY_PI_ADMITTED_READ_OWES_ITS_RESULT").toBe(1); + // The worker asks for the document before its answer has arrived. + const early = await refusal(dispatch({ ...ask, id: 2, method: "readBase" })); + expect(read, "SAFETY_PI_UNCHECKED_GRANT_NEVER_READS").toBe(0); + expect(String(early?.message), "SAFETY_PI_GRANT_IS_UNUSABLE_BEFORE_THE_LAST_CHECK").toContain("no matching server permission decision"); + // A concurrent request under the same id is denied, which refuses the id. + expect(await dispatch({ ...ask, id: 3, toolName: "bash", input: { command: "git push" } }), "SAFETY_PI_SAME_ID_REQUEST_IS_DENIED").toMatchObject({ behavior: "deny" }); + release(); + expect(await answer, "SAFETY_PI_REFUSED_ID_DENIES_THE_HELD_CALL").toMatchObject({ behavior: "deny" }); + expect(await refusal(dispatch({ ...ask, id: 4, method: "readBase" })), "SAFETY_PI_DENIED_CALL_LEAVES_NO_GRANT").toBeInstanceOf(Error); + expect(read, "SAFETY_PI_DENIED_CALL_NEVER_READS").toBe(0); + // Admitted, then refused: the refusal proves nothing, so the call stays owed. + expect(f.owed(), "SAFETY_PI_REFUSAL_KEEPS_THE_OBLIGATION").toBe(1); + await f.writes.safetyEnd("voyage"); + expect(f.failure(), "SAFETY_PI_REFUSED_ADMITTED_READ_IS_A_DURABLE_GAP").toBe("recording_failed"); + expect(f.chat().coverage.state, "SAFETY_PI_REFUSED_ADMITTED_READ_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + } finally { release(); await f.close(); } +}); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 46e30bedc7..70595d57bc 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -36,10 +36,23 @@ function installedRipgrep(root:string):string { /** `refused`: the result's reservation fails. `cancelled`: the turn is * stopped after the tool ran, just before its result is recorded. * `running`: the turn is stopped once the search has printed its matches but - * before its process exits, so the runtime dispatches neither result hook. */ -type Interruption="refused"|"cancelled"|"running"; + * before its process exits, so the runtime dispatches neither result hook. + * `duplicate`: the model sends the search twice under one id; the runtime + * admits both, and the second admission is denied once the first search has + * printed its matches, stopping the turn while that search runs. */ +type Interruption="refused"|"cancelled"|"running"|"duplicate"; +/** One model reply carrying each call as its own tool_use block. */ +function modelCalls(calls:{name:string;id:string;input:Record}[]):Response { + const events:unknown[]=[{type:"message_start",message:{id:"msg_ithaca",type:"message",role:"assistant",model:"claude-probe",content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:1,output_tokens:0}}}]; + calls.forEach((call,index)=>events.push( + {type:"content_block_start",index,content_block:{type:"tool_use",id:call.id,name:call.name,input:{}}}, + {type:"content_block_delta",index,delta:{type:"input_json_delta",partial_json:JSON.stringify(call.input)}}, + {type:"content_block_stop",index})); + events.push({type:"message_delta",delta:{stop_reason:"tool_use",stop_sequence:null},usage:{output_tokens:calls.length}},{type:"message_stop"}); + return new Response(events.map(event=>`event: ${(event as {type:string}).type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),{headers:{"content-type":"text/event-stream"}}); +} async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType;writes:ReturnType; - first:{results:number;failures:number;aborted:boolean};searched:boolean;replayed:string[]})=>void){ + first:{results:number;failures:number;aborted:boolean;admissions:number;refusals:number};searched:boolean;replayed:string[]})=>void){ const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); // A note: reading it records nothing before the tool runs, so only the // search output's own record stands between it and a complete chat. @@ -65,7 +78,9 @@ esac if(!Array.isArray(body.tools)||!body.tools.length)return nativeModelReply(); requests.push({turn,raw}); const first=turn===0&&requests.filter(r=>r.turn===0).length===1; - return nativeModelReply(first?{name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}}:undefined); + const search={name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}}; + if(first&&interruption==="duplicate")return modelCalls([search,search]); + return nativeModelReply(first?search:undefined); }}); async function voyage(turnId:string,sessionId:string|null,interrupt:boolean,resume?:string){ const controller=new AbortController(),bindingId=crypto.randomUUID(); @@ -76,7 +91,21 @@ esac } const collector=createSafetyCollector(db,writes,{turnId,bindingId,backendId:"claude",sessionId:()=>"ithaca",brainPath:brain,shellProxied:()=>false,signal:controller.signal,stop:error=>controller.abort(error)}); await collector.ready("claude",1); - const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:"allow"}),inputSafety:collector}},allowedTools:["Grep"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); + // Each admission the runtime makes passes the index wait first. Under a + // duplicate id the second waits until the first search has printed its + // matches, then Odysseus stops the turn and that admission is denied. + let admissions=0,refusals=0,refusal=()=>{}; + const refused=new Promise(resolve=>{refusal=resolve;}); + const awaitIndex=async()=>{ + if(!interrupt||interruption!=="duplicate"||++admissions<2)return; + const deadline=Date.now()+15000; + while(!existsSync(searched)&&Date.now()setTimeout(resolve,5)); + if(!existsSync(searched))throw new Error("The first search never ran"); + controller.abort(new Error("Odysseus stopped the turn while the first search ran")); + throw new Error("The second search under the same id is denied"); + }; + const inputSafety={...collector,refused:async(id:string)=>{await collector.refused!(id);refusals++;refusal();}}; + const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:"allow"}),inputSafety,awaitIndex}},allowedTools:["Grep"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); let results=0,failures=0; if(interrupt){ // The Grep result exists and the runtime holds it; only its record is at risk. @@ -95,17 +124,22 @@ esac const timer=setTimeout(()=>controller.abort(),20000); try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:["Grep"],...wiring,abortController:controller, ...(resume?{resume}:{}), - env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ + env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"||interruption==="duplicate"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; if("session_id" in message&&typeof message.session_id==="string")runtimeSession=message.session_id; }}catch{/* The interrupted turn is stopped. */} - finally{clearInterval(watching);clearTimeout(timer);db.exec("DROP TRIGGER IF EXISTS refuse_result");await writes.safetyEnd(turnId);} - return {results,failures,aborted:controller.signal.aborted}; + finally{ + clearInterval(watching);clearTimeout(timer);db.exec("DROP TRIGGER IF EXISTS refuse_result"); + // The denial lands before the turn's end, as it would once the hook returns. + if(interrupt&&interruption==="duplicate")await Promise.race([refused,new Promise(resolve=>setTimeout(resolve,2000))]); + await writes.safetyEnd(turnId); + } + return {results,failures,aborted:controller.signal.aborted,admissions,refusals}; } try{ const first=await voyage("voyage",null,true); expect(version,"SAFETY_ACTUAL_INSTALLED_RUNTIME").toBe(MEASURED_RUNTIME.claudeCode); - if(interruption==="running")expect(existsSync(searched),"SAFETY_ACTUAL_SEARCH_RAN").toBe(true); + if(interruption==="running"||interruption==="duplicate")expect(existsSync(searched),"SAFETY_ACTUAL_SEARCH_RAN").toBe(true); expect(first.aborted,"SAFETY_INTERRUPTED_RESULT_STOPS_ITS_TURN").toBe(true); expect(runtimeSession,"SAFETY_RUNTIME_SESSION_TO_RESUME").toBeDefined(); turn=1; @@ -118,7 +152,7 @@ esac .filter(block=>block.type==="tool_result"&&block.tool_use_id==="toolu_sirens").map(block=>typeof block.content==="string"?block.content:JSON.stringify(block.content)); expect(replayed.length,"SAFETY_RUNTIME_RESUMES_THE_INTERRUPTED_CALL").toBeGreaterThan(0); // The premise: interrupting the record did not keep the result out of the model's context. - if(interruption!=="running")expect(resumed.some(r=>r.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT").toBe(true); + if(interruption!=="running"&&interruption!=="duplicate")expect(resumed.some(r=>r.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT").toBe(true); check({db,writes,first,searched:existsSync(searched),replayed}); // Contained to its chat: the brain-wide recorder is untouched, and a // recovery has nothing to clear, so the chat stays restricted. @@ -168,3 +202,20 @@ test("a turn stopped while its search runs reaches neither result hook, and its // The gap names the call that still owed its record. expect(JSON.parse(voyage.failure_cause??"{}"),"SAFETY_UNRECORDED_RESULT_NAMES_ITS_CALL").toMatchObject({site:"safetyEnd",turnId:"voyage",message:expect.stringContaining("Grep (toolu_sirens)")}); }),60000); + +test("a denial under an id the runtime admitted twice cannot settle the search that already ran, so its chat keeps a permanent gap",()=>voyageHome("duplicate",({db,writes,first})=>{ + // The installed runtime admits the same tool_use id twice and runs the + // first search; its allow never reaches a callback, since `allowedTools` + // lists Grep bare. + expect(first.admissions,"SAFETY_RUNTIME_ADMITS_ONE_ID_TWICE").toBe(2); + expect(first.refusals,"SAFETY_SECOND_ADMISSION_IS_DENIED").toBeGreaterThan(0); + expect(first.results+first.failures,"SAFETY_RUNTIME_SKIPPED_BOTH_RESULT_HOOKS").toBe(0); + // The denial proves nothing about the search already running under that id. + const chat=writes.safety("homeward","ithaca"); + expect(chat.restriction,"SAFETY_DUPLICATE_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH").toBe("restricted"); + expect(chat.coverage.state,"SAFETY_DUPLICATE_DENIAL_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + expect(chat.coverage.epochs.find(e=>e.reason==="recording_failed"),"SAFETY_DUPLICATE_DENIAL_IS_A_RECORDING_GAP").toBeDefined(); + const voyage=db.query("SELECT failure,failure_cause FROM safety_collections WHERE turn_id='voyage'").get() as {failure:string|null;failure_cause:string|null}; + expect(voyage.failure,"SAFETY_DUPLICATE_DENIAL_GAP_IS_DURABLE").toBe("recording_failed"); + expect(JSON.parse(voyage.failure_cause??"{}"),"SAFETY_DUPLICATE_DENIAL_NAMES_ITS_CALL").toMatchObject({site:"safetyEnd",turnId:"voyage",message:expect.stringContaining("Grep (toolu_sirens)")}); +}),60000); From d088575c37ff484845caff38d2daebe80f49bfcc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 14:06:35 +0100 Subject: [PATCH 17/24] docs: re-anchor citations into the files this PR moves (#3812) Co-Authored-By: Claude Opus 5.5 --- docs/decisions/async-collaboration.md | 2 +- docs/decisions/claude-2.1.287-compatibility.md | 2 +- docs/decisions/claude-code-runtime.md | 4 ++-- docs/decisions/hardening.md | 2 +- docs/decisions/live-conversation.md | 2 +- docs/decisions/proportionate-containment.md | 2 +- docs/decisions/voice-permission.md | 2 +- docs/investigations/live-conversation-investigation.md | 4 ++-- docs/plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- docs/plans/reviewable-session-safety.md | 2 +- 12 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index d74e09da46..53dc14c7fc 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:674`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:698`). These are permission primitives, +optional inputs are (`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:673`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:697`). 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-2.1.287-compatibility.md b/docs/decisions/claude-2.1.287-compatibility.md index 618c970aba..71cab5da98 100644 --- a/docs/decisions/claude-2.1.287-compatibility.md +++ b/docs/decisions/claude-2.1.287-compatibility.md @@ -126,7 +126,7 @@ The backend builds the actual turn options and production permission handlers The explicit ask lives in (`enforcementHookFor`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`) and is registered under enforcement in -(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:742-745`). +(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:745-748`). `scripts/measure-claude-enforcement.ts` runs `createClaudeBackend().startTurn()` and forwards to the SDK resolved from that backend. Its query wrapper only diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 4d0203e9f6..ad72c2da95 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -268,9 +268,9 @@ than refuses on a mismatch.** first proof of that. - **Where it shows.** `/api/status`, which is behind the auth guard and already reports the source commit (`Operational status`, - `packages/ui-server/src/routes/health.ts:62-80`), and the run record. Not + `packages/ui-server/src/routes/health.ts:72-90`), and the run record. Not `/api/health`: it is public and deliberately carries no version - (`Public liveness probe`, `health.ts:15-17`). Not `brain doctor`: it runs on + (`Public liveness probe`, `health.ts:19-21`). Not `brain doctor`: it runs on the user's machine against a different binary. Why warn rather than refuse an unmeasured pair, given that what was measured is diff --git a/docs/decisions/hardening.md b/docs/decisions/hardening.md index d37237de94..d3c3ca86e2 100644 --- a/docs/decisions/hardening.md +++ b/docs/decisions/hardening.md @@ -146,7 +146,7 @@ instead, and treat 8 as the question it was answering. production (`adapter.adapt(msg)`, `packages/ui-backend-claude/src/turn-stream.ts:103`) and U33 changes frame consumption - (`handleServerMessage`, `packages/ui-react/src/ws-client/inbound.ts:187`), the + (`handleServerMessage`, `packages/ui-react/src/ws-client/inbound.ts:188`), the same symptom could come from either, so they are **0.34.0** (seam) and **0.34.1** (splits), each its own image. For the same reason the cron bin and emitters (U13/U14) ship as **0.33.0** with the denylist unchanged and the allowlist (U21) as diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index ff95643ed9..7771b8c45c 100644 --- a/docs/decisions/live-conversation.md +++ b/docs/decisions/live-conversation.md @@ -82,7 +82,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:816-872`); +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:815-871`); 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/proportionate-containment.md b/docs/decisions/proportionate-containment.md index b7a6b5b982..a53b22abec 100644 --- a/docs/decisions/proportionate-containment.md +++ b/docs/decisions/proportionate-containment.md @@ -15,7 +15,7 @@ whole brain (`latchSafety`, `packages/ui-server/src/governance/safety-store.ts:115-125`). From then on, turn admission threw for every chat, including new chats that had never seen untrusted input (`beginSafetyCollection`, -`packages/ui-server/src/governance/safety-store.ts:183-192`). The error that +`packages/ui-server/src/governance/safety-store.ts:193-202`). The error that set the flag was recorded as "capacity" while the store was at a fraction of a percent of its limits, and its real cause was never stored. The only way back was to stop the server and run `recoverSafetyRecording` from a script, a diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 88d0544ddc..c00a07f9cf 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -621,7 +621,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:674`) +(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:673`) — 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 08642c10fa..d1085b5387 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:585-721`). +(`export interface StartTurnRequest`, `packages/ui-sdk/src/server/backend.ts:584-720`). 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:816-872`). +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:815-871`). 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 e3b412701c..4059cc3433 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:585-721`); ordinary Claude turns create an SDK session, emit + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:584-720`); 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 8d8a401701..cf5dd87fca 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:585-721`)) + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:584-720`)) - 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 fb603a0098..aecfe7b5d4 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -148,7 +148,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:9-157`). `AgentBackend` exposes native list/read and read-only storage roots, not deletion -(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:816-872`). A storage root +(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:815-871`). 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 diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 2e8d10774e..1c30a016ea 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -25,7 +25,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. - Taint recording retains every independently observed signal and reads a durable revisioned aggregate, including pending/failure and explicit unknown coverage (`safetyProjection`, - `packages/ui-server/src/governance/safety-store.ts:357-362`). Legacy rows prove + `packages/ui-server/src/governance/safety-store.ts:415-420`). Legacy rows prove their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, From 5808ed44cdbbf4d739e6c564b6a8db4f6adc8555 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 15:35:16 +0100 Subject: [PATCH 18/24] fix(ui-server): let the host's denial of a call's only admission settle it, so a denied card leaves its chat normal (#3812) Holding every refusal as no proof gave every chat in which someone clicked Deny on a Claude permission card a permanent recording gap. That restricted the chat because its owner did the right thing, which is wider than the proportionate-containment rule allows. A refusal now discharges an admitted call's obligation only when all of these hold: - it is the backend's own denial before the call could run: a Claude permission callback deny or PreToolUse hook deny, or a Pi permission deny or gate block; - the runtime admitted a call under that id exactly once; - no allow was ever observed for that id. Anything else stays with the recorded result: a second admission of the id (the installed runtime's duplicate-id case), an allow followed by a refusal, a rejected request (a stopped turn, a replay), or an id whose admissions the backend never reported. Backends report each admission through a new internal `inputSafety.admitting(toolUseId)`, and say whether a refusal is their own denial (`refused(toolUseId, denied)`). Claude counts admissions per hook: each matching PreToolUse hook runs once per admission, so the highest per-hook count is the number of admissions, and a second admission is reported by whichever of its hooks starts first, before any of its waits or its begin(). Counting begin() calls would be wrong both ways: one admission records its input from several hooks, and the reviewer's second admission was denied before its begin(). Pi counts each permission request and each tool_call event. The counts and allows live in the turn's collector, not on the obligation row. An admission can be denied before any row exists, only that collector discharges its turn's obligations, and a restart gaps every open obligation whatever the counts say. Co-Authored-By: Claude Opus 5.5 --- .../3812-safety-recording-containment.md | 2 +- docs/decisions/session-safety-reviews.md | 49 +++++++----- .../ui-backend-claude/src/permission-hooks.ts | 38 ++++++--- .../tests/permission-wiring-units.test.ts | 41 +++++++--- packages/ui-backend-pi/src/permission-gate.ts | 17 ++-- packages/ui-backend-pi/src/worker-rpc.ts | 10 ++- .../tests/tools-permission.test.ts | 17 ++-- .../ui-backend-pi/tests/worker-rpc.test.ts | 23 +++--- packages/ui-sdk/src/server/backend.ts | 35 +++++--- .../src/governance/safety-collector.ts | 70 +++++++++++----- .../tests/safety-result-exits.test.ts | 80 ++++++++++++++----- .../tests/safety-result-retention.test.ts | 56 +++++++++---- 12 files changed, 302 insertions(+), 136 deletions(-) diff --git a/.changeset/3812-safety-recording-containment.md b/.changeset/3812-safety-recording-containment.md index c08deb4678..36231b2a97 100644 --- a/.changeset/3812-safety-recording-containment.md +++ b/.changeset/3812-safety-recording-containment.md @@ -7,7 +7,7 @@ A safety-recording failure now restricts only what it puts at risk, and the host recovers by itself (#3812, #3810). - **One turn, before delivery.** A failed safety begin, or a refused record of a tool's input before the tool runs, refuses only that turn with the new `SAFETY_RECORDING_UNAVAILABLE` error. The chat and the brain stay usable. When the refusal is for spent room, it says what to do: start a new chat (`safety_recording_chat_full`), or that retrying won't help (`safety_recording_brain_full`). Room that running turns or pending writes still hold is a plain retryable refusal. -- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails or whose report the host refuses: the runtime may already keep it in its session. Stopping a turn while a tool runs still records that tool's result. Every tool call the host admits owes its result's record until that record is written, and nothing else settles it: no refusal proves that an admitted call never ran. So a call whose result never arrives (a turn stopped before the runtime reported it, or a server that died mid-tool) leaves the gap, and so does a call denied after its admission. A permission grant is never usable before the host's last check of the call has passed. A turn's end waits for a result record already under way, and a result's record and its settlement are written together. The chat keeps running under its tainted policy; other chats are untouched. +- **One chat, after delivery.** Lost evidence marks only that chat with a permanent `recording_failed` gap. That includes a tool result whose record fails or whose report the host refuses: the runtime may already keep it in its session. Stopping a turn while a tool runs still records that tool's result. Every tool call the host admits owes its result's record until that record is written or the call is proved never to have run. Only one thing proves that: the host's own denial (for example a denied permission card) of the only call ever admitted under that id, with no allow before it. So a call whose result never arrives (a turn stopped before the runtime reported it, or a server that died mid-tool) leaves the gap, and so does a call refused any other way. A denied permission card leaves the chat as it was. A permission grant is never usable before the host's last check of the call has passed. A turn's end waits for a result record already under way, and a result's record and its settlement are written together. The chat keeps running under its tainted policy; other chats are untouched. - **The brain, only when the evidence store cannot take a scoped fact.** New turns still run, restricted, each with a permanent gap written before anything is sent. The server keeps retrying and clears the latch itself once the gaps are durable and every turn that predates the latch has ended, including one begun restricted under an earlier latch. A turn is refused only if even its restricted start cannot be written (`safety_recording_paused`). - **Boot** resolves a set latch and pending reservations automatically instead of refusing every turn. - **Diagnosable.** Each latch keeps its first cause and a count in the database, logs one structured line, and is shown to the owner as `safetyRecording` on `/api/status`, also while only the server process holds it (`cause.durable: false`). Errors are no longer all labelled `capacity`. Every recovery is recorded with who or what ran it. diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index 4b9a369492..672b13f2d7 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -102,24 +102,37 @@ running under the tainted policy, not refusing. leave the gap. The host does not rely on the runtime to report a result: the Claude runtime dispatches neither result hook for a turn stopped while a tool runs, and still keeps that call in its session. So every call - `begin()` admits is an obligation, recorded before the tool runs, and only - its durably recorded result discharges it. No refusal does: not a denial, - a rejected later `begin()`, a stopped turn or a replayed request. The host - does not see every allow (the Claude runtime runs a bare `allowedTools` - entry, or a rewrite hook's allow, without asking), and the installed - Claude runtime admits two calls under one id, so a refusal never proves - that an admitted call did not run. A call denied after its admission - therefore also leaves the gap; that false gap is the accepted cost. Only a - `begin()` rejected before its obligation is durable owes nothing, since - the backend runs nothing on that rejection. A refusal still refuses every - later admission and allow under its id. Each backend's allow (the Pi - dispatcher's, the Pi gate's pass, the Claude permission callback's) is - checked by the collector before the call can run, and the Pi dispatcher - publishes a call's grant only after that check, so no concurrent request - can use a grant for a call the check then refuses. A result's last record - and its discharge commit together. A collection that ends owing one, - however it ended, and an obligation still open at boot, leave the same - permanent gap. + `begin()` admits is an obligation, recorded before the tool runs. Its + durably recorded result discharges it. A refusal discharges it only when + it proves the call never ran, which needs all three of: + 1. it is the backend's own denial before the call could run: a Claude + permission callback deny (a denied permission card) or `PreToolUse` + hook deny, a Pi permission deny or gate block; + 2. it is the id's only admission: the runtime asked once to admit a call + under that id (each admission is counted before anything of it is + decided, whichever hook of it starts first); + 3. the backend never let a call under that id run. + + Anything else proves nothing, and only the recorded result discharges: + a second admission of the id (the installed Claude runtime admits two + calls under one id, and runs a bare `allowedTools` entry or a rewrite + hook's allow without asking), an allow followed by a refusal, a rejected + request (a stopped turn, a replayed Pi request), or an id whose + admissions the backend never reported. Such a call leaves the gap even + if it never ran. A rejected `begin()` discharges nothing by itself; the + denial the backend returns on it does. A `begin()` rejected before its + obligation is durable owes nothing. The counts and allows live in the + turn's collector, not on the obligation row: an admission can be denied + before any row exists, only that collector discharges, and a restart gaps + every open obligation. A refusal also refuses every later admission and + allow under its id. Each backend's allow (the Pi dispatcher's, the Pi + gate's pass, the Claude permission callback's) is checked by the + collector before the call can run, and the Pi dispatcher publishes a + call's grant only after that check, so no concurrent request can use a + grant for a call the check then refuses. A result's last record and its + discharge commit together. A collection that ends owing one, however it + ended, and an obligation still open at boot, leave the same permanent + gap. - **Evidence store unwritable** (the chat fact cannot commit): the brain latches through the emergency reserve, or, when even that fails, in the host process. New turns still begin, each with a permanent diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts index d7823d4e62..c56442d5d5 100644 --- a/packages/ui-backend-claude/src/permission-hooks.ts +++ b/packages/ui-backend-claude/src/permission-hooks.ts @@ -666,17 +666,32 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick { if (toolUseId) await req.bridge.inputSafety?.refused?.(toolUseId).catch(() => {}); }; + // Every deny this backend returns refuses the call's id at the collector, + // so no later admission or allow under it succeeds. It is the backend's own + // denial, before the call could run, so it discharges the call's result + // obligation when nothing else under the id could have run: the id's only + // admission, never allowed. The runtime admits two calls under one id, and + // runs a bare `allowedTools` entry or a rewrite hook's allow without asking, + // so a deny of a second admission proves nothing about the first (#3812). + const refuse = async (toolUseId: string | undefined) => { if (toolUseId) await req.bridge.inputSafety?.refused?.(toolUseId, true).catch(() => {}); }; + // The runtime dispatches every matching PreToolUse hook once per call it + // admits, all under that call's id. Each hook counts its own invocations + // per id, and the highest count is how many calls the runtime admitted + // under the id. So whichever hook of a second admission starts first + // reports it, before any of that admission's waits, decisions or begin(). + // Counting begin() calls instead would be wrong both ways: one admission + // records its input from several hooks, and a second admission can be + // denied before its begin() (#3812). + const admissions = new Map(); + const admit = (toolUseId: string, seen: Map) => { + const count = (seen.get(toolUseId) ?? 0) + 1; + seen.set(toolUseId, count); + if (count > (admissions.get(toolUseId) ?? 0)) { admissions.set(toolUseId, count); req.bridge.inputSafety?.admitting?.(toolUseId); } + }; const decideToolUse = canUseToolFor(ctx); // The callback's allow is the runtime's last gate: the call runs. The - // collector checks it first; one it can no longer let run is denied + // collector checks and notes it first, so no later deny under the id + // proves the call never ran; one it can no longer let run is denied // instead. const canUseTool: typeof decideToolUse = async (toolName, input, opts) => { const result = await decideToolUse(toolName, input, opts); @@ -696,12 +711,13 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick HookCallback = hook => async (...args) => { + const fence: (hook: HookCallback) => HookCallback = hook => { const seen = new Map(); return async (...args) => { + if (args[0].hook_event_name === "PreToolUse") admit(args[0].tool_use_id, seen); const output = await fenced(hook, args); if (args[0].hook_event_name === "PreToolUse" && "hookSpecificOutput" in output && output.hookSpecificOutput?.hookEventName === "PreToolUse" && output.hookSpecificOutput.permissionDecision === "deny") await refuse(args[0].tool_use_id); return output; - }; + }; }; async function fenced(hook: HookCallback, args: Parameters): Promise>> { let snapshot: AdmissionSafetySnapshot | undefined; let output: Awaited>; diff --git a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts index 9b6b0a879d..12b2493707 100644 --- a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts +++ b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts @@ -116,33 +116,35 @@ describe("the extracted callbacks", () => { }); }); -describe("refusals and the collector's last check", () => { - // Every deny this backend returns refuses the call's id at the host's - // collector, so nothing later under that id is admitted or let run. It - // discharges nothing: only a recorded result settles an admitted call - // (#3812). +describe("admissions, refusals and the collector's last check", () => { + // Every deny this backend returns is its own denial before the call could + // run, and refuses the call's id at the host's collector, so nothing later + // under that id is admitted or let run. The collector discharges the call + // on it only for the id's only admission, never allowed, so each admission + // the runtime makes is reported (#3812). function wiring(signal: AbortSignal, unchecked?: string) { - const refused: string[] = [], allowed: string[] = [], released: string[] = []; + const refused: [string, boolean | undefined][] = [], allowed: string[] = [], released: string[] = [], admitted: string[] = []; const { canUseTool, hooks } = createPermissionWiring({ req: { prompt: "Count the suitors in the hall", signal, bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "allow" }), - inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, + inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, admitting: (id: string) => { admitted.push(id); }, + refused: async (id: string, denied?: boolean) => { refused.push([id, denied]); }, allowed: async (id: string) => { if (id === unchecked) throw new Error("Safety operation was refused or not admitted; the call does not run"); allowed.push(id); } } } } as never, allowedTools: ["Read"], confirmPatterns: [], brainPath: "/srv/odysseus-brain", turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool(id: string) { released.push(id); } } as never, childEnv: {}, log: () => {}, }); const preToolUse = hooks!.PreToolUse!.find(group => !group.matcher)!.hooks[0]!; - return { canUseTool: canUseTool!, preToolUse, refused, allowed, released }; + return { canUseTool: canUseTool!, preToolUse, hooks: hooks!, refused, allowed, released, admitted }; } - test("a call the backend denies is refused at the collector", async () => { + test("a call the backend denies is refused at the collector as its own denial", async () => { const stopped = new AbortController(); stopped.abort(); const { canUseTool, preToolUse, refused } = wiring(stopped.signal); expect((await canUseTool("Glob", { pattern: "ithaca/*.md" }, { toolUseID: "oar-1", signal: stopped.signal } as never))?.behavior).toBe("deny"); const [input, , options] = hookCall("Grep", { pattern: "suitors" }); const output = await preToolUse({ ...(input as object), tool_use_id: "oar-2" } as never, "oar-2", options); expect((output as { hookSpecificOutput?: { permissionDecision?: string } }).hookSpecificOutput?.permissionDecision).toBe("deny"); - expect(refused, "CLAUDE_DENY_REFUSES_THE_CALL").toEqual(["oar-1", "oar-2"]); + expect(refused, "CLAUDE_DENY_REFUSES_THE_CALL").toEqual([["oar-1", true], ["oar-2", true]]); }); test("a call the backend lets run is checked by the collector and never refused", async () => { @@ -161,7 +163,24 @@ describe("refusals and the collector's last check", () => { const { canUseTool, refused, released } = wiring(live.signal, "oar-1"); const answer = await canUseTool("Glob", { pattern: "ithaca/*.md" }, { toolUseID: "oar-1", signal: live.signal } as never); expect(answer, "CLAUDE_UNCHECKED_ALLOW_IS_DENIED").toMatchObject({ behavior: "deny", message: expect.stringContaining("does not run") }); - expect(refused, "CLAUDE_UNCHECKED_ALLOW_IS_REFUSED").toEqual(["oar-1"]); + expect(refused, "CLAUDE_UNCHECKED_ALLOW_IS_REFUSED").toEqual([["oar-1", true]]); expect(released, "CLAUDE_UNCHECKED_ALLOW_RELEASES_ITS_LOCK").toContain("oar-1"); }); + + test("each admission the runtime makes is reported once, by whichever of its hooks starts first", async () => { + const live = new AbortController(); + const { hooks, admitted } = wiring(live.signal); + // A file write matches more than one PreToolUse hook; the runtime runs each once per admission. + const matching = hooks.PreToolUse!.filter(group => !group.matcher || new RegExp(group.matcher).test("Write")).map(group => group.hooks[0]!); + expect(matching.length, "CLAUDE_WRITE_PASSES_SEVERAL_HOOKS").toBeGreaterThan(1); + const call = [{ hook_event_name: "PreToolUse", tool_name: "Write", tool_input: { file_path: "/srv/odysseus-brain/notes/raft.md", content: "Sail at dawn." }, tool_use_id: "oar-3" } as never, + "oar-3", { signal: live.signal }] as const; + await Promise.all(matching.map(hook => hook(...call))); + expect(admitted, "CLAUDE_ONE_ADMISSION_IS_REPORTED_ONCE").toEqual(["oar-3"]); + // A second admission under the id: its first hook reports it before any wait of its own. + const second = matching[matching.length - 1]!(...call); + expect(admitted, "CLAUDE_SECOND_ADMISSION_IS_REPORTED_AT_ONCE").toEqual(["oar-3", "oar-3"]); + await Promise.all([second, ...matching.slice(0, -1).map(hook => hook(...call))]); + expect(admitted, "CLAUDE_SECOND_ADMISSION_IS_REPORTED_ONCE").toEqual(["oar-3", "oar-3"]); + }); }); diff --git a/packages/ui-backend-pi/src/permission-gate.ts b/packages/ui-backend-pi/src/permission-gate.ts index 00c1361186..e6cee9b4fc 100644 --- a/packages/ui-backend-pi/src/permission-gate.ts +++ b/packages/ui-backend-pi/src/permission-gate.ts @@ -108,16 +108,21 @@ export function createPermissionGate(options: PermissionGateOptions): InlineExte name: "brain-permission-gate", factory: (pi) => { pi.on("tool_call", async (event) => { - const answer = await admit(event), safety = turn.bridge?.inputSafety; - // A blocked call's id is refused at the collector, so nothing later - // under it is admitted or let through. That discharges nothing: only - // a recorded result settles a call `begin()` admitted (#3812). - if (answer?.block) { await safety?.refused?.(event.toolCallId); return answer; } + // Each tool_call event is one admission of its id, counted before + // anything is decided (#3812). + const safety = turn.bridge?.inputSafety; + safety?.admitting?.(event.toolCallId); + const answer = await admit(event); + // A block is this host's denial before the call runs. It refuses the + // id at the collector, so nothing later under it is admitted or let + // through, and for the id's only admission, never let through, it + // discharges the call's result obligation. + if (answer?.block) { await safety?.refused?.(event.toolCallId, true); return answer; } // The collector's last check before the call runs: one it can no // longer let run is blocked instead. try { await safety?.allowed?.(event.toolCallId); } catch (error) { - await safety?.refused?.(event.toolCallId); + await safety?.refused?.(event.toolCallId, true); return { block: true, reason: error instanceof Error ? error.message : "Safety recording refused this call." }; } return answer; diff --git a/packages/ui-backend-pi/src/worker-rpc.ts b/packages/ui-backend-pi/src/worker-rpc.ts index 44a6c30440..904869d3a7 100644 --- a/packages/ui-backend-pi/src/worker-rpc.ts +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -299,16 +299,20 @@ export function createPiWorkerRpcDispatcher(context: PiWorkerRpcContext): (msg: // gives only once the collector's last check passed (`permit`). Every // other answer, and every rejection (a replay, a stopped turn), refuses // the call's id at the collector, so no later request for it is admitted - // or let run. A refusal discharges nothing: it proves nothing about a - // call already admitted under that id (#3812). + // or let run. Each permission request is one admission of its id, counted + // before anything else, a replay included. Only a deny answer is this + // host's denial before the call could run: for the id's only admission, + // never allowed, it discharges the call's result obligation. A rejection + // proves nothing (#3812). const permission = msg.method === "permission" && safety?.refused ? safety : undefined; const refuse = (outcome: Promise): Promise => !permission ? outcome : outcome.then( async answer => { - if ((answer as { behavior?: string } | null)?.behavior !== "allow") await permission.refused!(msg.toolCallId); + if ((answer as { behavior?: string } | null)?.behavior !== "allow") await permission.refused!(msg.toolCallId, true); return answer; }, async error => { await permission.refused!(msg.toolCallId); throw error; }); try { + permission?.admitting?.(msg.toolCallId); if (!result || !safety) context.live(); if (msg.id <= lastRpcId) throw resultLoss(new Error("Replayed pi worker RPC")); lastRpcId = msg.id; diff --git a/packages/ui-backend-pi/tests/tools-permission.test.ts b/packages/ui-backend-pi/tests/tools-permission.test.ts index 2fe3457153..6ca30c795f 100644 --- a/packages/ui-backend-pi/tests/tools-permission.test.ts +++ b/packages/ui-backend-pi/tests/tools-permission.test.ts @@ -80,17 +80,20 @@ describe("approval policy (approvalReason)", () => { }); describe("tool_call permission gate", () => { - test("a call the gate blocks is refused at the collector", async () => { - // A blocked call's id is refused, so nothing later under it is admitted - // or let through; that discharges nothing (#3812). - const refused: string[] = []; + test("a call the gate blocks is refused at the collector as its own denial, and every tool_call is one admission", async () => { + // A block is the gate's own denial before the call runs: it refuses the + // id, and for the id's only admission, never let through, the collector + // discharges the call on it (#3812). + const refused: [string, boolean | undefined][] = [], admitted: string[] = []; const turn = createTurnContext(); const mock = makeMockBridge({ decision: { behavior: "deny", message: "Penelope declines" } }); - turn.bridge = { ...mock.bridge, inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); } } }; + turn.bridge = { ...mock.bridge, inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, + admitting: (id: string) => { admitted.push(id); }, refused: async (id: string, denied?: boolean) => { refused.push([id, denied]); } } }; const handler = gateHandler({ turn, allowedTools: ALLOWED, confirmPatterns: CONFIRM }); expect(await handler({ toolName: "write_file", toolCallId: "allowed", input: { path: "a.md", content: "x" } })).toBeUndefined(); expect(await handler({ toolName: "brain_archive", toolCallId: "declined", input: { path: "notes/suitors.md" } })).toMatchObject({ block: true }); - expect(refused, "PI_GATE_BLOCK_REFUSES_THE_CALL").toEqual(["declined"]); + expect(refused, "PI_GATE_BLOCK_REFUSES_THE_CALL").toEqual([["declined", true]]); + expect(admitted, "PI_GATE_EVERY_TOOL_CALL_IS_AN_ADMISSION").toEqual(["allowed", "declined"]); }); test("a call the gate lets through is checked by the collector first, and one the check refuses is blocked", async () => { @@ -100,7 +103,7 @@ describe("tool_call permission gate", () => { const turn = createTurnContext(); const mock = makeMockBridge({ decision: { behavior: "allow" } }); turn.bridge = { ...mock.bridge, inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, - refused: async (id: string) => { refused.push(id); }, + refused: async (id: string, denied?: boolean) => { if (denied) refused.push(id); }, allowed: async (id: string) => { if (id === "unchecked") throw new Error("Safety operation was refused or not admitted; the call does not run"); allowed.push(id); } } }; const handler = gateHandler({ turn, allowedTools: ALLOWED, confirmPatterns: CONFIRM }); expect(await handler({ toolName: "write_file", toolCallId: "checked", input: { path: "a.md", content: "x" } }), "PI_GATE_CHECKED_CALL_RUNS").toBeUndefined(); diff --git a/packages/ui-backend-pi/tests/worker-rpc.test.ts b/packages/ui-backend-pi/tests/worker-rpc.test.ts index 014cdaea00..a3f32fdead 100644 --- a/packages/ui-backend-pi/tests/worker-rpc.test.ts +++ b/packages/ui-backend-pi/tests/worker-rpc.test.ts @@ -214,11 +214,12 @@ test("an unavailable collector notice awaits durable failure and carries no tool test("every permission answer but allow refuses the call at the collector, and an allow is checked first", async () => { // Pi runs a call only on "allow". A denial or a rejection refuses the - // call's id, so nothing later under it is admitted or let run; that - // discharges nothing (#3812). - const refused: string[] = [], allowed: string[] = []; - const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, - allowed: async (id: string) => { allowed.push(id); } }; + // call's id, so nothing later under it is admitted or let run. Only a deny + // answer is the host's own denial, which can prove the call never ran; a + // rejection proves nothing. Every request is one admission (#3812). + const refused: [string, boolean | undefined][] = [], allowed: string[] = [], admitted: string[] = []; + const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, admitting: (id: string) => { admitted.push(id); }, + refused: async (id: string, denied?: boolean) => { refused.push([id, denied]); }, allowed: async (id: string) => { allowed.push(id); } }; const routed = harness({}, { applyBrain: async () => ({ ok: true }) as never, inputSafety }); expect(await routed.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-allowed"))).toEqual({ behavior: "allow" }); const unrouted = harness({}, { inputSafety }); @@ -228,19 +229,23 @@ test("every permission answer but allow refuses the call at the collector, and a const stopped = harness({ live: () => { if (++checks > 1) throw new Error("Pi worker RPC refused: turn is inactive, cancelled or revoked."); } }, { applyBrain: async () => ({ ok: true }) as never, inputSafety }); await expect(stopped.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-stopped"))).rejects.toThrow("turn is inactive"); - expect(refused, "PI_NON_ALLOW_PERMISSION_REFUSES_THE_CALL").toEqual(["call-denied", "call-stopped"]); + expect(refused, "PI_NON_ALLOW_PERMISSION_REFUSES_THE_CALL").toEqual([["call-denied", true], ["call-stopped", undefined]]); expect(allowed, "PI_ALLOWED_PERMISSION_IS_CHECKED_BEFORE_IT_RUNS").toEqual(["call-allowed"]); + // A later request in the stopped turn is an admission too, and only rejected. + await expect(stopped.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-stopped"))).rejects.toThrow(); + expect(admitted, "PI_EVERY_PERMISSION_REQUEST_IS_AN_ADMISSION").toEqual(["call-allowed", "call-denied", "call-stopped", "call-stopped"]); + expect(refused.at(-1), "PI_REJECTED_REQUEST_IS_NO_DENIAL").toEqual(["call-stopped", undefined]); }); test("an allow the collector's last check refuses is denied, and its grant never published", async () => { // The call's id was refused, or its latest admission did not complete: it // must not run, and nothing it could use may exist (#3812). - const refused: string[] = []; - const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string) => { refused.push(id); }, + const refused: [string, boolean | undefined][] = []; + const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, refused: async (id: string, denied?: boolean) => { refused.push([id, denied]); }, allowed: async () => { throw new Error("Safety operation was refused or not admitted; the call does not run"); } }; const { context, dispatch } = harness({}, { inputSafety }); const answer = await dispatch(rpc("permission", "read_file", { path: "notes/ithaca.md" }, "call-refused")); expect(answer, "PI_UNCHECKED_ALLOW_IS_DENIED").toMatchObject({ behavior: "deny", message: expect.stringContaining("does not run") }); expect(context.grants.has("call-refused"), "PI_UNCHECKED_ALLOW_LEAVES_NO_GRANT").toBe(false); - expect(refused, "PI_UNCHECKED_ALLOW_IS_REFUSED").toEqual(["call-refused"]); + expect(refused, "PI_UNCHECKED_ALLOW_IS_REFUSED").toEqual([["call-refused", true]]); }); diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index 03af9e96e8..ced614e5a2 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -189,20 +189,29 @@ export interface BackendBridge { * could record it: the turn's chat keeps a permanent gap. Resolves once * that gap is durable. */ lost?(toolUseId: string, toolName: string, cause: unknown): Promise; + /** @internal The runtime asks the backend to admit one call under this + * id. Call it once per admission, before the backend decides anything + * about it, however many gates (hooks, callbacks) that one admission + * passes through. A backend that calls `refused` must call this too. */ + admitting?(toolUseId: string): void; /** @internal The backend refused a call with this id. Every call `begin` - * admits owes its `result` from then on, and only a recorded `result` - * discharges it; still owed when the turn ends, it leaves the turn's - * chat a permanent gap. A refusal discharges nothing, since it cannot - * prove that a call admitted under the same id did not run: it refuses - * every later `begin` and `allowed` for the id. Call it for every - * refusal the backend returns, before returning it. Never rejects. */ - refused?(toolUseId: string): Promise; - /** @internal The backend's last check before it lets this call run. Call - * it before returning every allow, and hand out nothing the call could - * use (a grant, a capability) until it resolves; a backend that calls - * `refused` must call this too. Rejects when the call's id was refused - * or its latest `begin` did not complete; the backend then refuses the - * call instead. */ + * admits owes its `result` from then on; still owed when the turn ends, + * it leaves the turn's chat a permanent gap. A refusal discharges it only + * when it proves the call never ran: `denied` (the backend itself + * answered the admission with a deny before the call could run), for an + * id admitted exactly once and never `allowed`. Any other refusal (a + * rejected request, a second admission of the id, a refusal after an + * allow) leaves it to the recorded `result`. Every refusal refuses later + * `begin` and `allowed` calls for the id. Call it for every refusal the + * backend returns, before returning it. Never rejects. */ + refused?(toolUseId: string, denied?: boolean): Promise; + /** @internal The backend's last check before it lets this call run; from + * then on no refusal under the id discharges its call. Call it before + * returning every allow, and hand out nothing the call could use (a + * grant, a capability) until it resolves; a backend that calls `refused` + * must call this too. Rejects when the call's id was refused or its + * latest `begin` did not complete; the backend then refuses the call + * instead. */ allowed?(toolUseId: string): Promise; }; /** Validated, exact-base policy proposal; the server owns its explicit approval and write. */ diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index d48bd263d1..345cd253ef 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -17,6 +17,13 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option // that id is admitted or let run. type Operation={tool:string;inputHashes:Set;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string;owed:boolean;refused:boolean}; const operations=new Map(); + // What the backend reported about each id: how many times the runtime asked + // to admit a call under it, and whether the backend ever let one run. Kept + // in memory, apart from `operations` and the obligation rows: an admission + // can be denied before any begin(), so before any row exists (the reviewer's + // duplicate-id run), and only this collector discharges this turn's + // obligations; a restart gaps every open obligation whatever these say. + const calls=new Map(); const operation=(tool:string):Operation=>({tool,inputHashes:new Set(),id:crypto.randomUUID(),occurrences:[],done:false,admitted:false,signals:[],owed:false,refused:false}); const base=()=>({turnId:options.turnId,sessionId:options.sessionId(),actor:options.actor??"interactive" as const,model:null,profile:null}); const marked=(path:string)=>isMarkedUntrusted(db,path); @@ -37,8 +44,9 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(failures.length>1)throw new AggregateError(failures,`Safety input refused: ${String(error)}`); throw error; }; - // Only a recorded result discharges an obligation. A discharge that cannot - // commit leaves it, and so its chat's gap when the collection ends. + // A recorded result discharges an obligation, and so does a denial that + // proves the call never ran (`refused`). A discharge that cannot commit + // leaves it, and so its chat's gap when the collection ends. const discharge=async(op:Operation)=>{ if(!op.owed)return; try{await writes.safetyDischarge(options.turnId,op.id);op.owed=false;}catch{/* Still owed: the end gaps it. */} @@ -66,18 +74,14 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option async ready(backend,version){assertLive();await writes.safetyReady(options.turnId,backend,version);options.onReady?.();}, async unavailable(){return fail(new Error("Input collection is not qualified for this runtime configuration"));}, // Every call begin() admits owes its result's record from the moment its - // obligation is durable, and only that record discharges it (#3812). No - // refusal does, not even a rejected later begin() for the same id: the - // host does not see every allow (the Claude runtime runs a bare - // `allowedTools` entry, or a rewrite hook's allow, without asking), and a - // runtime can admit two calls under one id, so no refusal proves an - // admitted call did not run. A call refused before it ran therefore still - // gaps its chat; that false gap is the accepted cost. A begin() rejected - // before its obligation is durable owes nothing: the backend awaits it - // before running the tool, and runs nothing on rejection. The obligation is - // the host's own record, so it holds whatever the runtime delivers: - // cancellation, abort, a result hook the runtime skips, or process death - // all leave the gap. + // obligation is durable (#3812). Its recorded result discharges it, and so + // does the one refusal that proves it never ran (`refused`); a rejected + // begin() does not by itself, since the backend's denial that follows it + // is that refusal. A begin() rejected before its obligation is durable + // owes nothing: the backend awaits it before running the tool, and runs + // nothing on rejection. The obligation is the host's own record, so it + // holds whatever the runtime delivers: cancellation, abort, a result hook + // the runtime skips, or process death all leave the gap. begin(toolUseId,tool,input){return serial(toolUseId,async()=>{ assertLive(); // Refused: the runtime never runs it, and refusing again is no failure. @@ -138,21 +142,43 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option await discharge(op); }catch(error){return fail(error);} },true));}, - // The backend refused a call with this id. That proves nothing about a call - // already admitted under the id, so it discharges nothing; it refuses every - // later begin() and allow for the id, so a parallel hook or request cannot - // reopen it. Never rejects. - refused(toolUseId){return serial(toolUseId,async()=>{ - const op=operations.get(toolUseId); - if(op)op.refused=true;else if(operations.size<2000)operations.set(toolUseId,{...operation(""),refused:true}); + // The runtime asks to admit one call under this id. Counted at once, not + // queued: a refusal already queued for the id then sees the new admission + // and proves nothing. An id the collector cannot track keeps no count, so + // no refusal discharges it. + admitting(toolUseId){ + const call=calls.get(toolUseId); + if(call)call.admissions++;else if(calls.size<2000)calls.set(toolUseId,{admissions:1,allowed:false}); + }, + // The backend refused a call with this id; a later begin() or allow for the + // id is refused too, so a parallel hook or request cannot reopen it. The + // refusal proves the call never ran, and discharges its obligation, only + // when it is the backend's own denial (`denied`: a Claude permission + // callback or PreToolUse hook deny, a Pi permission deny or gate block), of + // the only admission ever made under the id, and the backend never let a + // call under it run. Anything else proves nothing and leaves the + // obligation to its recorded result: a second admission of the id (the + // Claude runtime admits two calls under one id), an allow followed by a + // refusal, a rejected request (a stopped turn, a replay). Never rejects. + refused(toolUseId,denied=false){return serial(toolUseId,async()=>{ + const op=operations.get(toolUseId),call=calls.get(toolUseId); + const proves=denied&&call?.admissions===1&&!call.allowed; + if(!op){if(operations.size<2000)operations.set(toolUseId,{...operation(""),refused:true});return;} + op.refused=true; + if(proves&&!op.done)await discharge(op); },true).catch(()=>{});}, - // The backend's last check before it lets this call run. A call whose id + // The backend's last check before it lets this call run, noted so that no + // later refusal under the id proves the call never ran. A call whose id // was refused, or whose latest begin() did not complete, must not run: the // backend refuses it instead, and hands out nothing the call could use // until this resolves. allowed(toolUseId){return serial(toolUseId,async()=>{ const op=operations.get(toolUseId); if(op&&(op.refused||!op.admitted))throw new Error("Safety operation was refused or not admitted; the call does not run"); + const call=calls.get(toolUseId); + if(call)call.allowed=true; + else if(calls.size<2000)calls.set(toolUseId,{admissions:0,allowed:true}); + else throw new Error("Safety allowance capacity exceeded; the call does not run"); },true);}, // A result the backend could not hand over (a refused or malformed report): // its chat keeps a permanent gap. Resolves once that gap is durable. diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index d08a03324e..77bb39d9f6 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -158,43 +158,81 @@ test("a call admitted and never reported leaves its chat a permanent gap when it } finally { await f.close(); } }); -// No refusal proves an admitted call never ran: the Claude runtime runs a -// bare `allowedTools` entry without asking and admits two calls under one id -// (`safety-result-retention.test.ts`). So a call refused after its admission -// still gaps its chat; that false gap is the accepted cost (#3812). -test("a call refused after its admission stays owed, and only a recorded result discharges a call", async () => { +test("a call the backend denies on its only admission owes nothing, and a recorded result discharges its call", async () => { const f = await voyage(); try { - await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); - await f.collector.begin("call_oar", "grep", { pattern: "oar" }); - // The gate refuses the first call after admitting it, with no allow seen. - await f.collector.refused!("call_raft"); + f.collector.admitting?.("call_raft"); await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + f.collector.admitting?.("call_oar"); await f.collector.begin("call_oar", "grep", { pattern: "oar" }); + // The gate denies the first call after admitting it: it never runs. + await f.collector.refused!("call_raft", true); // A refused call stays refused: a parallel admission cannot reopen it. expect(String((await refusal(f.collector.begin("call_raft", "grep", { pattern: "sirens" })))?.message), "SAFETY_REFUSED_CALL_STAYS_REFUSED").toContain("refused"); expect(f.controller.signal.aborted, "SAFETY_REFUSED_CALL_DOES_NOT_STOP_ITS_TURN").toBe(false); await f.collector.result("call_oar", "grep", "", true); - expect(f.db.query("SELECT tool_use_id FROM safety_obligations").all(), "SAFETY_REFUSAL_DISCHARGES_NOTHING_A_RESULT_DOES").toEqual([{ tool_use_id: "call_raft" }]); + expect(f.owed(), "SAFETY_REFUSED_AND_RECORDED_CALLS_OWE_NOTHING").toBe(0); await f.writes.safetyEnd("voyage"); - expect(f.failure(), "SAFETY_REFUSED_ADMITTED_CALL_IS_A_DURABLE_GAP").toBe("recording_failed"); - expect(f.cause(), "SAFETY_REFUSED_ADMITTED_CALL_NAMES_ITS_CALL").toMatchObject({ site: "safetyEnd", message: expect.stringContaining("grep (call_raft)") }); - expect(f.chat().coverage.state, "SAFETY_REFUSED_ADMITTED_CALL_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + expect(f.failure(), "SAFETY_REFUSED_CALL_LEAVES_NO_GAP").toBeNull(); + expect(f.chat().coverage.state, "SAFETY_DISCHARGED_CALLS_KEEP_COVERAGE").toBe("complete"); } finally { await f.close(); } }); -test("a call refused when its edited input cannot be recorded stays owed from its first admission", async () => { +test("a call refused when its edited input cannot be recorded owes nothing", async () => { const f = await voyage(); try { - await f.collector.begin("call_aeolus", "WebFetch", { url: "https://example.com/aeolus" }); + f.collector.admitting?.("call_aeolus"); await f.collector.begin("call_aeolus", "WebFetch", { url: "https://example.com/aeolus" }); expect(f.owed(), "SAFETY_ADMITTED_FETCH_OWES_ITS_RESULT").toBe(1); // An approval edits the call; recording the edited input is refused, so - // the backend refuses the call. That later begin() proves nothing about - // the call its first admission let through. + // the backend denies the call, which never runs. f.db.exec("CREATE TRIGGER refuse_input BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced input reservation failure'); END"); expect(await refusal(f.collector.begin("call_aeolus", "WebFetch", { url: "https://example.com/zephyr" })), "SAFETY_UNRECORDED_EDIT_REFUSES_THE_CALL").toBeInstanceOf(Error); f.db.exec("DROP TRIGGER refuse_input"); - // Refused before the edit could run: that refusal alone gaps nothing. - expect(f.failure(), "SAFETY_REFUSED_EDIT_GAPS_NOTHING_BY_ITSELF").toBeNull(); - expect(f.owed(), "SAFETY_REFUSED_EDIT_KEEPS_THE_FIRST_OBLIGATION").toBe(1); + await f.collector.refused!("call_aeolus", true); + expect(f.owed(), "SAFETY_REFUSED_EDIT_OWES_NOTHING").toBe(0); + await f.writes.safetyEnd("voyage"); + expect(f.failure(), "SAFETY_REFUSED_EDIT_LEAVES_NO_GAP").toBeNull(); + } finally { await f.close(); } +}); + +// A refusal proves an admitted call never ran only when it is the backend's +// own denial of the id's only admission, which nothing let run. Anything +// else leaves the call to its recorded result (#3812): a rejected request (a +// stopped turn, a replay), a second admission of the id (the installed Claude +// runtime admits two calls under one id: `safety-result-retention.test.ts`), +// an allow before the refusal, or an id whose admissions were never reported. +for (const why of ["rejected", "readmitted", "allowed", "unreported"] as const) test(`a refusal that cannot prove an admitted call never ran leaves it owed: ${why}`, async () => { + const f = await voyage(); try { + if (why !== "unreported") f.collector.admitting?.("call_raft"); + await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); + if (why === "allowed") await f.collector.allowed!("call_raft"); + if (why === "readmitted") f.collector.admitting?.("call_raft"); + await f.collector.refused!("call_raft", why !== "rejected"); + expect(f.owed(), "SAFETY_UNPROVEN_REFUSAL_KEEPS_THE_OBLIGATION").toBe(1); + await f.writes.safetyEnd("voyage"); + expect(f.failure(), "SAFETY_UNPROVEN_REFUSAL_IS_A_DURABLE_GAP").toBe("recording_failed"); + expect(f.cause(), "SAFETY_UNPROVEN_REFUSAL_NAMES_ITS_CALL").toMatchObject({ site: "safetyEnd", message: expect.stringContaining("grep (call_raft)") }); + expect(f.chat().coverage.state, "SAFETY_UNPROVEN_REFUSAL_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + } finally { await f.close(); } +}); + +// Penelope denies a permission card: the Claude callback, the runtime's last +// gate, refused the id's only admission, so the search never ran (#3812). +test("a Claude call denied at its permission card on its only admission owes nothing, and its chat stays normal", async () => { + const f = await voyage(); try { + const wiring = createPermissionWiring({ req: { prompt: "Listen for the sirens.", signal: f.controller.signal, + bridge: { emit() {}, requestPermission: async () => ({ behavior: "deny", message: "Penelope declines the search" }), inputSafety: f.collector } } as never, + allowedTools: [], confirmPatterns: [], brainPath: f.brain, childEnv: { PATH: "/usr/bin:/bin" }, log() {}, + turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool() {} } as never }); + const input = { pattern: "sirens", path: f.brain }, options = { toolUseID: "toolu_sirens", signal: new AbortController().signal } as never; + // The runtime admits the search: its hook records the input and the obligation. + const preToolUse = wiring.hooks!.PreToolUse!.find(group => !group.matcher)!.hooks[0]!; + const hooked = await preToolUse({ hook_event_name: "PreToolUse", tool_name: "Grep", tool_input: input, tool_use_id: "toolu_sirens" } as never, "toolu_sirens", { signal: new AbortController().signal }); + expect((hooked as { hookSpecificOutput?: { permissionDecision?: string } }).hookSpecificOutput?.permissionDecision, "SAFETY_CLAUDE_HOOK_LEAVES_THE_CALL_TO_ITS_CARD").toBeUndefined(); + expect(f.owed(), "SAFETY_CLAUDE_ADMITTED_SEARCH_OWES_ITS_RESULT").toBe(1); + // Grep is outside the turn's allowlist, so the runtime asks the callback. + expect((await wiring.canUseTool!("Grep", input, options))?.behavior, "SAFETY_CLAUDE_CARD_IS_DENIED").toBe("deny"); + expect(f.owed(), "SAFETY_CLAUDE_CARD_DENY_DISCHARGES_THE_CALL").toBe(0); await f.writes.safetyEnd("voyage"); - expect(f.failure(), "SAFETY_REFUSED_EDIT_IS_A_DURABLE_GAP").toBe("recording_failed"); + expect(f.failure(), "SAFETY_CLAUDE_CARD_DENY_LEAVES_NO_GAP").toBeNull(); + expect(f.chat().restriction, "SAFETY_CLAUDE_CARD_DENY_KEEPS_THE_CHAT_NORMAL").toBe("normal"); + expect(f.chat().coverage.state, "SAFETY_CLAUDE_CARD_DENY_KEEPS_COVERAGE").toBe("complete"); } finally { await f.close(); } }); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 70595d57bc..89ee61c58c 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -39,8 +39,10 @@ function installedRipgrep(root:string):string { * before its process exits, so the runtime dispatches neither result hook. * `duplicate`: the model sends the search twice under one id; the runtime * admits both, and the second admission is denied once the first search has - * printed its matches, stopping the turn while that search runs. */ -type Interruption="refused"|"cancelled"|"running"|"duplicate"; + * printed its matches, stopping the turn while that search runs. + * `denied`: nothing interrupts; the search is outside the turn's allowlist, + * the runtime asks the permission callback, and Penelope denies the card. */ +type Interruption="refused"|"cancelled"|"running"|"duplicate"|"denied"; /** One model reply carrying each call as its own tool_use block. */ function modelCalls(calls:{name:string;id:string;input:Record}[]):Response { const events:unknown[]=[{type:"message_start",message:{id:"msg_ithaca",type:"message",role:"assistant",model:"claude-probe",content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:1,output_tokens:0}}}]; @@ -52,7 +54,7 @@ function modelCalls(calls:{name:string;id:string;input:Record}[] return new Response(events.map(event=>`event: ${(event as {type:string}).type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),{headers:{"content-type":"text/event-stream"}}); } async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType;writes:ReturnType; - first:{results:number;failures:number;aborted:boolean;admissions:number;refusals:number};searched:boolean;replayed:string[]})=>void){ + first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number};searched:boolean;replayed:string[]})=>void){ const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); // A note: reading it records nothing before the tool runs, so only the // search output's own record stands between it and a complete chat. @@ -94,18 +96,26 @@ esac // Each admission the runtime makes passes the index wait first. Under a // duplicate id the second waits until the first search has printed its // matches, then Odysseus stops the turn and that admission is denied. - let admissions=0,refusals=0,refusal=()=>{}; + let indexWaits=0,admitted=0,cards=0,refusals=0,refusal=()=>{}; const refused=new Promise(resolve=>{refusal=resolve;}); const awaitIndex=async()=>{ - if(!interrupt||interruption!=="duplicate"||++admissions<2)return; + if(!interrupt||interruption!=="duplicate"||++indexWaits<2)return; const deadline=Date.now()+15000; while(!existsSync(searched)&&Date.now()setTimeout(resolve,5)); if(!existsSync(searched))throw new Error("The first search never ran"); controller.abort(new Error("Odysseus stopped the turn while the first search ran")); throw new Error("The second search under the same id is denied"); }; - const inputSafety={...collector,refused:async(id:string)=>{await collector.refused!(id);refusals++;refusal();}}; - const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:"allow"}),inputSafety,awaitIndex}},allowedTools:["Grep"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); + // What the host reports to the collector, counted as it passes. + const inputSafety={...collector,admitting:(id:string)=>{admitted++;collector.admitting?.(id);}, + refused:async(id:string,denied?:boolean)=>{await collector.refused!(id,denied);refusals++;refusal();}}; + // The runtime lists Grep only when its allowlist names it, and then runs it + // without asking. So the denied search runs under an enforced turn + // allowlist that leaves Grep out: the host's hook asks, and the runtime + // consults the callback, as it does for every call outside it. + const denying=interrupt&&interruption==="denied"; + const requestPermission=async()=>{cards++;return denying?{behavior:"deny" as const,message:"Penelope declines the search"}:{behavior:"allow" as const};}; + const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,enforceAllowedTools:denying,bridge:{emit(){},requestPermission,inputSafety,awaitIndex}},allowedTools:denying?[]:["Grep"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); let results=0,failures=0; if(interrupt){ // The Grep result exists and the runtime holds it; only its record is at risk. @@ -124,7 +134,7 @@ esac const timer=setTimeout(()=>controller.abort(),20000); try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:["Grep"],...wiring,abortController:controller, ...(resume?{resume}:{}), - env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"||interruption==="duplicate"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ + env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"||interruption==="duplicate"||interruption==="denied"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; if("session_id" in message&&typeof message.session_id==="string")runtimeSession=message.session_id; }}catch{/* The interrupted turn is stopped. */} @@ -134,13 +144,13 @@ esac if(interrupt&&interruption==="duplicate")await Promise.race([refused,new Promise(resolve=>setTimeout(resolve,2000))]); await writes.safetyEnd(turnId); } - return {results,failures,aborted:controller.signal.aborted,admissions,refusals}; + return {results,failures,aborted:controller.signal.aborted,indexWaits,admitted,cards,refusals}; } try{ const first=await voyage("voyage",null,true); expect(version,"SAFETY_ACTUAL_INSTALLED_RUNTIME").toBe(MEASURED_RUNTIME.claudeCode); if(interruption==="running"||interruption==="duplicate")expect(existsSync(searched),"SAFETY_ACTUAL_SEARCH_RAN").toBe(true); - expect(first.aborted,"SAFETY_INTERRUPTED_RESULT_STOPS_ITS_TURN").toBe(true); + if(interruption!=="denied")expect(first.aborted,"SAFETY_INTERRUPTED_RESULT_STOPS_ITS_TURN").toBe(true); expect(runtimeSession,"SAFETY_RUNTIME_SESSION_TO_RESUME").toBeDefined(); turn=1; await voyage("homeward","ithaca",false,runtimeSession); @@ -152,13 +162,14 @@ esac .filter(block=>block.type==="tool_result"&&block.tool_use_id==="toolu_sirens").map(block=>typeof block.content==="string"?block.content:JSON.stringify(block.content)); expect(replayed.length,"SAFETY_RUNTIME_RESUMES_THE_INTERRUPTED_CALL").toBeGreaterThan(0); // The premise: interrupting the record did not keep the result out of the model's context. - if(interruption!=="running"&&interruption!=="duplicate")expect(resumed.some(r=>r.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT").toBe(true); + if(interruption==="refused"||interruption==="cancelled")expect(resumed.some(r=>r.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT").toBe(true); check({db,writes,first,searched:existsSync(searched),replayed}); // Contained to its chat: the brain-wide recorder is untouched, and a - // recovery has nothing to clear, so the chat stays restricted. + // recovery has nothing to clear, so the chat keeps its restriction (or, + // with nothing lost, stays normal). expect(db.query("SELECT failed FROM safety_meta").get(),"SAFETY_INTERRUPTED_RESULT_NEVER_LATCHES_THE_BRAIN").toEqual({failed:0}); recoverSafetyRecording(db,{trigger:"owner",actor:"penelope"}); - expect(writes.safety(null,"ithaca").restriction,"SAFETY_INTERRUPTED_RESULT_SURVIVES_RECOVERY").toBe("restricted"); + expect(writes.safety(null,"ithaca").restriction,"SAFETY_INTERRUPTED_RESULT_SURVIVES_RECOVERY").toBe(interruption==="denied"?"normal":"restricted"); }finally{origin.stop(true);await writer.close();db.close();rmSync(root,{recursive:true,force:true});} } @@ -207,7 +218,7 @@ test("a denial under an id the runtime admitted twice cannot settle the search t // The installed runtime admits the same tool_use id twice and runs the // first search; its allow never reaches a callback, since `allowedTools` // lists Grep bare. - expect(first.admissions,"SAFETY_RUNTIME_ADMITS_ONE_ID_TWICE").toBe(2); + expect(first.indexWaits,"SAFETY_RUNTIME_ADMITS_ONE_ID_TWICE").toBe(2); expect(first.refusals,"SAFETY_SECOND_ADMISSION_IS_DENIED").toBeGreaterThan(0); expect(first.results+first.failures,"SAFETY_RUNTIME_SKIPPED_BOTH_RESULT_HOOKS").toBe(0); // The denial proves nothing about the search already running under that id. @@ -218,4 +229,21 @@ test("a denial under an id the runtime admitted twice cannot settle the search t const voyage=db.query("SELECT failure,failure_cause FROM safety_collections WHERE turn_id='voyage'").get() as {failure:string|null;failure_cause:string|null}; expect(voyage.failure,"SAFETY_DUPLICATE_DENIAL_GAP_IS_DURABLE").toBe("recording_failed"); expect(JSON.parse(voyage.failure_cause??"{}"),"SAFETY_DUPLICATE_DENIAL_NAMES_ITS_CALL").toMatchObject({site:"safetyEnd",turnId:"voyage",message:expect.stringContaining("Grep (toolu_sirens)")}); + // What kept it: the host saw the second admission before its denial. + expect(first.admitted,"SAFETY_HOST_REPORTS_BOTH_ADMISSIONS").toBe(2); +}),60000); + +test("a search denied at its permission card never runs, and its chat stays normal with no gap",()=>voyageHome("denied",({db,writes,first,searched})=>{ + // The runtime asks the callback, its last gate, and Penelope's deny keeps + // the search from running at all. + expect(first.cards,"SAFETY_RUNTIME_ASKS_THE_CALLBACK").toBe(1); + expect(searched,"SAFETY_DENIED_SEARCH_NEVER_RAN").toBe(false); + // The denial of the id's only admission proves the call never ran. + expect(db.query("SELECT failure,gap FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_CARD_DENY_LEAVES_NO_GAP").toEqual({failure:null,gap:null}); + const chat=writes.safety("homeward","ithaca"); + expect(chat.restriction,"SAFETY_CARD_DENY_KEEPS_THE_CHAT_NORMAL").toBe("normal"); + expect(chat.coverage.state,"SAFETY_CARD_DENY_KEEPS_COVERAGE").toBe("complete"); + // What proved it: the host saw one admission under the id, and its deny. + expect(first.admitted,"SAFETY_RUNTIME_ADMITS_THE_DENIED_SEARCH_ONCE").toBe(1); + expect(first.refusals,"SAFETY_CARD_DENY_IS_REPORTED").toBeGreaterThan(0); }),60000); From d039d73856de671dbdec1538c312fc1d27b6380a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 15:35:42 +0100 Subject: [PATCH 19/24] docs: re-anchor citations the narrowed admission rule moved (#3812) Co-Authored-By: Claude Opus 5.5 --- docs/decisions/async-collaboration.md | 2 +- docs/decisions/claude-2.1.287-compatibility.md | 2 +- docs/decisions/live-conversation.md | 2 +- docs/decisions/voice-permission.md | 2 +- docs/investigations/live-conversation-investigation.md | 4 ++-- docs/plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index 53dc14c7fc..ad13172118 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:673`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:697`). These are permission primitives, +optional inputs are (`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:682`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:706`). 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-2.1.287-compatibility.md b/docs/decisions/claude-2.1.287-compatibility.md index 71cab5da98..f85ab89077 100644 --- a/docs/decisions/claude-2.1.287-compatibility.md +++ b/docs/decisions/claude-2.1.287-compatibility.md @@ -126,7 +126,7 @@ The backend builds the actual turn options and production permission handlers The explicit ask lives in (`enforcementHookFor`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`) and is registered under enforcement in -(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:745-748`). +(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:761-764`). `scripts/measure-claude-enforcement.ts` runs `createClaudeBackend().startTurn()` and forwards to the SDK resolved from that backend. Its query wrapper only diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index 7771b8c45c..4e95c685ca 100644 --- a/docs/decisions/live-conversation.md +++ b/docs/decisions/live-conversation.md @@ -82,7 +82,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:815-871`); +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:824-880`); 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/voice-permission.md b/docs/decisions/voice-permission.md index c00a07f9cf..85a22f15c7 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -621,7 +621,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:673`) +(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:682`) — 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 d1085b5387..b1c39b3c47 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:584-720`). +(`export interface StartTurnRequest`, `packages/ui-sdk/src/server/backend.ts:593-729`). 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:815-871`). +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:824-880`). 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 4059cc3433..2c8def0543 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:584-720`); ordinary Claude turns create an SDK session, emit + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:593-729`); 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 cf5dd87fca..2fdae214db 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:584-720`)) + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:593-729`)) - 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 aecfe7b5d4..8ef78c8a66 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -148,7 +148,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:9-157`). `AgentBackend` exposes native list/read and read-only storage roots, not deletion -(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:815-871`). A storage root +(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:824-880`). 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 From c68a17bd9c35460b152a47e9fb3a97dcea009293 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 15:37:29 +0100 Subject: [PATCH 20/24] docs: re-anchor citations into protocol.ts and app.ts that this PR moves (#3812) Co-Authored-By: Claude Opus 5.5 --- docs/decisions/design-kit/sessions-and-drafts.md | 2 +- docs/decisions/http-api-boundary.md | 2 +- docs/plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 4 ++-- docs/plans/chat-history-deletion.md | 2 +- docs/plans/voice-conversation.md | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/decisions/design-kit/sessions-and-drafts.md b/docs/decisions/design-kit/sessions-and-drafts.md index 2ff7090ea9..046fc4bcf0 100644 --- a/docs/decisions/design-kit/sessions-and-drafts.md +++ b/docs/decisions/design-kit/sessions-and-drafts.md @@ -359,7 +359,7 @@ event deletes the whole set. Draft content never enters this record (§5). null, no time is printed. - **`lastActiveAt` and `lastTouched` are never read.** A newer `lastActiveAt` can mean that a new turn started - (`export interface ChatSession`, `packages/ui-sdk/src/protocol.ts:1749-1779`), + (`export interface ChatSession`, `packages/ui-sdk/src/protocol.ts:1753-1783`), and `lastTouched` is LRU bookkeeping for buffer eviction. **Merging snapshots and live frames.** diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index 1176e9b697..572ca155d1 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -50,7 +50,7 @@ The source audit on 2026-09-30 used public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1040`), and the WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1261`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1283-1304`). That order establishes access; +`packages/ui-server/src/app.ts:1285-1306`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 052f3831a8..e8fc69df83 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -336,7 +336,7 @@ Stated before the requirements because five of them derive from it. item makes no model call **and creates no Activity run** · T1 batch classification · T2 full agent run · T3 the user. - R39. **T1 batches are bounded by tokens and bytes, not count.** One share's text may carry ~200 KB - (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2692`), so "up to 20 items" is ~4 MB before overhead. + (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2696`), so "up to 20 items" is ~4 MB before overhead. Per-item truncation, a batch token budget, and independent structured outputs per item. - R40. **Every model-bearing operation is billed, recorded, classified, and counted**: T1 batches, T2 runs, retries, redo re-derivation, state compaction, premise revalidation, diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index b6949c5a6a..f777853e60 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -154,7 +154,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. (`async deliverPending(notifier) {`, `packages/ui-server/src/activity/push-sender.ts:218-286`) are run-bound and do not maintain an Actions aggregate count. - **Share provenance/limits:** (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:101`) assigns the source in server code. - (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2692`) bounds text, not binary uploads; + (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2696`) bounds text, not binary uploads; extracted T1 context needs its own byte/token bound. - **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1346-1358`) gates WS starts; (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`) owns tool locks. @@ -807,7 +807,7 @@ recovered tick after killing the interval - T1: one batched classification call producing **independent structured output per item**, so one malformed item does not poison the batch - Batching bounded by a **token/byte budget**, not a count, with per-item truncation — a single - share may carry ~200 KB (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2692`). Budget: **40k input tokens per + share may carry ~200 KB (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2696`). Budget: **40k input tokens per batch, 4k per item** - **Batch completeness is verified, and missing items are re-submitted individually.** Every submitted item id must come back; any that does not is retried alone, then escalated if it diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 03dac12c42..f14c4e8195 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -334,7 +334,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1373-1423`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1375-1425`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:274-287`). A caller deadline diff --git a/docs/plans/voice-conversation.md b/docs/plans/voice-conversation.md index 579fa55750..e754470b18 100644 --- a/docs/plans/voice-conversation.md +++ b/docs/plans/voice-conversation.md @@ -207,7 +207,7 @@ existing pronunciation overrides only as disclosed text correction, retaining the distinction between recognized words and submitted text. The present `AsrEvent` carries partial/final text and `endsTurn`, not confidence, overlap evidence or an output transcript (`AsrEvent`, -`packages/ui-sdk/src/protocol.ts:2064`). #317 must resolve those gaps rather +`packages/ui-sdk/src/protocol.ts:2068`). #317 must resolve those gaps rather than pretending that dictation supplies them. Assistant text remains the generated answer; playback progress is a separate From a5c7ed87fb962eaa0320f0a97d3de1e5b80868f6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 17:21:31 +0100 Subject: [PATCH 21/24] fix(ui-server): count a reused call id under another tool as a new admission (#3812) The Claude backend counted admissions per hook, keyed by call id alone. When a different tool reused an id, its hooks were not the ones that had seen the id. A Bash call reusing an auto-allowed Grep's id reached the mutating hook first, which had never seen that id, so its count did not pass the maximum. Its denial then found one admission and discharged the Grep's obligation before the shared hook counted the Bash call. The chat ended normal and complete, although the search had run. Admissions are now counted per (tool name, id). For one tool name, the same hooks run on every admission, so whichever hook starts first counts it. Backends report the tool name with each admission. The collector keeps the tool names seen for each id. A refusal discharges an obligation only when the id was admitted exactly once, under one tool name, and was never allowed. Also brings three comments that still described the superseded no-refusal rule in line with the narrowed rule. Co-Authored-By: Claude Opus 5.5 --- docs/decisions/session-safety-reviews.md | 12 ++- .../ui-backend-claude/src/permission-hooks.ts | 31 +++--- .../tests/permission-wiring-units.test.ts | 17 +++ packages/ui-backend-pi/src/permission-gate.ts | 2 +- packages/ui-backend-pi/src/worker-rpc.ts | 2 +- .../tests/tools-permission.test.ts | 4 +- .../ui-backend-pi/tests/worker-rpc.test.ts | 4 +- packages/ui-sdk/src/server/backend.ts | 10 +- .../ui-server/src/governance/event-writes.ts | 5 +- .../src/governance/safety-collector.ts | 49 +++++---- .../ui-server/src/governance/safety-store.ts | 8 +- .../tests/safety-result-exits.test.ts | 20 ++-- .../tests/safety-result-retention.test.ts | 100 ++++++++++++++++-- 13 files changed, 193 insertions(+), 71 deletions(-) diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index 672b13f2d7..135f577f5e 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -109,14 +109,16 @@ running under the tainted policy, not refusing. permission callback deny (a denied permission card) or `PreToolUse` hook deny, a Pi permission deny or gate block; 2. it is the id's only admission: the runtime asked once to admit a call - under that id (each admission is counted before anything of it is - decided, whichever hook of it starts first); + under that id, under one tool name (each admission is counted per tool + name before anything of it is decided, whichever hook of it starts + first, so a reused id under another tool counts even when its hooks + differ); 3. the backend never let a call under that id run. Anything else proves nothing, and only the recorded result discharges: - a second admission of the id (the installed Claude runtime admits two - calls under one id, and runs a bare `allowedTools` entry or a rewrite - hook's allow without asking), an allow followed by a refusal, a rejected + a second admission of the id, under the same tool name or another (the + installed Claude runtime admits two calls under one id, and runs a bare + `allowedTools` entry or a rewrite hook's allow without asking), an allow followed by a refusal, a rejected request (a stopped turn, a replayed Pi request), or an id whose admissions the backend never reported. Such a call leaves the gap even if it never ran. A rejected `begin()` discharges nothing by itself; the diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts index c56442d5d5..d4f2598d0e 100644 --- a/packages/ui-backend-claude/src/permission-hooks.ts +++ b/packages/ui-backend-claude/src/permission-hooks.ts @@ -674,19 +674,24 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick { if (toolUseId) await req.bridge.inputSafety?.refused?.(toolUseId, true).catch(() => {}); }; - // The runtime dispatches every matching PreToolUse hook once per call it - // admits, all under that call's id. Each hook counts its own invocations - // per id, and the highest count is how many calls the runtime admitted - // under the id. So whichever hook of a second admission starts first - // reports it, before any of that admission's waits, decisions or begin(). - // Counting begin() calls instead would be wrong both ways: one admission - // records its input from several hooks, and a second admission can be - // denied before its begin() (#3812). + // The runtime dispatches every PreToolUse hook whose matcher takes the + // call's tool name, once per call it admits, under that call's id. So for + // one tool name the same hooks run on every admission. Each hook counts its + // own invocations per (tool name, id), and the highest count is how many + // calls the runtime admitted under that id for that tool: whichever hook of + // a later admission starts first reports it, before any of that + // admission's waits, decisions or begin(). Keyed by id alone, a call under + // a reused id with another tool name would pass hooks that never saw the + // id, and its denial could land before a shared hook counted it. Counting + // begin() calls instead would be wrong both ways: one admission records its + // input from several hooks, and a later admission can be denied before its + // begin() (#3812). const admissions = new Map(); - const admit = (toolUseId: string, seen: Map) => { - const count = (seen.get(toolUseId) ?? 0) + 1; - seen.set(toolUseId, count); - if (count > (admissions.get(toolUseId) ?? 0)) { admissions.set(toolUseId, count); req.bridge.inputSafety?.admitting?.(toolUseId); } + const admit = (toolUseId: string, toolName: string, seen: Map) => { + const key = JSON.stringify([toolName, toolUseId]); + const count = (seen.get(key) ?? 0) + 1; + seen.set(key, count); + if (count > (admissions.get(key) ?? 0)) { admissions.set(key, count); req.bridge.inputSafety?.admitting?.(toolUseId, toolName); } }; const decideToolUse = canUseToolFor(ctx); // The callback's allow is the runtime's last gate: the call runs. The @@ -712,7 +717,7 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick HookCallback = hook => { const seen = new Map(); return async (...args) => { - if (args[0].hook_event_name === "PreToolUse") admit(args[0].tool_use_id, seen); + if (args[0].hook_event_name === "PreToolUse") admit(args[0].tool_use_id, args[0].tool_name, seen); const output = await fenced(hook, args); if (args[0].hook_event_name === "PreToolUse" && "hookSpecificOutput" in output && output.hookSpecificOutput?.hookEventName === "PreToolUse" && output.hookSpecificOutput.permissionDecision === "deny") await refuse(args[0].tool_use_id); diff --git a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts index 12b2493707..17dbcc1f1d 100644 --- a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts +++ b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts @@ -183,4 +183,21 @@ describe("admissions, refusals and the collector's last check", () => { await Promise.all([second, ...matching.slice(0, -1).map(hook => hook(...call))]); expect(admitted, "CLAUDE_SECOND_ADMISSION_IS_REPORTED_ONCE").toEqual(["oar-3", "oar-3"]); }); + + test("a reused id under another tool name is a new admission, reported by its first hook even when that hook never saw the id", async () => { + const live = new AbortController(); + const { hooks, admitted } = wiring(live.signal); + const common = hooks.PreToolUse!.find(group => !group.matcher)!.hooks[0]!; + const mutating = hooks.PreToolUse!.find(group => group.matcher && new RegExp(group.matcher).test("Bash") && !/Agent/.test(group.matcher))!.hooks[0]!; + const as = (tool_name: string, tool_input: Record) => [{ hook_event_name: "PreToolUse", tool_name, tool_input, tool_use_id: "oar-4" } as never, "oar-4", { signal: live.signal }] as const; + // The runtime admits a search: only the common hook matches it. + await common(...as("Grep", { pattern: "suitors" })); + expect(admitted, "CLAUDE_SEARCH_ADMISSION_IS_REPORTED").toEqual(["oar-4"]); + // A shell call reuses the id. Its mutating hook starts first and has never + // seen the id, yet the admission is reported before that hook decides. + const shell = mutating(...as("Bash", { command: "echo rafts", run_in_background: true })); + expect(admitted, "CLAUDE_REUSED_ID_UNDER_ANOTHER_TOOL_IS_A_NEW_ADMISSION").toEqual(["oar-4", "oar-4"]); + await shell; await common(...as("Bash", { command: "echo rafts", run_in_background: true })); + expect(admitted, "CLAUDE_REUSED_ID_ADMISSION_IS_REPORTED_ONCE").toEqual(["oar-4", "oar-4"]); + }); }); diff --git a/packages/ui-backend-pi/src/permission-gate.ts b/packages/ui-backend-pi/src/permission-gate.ts index e6cee9b4fc..39ab864b2e 100644 --- a/packages/ui-backend-pi/src/permission-gate.ts +++ b/packages/ui-backend-pi/src/permission-gate.ts @@ -111,7 +111,7 @@ export function createPermissionGate(options: PermissionGateOptions): InlineExte // Each tool_call event is one admission of its id, counted before // anything is decided (#3812). const safety = turn.bridge?.inputSafety; - safety?.admitting?.(event.toolCallId); + safety?.admitting?.(event.toolCallId, event.toolName); const answer = await admit(event); // A block is this host's denial before the call runs. It refuses the // id at the collector, so nothing later under it is admitted or let diff --git a/packages/ui-backend-pi/src/worker-rpc.ts b/packages/ui-backend-pi/src/worker-rpc.ts index 904869d3a7..4c71f007c5 100644 --- a/packages/ui-backend-pi/src/worker-rpc.ts +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -312,7 +312,7 @@ export function createPiWorkerRpcDispatcher(context: PiWorkerRpcContext): (msg: }, async error => { await permission.refused!(msg.toolCallId); throw error; }); try { - permission?.admitting?.(msg.toolCallId); + permission?.admitting?.(msg.toolCallId, msg.toolName); if (!result || !safety) context.live(); if (msg.id <= lastRpcId) throw resultLoss(new Error("Replayed pi worker RPC")); lastRpcId = msg.id; diff --git a/packages/ui-backend-pi/tests/tools-permission.test.ts b/packages/ui-backend-pi/tests/tools-permission.test.ts index 6ca30c795f..0c75aa5d28 100644 --- a/packages/ui-backend-pi/tests/tools-permission.test.ts +++ b/packages/ui-backend-pi/tests/tools-permission.test.ts @@ -88,12 +88,12 @@ describe("tool_call permission gate", () => { const turn = createTurnContext(); const mock = makeMockBridge({ decision: { behavior: "deny", message: "Penelope declines" } }); turn.bridge = { ...mock.bridge, inputSafety: { ready: async () => {}, begin: async () => {}, result: async () => {}, - admitting: (id: string) => { admitted.push(id); }, refused: async (id: string, denied?: boolean) => { refused.push([id, denied]); } } }; + admitting: (id: string, tool?: string) => { admitted.push(`${tool}:${id}`); }, refused: async (id: string, denied?: boolean) => { refused.push([id, denied]); } } }; const handler = gateHandler({ turn, allowedTools: ALLOWED, confirmPatterns: CONFIRM }); expect(await handler({ toolName: "write_file", toolCallId: "allowed", input: { path: "a.md", content: "x" } })).toBeUndefined(); expect(await handler({ toolName: "brain_archive", toolCallId: "declined", input: { path: "notes/suitors.md" } })).toMatchObject({ block: true }); expect(refused, "PI_GATE_BLOCK_REFUSES_THE_CALL").toEqual([["declined", true]]); - expect(admitted, "PI_GATE_EVERY_TOOL_CALL_IS_AN_ADMISSION").toEqual(["allowed", "declined"]); + expect(admitted, "PI_GATE_EVERY_TOOL_CALL_IS_AN_ADMISSION").toEqual(["write_file:allowed", "brain_archive:declined"]); }); test("a call the gate lets through is checked by the collector first, and one the check refuses is blocked", async () => { diff --git a/packages/ui-backend-pi/tests/worker-rpc.test.ts b/packages/ui-backend-pi/tests/worker-rpc.test.ts index a3f32fdead..bd023b68b3 100644 --- a/packages/ui-backend-pi/tests/worker-rpc.test.ts +++ b/packages/ui-backend-pi/tests/worker-rpc.test.ts @@ -218,7 +218,7 @@ test("every permission answer but allow refuses the call at the collector, and a // answer is the host's own denial, which can prove the call never ran; a // rejection proves nothing. Every request is one admission (#3812). const refused: [string, boolean | undefined][] = [], allowed: string[] = [], admitted: string[] = []; - const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, admitting: (id: string) => { admitted.push(id); }, + const inputSafety = { ready: async () => {}, begin: async () => {}, result: async () => {}, admitting: (id: string, tool?: string) => { admitted.push(`${tool}:${id}`); }, refused: async (id: string, denied?: boolean) => { refused.push([id, denied]); }, allowed: async (id: string) => { allowed.push(id); } }; const routed = harness({}, { applyBrain: async () => ({ ok: true }) as never, inputSafety }); expect(await routed.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-allowed"))).toEqual({ behavior: "allow" }); @@ -233,7 +233,7 @@ test("every permission answer but allow refuses the call at the collector, and a expect(allowed, "PI_ALLOWED_PERMISSION_IS_CHECKED_BEFORE_IT_RUNS").toEqual(["call-allowed"]); // A later request in the stopped turn is an admission too, and only rejected. await expect(stopped.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }, "call-stopped"))).rejects.toThrow(); - expect(admitted, "PI_EVERY_PERMISSION_REQUEST_IS_AN_ADMISSION").toEqual(["call-allowed", "call-denied", "call-stopped", "call-stopped"]); + expect(admitted, "PI_EVERY_PERMISSION_REQUEST_IS_AN_ADMISSION").toEqual(["brain_add:call-allowed", "brain_add:call-denied", "brain_add:call-stopped", "brain_add:call-stopped"]); expect(refused.at(-1), "PI_REJECTED_REQUEST_IS_NO_DENIAL").toEqual(["call-stopped", undefined]); }); diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index ced614e5a2..6e312598c5 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -190,10 +190,12 @@ export interface BackendBridge { * that gap is durable. */ lost?(toolUseId: string, toolName: string, cause: unknown): Promise; /** @internal The runtime asks the backend to admit one call under this - * id. Call it once per admission, before the backend decides anything - * about it, however many gates (hooks, callbacks) that one admission - * passes through. A backend that calls `refused` must call this too. */ - admitting?(toolUseId: string): void; + * id, for this tool. Call it once per admission, before the backend + * decides anything about it, however many gates (hooks, callbacks) that + * one admission passes through. An id admitted more than once, or under + * more than one tool name, is never discharged by a refusal. A backend + * that calls `refused` must call this too. */ + admitting?(toolUseId: string, toolName?: string): void; /** @internal The backend refused a call with this id. Every call `begin` * admits owes its `result` from then on; still owed when the turn ends, * it leaves the turn's chat a permanent gap. A refusal discharges it only diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index f793a9c8d3..e264867072 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -94,8 +94,9 @@ export interface GovernanceWrites { * `SafetyRecordingUnavailable`: the call has not run, and the backend * refuses it. */ safetyOblige(turnId:string,obligationId:string,toolUseId:string,tool:string):Promise; - /** The call's result is durably recorded; nothing else discharges it, a - * refusal included. A failure leaves the obligation, and so the gap. */ + /** The call's result is durably recorded, or the backend's own denial of + * the only admission under its id, never allowed, proves it never ran. A + * failure leaves the obligation, and so the gap. */ safetyDischarge(turnId:string,obligationId:string):Promise; /** Ends the turn's collection once its result records under way settle. */ safetyEnd(turnId:string):Promise; diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index 345cd253ef..839abd45ba 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -18,12 +18,17 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option type Operation={tool:string;inputHashes:Set;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string;owed:boolean;refused:boolean}; const operations=new Map(); // What the backend reported about each id: how many times the runtime asked - // to admit a call under it, and whether the backend ever let one run. Kept - // in memory, apart from `operations` and the obligation rows: an admission - // can be denied before any begin(), so before any row exists (the reviewer's - // duplicate-id run), and only this collector discharges this turn's - // obligations; a restart gaps every open obligation whatever these say. - const calls=new Map(); + // to admit a call under it, for each tool name it came under, and whether + // the backend ever let one run. Kept in memory, apart from `operations` and + // the obligation rows: an admission can be denied before any begin(), so + // before any row exists (the reviewer's duplicate-id run), and only this + // collector discharges this turn's obligations; a restart gaps every open + // obligation whatever these say. Two tool names already make the id + // unprovable, so a third is not kept. + const calls=new Map;allowed:boolean}>(); + // A refusal can prove the call never ran only for an id admitted once, + // under one tool name, and never allowed. + const once=(call:{tools:Map;allowed:boolean}|undefined)=>!!call&&!call.allowed&&call.tools.size===1&&[...call.tools.values()][0]===1; const operation=(tool:string):Operation=>({tool,inputHashes:new Set(),id:crypto.randomUUID(),occurrences:[],done:false,admitted:false,signals:[],owed:false,refused:false}); const base=()=>({turnId:options.turnId,sessionId:options.sessionId(),actor:options.actor??"interactive" as const,model:null,profile:null}); const marked=(path:string)=>isMarkedUntrusted(db,path); @@ -142,27 +147,29 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option await discharge(op); }catch(error){return fail(error);} },true));}, - // The runtime asks to admit one call under this id. Counted at once, not - // queued: a refusal already queued for the id then sees the new admission - // and proves nothing. An id the collector cannot track keeps no count, so - // no refusal discharges it. - admitting(toolUseId){ - const call=calls.get(toolUseId); - if(call)call.admissions++;else if(calls.size<2000)calls.set(toolUseId,{admissions:1,allowed:false}); + // The runtime asks to admit one call under this id, for this tool. Counted + // at once, not queued: a refusal already queued for the id then sees the + // new admission and proves nothing. An id the collector cannot track keeps + // no count, so no refusal discharges it. + admitting(toolUseId,toolName=""){ + let call=calls.get(toolUseId); + if(!call){if(calls.size>=2000)return;calls.set(toolUseId,call={tools:new Map(),allowed:false});} + if(call.tools.has(toolName)||call.tools.size<2)call.tools.set(toolName,(call.tools.get(toolName)??0)+1); }, // The backend refused a call with this id; a later begin() or allow for the // id is refused too, so a parallel hook or request cannot reopen it. The // refusal proves the call never ran, and discharges its obligation, only // when it is the backend's own denial (`denied`: a Claude permission // callback or PreToolUse hook deny, a Pi permission deny or gate block), of - // the only admission ever made under the id, and the backend never let a - // call under it run. Anything else proves nothing and leaves the - // obligation to its recorded result: a second admission of the id (the - // Claude runtime admits two calls under one id), an allow followed by a - // refusal, a rejected request (a stopped turn, a replay). Never rejects. + // the only admission ever made under the id, under its only tool name, and + // the backend never let a call under it run. Anything else proves nothing + // and leaves the obligation to its recorded result: a second admission of + // the id, under the same tool or another (the Claude runtime admits two + // calls under one id), an allow followed by a refusal, a rejected request + // (a stopped turn, a replay). Never rejects. refused(toolUseId,denied=false){return serial(toolUseId,async()=>{ - const op=operations.get(toolUseId),call=calls.get(toolUseId); - const proves=denied&&call?.admissions===1&&!call.allowed; + const op=operations.get(toolUseId); + const proves=denied&&once(calls.get(toolUseId)); if(!op){if(operations.size<2000)operations.set(toolUseId,{...operation(""),refused:true});return;} op.refused=true; if(proves&&!op.done)await discharge(op); @@ -177,7 +184,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(op&&(op.refused||!op.admitted))throw new Error("Safety operation was refused or not admitted; the call does not run"); const call=calls.get(toolUseId); if(call)call.allowed=true; - else if(calls.size<2000)calls.set(toolUseId,{admissions:0,allowed:true}); + else if(calls.size<2000)calls.set(toolUseId,{tools:new Map(),allowed:true}); else throw new Error("Safety allowance capacity exceeded; the call does not run"); },true);}, // A result the backend could not hand over (a refused or malformed report): diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index 7c479d43d9..8c5ca6f425 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -352,10 +352,10 @@ const OBLIGATIONS = 2048; const clipText=(text:string)=>clip(text.replace(/[\u0000-\u001f\u007f]/g," "),128); /** * A tool call admitted before it runs owes its result's record (#3812). It - * is owed until that record is durable; no refusal discharges it, since none - * proves an admitted call did not run. Owing it is restrictive only: it needs - * no healthy recorder, only an open collection to gap if the result never - * comes. + * is owed until that record is durable, or until the backend's own denial of + * the only admission under its id, under one tool name and never allowed, + * proves it never ran. Owing it is restrictive only: it needs no healthy + * recorder, only an open collection to gap if the result never comes. */ export function openSafetyObligation(db:Database,turnId:string,id:string,toolUseId:string,tool:string,at=Date.now()):void { db.transaction(()=>{ diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 77bb39d9f6..d6c00dc180 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -1,8 +1,9 @@ /** Every exit between a tool running and its result's record either records * the result or leaves its chat a permanent gap, in both backends (#3812). * Every call `begin()` admits owes its result until the record is durable, - * and no refusal discharges it; one still owed when its collection ends, or - * at boot, is a gap. The installed Claude runtime's replay of a stopped + * or until the backend's own denial of the id's only admission, under one + * tool name and never allowed, proves it never ran; one still owed when its + * collection ends, or at boot, is a gap. The installed Claude runtime's replay of a stopped * turn's result, and its skipped result hooks, are proved in * `safety-result-retention.test.ts`; these drive the remaining exits against * the real host ledger. Keyless and offline. */ @@ -194,15 +195,18 @@ test("a call refused when its edited input cannot be recorded owes nothing", asy // A refusal proves an admitted call never ran only when it is the backend's // own denial of the id's only admission, which nothing let run. Anything // else leaves the call to its recorded result (#3812): a rejected request (a -// stopped turn, a replay), a second admission of the id (the installed Claude -// runtime admits two calls under one id: `safety-result-retention.test.ts`), -// an allow before the refusal, or an id whose admissions were never reported. -for (const why of ["rejected", "readmitted", "allowed", "unreported"] as const) test(`a refusal that cannot prove an admitted call never ran leaves it owed: ${why}`, async () => { +// stopped turn, a replay), a second admission of the id under the same tool +// or another (the installed Claude runtime admits two calls under one id: +// `safety-result-retention.test.ts`), an allow before the refusal, or an id +// whose admissions were never reported. +for (const why of ["rejected", "readmitted", "retooled", "allowed", "unreported"] as const) test(`a refusal that cannot prove an admitted call never ran leaves it owed: ${why}`, async () => { const f = await voyage(); try { - if (why !== "unreported") f.collector.admitting?.("call_raft"); + if (why !== "unreported") f.collector.admitting?.("call_raft", "grep"); await f.collector.begin("call_raft", "grep", { pattern: "sirens" }); if (why === "allowed") await f.collector.allowed!("call_raft"); - if (why === "readmitted") f.collector.admitting?.("call_raft"); + if (why === "readmitted") f.collector.admitting?.("call_raft", "grep"); + // Another tool reuses the id: its one admission is the id's second. + if (why === "retooled") f.collector.admitting?.("call_raft", "bash"); await f.collector.refused!("call_raft", why !== "rejected"); expect(f.owed(), "SAFETY_UNPROVEN_REFUSAL_KEEPS_THE_OBLIGATION").toBe(1); await f.writes.safetyEnd("voyage"); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 89ee61c58c..a4118d3d04 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -41,8 +41,12 @@ function installedRipgrep(root:string):string { * admits both, and the second admission is denied once the first search has * printed its matches, stopping the turn while that search runs. * `denied`: nothing interrupts; the search is outside the turn's allowlist, - * the runtime asks the permission callback, and Penelope denies the card. */ -type Interruption="refused"|"cancelled"|"running"|"duplicate"|"denied"; + * the runtime asks the permission callback, and Penelope denies the card. + * `retooled`: the model sends the search and a Read of the note under the + * same id. The Read's native-read hook, which never saw that id, waits until + * the search has printed its matches, stops the turn and denies the Read; + * the hook shared by both tools is held until that denial has landed. */ +type Interruption="refused"|"cancelled"|"running"|"duplicate"|"denied"|"retooled"; /** One model reply carrying each call as its own tool_use block. */ function modelCalls(calls:{name:string;id:string;input:Record}[]):Response { const events:unknown[]=[{type:"message_start",message:{id:"msg_ithaca",type:"message",role:"assistant",model:"claude-probe",content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:1,output_tokens:0}}}]; @@ -82,6 +86,7 @@ esac const first=turn===0&&requests.filter(r=>r.turn===0).length===1; const search={name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}}; if(first&&interruption==="duplicate")return modelCalls([search,search]); + if(first&&interruption==="retooled")return modelCalls([search,{name:"Read",id:search.id,input:{file_path:path}}]); return nativeModelReply(first?search:undefined); }}); async function voyage(turnId:string,sessionId:string|null,interrupt:boolean,resume?:string){ @@ -107,7 +112,7 @@ esac throw new Error("The second search under the same id is denied"); }; // What the host reports to the collector, counted as it passes. - const inputSafety={...collector,admitting:(id:string)=>{admitted++;collector.admitting?.(id);}, + const inputSafety={...collector,admitting:(id:string,tool?:string)=>{admitted++;collector.admitting?.(id,tool);}, refused:async(id:string,denied?:boolean)=>{await collector.refused!(id,denied);refusals++;refusal();}}; // The runtime lists Grep only when its allowlist names it, and then runs it // without asking. So the denied search runs under an enforced turn @@ -115,7 +120,19 @@ esac // consults the callback, as it does for every call outside it. const denying=interrupt&&interruption==="denied"; const requestPermission=async()=>{cards++;return denying?{behavior:"deny" as const,message:"Penelope declines the search"}:{behavior:"allow" as const};}; - const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,enforceAllowedTools:denying,bridge:{emit(){},requestPermission,inputSafety,awaitIndex}},allowedTools:denying?[]:["Grep"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); + // Under `retooled`, the Read's native-read hook stops the turn once the + // search has printed its matches, and refuses the Read. + const retooling=interrupt&&interruption==="retooled",tools=retooling?["Grep","Read"]:["Grep"]; + const fileVersions={beginRead:async()=>{ + const deadline=Date.now()+15000; + while(!existsSync(searched)&&Date.now()setTimeout(resolve,5)); + if(!existsSync(searched))throw new Error("The search never ran"); + controller.abort(new Error("Odysseus stopped the turn after the search ran")); + throw new Error("The Read under the same id is refused"); + }}; + const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,enforceAllowedTools:denying,bridge:{emit(){},requestPermission,inputSafety,awaitIndex}},allowedTools:denying?[]:tools,confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},...(retooling?{fileVersions:fileVersions as never}:{}),log(){}}); + // The hook both tools share is held for the Read until its denial landed. + if(retooling)for(const group of wiring.hooks!.PreToolUse!)if(!group.matcher)group.hooks=group.hooks.map(hook=>async(...args)=>{if((args[0] as {tool_name?:string}).tool_name==="Read")await refused;return hook(...args);}); let results=0,failures=0; if(interrupt){ // The Grep result exists and the runtime holds it; only its record is at risk. @@ -132,16 +149,16 @@ esac // Stop the turn the moment the search has printed its matches. const watching=interrupt&&interruption==="running"?setInterval(()=>{if(existsSync(searched))controller.abort(new Error("Odysseus stopped the turn while the search ran"));},5):undefined; const timer=setTimeout(()=>controller.abort(),20000); - try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:["Grep"],...wiring,abortController:controller, + try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:tools,...wiring,abortController:controller, ...(resume?{resume}:{}), - env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"||interruption==="duplicate"||interruption==="denied"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ + env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"||interruption==="duplicate"||interruption==="denied"||interruption==="retooled"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; if("session_id" in message&&typeof message.session_id==="string")runtimeSession=message.session_id; }}catch{/* The interrupted turn is stopped. */} finally{ clearInterval(watching);clearTimeout(timer);db.exec("DROP TRIGGER IF EXISTS refuse_result"); // The denial lands before the turn's end, as it would once the hook returns. - if(interrupt&&interruption==="duplicate")await Promise.race([refused,new Promise(resolve=>setTimeout(resolve,2000))]); + if(interrupt&&(interruption==="duplicate"||interruption==="retooled"))await Promise.race([refused,new Promise(resolve=>setTimeout(resolve,2000))]); await writes.safetyEnd(turnId); } return {results,failures,aborted:controller.signal.aborted,indexWaits,admitted,cards,refusals}; @@ -149,7 +166,7 @@ esac try{ const first=await voyage("voyage",null,true); expect(version,"SAFETY_ACTUAL_INSTALLED_RUNTIME").toBe(MEASURED_RUNTIME.claudeCode); - if(interruption==="running"||interruption==="duplicate")expect(existsSync(searched),"SAFETY_ACTUAL_SEARCH_RAN").toBe(true); + if(interruption==="running"||interruption==="duplicate"||interruption==="retooled")expect(existsSync(searched),"SAFETY_ACTUAL_SEARCH_RAN").toBe(true); if(interruption!=="denied")expect(first.aborted,"SAFETY_INTERRUPTED_RESULT_STOPS_ITS_TURN").toBe(true); expect(runtimeSession,"SAFETY_RUNTIME_SESSION_TO_RESUME").toBeDefined(); turn=1; @@ -247,3 +264,70 @@ test("a search denied at its permission card never runs, and its chat stays norm expect(first.admitted,"SAFETY_RUNTIME_ADMITS_THE_DENIED_SEARCH_ONCE").toBe(1); expect(first.refusals,"SAFETY_CARD_DENY_IS_REPORTED").toBeGreaterThan(0); }),60000); + +test("a denial of another tool under the search's id cannot settle the search that already ran, so its chat keeps a permanent gap",()=>voyageHome("retooled",({db,writes,first})=>{ + // The runtime ran the search and was stopped before either result hook. + expect(first.results+first.failures,"SAFETY_RUNTIME_SKIPPED_BOTH_RESULT_HOOKS").toBe(0); + // The Read's own hook denied it before the shared hook counted it: that + // denial proves nothing about the search under the same id. + const chat=writes.safety("homeward","ithaca"); + expect(chat.restriction,"SAFETY_RETOOLED_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH").toBe("restricted"); + expect(chat.coverage.state,"SAFETY_RETOOLED_DENIAL_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + const voyage=db.query("SELECT failure,failure_cause FROM safety_collections WHERE turn_id='voyage'").get() as {failure:string|null;failure_cause:string|null}; + expect(voyage.failure,"SAFETY_RETOOLED_DENIAL_GAP_IS_DURABLE").toBe("recording_failed"); + expect(JSON.parse(voyage.failure_cause??"{}"),"SAFETY_RETOOLED_DENIAL_NAMES_ITS_CALL").toMatchObject({site:"safetyEnd",turnId:"voyage",message:expect.stringContaining("(toolu_sirens)")}); + // What kept it: the Read was reported as a second admission of the id. + expect(first.admitted,"SAFETY_HOST_REPORTS_THE_READ_AS_A_SECOND_ADMISSION").toBeGreaterThanOrEqual(2); +}),60000); + +/** The model searches, then reuses the search's id for a background shell + * call. The runtime runs the search, whose result report is dropped here, + * the way a stopped turn loses it, and then admits the shell call. That + * call's own hook, which never saw the id, denies it, in the runtime's own + * hook order or with the hook both tools share starting late. */ +for(const late of [false,true])test(`a denied shell call reusing a search's id cannot settle the search that ran${late?", even when the shared hook starts late":""}`,async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retool-")),brain=join(root,"brain"),home=join(root,"home"); + mkdirSync(join(brain,"notes"),{recursive:true});mkdirSync(home); + const path=join(brain,"notes","sirens.md");writeFileSync(path,`${SONG}\n`); + const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); + holdSafetyRecovery(db); + const controller=new AbortController(),bindingId=crypto.randomUUID(); + await writes.safetyBegin({turnId:"voyage",bindingId,sessionId:null,principalId:"odysseus",backendId:"claude",at:0}); + db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners VALUES('ithaca','odysseus',0)"); + safetyCatalogCreated(db,"ithaca","odysseus","voyage");await writes.bind("voyage","ithaca"); + const collector=createSafetyCollector(db,writes,{turnId:"voyage",bindingId,backendId:"claude",sessionId:()=>"ithaca",brainPath:brain,shellProxied:()=>false,signal:controller.signal}); + await collector.ready("claude",1); + let admitted=0,refusals=0,requests=0,replayed=false,version:string|undefined; + const inputSafety={...collector,admitting:(id:string,tool?:string)=>{admitted++;collector.admitting?.(id,tool);}, + refused:async(id:string,denied?:boolean)=>{await collector.refused!(id,denied);refusals++;}, + // The search's result never reaches the host. + result:async()=>{}}; + const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:"allow"}),inputSafety}},allowedTools:["Grep","Bash"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); + if(late)for(const group of wiring.hooks!.PreToolUse!)if(!group.matcher)group.hooks=group.hooks.map(hook=>async(...args)=>{if((args[0] as {tool_name?:string}).tool_name==="Bash")await new Promise(resolve=>setTimeout(resolve,150));return hook(...args);}); + const origin=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(request){ + if(new URL(request.url).pathname!=="/v1/messages")return Response.json({}); + const raw=await request.text(),body=JSON.parse(raw); + if(!Array.isArray(body.tools)||!body.tools.length)return nativeModelReply(); + requests++;if(requests>1&&raw.includes(SONG))replayed=true; + return nativeModelReply(requests===1?{name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}} + :requests===2?{name:"Bash",id:"toolu_sirens",input:{command:"echo rafts",run_in_background:true}}:undefined); + }}); + const timer=setTimeout(()=>controller.abort(),20000); + try{ + for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:4,permissionMode:"default",allowedTools:["Grep","Bash"],...wiring,abortController:controller, + env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),PATH:process.env.PATH??"/usr/bin:/bin",ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ + if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; + } + await writes.safetyEnd("voyage"); + expect(version,"SAFETY_ACTUAL_INSTALLED_RUNTIME").toBe(MEASURED_RUNTIME.claudeCode); + expect(replayed,"SAFETY_RUN_SEARCH_REACHED_THE_MODEL").toBe(true); + expect(refusals,"SAFETY_SHELL_CALL_UNDER_THE_SEARCH_ID_IS_DENIED").toBeGreaterThan(0); + // The shell call's denial proves nothing about the search under its id. + const chat=writes.safety(null,"ithaca"); + expect(chat.restriction,"SAFETY_RETOOLED_SHELL_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH").toBe("restricted"); + expect(chat.coverage.state,"SAFETY_RETOOLED_SHELL_DENIAL_NEVER_LOOKS_COMPLETE").toBe("incomplete"); + expect(db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_RETOOLED_SHELL_DENIAL_GAP_IS_DURABLE").toEqual({failure:"recording_failed"}); + // What kept it: the shell call was reported as a second admission of the id. + expect(admitted,"SAFETY_HOST_REPORTS_THE_SHELL_CALL_AS_A_SECOND_ADMISSION").toBeGreaterThanOrEqual(2); + }finally{clearTimeout(timer);origin.stop(true);await writer.close();db.close();rmSync(root,{recursive:true,force:true});} +},60000); From 663b9041643cd59f19068e4e14243ec695445cdb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 17:21:41 +0100 Subject: [PATCH 22/24] docs: re-anchor citations the per-tool admission count moved (#3812) Co-Authored-By: Claude Opus 5.5 --- docs/decisions/async-collaboration.md | 2 +- docs/decisions/claude-2.1.287-compatibility.md | 2 +- docs/decisions/live-conversation.md | 2 +- docs/decisions/voice-permission.md | 2 +- docs/investigations/live-conversation-investigation.md | 4 ++-- docs/plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index ad13172118..549128de6f 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:682`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:706`). These are permission primitives, +optional inputs are (`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:684`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:708`). 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-2.1.287-compatibility.md b/docs/decisions/claude-2.1.287-compatibility.md index f85ab89077..9a26d969ee 100644 --- a/docs/decisions/claude-2.1.287-compatibility.md +++ b/docs/decisions/claude-2.1.287-compatibility.md @@ -126,7 +126,7 @@ The backend builds the actual turn options and production permission handlers The explicit ask lives in (`enforcementHookFor`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`) and is registered under enforcement in -(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:761-764`). +(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:766-769`). `scripts/measure-claude-enforcement.ts` runs `createClaudeBackend().startTurn()` and forwards to the SDK resolved from that backend. Its query wrapper only diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index 4e95c685ca..99dd5b6504 100644 --- a/docs/decisions/live-conversation.md +++ b/docs/decisions/live-conversation.md @@ -82,7 +82,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:824-880`); +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:826-882`); 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/voice-permission.md b/docs/decisions/voice-permission.md index 85a22f15c7..77689f00a5 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -621,7 +621,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:682`) +(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:684`) — 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 b1c39b3c47..de70b6468e 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:593-729`). +(`export interface StartTurnRequest`, `packages/ui-sdk/src/server/backend.ts:595-731`). 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:824-880`). +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:826-882`). 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 e8fc69df83..8c70e31e7d 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:593-729`); ordinary Claude turns create an SDK session, emit + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:595-731`); 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 f777853e60..78e430faab 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:593-729`)) + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:595-731`)) - 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 f14c4e8195..3aef573bf6 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -148,7 +148,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:9-157`). `AgentBackend` exposes native list/read and read-only storage roots, not deletion -(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:824-880`). A storage root +(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:826-882`). 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 From 7ad2bb7ccaaf9542ba06023256d0f9b1604f6ac8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:37:45 +0100 Subject: [PATCH 23/24] docs: re-anchor the share-size citations this PR moves (#3812) Co-Authored-By: Claude Opus 5.5 --- docs/plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 8c70e31e7d..c14c8d78ea 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -336,7 +336,7 @@ Stated before the requirements because five of them derive from it. item makes no model call **and creates no Activity run** · T1 batch classification · T2 full agent run · T3 the user. - R39. **T1 batches are bounded by tokens and bytes, not count.** One share's text may carry ~200 KB - (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2696`), so "up to 20 items" is ~4 MB before overhead. + (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2701`), so "up to 20 items" is ~4 MB before overhead. Per-item truncation, a batch token budget, and independent structured outputs per item. - R40. **Every model-bearing operation is billed, recorded, classified, and counted**: T1 batches, T2 runs, retries, redo re-derivation, state compaction, premise revalidation, diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 78e430faab..efcd04f9dc 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -154,7 +154,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. (`async deliverPending(notifier) {`, `packages/ui-server/src/activity/push-sender.ts:218-286`) are run-bound and do not maintain an Actions aggregate count. - **Share provenance/limits:** (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:101`) assigns the source in server code. - (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2696`) bounds text, not binary uploads; + (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2701`) bounds text, not binary uploads; extracted T1 context needs its own byte/token bound. - **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1346-1358`) gates WS starts; (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`) owns tool locks. @@ -807,7 +807,7 @@ recovered tick after killing the interval - T1: one batched classification call producing **independent structured output per item**, so one malformed item does not poison the batch - Batching bounded by a **token/byte budget**, not a count, with per-item truncation — a single - share may carry ~200 KB (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2696`). Budget: **40k input tokens per + share may carry ~200 KB (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2701`). Budget: **40k input tokens per batch, 4k per item** - **Batch completeness is verified, and missing items are re-submitted individually.** Every submitted item id must come back; any that does not is retried alone, then escalated if it From 6c7331bd052d3e53c75882f59708bfa45fc9b63c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 23:45:38 +0100 Subject: [PATCH 24/24] chore(scripts): re-audit inbound.ts after it gained the refusal reason (#3812) The browser dispatch audit pins inbound.ts by hash. It now also imports refusalReason from lib/turn-failure.ts, which imports only protocol types and constants; inbound.ts still takes only runStateForFrame from the chat handlers and never reaches chatFrameHandlers. Co-Authored-By: Claude Opus 5.5 --- scripts/source-browser-dispatch.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/source-browser-dispatch.ts b/scripts/source-browser-dispatch.ts index eacaa6c5a3..ed3a290b7e 100644 --- a/scripts/source-browser-dispatch.ts +++ b/scripts/source-browser-dispatch.ts @@ -13,7 +13,10 @@ const helperConsumers:Record={ // driver before demux; this consumer still imports only runStateForFrame. // Re-audited when #1362 moved inbound routing out of connection.ts: only // runStateForFrame is imported; it never acquires or mutates chatFrameHandlers. - "packages/ui-react/src/ws-client/inbound.ts":"b9a95fc0d8bcb82723fd93aa17faa492702dc4bbc747abb4a11d02f41c99e7c5", + // Re-audited for #3812: inbound.ts gained refusalReason from lib/turn-failure.ts, + // which imports only protocol types and constants; still only runStateForFrame + // from the chat handlers. + "packages/ui-react/src/ws-client/inbound.ts":"513ef019608371d41da3d15c3f48fdc2a8bcbb49882975b6f8099e2cd0a2d64c", "packages/ui-react/src/hooks/use-websocket.ts":"6edd8b289fa4dcf7f0a512ce1275bd9e9c70661ce5630e22503b4b1d888cf557" }; // Re-audited for #3155: chat.ts only gained `attachmentFiles` in its history