diff --git a/.changeset/3812-safety-recording-containment.md b/.changeset/3812-safety-recording-containment.md
new file mode 100644
index 0000000000..36231b2a97
--- /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 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 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.
+- **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, 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 9b6bd7b28f..ff63a06a62 100644
--- a/api-report/ui-sdk.txt
+++ b/api-report/ui-sdk.txt
@@ -7684,7 +7684,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" | "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/async-collaboration.md b/docs/decisions/async-collaboration.md
index 4d31f70758..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: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: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
@@ -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 c1a650722f..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:715-718`).
+(`...(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/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md
index df7244dd36..8c25b6f8dc 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:65-83`), and the run record. Not
+ `packages/ui-server/src/routes/health.ts:73-91`), 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/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/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/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/decisions/live-conversation.md b/docs/decisions/live-conversation.md
index d96e3ad391..d2ddb4ec87 100644
--- a/docs/decisions/live-conversation.md
+++ b/docs/decisions/live-conversation.md
@@ -148,7 +148,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: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/proportionate-containment.md b/docs/decisions/proportionate-containment.md
index baf20815f5..2e84820035 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: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/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md
index ed2eb31511..135f577f5e 100644
--- a/docs/decisions/session-safety-reviews.md
+++ b/docs/decisions/session-safety-reviews.md
@@ -72,6 +72,90 @@ 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 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`). 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, 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. 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, 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, 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
+ 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
+ `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 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.
+
+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`, 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
+become clean.
+
## Human authority and policy publication
Initially **only a live password-mode human owner** may commit a verdict or
diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md
index 79e694bba0..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:642`)
+(`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/http-api-coverage.md b/docs/http-api-coverage.md
index 5a2ef4cd8d..bb341c7eff 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 |
@@ -198,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: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/http-api.md b/docs/http-api.md
index 5eb16eb1f2..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
@@ -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. |
@@ -212,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.
@@ -393,6 +394,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 e39d819d57..4bdb3531d4 100644
--- a/docs/integration-contract/http.md
+++ b/docs/integration-contract/http.md
@@ -296,6 +296,40 @@ 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, 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.
+
+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 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
+(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/docs/integration-contract/wire.md b/docs/integration-contract/wire.md
index 9693e44bbb..f29304d0cd 100644
--- a/docs/integration-contract/wire.md
+++ b/docs/integration-contract/wire.md
@@ -173,6 +173,17 @@ 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). 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
`resetsAt`. Neither automatically retries. A conversation block offers the
diff --git a/docs/investigations/live-conversation-investigation.md b/docs/investigations/live-conversation-investigation.md
index 91423df40e..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:553-650`).
+(`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:784-827`).
+(`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 2ae42c4c7f..c14c8d78ea 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: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
@@ -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: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 ddec275d13..efcd04f9dc 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.
@@ -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: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:2692`). 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
@@ -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: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 3d23055b15..b320a19501 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: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
@@ -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/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md
index bdc411696c..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:232-237`). 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`,
@@ -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/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
diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts
index 792397c9d5..d4f2598d0e 100644
--- a/packages/ui-backend-claude/src/permission-hooks.ts
+++ b/packages/ui-backend-claude/src/permission-hooks.ts
@@ -666,13 +666,64 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick { if (toolUseId) await req.bridge.inputSafety?.refused?.(toolUseId, true).catch(() => {}); };
+ // 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, 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
+ // 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);
+ 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);
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 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, 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);
+ return output;
+ }; };
+ async function fenced(hook: HookCallback, args: Parameters): Promise>> {
let snapshot: AdmissionSafetySnapshot | undefined;
let output: Awaited>;
try {
@@ -690,7 +741,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..17dbcc1f1d 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,89 @@ describe("the extracted callbacks", () => {
expect(locks).toEqual(["oar-1"]);
});
});
+
+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, 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 () => {}, 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, hooks: hooks!, refused, allowed, released, admitted };
+ }
+
+ 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", true], ["oar-2", true]]);
+ });
+
+ 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 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'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_UNCHECKED_ALLOW_IS_DENIED").toMatchObject({ behavior: "deny", message: expect.stringContaining("does not run") });
+ 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"]);
+ });
+
+ 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 0a745a56b9..39ab864b2e 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,26 @@ export function createPermissionGate(options: PermissionGateOptions): InlineExte
name: "brain-permission-gate",
factory: (pi) => {
pi.on("tool_call", async (event) => {
+ // 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, 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
+ // 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, true);
+ return { block: true, reason: error instanceof Error ? error.message : "Safety recording refused this call." };
+ }
+ 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 +155,7 @@ export function createPermissionGate(options: PermissionGateOptions): InlineExte
Object.assign(target, decision.updatedInput);
}
return undefined;
- });
+ }
},
};
}
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..4c71f007c5 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;
}
@@ -258,7 +275,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 +290,49 @@ 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;
+ // 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. 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, true);
+ return answer;
+ },
+ async error => { await permission.refused!(msg.toolCallId); throw error; });
try {
- context.live();
- if (msg.id <= lastRpcId) throw new Error("Replayed pi worker RPC");
+ 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;
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)) : refuse(answer);
+ } catch (error) { return result && safety ? keepResultLoss(safety, msg, error) : refuse(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-backend-pi/tests/tools-permission.test.ts b/packages/ui-backend-pi/tests/tools-permission.test.ts
index 101758bd30..0c75aa5d28 100644
--- a/packages/ui-backend-pi/tests/tools-permission.test.ts
+++ b/packages/ui-backend-pi/tests/tools-permission.test.ts
@@ -80,6 +80,39 @@ describe("approval policy (approvalReason)", () => {
});
describe("tool_call permission gate", () => {
+ 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 () => {},
+ 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(["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 () => {
+ // 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, 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();
+ 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_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 () => {
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..bd023b68b3 100644
--- a/packages/ui-backend-pi/tests/worker-rpc.test.ts
+++ b/packages/ui-backend-pi/tests/worker-rpc.test.ts
@@ -211,3 +211,41 @@ 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 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. 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, 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" });
+ 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", 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(["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]);
+});
+
+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, 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", true]]);
+});
diff --git a/packages/ui-kit/vitest.config.ts b/packages/ui-kit/vitest.config.ts
index 8c14b3cae7..20bc3a25fa 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/src/lib/draft-client.ts b/packages/ui-react/src/lib/draft-client.ts
index 5c4c9afd0e..f5ad7126ed 100644
--- a/packages/ui-react/src/lib/draft-client.ts
+++ b/packages/ui-react/src/lib/draft-client.ts
@@ -744,7 +744,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") {
@@ -757,7 +757,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..bd0b21bc30 100644
--- a/packages/ui-react/src/lib/turn-failure.ts
+++ b/packages/ui-react/src/lib/turn-failure.ts
@@ -14,8 +14,45 @@ 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;
+ 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. */
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,
+ };
+ // 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.",
+ 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..ca57cbb06e 100644
--- a/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx
+++ b/packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx
@@ -430,3 +430,28 @@ 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("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");
diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts
index 62d8ef351e..613318fac7 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" | "safety_recording_chat_full" | "safety_recording_brain_full" | "unknown";
/**
* First-party failure classes, shared by emitters and reviewed diagnostics.
@@ -1400,6 +1400,10 @@ 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",
+ safety_recording_chat_full: "safety_recording_chat_full",
+ safety_recording_brain_full: "safety_recording_brain_full",
unknown: "unknown",
});
diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts
index de8a6c9cfd..6e312598c5 100644
--- a/packages/ui-sdk/src/server/backend.ts
+++ b/packages/ui-sdk/src/server/backend.ts
@@ -185,6 +185,36 @@ 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;
+ /** @internal The runtime asks the backend to admit one call under this
+ * 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
+ * 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. */
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
new file mode 100644
index 0000000000..789454fc91
--- /dev/null
+++ b/packages/ui-server/migrations/085_safety_recording_containment.sql
@@ -0,0 +1,41 @@
+-- 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,
+ -- Some latched loss named no chat: recovery must gap every collection.
+ 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,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 (
+ 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
+);
+-- 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/app.ts b/packages/ui-server/src/app.ts
index 29b2c923e4..cbccb5f8f5 100644
--- a/packages/ui-server/src/app.ts
+++ b/packages/ui-server/src/app.ts
@@ -1091,6 +1091,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/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..e264867072 100644
--- a/packages/ui-server/src/governance/event-writes.ts
+++ b/packages/ui-server/src/governance/event-writes.ts
@@ -8,8 +8,10 @@
*/
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";
+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";
import { Database } from "bun:sqlite";
import {assertLive,ChatRetiredError} from "../ws/chat-lifecycle.js";
@@ -23,28 +25,53 @@ 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,sessionId:string|null=null)=>{
+ let scope:string;
+ 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"))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",row.sessionId); 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),
+ 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.
- 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",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))latchSafety(db,row.turnId,error instanceof SafetyUnavailable?"capacity":"recording_failed");throw error;}
+ // `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),
// Classification reads the turn's earlier events on the same connection,
@@ -58,21 +85,44 @@ 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;
+ /** 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'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;
- 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;
/**
* 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. */
- firstTaint(input: GovernanceEventInput<"taint">): Promise;
+ /** `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;
+ /** 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
@@ -88,6 +138,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);
@@ -98,67 +153,164 @@ 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);
+ // 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,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)});
};
- 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)retainedForBrain(turnId,notice,cause);
+ 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;}
+ retainedForBrain(turnId,error);
+ };
+ 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);
- 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))))) {
+ // 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).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 };
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;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.
+ 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); });
};
+ watchLatch();
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)),
+ 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),
+ 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);
- 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 +325,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..839abd45ba 100644
--- a/packages/ui-server/src/governance/safety-collector.ts
+++ b/packages/ui-server/src/governance/safety-collector.ts
@@ -5,56 +5,119 @@ 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";
+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 {
- const operations=new Map;id:string;occurrences:string[];done: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 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();
+ // What the backend reported about each id: how many times the runtime asked
+ // 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);
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);}
- try{await writes.safetyFail(options.turnId);}
+ 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)}`);
throw error;
};
+ // 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. */}
+ };
const tails=new Map>();let queued=0;
- const serial=(id:string,work:()=>Promise):Promise=>{
+ // 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++;
- 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;
};
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 from the moment its
+ // 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.
+ if(operations.get(toolUseId)?.refused)throw new Error("Safety operation was refused; the call does not run");
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,signals:[] as IngestionSignal[]};
+ 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);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}});
+ 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);}
+ }catch(error){return fail(error,true);}
});},
- result(toolUseId,tool,output,finalized,segments){return serial(toolUseId,async()=>{
- assertLive();
+ // 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; 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)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.
@@ -62,15 +125,73 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option
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);
}
- // 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}});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}});
- op.done=true;op.outputHash=outputHash;assertLive();
+ // 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;
+ // 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 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, 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);
+ 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);
+ },true).catch(()=>{});},
+ // 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,{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):
+ // 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 8df0772e15..5114c982f6 100644
--- a/packages/ui-server/src/governance/safety-queue.ts
+++ b/packages/ui-server/src/governance/safety-queue.ts
@@ -3,10 +3,16 @@ 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>}>();
+ /** 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;
+ /** 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,lostTurns:new Set(),unscopedLoss:false,listeners:new Set()};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;
}
@@ -16,11 +22,16 @@ 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),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 750aa6a54c..8c5ca6f425 100644
--- a/packages/ui-server/src/governance/safety-store.ts
+++ b/packages/ui-server/src/governance/safety-store.ts
@@ -18,36 +18,154 @@ 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); } }
+/** 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 {
+ 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
+ * 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;
+ /** 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";
+ // 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;
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","brain");
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"|"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 }
+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 {
+ // 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 {
+ 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),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);
- 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,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){
+ 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;
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");
+}
+/** Room for collections not yet in a chat frees itself as open ones bind to
+ * their chats and pending writes settle. Only ended unbound collections hold
+ * it for good: the brain's room is spent only when they alone leave no room
+ * for one more collection. */
+function unboundScope(db:Database):SafetyCapacityScope {
+ const ended=one<{n:number;bytes:number}>(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);
@@ -57,13 +175,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 SafetyUnavailable("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 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",unboundScope(db));
}
}
/** Must commit before any first-turn bytes or tool execution. Callbacks cannot create a session. */
@@ -73,7 +196,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 +217,28 @@ 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",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 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",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)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",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=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 +278,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 SafetyUnavailable("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 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",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));
@@ -178,12 +306,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","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 SafetyUnavailable("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);
@@ -219,11 +347,66 @@ 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'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(()=>{
+ 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. 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
+ // 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);
+ }
+ // 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[];
@@ -298,11 +481,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));}
- if(one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_pending").n)latchSafety(db,null,"recording_failed");
+ // 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 {
@@ -324,14 +514,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","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);
}).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 +533,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,true);}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 +581,89 @@ 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). `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),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,
+ 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 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";
+ // 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(()=>{
- 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<{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.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","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.",
+ 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)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();
- db.query("DELETE FROM safety_pending").run();
+ 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
+ // 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();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.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});
+ }
+ return {recovered,trigger,actor,at,gapped,cause};
}
diff --git a/packages/ui-server/src/routes/health.ts b/packages/ui-server/src/routes/health.ts
index e5197c5324..c20a5fe444 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 { SystemStatus, 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";
@@ -60,17 +64,26 @@ 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 journalRecovery = deps.getJournalRecovery?.();
const nativeRecovery = deps.getNativeRecovery?.();
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({
...(journalRecovery ? { journalRecovery } : {}),
@@ -94,6 +107,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
@@ -102,5 +116,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/src/ws/bridge-capabilities/turn-error.ts b/packages/ui-server/src/ws/bridge-capabilities/turn-error.ts
index 92ae67c252..e9dca08287 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,16 @@ 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), 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));
} 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/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 = {
"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 } },
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-containment.test.ts b/packages/ui-server/tests/safety-containment.test.ts
new file mode 100644
index 0000000000..caf92bc3ef
--- /dev/null
+++ b/packages/ui-server/tests/safety-containment.test.ts
@@ -0,0 +1,520 @@
+/** 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, 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 }); });
+
+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), "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(); }
+});
+
+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", "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);
+ 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, durable: true } });
+ 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", "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");
+});
+
+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(); }
+});
+
+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", "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(); }
+});
+
+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");
+ 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 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 });
+ // 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");
+});
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..801c973fc8 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,12 @@ 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");
+ // 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});
+ 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 +322,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 +392,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 +401,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..1508f0e092 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,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);
- expect(f.writes.recordingAvailable("voyage","ithaca")).toBe(false);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"));
@@ -223,7 +230,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-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts
new file mode 100644
index 0000000000..d6c00dc180
--- /dev/null
+++ b/packages/ui-server/tests/safety-result-exits.test.ts
@@ -0,0 +1,457 @@
+/** 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 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. */
+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 { 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";
+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. */
+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, 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(),
+ 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(); } };
+}
+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(); }
+});
+
+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 denies on its only admission owes nothing, and a recorded result discharges its call", async () => {
+ const f = await voyage(); try {
+ 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.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 {
+ 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 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");
+ 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 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", "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", "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");
+ 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_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(); }
+});
+
+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(); }
+});
+
+/** 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 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;
+ 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");
+ 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(); }
+});
+
+// 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
new file mode 100644
index 0000000000..a4118d3d04
--- /dev/null
+++ b/packages/ui-server/tests/safety-result-retention.test.ts
@@ -0,0 +1,333 @@
+/** 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). 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 {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";
+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.";
+
+/** 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.
+ * `running`: the turn is stopped once the search has printed its matches but
+ * 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.
+ * `denied`: nothing interrupts; the search is outside the turn's allowlist,
+ * 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}}}];
+ 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;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.
+ 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.
+ 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;
+ 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){
+ 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);
+ // 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 indexWaits=0,admitted=0,cards=0,refusals=0,refusal=()=>{};
+ const refused=new Promise(resolve=>{refusal=resolve;});
+ const awaitIndex=async()=>{
+ 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");
+ };
+ // What the host reports to the collector, counted as it passes.
+ 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
+ // 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};};
+ // 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.
+ 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 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:tools,...wiring,abortController:controller,
+ ...(resume?{resume}:{}),
+ 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"||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};
+ }
+ try{
+ const first=await voyage("voyage",null,true);
+ expect(version,"SAFETY_ACTUAL_INSTALLED_RUNTIME").toBe(MEASURED_RUNTIME.claudeCode);
+ 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;
+ 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.
+ 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 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(interruption==="denied"?"normal":"restricted");
+ }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,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");
+ 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,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();
+ 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);
+
+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);
+
+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.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.
+ 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)")});
+ // 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);
+
+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);
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();
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