Skip to content

CONTRACT: fix(ui-server): contain a safety-recording failure to what it puts at risk and recover automatically (#3812, #3810) - #3827

Merged
schlessera merged 37 commits into
mainfrom
fix/3812-proportionate-safety-recording
Nov 11, 2026
Merged

schlessera merged 37 commits into
mainfrom
fix/3812-proportionate-safety-recording

Conversation

@schlessera

@schlessera schlessera commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner

Closes #3812
Closes #3810

What changes

A hosted instance refused every turn in every chat after one turn's safety-recording write failed: the guard set one durable flag for the whole brain, labelled it capacity, kept no cause, and only a hand-run script cleared it. This PR applies the maintainer's 2026-11-09 ruling (#3812, proportionate containment) and keeps #3810's diagnostics, with #3812's restrict-before-refuse superseding #3810's "a latched recorder still refuses turns".

Failure Before Now
safetyBegin fails, or a tool's input record is refused before the tool runs (the backend awaits begin before executing) Brain latched as capacity; every turn refused That one turn is refused with SAFETY_RECORDING_UNAVAILABLE. Nothing latches. Spent room says what frees it: safety_recording_chat_full (start a new chat) or safety_recording_brain_full (retrying won't help).
Evidence lost after delivery (safetyFail, failed commit, loss at end, any failure recording a tool result, a result report the host refuses) Brain latched Only that turn's collection takes the failure and its first cause. Its chat keeps a permanent recording_failed gap and runs restricted; its producer stops. Other chats are unaffected. A reservation still open when its collection ends becomes the same gap. A result is never "before delivery": its bytes exist, and the Claude runtime replays it on resume. A turn stopped while a tool runs still records that tool's result. Every call admitted before it runs owes its result's record until that record is durable, or until the host's own denial of the only admission under that id, with no allow before it, proves the call never ran. A collection that ends owing one (a turn stopped before the runtime reported the result, a hook the runtime never ran, a call refused any other way) and a call still owed at boot leave the same gap. A denied permission card leaves the chat as it was.
The chat fact itself cannot commit (store unwritable) Brain latched (or in-process only) Brain latches through the emergency reserve, or in-process. New turns still begin, each with a permanent recording_failed gap committed before delivery, and run under the tainted policy. A reconciler keeps retrying (backoff up to 1/min, no retry cap) and clears the latch with recoverSafetyRecording semantics once every producer that predates it has ended, failed or not.
Restricted begin cannot commit either n/a The one enumerated outright refusal: safety_recording_paused (SafetyRecordingUnavailable, safety-store.ts).
Boot with failed=1 or pending reservations Every turn refused until the script Resolved at boot after restart classification, gaps first. A legacy row that cannot migrate gaps its own turn instead of latching capacity.

Diagnosability (#3810):

  • Only a capacity check (SafetyCapacityExhausted) classifies as capacity; everything else is recording_failed, in all facades and the migration.
  • The first latch cause (class, message, bounded stack, site, turn, time) and a count live in safety_latch; chat-scoped causes in safety_collections.failure_cause. Identifiers and error text only.
  • One structured stderr line per latch, chat failure, in-process retention, pre-delivery refusal and recovery.
  • Owner GET /api/status gains safetyRecording (latched, since, reason, cause, retained, lastRecovery); other principals never see it. While only this process holds the loss, cause is that in-memory cause with durable: false.
  • POST /api/status/safety-recording/recover (owner) is the fallback and the production caller of recoverSafetyRecording: strict quiescence, 409 producers_open without changing anything, actor recorded.
  • Every recovery (boot, automatic, owner) is audited in safety_recoveries with trigger, actor, time, gapped count and the cause it cleared.
  • The PWA says "Safety recording is paused on this server. Nothing was sent; try again in a minute.", "Safety recording failed before this was sent. Nothing ran; try again.", "This chat has no room left for safety records. Nothing was sent; start a new chat to continue." or "This server has no room left for safety records. Nothing was sent, and retrying won't help." instead of "The brain refused this message."

Contract (additive, CONTRACT: commits): error code SAFETY_RECORDING_UNAVAILABLE and failure classes safety_recording_unavailable / safety_recording_paused / safety_recording_chat_full / safety_recording_brain_full (wire); safetyRecording status field (with cause.durable) and the recovery route (http, http-api). Projection reasons and the wire meaning of recording_failed are unchanged. Migration 085 adds restricted_begin, failure_cause, safety_latch, safety_recoveries, safety_obligations.

Security properties kept

  • An unknown never becomes clean: every turn whose evidence may be lost keeps a permanent gap (recording_failed, recording_failed_recovered or host_restart_unknown); no recovery clears a gap or an unresolved occurrence.
  • A turn that runs during a brain latch has its permanent gap committed before delivery, so losing its later evidence changes nothing; that is why it may dispatch while the brain is latched.
  • A turn whose own chat failed still has its producer stopped (sync refusal, recordingAvailable false) until its collection ends.
  • Only a tool's input, recorded before the tool runs, may be refused without a gap. Verified for every begin caller: Claude's PreToolUse hooks and canUseTool deny on failure; Pi's beforeToolCall and tool_call handlers throw, and pi-agent-core's prepareToolCall turns that into an error result without executing. A result that reaches the host is recorded whatever happened to its turn, and every result the host cannot record, in both backends, leaves a permanent gap on its chat (exit-path audit under Review follow-up).
  • The host does not depend on the runtime reporting a result. Every call begin() admits is an obligation, durable before the tool runs. Its durably recorded result discharges it; the record and the discharge commit together. A refusal discharges it only when it proves the call never ran: the backend's own denial, of the only admission ever made under the id, under one tool name, with no allow observed (fifth and sixth reviews). A second admission of the id, an allow before the refusal, a rejected request or an unreported admission proves nothing. A collection that ends owing one, through cancellation, abort, a missing hook, an unproven refusal or a restart, leaves its chat a permanent gap naming the call.
  • A Pi permission grant is published only after the collector's last check of the call has passed, with no wait between the grant and the answer, so no concurrent request can use a grant for a call that check refuses.
  • A loss for a turn with no collection has no chat to carry it and still restricts the brain.
  • Tests that drove the old brain-wide semantics were rewritten to the new scope; each still proves its original property (failed notice restricts, final provider admission rechecks loss, approvals withdraw on related loss) and gained the other-chat counterpart.

Proportionate-containment checklist

  • What triggers it, what it does not cover? A safety-recording write that fails: begin, reservation, commit, producer failure notice, loss at end, migration, pending at restart. Taint semantics, SAFETY_LIMITS and other guards are out of scope.
  • What does it restrict, why nothing narrower? The turn (before delivery), else the turn's chat (permanent gap), else the brain, and the brain only when no chat fact can commit, because then no narrower durable record exists.
  • Restricted mode considered before refusing? Yes: chats and new turns run under the tainted policy. Refusal remains only when even the restricted begin cannot commit, because then the restriction could not survive a restart.
  • How does it clear? Automatically: per chat, the gap is permanent by design and the chat keeps running restricted; brain-wide, attemptSafetyRecovery (event-writes.ts) on a backoff timer, plus boot recovery in createUiDb. Owner route is a fallback only; a human adds nothing there.
  • Where is the cause recorded, how does the owner see it? safety_latch, safety_collections.failure_cause, safety_recoveries, one log line each; owner /api/status.safetyRecording.
  • Which test shows one scope failing leaves another usable? Pinned browser: safety-gap.layout.tsx "a second chat stays usable while one chat carries a recording gap" (real app, real recorder, real Chat page). safety-containment.test.ts: "a failed safetyBegin refuses only that turn…", "a lost post-delivery occurrence restricts its chat permanently and leaves another chat normal", "an unwritable evidence store restricts the brain, new turns run restricted, and it clears itself"; approval-scope-isolation "other chat loss"; session-safety-boundaries "other-chat-recording-loss".

Review follow-up

Sixth review, at 07165d5

One blocking finding (P1) and one nonblocking (P3). Both are fixed.

  • P1 (security), fixed: a different tool reusing an id was undercounted. Claude counted admissions per hook, keyed by id alone, and took the highest count across hooks. A Bash call that reused an auto-allowed Grep's id passed the mutating hook first. That hook had never seen the id, so its count of one did not raise the maximum. Its deny then found one admission and discharged the Grep's obligation, before the hook both tools share counted the Bash call. The chat ended normal and complete, although the search had run.
    Fix (as specified):
    • Claude counts per (tool name, id). For one tool name, the same hooks match on every admission, so whichever hook of a later admission starts first reports it.
    • admitting(toolUseId, toolName) carries the tool name, in both backends.
    • The collector keeps the tool names seen for each id. A refusal discharges an obligation only when the id was admitted exactly once, under one tool name, and was never allowed. Once two tool names are seen, the id can't be discharged by refusal, so a third is not kept.
  • P3, fixed: the three stale comments now state the narrowed rule: event-writes.ts (safetyDischarge), safety-store.ts (openSafetyObligation), and the safety-result-exits header. session-safety-reviews.md condition 2 now says "under one tool name".

New permanent tests: the reviewer's two cross-tool probes, on the installed runtime (Odysseus world, offline).

  • safety-result-retention "a denied shell call reusing a search's id cannot settle the search that ran". This is the natural-order probe, with the search's result report dropped. A second variant holds the shared hook 150 ms. The search's bytes reach the model, the background Bash under the same id is denied by its own hook, and the chat stays restricted with a durable recording_failed gap.
  • safety-result-retention "a denial of another tool under the search's id cannot settle the search that already ran…" (retooled mode). This one uses real cancellation under controlled hook scheduling. The Read's native-read hook waits until the search has printed its matches, stops the turn and denies the Read. The shared hook is held until that deny lands. Both result hooks are skipped, and the chat stays restricted with a gap naming toolu_sirens.
  • Also:
    • safety-result-exits gains a retooled variant: one admission under grep, one under bash, then a deny, and the call stays owed;
    • permission-wiring-units "a reused id under another tool name is a new admission, reported by its first hook even when that hook never saw the id";
    • the Pi unit stubs now check the tool name reported with each admission.
  • The single card Deny (installed runtime and real wiring) still ends with no gap and a normal chat.

Failing-first. The four guard sources were checked out from 07165d5, with this branch's tests: 6 fail, 112 pass, exit 1.

  • SAFETY_RETOOLED_SHELL_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH fails in both shell variants (expected restricted, received normal).
  • SAFETY_RETOOLED_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH fails (expected restricted, received normal).
  • The rest are the new reporting assertions: CLAUDE_REUSED_ID_UNDER_ANOTHER_TOOL_IS_A_NEW_ADMISSION, PI_EVERY_PERMISSION_REQUEST_IS_AN_ADMISSION and PI_GATE_EVERY_TOOL_CALL_IS_AN_ADMISSION.
  • The collector's retooled variant passes on 07165d5 too: that collector already counted the two reports as two admissions. It pins the collector's own tool-name rule.

Mutations. Run at the fix, each restored with git checkout HEAD --; tree clean afterwards. Every one exits 1:

Mutation Fails
Per-tool guard, backend: Claude keys its admission counters by id alone, as at 07165d5 4 tests: both shell variants (SAFETY_RETOOLED_SHELL_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH), SAFETY_RETOOLED_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH, CLAUDE_REUSED_ID_UNDER_ANOTHER_TOOL_IS_A_NEW_ADMISSION
Per-tool guard, collector: the one-tool-name condition is dropped 5 tests: the same three installed tests; retooled (SAFETY_UNPROVEN_REFUSAL_KEEPS_THE_OBLIGATION); the Pi grant test (SAFETY_PI_REFUSAL_KEEPS_THE_OBLIGATION, where brain_read_base then bash reuse an id)
Count guard: any count for the one tool counts as the only admission SAFETY_DUPLICATE_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH, readmitted

Runs after the sixth follow-up. Each exit code was read from its own command.

At a4ab6c5 (the fix, with origin/main 0129244 merged):

  • The reviewer's 53-file focused set: exit 0.
  • Provider history (both backends), no-console and http-inventory: exit 0.
  • Every test file in ui-backend-claude: exit 0. Also ui-backend-pi and ui-sdk, both exit 0.
  • tsc --noEmit (16 GB heap), bun run lint and bun run api-report (no diff): each exit 0.
  • ui-server package: incomplete locally, left to hosted CI. The host's load average was 29–37 on 32 cores, from other workers, and after 80 minutes the run was stopped (earlier runs took about 50). It recorded one failure, a load-related timeout in a file this PR doesn't touch: hygiene-media-effects "mixed versions: a keep-copy answer…", where the brain hygiene CLI subprocess was killed at the 30 s budget (exited null). That file passed on its own on the same host (34/34, exit 0), and the failure is filed as ui-server: a hygiene keep-copy mixed-versions test exceeds its 30 s budget under load, and its CLI subprocess is killed #3878.

At 7ad2bb7 (origin/main b77987a merged, which touches none of this PR's guard files):

  • tsc --noEmit (16 GB heap): exit 0.
  • bun run api-report: exit 0, no diff.
  • The five targeted files: 118/118, exit 0.
  • bun run check:pr --base origin/main: exit 0 (receipt below).

Failing-first and mutations ran at a5c7ed8, before those merges, which touched none of the guard sources or their tests.

Fifth review, at 8abd1d0

Two blocking findings, P1a and P1b. Both are fixed. P1a went through two coordinator decisions, described below. Each new test fails on the source it guards against, at its named assertion, and each guard has a mutation receipt. The earlier rounds' fixes are unchanged and still pass (runs below).

  • P1a (security), fixed: a refusal settled a Claude call that had already run. The installed Claude 2.1.293 admits the same tool_use_id twice. In the reviewer's run:

    1. the first real Grep ran;
    2. the turn was stopped while it ran, so neither result hook fired;
    3. the second admission was denied at its index wait, before its begin();
    4. that denial discharged the first call's obligation, and the chat ended normal and complete with no gap.

    The round-4 allow note couldn't catch this. Bare allowedTools runs a call without ever consulting canUseTool, and the Agent and Bash rewrite hooks can return allow the same way.

    • First decision (a04ba5d): no refusal discharges an obligation once begin() has made it durable. A measurement against that commit showed the cost was too coarse. A user's Deny on a Claude permission card comes after the hook's begin(), so every denied card left that chat a permanent recording_failed gap and ran it restricted. A probe confirmed it: Grep outside the allowlist, card denied → failure: recording_failed, restriction: restricted.

    • Coordinator's narrowed decision (5808ed4), under proportionate containment rules 1 and 2: a refusal discharges an obligation only when all three of these hold.

      1. It is the backend's own denial before the call could run: a Claude canUseTool deny (which covers a denied card), a Claude PreToolUse hook deny, or a Pi permission deny or gate block.
      2. The runtime admitted a call under that id exactly once.
      3. No allow was ever observed for that id.

      Anything else proves nothing, and only the recorded result discharges. That covers a second admission (the reviewer's case), an allow followed by a refusal, a rejected request (a stopped turn, a replayed Pi request), and an id whose admissions were never reported. Rationale: when the gate denied the only admission of that id, the tool could not have run under it. The duplicate-id attack needs two admissions, and the second one makes the id undischargeable by refusal.

    • How admissions are counted. Backends report each admission through a new internal inputSafety.admitting(toolUseId). refused(toolUseId, denied) now says whether the refusal is the backend's own denial.

      • Claude counts per hook. Each matching PreToolUse hook runs once per admission, so the highest per-hook count is the number of admissions. The count is taken synchronously at the start of each fenced hook, so a second admission is reported by whichever of its hooks starts first, before any of its waits, decisions or begin().
      • Counting begin() calls would be wrong both ways. One admission records its input from several hooks (for example the RTK rewrite and the mutating hook for one Bash call). And the reviewer's second admission was denied before it ever reached begin().
      • Pi counts each permission request (a replay included) and each tool_call event. Only a deny answer is a denial; a dispatcher rejection is not.
    • Where the counts live. In the turn's collector, not on the obligation row:

      • an admission can be denied before any row exists, as in the reviewer's run;
      • only that collector discharges its turn's obligations;
      • a restart gaps every open obligation whatever the counts say;
      • a write per admission would add a round trip for no safety gain.

      An id the collector can't track (more than 2,000 in one turn) keeps no count, so no refusal discharges it. allowed() again notes the allow, and refuses the call when it can't. A rejected begin() discharges nothing by itself; the denial the backend returns on it does, if the three conditions hold.

    • Stopped turns (confirmed by the coordinator). A Claude PreToolUse hook or canUseTool that denies because the turn was cancelled is still the backend's own pre-execution deny. On the id's only admission, with no allow observed, it discharges, because that gate refused the call. Pi's stopped-turn rejection (the dispatcher rejects the request because the turn is no longer live) is a rejection, not a deny, so condition 1 excludes it and the call stays owed. Pinned by PI_REJECTED_REQUEST_IS_NO_DENIAL and the rejected variant.

  • P1b (security), fixed: a Pi grant was usable before the collector's last check. The permission handler published the grant, and only then did the dispatcher await allowed(). A concurrent readBase for the same id used the grant while a same-id refusal was turning the answer into a deny. Real note bytes came back, both permission answers said deny, and the chat ended normal and complete.
    Fix: the handler's new permit() step runs in this order:

    1. the collector's check;
    2. a recheck of liveness and of the call's standing admission (revalidatePiAdmission, or safetyAdmissionRefusal for an application tool);
    3. publishing the grant, with no wait between the grant and the answer.

    A refused check denies the call and publishes nothing. A stopped turn rejects it. The dispatcher's wrapper now only refuses non-allow outcomes.

Audit: every place a Pi grant or capability becomes usable.

Where What becomes usable Ordering now
permission (worker RPC) The call's grant Published last, after the collector's check and both rechecks (fixed)
permission, application tool An allow with no grant; the server route authorizes the application Answered only after the check
lock A lock id Uses an existing grant and revalidates under the lock. Then publishes the lock id, with no later wait or refusal
admission (final bash) { ok: true } Uses the grant, revalidates, deletes the grant. No later wait
fileObservation Nothing; records a phase against a grant Uses an existing grant
bridge, readBase Nothing Delete the grant before they use it
apply Nothing; no grant The server route checks the exact application
In-process gate (tool_call) The pass itself Returned only after allowed() resolves
rememberPiAdmission A standing-admission record Not usable alone. lock, admission and the in-process bash recheck each need a grant or a gate pass as well

New permanent tests (Odysseus world, keyless, offline):

  • safety-result-retention "a denial under an id the runtime admitted twice cannot settle the search that already ran, so its chat keeps a permanent gap". This is the reviewer's reproduction:

    • the installed Claude runtime (MEASURED_RUNTIME);
    • a scripted loopback model that sends two Grep blocks under one id;
    • the real runtime ripgrep, behind a wrapper that marks when its matches are out;
    • a second admission that waits for that mark, stops the turn, and is denied at its index wait.

    It asserts that the runtime admits the id twice, that both result hooks are skipped, that the chat is restricted and incomplete with a recording_failed gap naming Grep (toolu_sirens), and that the host reported both admissions.

  • safety-result-retention "a search denied at its permission card never runs, and its chat stays normal with no gap". The installed runtime, under an enforced turn allowlist that leaves Grep out, asks the callback once. Penelope denies the card. The test asserts that the search never ran (the wrapper's mark is absent), that there is no gap, and that the chat stays normal and complete, also after recovery. It also asserts that the host saw exactly one admission. (The runtime exposes Grep only when its own allowlist names it, and then runs it without asking. So the card is reached through the enforced allowlist, the production path for an off-list call.)

  • safety-result-exits:

    • "a Pi grant is unusable until the collector's last check passes, and a call refused at that check stays owed" (P1b). Real collector, write worker, live-safety projection and a fixed allowlist. The test holds the collector's check, sends readBase early, then sends a denied bash request under the same id. It asserts that nothing is read, both answers deny, the obligation is kept (two admissions), and the end leaves the gap.
    • "a refusal that cannot prove an admitted call never ran leaves it owed", ×4 (rejected, readmitted, allowed, unreported): one variant per condition, plus the untracked default.
    • "a Claude call denied at its permission card on its only admission owes nothing, and its chat stays normal": the real permission wiring and collector.
  • Backend units:

    • permission-wiring-units "each admission the runtime makes is reported once, by whichever of its hooks starts first": a Write passes several hooks.
    • Denial flags and admission reports are pinned in the existing Claude, Pi gate and Pi dispatcher unit tests.

Failing-first. The guard sources (safety-collector.ts, worker-rpc.ts, permission-gate.ts, permission-hooks.ts) were checked out from the named commit, with this branch's tests:

  • On 8abd1d0 (the reviewed head): 13 fail, 100 pass, exit 1. The finding tests fail at their named assertions:

    Test Fails at
    duplicate-id (installed Claude) SAFETY_DUPLICATE_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH (expected restricted, received normal), after SAFETY_RUNTIME_ADMITS_ONE_ID_TWICE, SAFETY_SECOND_ADMISSION_IS_DENIED and SAFETY_RUNTIME_SKIPPED_BOTH_RESULT_HOOKS passed
    Pi grant SAFETY_PI_UNCHECKED_GRANT_NEVER_READS (expected 0, received 1)
    refusal proves nothing: rejected, readmitted, unreported SAFETY_UNPROVEN_REFUSAL_KEEPS_THE_OBLIGATION (expected 1, received 0)

    The other failures are the new reporting assertions, which 8abd1d0's backends don't make: CLAUDE_ONE_ADMISSION_IS_REPORTED_ONCE, PI_NON_ALLOW_PERMISSION_REFUSES_THE_CALL, PI_GATE_BLOCK_REFUSES_THE_CALL and similar. On 8abd1d0 a card Deny already left no gap, so the installed card-deny test gets past its gap checks there. It fails only at SAFETY_RUNTIME_ADMITS_THE_DENIED_SEARCH_ONCE.

  • On a04ba5d (the first, unnarrowed P1a): 12 fail, 101 pass, exit 1. The narrowing tests fail at their named assertions:

    Test Fails at
    installed card deny SAFETY_CARD_DENY_LEAVES_NO_GAP
    wiring card deny SAFETY_CLAUDE_CARD_DENY_DISCHARGES_THE_CALL (expected 0, received 1)
    restored "a call the backend denies on its only admission owes nothing…" SAFETY_REFUSED_AND_RECORDED_CALLS_OWE_NOTHING (expected 0, received 1)
    restored "a call refused when its edited input cannot be recorded owes nothing" SAFETY_REFUSED_EDIT_OWES_NOTHING (expected 0, received 1)

Mutations. Run at the narrowed fix, each restored with git checkout HEAD --; tree clean afterwards. Every one exits 1:

Mutation Fails
Admission-count guard: any count ≥ 1 counts as the only admission 3 tests: the installed duplicate-id test (SAFETY_DUPLICATE_DENIAL_CANNOT_SETTLE_THE_RUN_SEARCH, normal); readmitted (SAFETY_UNPROVEN_REFUSAL_KEEPS_THE_OBLIGATION); the Pi grant test (SAFETY_PI_REFUSAL_KEEPS_THE_OBLIGATION)
Denial guard: any refusal counts as a denial rejected (SAFETY_UNPROVEN_REFUSAL_KEEPS_THE_OBLIGATION)
Allow guard: an observed allow is ignored allowed (SAFETY_UNPROVEN_REFUSAL_KEEPS_THE_OBLIGATION); "a Claude call its callback allowed stays owed…" (SAFETY_LATER_REFUSAL_KEEPS_THE_OBLIGATION)
Claude reports every hook invocation as an admission CLAUDE_ONE_ADMISSION_IS_REPORTED_ONCE
Claude counts an admission after its hook, not before CLAUDE_SECOND_ADMISSION_IS_REPORTED_AT_ONCE
Pi dispatcher doesn't report admissions PI_EVERY_PERMISSION_REQUEST_IS_AN_ADMISSION. An unreported id is fail-safe: it can't be discharged by refusal
permit() publishes the grant before the check, withdrawing it on refusal as 8abd1d0 did SAFETY_PI_UNCHECKED_GRANT_NEVER_READS

Existing tests changed, and why.

  • safety-result-exits, reverted to their original expectations, which the narrowed rule makes correct again:
    • "a call the backend refuses owes nothing, and a recorded result discharges its call" is now "a call the backend denies on its only admission owes nothing, and a recorded result discharges its call". The original assertions are back: SAFETY_REFUSED_CALL_STAYS_REFUSED, SAFETY_REFUSED_CALL_DOES_NOT_STOP_ITS_TURN, SAFETY_REFUSED_AND_RECORDED_CALLS_OWE_NOTHING, SAFETY_REFUSED_CALL_LEAVES_NO_GAP and SAFETY_DISCHARGED_CALLS_KEEP_COVERAGE. The only change: it reports one admission per call, and the refusal is the backend's denial (refused(id, true)).
    • "a call refused when its edited input cannot be recorded owes nothing": its original name and assertions are back. It reports the admission and adds the denial the backend returns on the rejected edit. A rejected begin() no longer discharges by itself, so SAFETY_REFUSED_EDIT_OWES_NOTHING now follows that denial.
    • Neither keeps an a04ba5d-era assertion; the strict "stays owed" cases moved into the four-variant test.
  • safety-result-retention: the harness gains the duplicate and denied modes. Its collector wrapper now forwards the denial flag and counts admissions. The three existing cases are unchanged.
  • Backend units, with assertions extended to pin condition 1 and admission reporting:
    • permission-wiring-units: the describe is now "admissions, refusals and the collector's last check". CLAUDE_DENY_REFUSES_THE_CALL and CLAUDE_UNCHECKED_ALLOW_IS_REFUSED now expect [id, true].
    • tools-permission: PI_GATE_BLOCK_REFUSES_THE_CALL expects [id, true], plus PI_GATE_EVERY_TOOL_CALL_IS_AN_ADMISSION.
    • worker-rpc: a deny is [id, true] and a rejection [id, undefined], plus PI_EVERY_PERMISSION_REQUEST_IS_AN_ADMISSION and PI_REJECTED_REQUEST_IS_NO_DENIAL. PI_UNCHECKED_ALLOW_IS_REFUSED expects [id, true].
    • Names and labels that said "never runs", "owes no result" or "noted" were updated (*_CHECKED, *_UNCHECKED_*).

Docs.

  • session-safety-reviews.md states the three conditions, what stays conservative, where the counts live, and the grant ordering.
  • The changeset says the same for users: a denied permission card leaves the chat as it was.
  • The @internal SDK docs for admitting, refused and allowed are updated.
  • Citations into the files this PR moves are re-anchored. check-citations finds none drifted in this round's files; 310 are drifted in the repo, down from 334.
  • api-report: no diff, since admitting is @internal.

Containment checklist, for the changed guards. Each one only keeps or adds restriction relative to a recorded result.

  • A refusal that proves nothing keeps its obligation; at worst its one chat gets a permanent gap, and the gap's cause names the call.
  • A refused last check refuses one call, and the turn continues.
  • A denied card no longer restricts anything.
  • Nothing latches the brain, and no new state needs a human to clear it.

Runs after the fifth follow-up. Each exit code was read from its own command.

At c68a17b (the narrowed fix, with origin/main 46085b2 merged; 07165d5 then also merges main's test-only 7f1c158, in packages/common, which this PR does not touch):

  • The reviewer's 53-file focused set: 945/945, exit 0.
  • Provider history (provider-history and provider-history-apify, both backends), plus no-console and http-inventory: 43/43, exit 0.
  • Every test file in the four packages this PR touches:
    • ui-backend-claude: 876/876, exit 0.
    • ui-backend-pi: 595/595, exit 0.
    • ui-sdk: 1374 pass, 1 skip, exit 0.
    • ui-server: 5720/5720 across 457 files, exit 0.
  • tsc --noEmit (16 GB heap): exit 0.
  • bun run lint: exit 0.
  • bun run api-report: exit 0, no diff.
  • bun run check:pr --base origin/main: exit 0 at 07165d5, mode focused; all five checks passed: lint and leakage gates, environment documentation, pending changeset package names, contribution changeset, affected fast invariants (receipt below).

Before the narrowing, at a04ba5d+d088575c3 (origin/main 5537ccb merged), the same set was green:

  • focused 934/934;
  • guards 43/43;
  • claude 875/875, pi 595/595, sdk 1372 + 1 skip;
  • ui-server 5710/5710 across 457 files.

Failing-first and mutations ran at 5808ed4, before origin/main 46085b2 was merged. That merge touched none of the guard sources or their tests.

Left open after this round.

  • Conservative gaps that remain, all where the host cannot prove a call never ran:
    • a refusal of a second admission of the same id;
    • a refusal after an allow, including a stale outward-plan recheck in Pi's permit() after the collector's check;
    • a Pi dispatcher rejection (a stopped turn, a replay);
    • an obligation whose admission was never reported;
    • a deny the host did not return (a settings deny rule).
  • Assumptions the Claude admission count rests on. Each matching PreToolUse hook runs once per admission, and the runtime never runs a call before all its hooks have returned. The duplicate-id and card-deny tests characterize both on the installed 2.1.293.
  • Cost. Admission counts and allows are in memory and add no write.

Fourth review, at 0085b9b

One blocking finding (P1) and one regression from the obligation ledger (P2). Both are fixed. Each new test fails on 0085b9b's sources at its named assertion, and each guard has a mutation receipt. The earlier rounds' fixes are unchanged and still pass (runs below).

  • P1 (security), fixed: a later Pi refusal erased the obligation of a call that had already run. The dispatcher called refused(toolCallId) on every permission denial or rejection, and the collector deleted the obligation. So a call could be allowed, run the real curated grep, go unreported, and then lose its obligation to a later permission request for the same id: a replay rejection, a stopped-turn rejection or a denial. Its chat then ended normal and complete. Rejecting a later request proves nothing about an earlier call.
    Fix: a refusal discharges an obligation only if the backend never let that call run. Each backend notes its allow with a new internal inputSafety.allowed(toolUseId) before it returns the allow:

    • the Pi dispatcher's permission allow;
    • the Pi in-process gate's pass;
    • Claude's canUseTool allow, which is the runtime's last gate.

    Once a call is noted as allowed, it stays owed until its result is recorded. A later refusal of the same id discharges nothing, and neither does a rejected begin(), a stopped turn or a replay. The rule is enforced in one place, the collector (dischargeRefused), and it covers all four refusal sites:

    • a rejected begin();
    • Claude hook and callback denials;
    • Pi permission answers;
    • Pi gate blocks.

    allowed() rejects a call that was already refused, or whose latest begin() didn't complete. The backend then refuses the call instead of running it with no obligation. The Pi dispatcher also withdraws its grant. The note is kept in memory on the turn's collector, the finding's second option: only that collector discharges, and a restart gaps every open obligation anyway.

  • P2 (regression), fixed: shutdown could gap a result that was already recorded. The result's finalized exposure committed in one transaction and the obligation's discharge in the next. A collection end landing between the two gapped a durable record (SAFETY_CANCELLED_RECORDED_RESULT_IS_NO_GAP failed in both of the reviewer's runs).
    Fix: the result's last exposure write now carries the obligation id, and safetyCommit discharges it in the same transaction (discharged: true confirms it). No end and no restart can see the record durable and the call still owed. A result with nothing to record is recorded by its discharge alone. A record that fails stays owed, and the chat keeps its gap, as before.
    That alone left the real-runtime test a race: the end could still land before the record's first write. So safetyEnd now also waits, bounded at 10 s with an unref'd timer, for that turn's result records already under way, and then ends the collection. Stopping a turn already refused new tools but never a record; the end now keeps that promise. A record that starts after the end began is refused and gapped, as before. A record that has not settled within the bound is refused by the end, and its chat keeps the gap.

Exit-path audit, allowed calls. Extends the third review's table.

Backend Path 0085b9b Now Test
Pi host Allowed, ran (real curated grep), unreported; later permission RPC reusing its id is rejected as a replay Discharged → normal, complete Owed → gap naming the call safety-result-exits "a Pi call allowed and run stays owed…: replayed"
Pi host Same; the later RPC is rejected because the turn stopped Discharged Owed → gap "…: stopped"
Pi host Same; the later RPC is denied Discharged Owed → gap "…: denied"
Collector (via Pi host) Same; the later RPC's begin() is rejected (its edited input cannot be recorded, before delivery, which gaps nothing by itself) Discharged Owed → gap "…: unrecordable"
Pi in process Gate let the call through, the search ran; a later tool_call for the id is blocked Discharged Owed → gap "a Pi call the in-process gate let through stays owed…"
Claude canUseTool allowed, the turn stopped before either result hook; a later fenced PreToolUse deny and canUseTool deny for the id Discharged Owed → gap "a Claude call its callback allowed stays owed…"
Any An allow the collector can't note (the call was refused, or its begin() didn't complete) Ran with no obligation Refused instead (Pi dispatcher also drops its grant) PI_UNNOTED_ALLOW_IS_DENIED, PI_GATE_UNNOTED_CALL_IS_BLOCKED, CLAUDE_UNNOTED_ALLOW_IS_DENIED
Collector Result recorded; the end or a restart lands right after the last exposure commits Still owed → permanent gap Discharged in that commit: no gap, none at boot "a result's last record discharges its call in the same commit…"
Collector The turn stops as its result arrives; the end is issued while the record is halfway (occurrence written, exposure not) End refuses the rest → gap End waits, then the record completes: reviewable, no gap "a collection's end waits for a stopped turn's result record already under way"

The four refusal sites from the third review still discharge when the backend never let the call run. Those tests are unchanged and pass: CLAUDE_DENY_REFUSES_THE_CALL, PI_NON_ALLOW_PERMISSION_REFUSES_THE_CALL, PI_GATE_BLOCK_REFUSES_THE_CALL, SAFETY_REFUSED_EDIT_OWES_NOTHING, SAFETY_REFUSED_AND_RECORDED_CALLS_OWE_NOTHING.

Failing-first. The new and extended tests, run against 0085b9b's sources (the 7 source files checked out from 0085b9b, tests from this branch). 13 fail, 88 pass, exit 1. Each fails at its named assertion:

Test Fails on 0085b9b at
safety-result-exits "a Pi call allowed and run stays owed whatever a later request for it says", ×4 (replayed, stopped, denied, unrecordable) SAFETY_LATER_REFUSAL_KEEPS_THE_OBLIGATION, after SAFETY_PI_CALL_IS_ALLOWED, SAFETY_PI_ALLOWED_CALL_OWES_ITS_RESULT and SAFETY_PI_ALLOWED_SEARCH_RAN passed (and, for unrecordable, SAFETY_PI_REFUSED_ADMISSION_GAPS_NOTHING_BY_ITSELF)
safety-result-exits "a Pi call the in-process gate let through stays owed…" SAFETY_LATER_REFUSAL_KEEPS_THE_OBLIGATION
safety-result-exits "a Claude call its callback allowed stays owed…" SAFETY_LATER_REFUSAL_KEEPS_THE_OBLIGATION
safety-result-exits "a result's last record discharges its call in the same commit…" SAFETY_RECORDED_RESULT_IS_DISCHARGED_IN_ITS_OWN_COMMIT (owed 1 after SAFETY_RESULT_RECORD_IS_DURABLE)
safety-result-exits "a collection's end waits for a stopped turn's result record already under way" SAFETY_END_WAITS_FOR_A_RECORD_UNDER_WAY (ended: 1 while the record was held)
worker-rpc "every permission answer but allow…" (extended) PI_ALLOWED_PERMISSION_IS_NOTED_BEFORE_IT_RUNS
worker-rpc "an allow the collector can no longer note is denied, and its grant withdrawn" PI_UNNOTED_ALLOW_IS_DENIED
tools-permission "a call the gate lets through is noted before it runs…" PI_GATE_UNNOTED_CALL_IS_BLOCKED
permission-wiring-units "a call the backend lets run stays owed" (extended) CLAUDE_CALLBACK_ALLOW_IS_NOTED
permission-wiring-units "a callback allow the collector cannot note is denied instead" CLAUDE_UNNOTED_ALLOW_IS_DENIED

The P2 interleaving tests are deterministic, with no sleeps. One holds the collector inside its own writes.record call. The other uses the write worker's FIFO idle() barrier: had the end been sent, the writer has applied it by then.

Mutations. Run at the fix, each restored with git checkout HEAD --; tree clean afterwards. Exit 1 for every one:

Mutation Fails
refused() ignores the allow 6 tests at SAFETY_LATER_REFUSAL_KEEPS_THE_OBLIGATION: Pi replayed, stopped, denied, unrecordable; Pi gate; Claude
A rejected begin() ignores the allow Pi unrecordable at SAFETY_LATER_REFUSAL_KEEPS_THE_OBLIGATION (only it)
Pi dispatcher doesn't note its allow PI_ALLOWED_PERMISSION_IS_NOTED_BEFORE_IT_RUNS, PI_UNNOTED_ALLOW_IS_DENIED, and the 4 Pi dispatcher variants
Pi gate doesn't note its pass PI_GATE_UNNOTED_CALL_IS_BLOCKED, the gate end-to-end test
Claude canUseTool doesn't note its allow CLAUDE_CALLBACK_ALLOW_IS_NOTED, CLAUDE_UNNOTED_ALLOW_IS_DENIED, the Claude end-to-end test
safetyCommit skips the discharge, which falls back to a separate commit SAFETY_RECORDED_RESULT_IS_DISCHARGED_IN_ITS_OWN_COMMIT
safetyEnd doesn't wait for records under way SAFETY_END_WAITS_FOR_A_RECORD_UNDER_WAY

The reviewer's regression. safety-result-retention "a turn stopped as its result arrives still records the result the runtime replays" (SAFETY_CANCELLED_RECORDED_RESULT_IS_NO_GAP, installed Claude, real resume) passed 10 consecutive runs, each exit 0.

Existing tests changed.

  • worker-rpc "every permission answer but allow…" gives its fake collector allowed and asserts that the allow is noted. The dispatcher now refuses discharge through a collector that cannot note allows, so a collector without allowed would no longer see the refusals this test counts.
  • permission-wiring-units' wiring() helper records allows and lock releases.

Assertions are otherwise unchanged.

The reviewer's barrier probe, which holds safetyDischarge, no longer reaches its barrier: a result with occurrences now discharges inside its last commit. The new "same commit" test holds that commit instead.

Docs. session-safety-reviews.md states the allow rule, the single commit and the end's wait. The changeset says the same for users. Twelve citations into the files this PR touches are re-anchored (check-citations: none drifted in those files; 323 drifted in the repo, down from 335).

Containment checklist, for the changed guards. Each one only keeps or adds restriction.

  • The allow rule keeps an obligation, so at worst the one chat gets a permanent gap, with its cause naming the call (site: "safetyEnd" or "boot-obligation").
  • A rejected allowed() refuses one call, and the turn continues.
  • The end's wait holds only that turn's teardown, bounded and unref'd, and then proceeds. A record still unsettled at that point is refused and gaps only its chat.
  • Nothing latches the brain, and no new state needs a human to clear it.

Runs after the fourth follow-up (at 8abd1d0, with origin/main d79eeed merged; each exit code read from its command):

  • Every test file in the four packages this PR touches, at 9e6802a's sources (origin/main d79eeed merged):
    • ui-sdk: 1372 pass, 1 skip, exit 0.
    • ui-backend-pi: 595/595, exit 0.
    • ui-backend-claude: 875/875, exit 0.
    • ui-server: 5699/5700, exit 1. The one failure was http-inventory. Its prose count said 179 declared endpoints, but the app declares 180. This has been wrong since the recovery route was added in an earlier round. It is fixed in 862316a, and the test now passes 5/5.
  • Focused, 49 files: the third round's 44, plus worker-session, worker-session-units, provider-history and provider-history-apify for both backends, at the same sources. 855/855, exit 0.
  • Provider history (provider-history, provider-history-apify, both backends): 35/35, exit 0.
  • no-console: 3/3, exit 0.
  • After merging origin/main 61c97a5, at 8abd1d0:
    • tsc --noEmit (16 GB heap): exit 0.
    • bun run lint: exit 0.
    • bun run api-report: exit 0, no diff. allowed is @internal.
    • Focused set plus http-inventory and main's changed native-journal-observer, reference-worktree-journal and compute-host (53 files): 932/932, exit 0.
    • bun run check:pr --base origin/main: exit 0 (receipt below).

Left open after this round.

  • Claude auto-allowed calls. (Closed in the fifth review: the installed runtime does admit an id twice, and a refusal of a second admission now proves nothing.) A Claude call auto-allowed by bare allowedTools never reaches canUseTool, so the host sees no allow for it. A PreToolUse hook's allow is no such signal either: a parallel hook's deny wins. If the runtime admitted the same tool_use_id again after running it, a deny of that second admission would still discharge the call. The installed runtime admits each id once. Pi worker requests, which are adversarial input, are fully covered. Closing this for Claude needs a host-visible signal that the runtime has started the tool, and the SDK has none.
  • Waits and cost. The end's wait for records under way is bounded at 10 s. allowed() is in memory and adds no write. A result with occurrences no longer pays a separate discharge round trip; a result with nothing to record still pays one.

Third review, at e162f73

One blocking finding; everything else passed. The fix has a failing-first run on e162f73's sources and a mutation receipt for every new guard. The first and second rounds' fixes are unchanged and still pass (below).

  • P1 (security), fixed: a turn cancelled before Claude ran either result hook kept no taint. A turn stopped after the search had printed its matches, but before the runtime dispatched post-tool hooks, reached neither PostToolUse nor PostToolUseFailure. The runtime still kept the call in its session (in the reviewer's run, the matched note was replayed on resume), and the chat reported normal, complete, zero unresolved. Ending a collection assumed a missing hook leaves an open exposure, but Grep has no input-side occurrence. Fix: an obligation ledger. Every call begin() admits is recorded as an obligation (safety_obligations, migration 085) before the tool runs. It is discharged only when the call's result is durably recorded, or when the backend refuses the call, which proves it never ran. A collection that ends owing one, however it ended, gets a permanent recording_failed gap naming the call (failure_cause.site: "safetyEnd"). An obligation still open at boot gets the same gap (site: "boot-obligation"). The ledger is the host's own record, so it does not depend on Claude delivering any hook. Refusals that discharge: a rejected begin() (both backends refuse the call on rejection), every deny a fenced Claude PreToolUse hook or canUseTool returns, every Pi permission answer other than allow (a deny or a rejection: pi-agent-core's prepareToolCall blocks the call before it runs), and a Pi tool_call block. A refused call stays refused, so a parallel hook's later begin() cannot reopen it. Round 2's semantics hold: a stopped turn's fully observed result is recorded as an occurrence, discharges its call, and leaves no gap.
  • Pi's host has the same shape (admission at permission, result at safetyResult), so the same ledger covers it. A worker that dies mid-tool, or never reports, leaves the gap.

Exit-path audit, obligation ledger. Extends the second review's audit below, whose restart row now also names the owed call's gap. Each path between begin() admitting a call and its result's record now records the result, refuses the call, or leaves the chat a permanent gap, whatever the runtime delivers.

Backend Path e162f73 Now Test
Claude Turn stopped while the tool runs, before post-tool dispatch: neither result hook runs, the runtime keeps the call Neither: normal, complete Owed at end → gap naming the call safety-result-retention "a turn stopped while its search runs…" (installed Claude, real resume)
Collector Collection ends owing an admitted call (cancelled, aborted, never reported, either backend) Neither Gap (site: "safetyEnd") safety-result-exits "a call admitted and never reported…"
Host Process dies after admission host_restart_unknown only Plus the owed call's own gap (site: "boot-obligation"); a recorded call in the same turn is not named safety-result-exits "…still owed when the host dies…"
Collector Result recorded (also for a stopped turn) n/a Discharged; no gap SAFETY_CANCELLED_RECORDED_RESULT_IS_NO_GAP, SAFETY_REFUSED_AND_RECORDED_CALLS_OWE_NOTHING
Claude Fenced PreToolUse deny (cancel, stale admission, policy, a hook that throws) or canUseTool deny n/a Refused: owes nothing permission-wiring-units "refusals owe no result"
Pi host permission answer other than allow (deny, or rejection such as a stop after admission) n/a Refused: owes nothing worker-rpc "every permission answer but allow…"
Pi in process tool_call gate block n/a Refused: owes nothing tools-permission "a call the gate blocks…"
Collector Re-admission rejected (an edited input that cannot be recorded) n/a Rejected begin() is a refusal: owes nothing, no gap safety-result-exits "…edited input cannot be recorded…"
Collector The obligation itself cannot be recorded n/a Before the call runs: SafetyRecordingUnavailable, call refused, no gap safety-result-exits "…admission cannot be recorded…"
Collector begin() after a refusal of the same call (a parallel hook) n/a Refused again without stopping the turn; cannot reopen the call SAFETY_REFUSED_CALL_STAYS_REFUSED
Collector A discharge that cannot commit n/a Still owed → gap at end (fail closed) by construction

Failing-first (e162f73 sources, the reviewer's reproduction made permanent):

Test e162f73 now
safety-result-retention "a turn stopped while its search runs reaches neither result hook, and its chat keeps a permanent gap" (installed Claude 2.1.293; the search is the installed runtime's own ripgrep, behind a wrapper that holds its exit) SAFETY_UNRECORDED_RESULT_RESTRICTS_ITS_CHAT: expected restricted, received normal, after SAFETY_ACTUAL_SEARCH_RAN, SAFETY_RUNTIME_RESUMES_THE_INTERRUPTED_CALL, SAFETY_RUNTIME_SKIPPED_BOTH_RESULT_HOOKS and SAFETY_RUNTIME_KEEPS_THE_CALL_IN_ITS_SESSION passed pass, 5 consecutive runs

The runtime's resumed session carries either the matches or its own "[Tool call interrupted…]" note for the call (the reviewer saw both); the test accepts either and asserts the gap. The ledger's unit tests use the new API (refused, safety_obligations), so their red receipts are the mutations below.

Mutations (scratch worktree at the fix; each restored, tree clean after):

Mutation Fails
End does not gap owed calls SAFETY_UNRECORDED_RESULT_RESTRICTS_ITS_CHAT (installed Claude), SAFETY_OWED_RESULT_IS_A_DURABLE_GAP
Boot does not gap owed calls SAFETY_OWED_AT_RESTART_IS_A_DURABLE_GAP
begin() opens no obligation SAFETY_UNRECORDED_RESULT_RESTRICTS_ITS_CHAT, SAFETY_ADMITTED_CALL_OWES_ITS_RESULT, and 3 more
Recorded result not discharged SAFETY_CANCELLED_RECORDED_RESULT_IS_NO_GAP (installed Claude), SAFETY_REFUSED_AND_RECORDED_CALLS_OWE_NOTHING, SAFETY_ONLY_THE_UNREPORTED_CALL_IS_OWED
Refusal not discharged SAFETY_REFUSED_AND_RECORDED_CALLS_OWE_NOTHING
Rejected begin() not discharged SAFETY_REFUSED_EDIT_OWES_NOTHING
A refused call can be readmitted SAFETY_REFUSED_CALL_STAYS_REFUSED
Obligation failure not classed before delivery SAFETY_UNRECORDED_ADMISSION_REFUSES_THE_CALL
Fenced Claude PreToolUse deny not refused CLAUDE_DENY_REFUSES_THE_CALL
Claude canUseTool deny not refused CLAUDE_DENY_REFUSES_THE_CALL
Pi rejected permission not refused PI_NON_ALLOW_PERMISSION_REFUSES_THE_CALL
Pi denied permission not refused PI_NON_ALLOW_PERMISSION_REFUSES_THE_CALL
Pi gate block not refused PI_GATE_BLOCK_REFUSES_THE_CALL

Existing test changed. live-safety-admission "parallel Claude native-read" checked that the sibling hook had returned after a single setImmediate. Every admission is now a write-worker round trip, so the probe waits on a completion barrier (every sibling hook returned) instead, per test waits. The fence property it proves, and its assertions, are unchanged. safety-result-retention's helper gained the running mode and counts both result hooks; its two earlier cases are unchanged.

Runs after the third follow-up (at 0085b9b, with origin/main a75d54a merged; exit codes read from each command):

  • Focused, 44 files: every safety-* suite in ui-server, every suite using createSafetyCollector, session-safety-boundaries, approval-scope-isolation, http-supported-mounts, live-safety-admission, owner-safety-review, host-publication-safety, web-pi-delivery, chat-deletion, chat-lifecycle, native-history-removal, db-migration-runner, journal-database, software-status, relay-recording-settlement, ws-apify, no-console; ui-backend-pi worker-rpc, tools-permission, extension-inspection, worker-session, worker-session-units; ui-backend-claude permission-wiring-units, follow-up, characterization-permissions, allowlist-enforcement, confirm-bash, confirm-archive, edited-approval; ui-react render/turn-failure; root first-party-failure-classes: 759/759, exit 0.
  • Provider history (ui-backend-claude and ui-backend-pi provider-history, provider-history-apify): 35/35, exit 0.
  • safety-result-retention, 5 consecutive runs before the merge (0fadb44b2, same sources): 3/3 each, exit 0.
  • tsc --noEmit (16 GB heap): exit 0. bun run lint: exit 0. bun run api-report: exit 0, no diff (refused is @internal).
  • bun run check:pr --base origin/main at 0085b9b: exit 0 (receipt below).
  • Migration note: origin/main added 085_journal_object_quarantine.journal.sql. The runner keys receipts on file names, so both 085 files apply (db-migration-runner, journal-database, safety-ledger green).

Second and first reviews, at 511e94a and 88e5805

Moved, unchanged, to this comment to keep the body under GitHub's size limit. Their fixes still hold; see the runs above.

Validation

Failing-first. A probe using only APIs present on both trees (zz-containment-receipts.test.ts, not committed) on origin/main e8ea534, then on this branch:

Receipt origin/main this branch
RECEIPT_3812_BEGIN_FAILURE_REFUSES_ONLY_ITS_TURN fail: same chat refused: Safety recording requires recovery pass
RECEIPT_3812_CHAT_LOSS_LEAVES_OTHER_CHAT_USABLE fail: other chat restricted, expected normal pass
RECEIPT_3812_UNWRITABLE_NOTICE_STILL_RUNS_NEW_TURNS_RESTRICTED fail: new turn refused: Safety recording requires recovery pass
RECEIPT_3812_INCIDENT_STATE_BOOTS_AND_ADMITS (failed=1, reason='capacity', no pending, no open) fail: failed still 1 after boot pass
RECEIPT_3810_NON_CAPACITY_RESERVE_ERROR_IS_RECORDING_FAILED fail: received capacity pass

Mutations (scratch worktree at the PR head; each restored):

Mutation Fails
Re-latch the brain on a safetyBegin error a failed safetyBegin refuses only that turn…
Refuse instead of restrict under the brain latch an unwritable evidence store … clears itself, a durable brain latch … (refused as paused)
Skip automatic recovery same two (condition not reached), automatic recovery waits for an uncovered producer to drain
Skip boot recovery SAFETY_INCIDENT_STATE_RECOVERS_AT_BOOT
Restricted-begun turn treated as unrecordable SAFETY_BRAIN_RESTRICTION_RUNS_NEW_TURNS
Classify every error as capacity 5 tests, incl. SAFETY_NON_CAPACITY_ERRORS_ARE_RECORDING_FAILED, SAFETY_RESERVE_ERROR_IS_RECORDING_FAILED, SAFETY_MIGRATION_FAILURE_IS_RECORDING_FAILED
Later latch overwrites the first cause SAFETY_LATER_LATCH_ONLY_COUNTS
Status shown to every principal SAFETY_STATUS_HIDDEN_FROM_OTHERS
Orphan reservation not gapped at collection end SAFETY_FAILED_COMMIT_CHAT_RUNS_RESTRICTED (safety-ledger)
Early refusal under a latch retains nothing a producer refused under a brain latch still leaves its own chat a durable gap
Unnamed loss latched as scoped SAFETY_UNNAMED_LOSS_IS_DURABLY_UNSCOPED
Session-named loss latches the brain SAFETY_SESSION_LOSS_NEVER_LATCHES_THE_BRAIN
Capacity class lost across the worker SAFETY_CAPACITY_SURVIVES_THE_WORKER
Retained in-process cause discarded SAFETY_RETAINED_LOSS_KEEPS_ITS_ORIGINAL_CAUSE
PWA: drop refusalReason browser: the paused recorder is named: expected 'The brain refused this message.' to be 'Safety recording is paused on this se…'

Runs.

  • safety-containment.test.ts 16/16; every suite importing the changed governance modules plus http-supported-mounts and governance-roadblocks: 33 files, 590 pass before the last two fixes, then the touched ones re-run green (safety-occurrences, http-supported-mounts, safety-containment, safety-ledger, safety-loss-recovery, governance-roadblocks: 250/250; then 70/70 after the review fixes). The complete ui-server package suite is ~10 h locally and is left to hosted proof.
  • ui-react draft-store, render/turn-failure, render/worker-host-notice: 88/88.
  • Browser, pinned image: node scripts/visual.mjs --project=ui-react-layout --filter=outgoing-snapshots: 9/9, incl. the new refusal-copy case.
  • tsc --noEmit clean; bun run lint clean.

Existing tests changed and why. They encoded the brain-wide latch. Each keeps its original property under the new scope: a loss notice that cannot commit still restricts (the injection now fails the chat fact too); final provider admission still rechecks a loss (now the turn's own) and gains other-chat-recording-loss (passes); approvals still withdraw on related loss (own loss) and survive another chat's (other chat loss); capacity still refuses before delivery and still refuses new chats at a full brain, but no longer burns the emergency cell. hold-safety-recovery.ts keeps the reconciler from racing tests that drive recovery by hand. The 081 replay test also replays 085.

Independent review. gpt-6-astra (high), adversarial ledger on git diff origin/main...HEAD: two P1 findings (an early refusal under a latch retained no loss; a loss with no collection latched the brain with no durable scope, so recovery gapped nothing), three P2 (capacity class lost across the worker, retained cause discarded, two assertions that could pass on a broken tree). All five were confirmed and fixed in fix(ui-server): never let recovery clear a loss that named no chat, each with a mutation receipt above. It verified: uncovered open producers block automatic recovery, restricted-begun turns stay restricted after recovery, the reconciler's checks and clearing share one transaction, the status field is owner-only and the recovery POST sits behind the global origin policy.

Not covered here.

  • The obligation ledger fails closed wherever the host cannot prove an admitted call never ran. A deny the host did not return (a project-settings deny rule), a Pi call the worker drops after an "allow" because the turn stopped in between, a refusal of an id admitted twice, and a refusal after an allow all leave the gap, even if the call never ran. Discharging on those would trust a runtime signal; none is used. The ledger assumes, as the existing approval gates already do, that the Claude runtime never runs a call whose PreToolUse hooks have not all returned, and runs each matching PreToolUse hook once per admission.
  • Each admitted call costs one more write-worker round trip before it runs (its obligation). A result that records nothing pays one more for its discharge; a result with records discharges inside its last record's commit. Counting admissions and noting allows is in memory and costs no write.
  • Restart with a durable latch whose loss named no chat gaps every chat in the brain. That's conservative by design; only a compatibility producer with neither a turn nor a session can reach it.

Collisions. recorded in a comment with the head before confirmation.

check:pr (--base origin/main, after the sixth review follow-up, at 7ad2bb7 with origin/main b77987a merged; exit 0):

{
  "version": 1,
  "kind": "brain-check-pr-receipt",
  "head": "6c7331bd052d3e53c75882f59708bfa45fc9b63c",
  "base": "origin/main",
  "mode": "focused",
  "startedAt": "2026-11-10T23:12:48.870Z",
  "finishedAt": "2026-11-10T23:14:36.441Z",
  "checks": [
    {
      "name": "all lint and leakage gates",
      "categories": [
        "changeset"
      ],
      "outcome": "passed",
      "elapsedMs": 11711.230719
    },
    {
      "name": "environment documentation",
      "categories": [
        "changeset"
      ],
      "outcome": "passed",
      "elapsedMs": 94.46436099999846
    },
    {
      "name": "pending changeset package names",
      "categories": [
        "changeset"
      ],
      "outcome": "passed",
      "elapsedMs": 60.56257000000005
    },
    {
      "name": "contribution changeset",
      "categories": [
        "changeset"
      ],
      "outcome": "passed",
      "elapsedMs": 19.174386999999115
    },
    {
      "name": "affected fast invariants",
      "categories": [
        "verify",
        "unit"
      ],
      "outcome": "passed",
      "elapsedMs": 95594.809689
    }
  ]
}

🤖 Generated with Claude Code

schlessera and others added 6 commits November 10, 2026 06:23
…it puts at risk (#3812, #3810)

A single turn's safety-write error used to set one durable flag for the
whole brain, after which every turn in every chat was refused until an
operator ran a script. The failure is now contained at the narrowest scope
that durably takes it, and the host recovers by itself:

- Before delivery (a failed begin, or a refused reservation whose producer
  holds its input) refuses that one turn with the retryable
  SAFETY_RECORDING_UNAVAILABLE error. Nothing latches.
- Lost evidence after delivery marks only that turn's collection failed, so
  its chat keeps a permanent recording_failed gap and runs restricted.
  A reservation still open when its collection ends becomes the same gap.
- Only when that chat fact cannot commit does the brain latch, through the
  emergency reserve or in-process. New turns still begin, each with a
  permanent gap committed before delivery, and run under the tainted
  policy. A turn is refused only when that restricted begin cannot commit
  (safety_recording_paused). A reconciler retries, backing off to once a
  minute, and clears the latch once the producers that predate it drained.
- Boot resolves a set latch and pending reservations after restart
  classification; a legacy row that cannot migrate gaps its own turn.

Every latch keeps its first cause and a count (safety_latch), logs one
structured stderr line, and only a capacity check classifies as capacity.
Every recovery is audited in safety_recoveries with trigger, actor, time
and the cleared cause.

Contract: additive error code SAFETY_RECORDING_UNAVAILABLE and failure
classes safety_recording_unavailable / safety_recording_paused
(docs/integration-contract/wire.md). Projection reasons are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…owner recovery fallback (#3810)

Owner GET /api/status gains safetyRecording: whether the brain-wide recorder
is latched, since when, its reason and first cause, whether only this
process retains the loss, and the last recovery. Other principals never see
it. POST /api/status/safety-recording/recover gives recoverSafetyRecording a
production caller as the owner's fallback to automatic recovery: it refuses
with 409 producers_open, changing nothing, while a producer is open, and
records the owner as the actor.

Contract: additive status field and route
(docs/integration-contract/http.md#safety-recording-status-additive-3810).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…iled (#3810)

A message refused with SAFETY_RECORDING_UNAVAILABLE now returns with copy
that says safety recording failed or is paused and that nothing was sent,
instead of "The brain refused this message." A failed turn with the new
failure classes reads the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eservations

Self-review and the affected suites found four gaps in the containment
change:

- A brain latch raised inside a worker call that does not report its scope
  (a loss at safetyEnd, a peer process) never scheduled automatic recovery.
  Every call now checks for a latch when it settles.
- Construction checked the latch unguarded and threw on a broken store.
- An in-process-only brain restriction logged nothing; it now logs one line.
- Automatic recovery deleted every pending reservation, including those of
  open collections it had just gapped, so their commits failed. It now
  removes only reservations of ended collections; an open one is resolved by
  its own end.

Also registers the recovery route in the mounted-route lifetime audit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…3812)

An independent review found two paths where automatic recovery could clear
the brain latch with a possibly delivered input left ungapped:

- A producer refused early under a latch (or after its own chat failed)
  retained nothing. A producer that does not hold its input now records its
  chat's loss before the refusal returns; one that holds it gets the
  retryable before-delivery refusal.
- A loss with no collection of its own latched the brain with no scope, so
  recovery gapped nothing. A known chat now takes a failed epoch of its own
  without latching the brain; a loss that names no chat marks the latch
  `unscoped`, durably, and recovery then gaps every collection, also after
  a restart.

Also from the review: a capacity cause keeps its class across the write
worker, the queue-capacity refusal is classified as capacity, a loss only
this process retained keeps its original cause for the recovery audit, and
two assertions that could pass on a broken tree now check the durable fact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ute (#3810)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@schlessera schlessera added this to the 0.45.0 milestone Nov 10, 2026
@schlessera schlessera added type: fix Something is broken and must behave the way it is documented. area: ui-server Hono app factory: turn coordinator, auth, session catalog, routes, cron. area: ui-react React chat/files/voice components, stores, WebSocket transport. contract Touches the integration contract: CONTRACT: commit, contract doc updated in the same commit. labels Nov 10, 2026
@uploads-sh

uploads-sh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

No uploads on this PR yet

This PR changes UI files (packages/ui-react/tests/browser/outgoing-snapshots.offline.tsx, packages/ui-react/tests/browser/safety-gap-scene.tsx and packages/ui-react/tests/browser/safety-gap.layout.tsx). Screenshots help reviewers see what changed.

  • From the CLI: uploads put before.png after.png --pr 3827
  • From an agent: ask it to attach screenshots with uploads.sh
  • By hand: drag images into the PR description and they're imported automatically
Tips for agents

Label each shot so reviewers know what they're seeing. Labels apply to every file in a call, so run one put per shot:

uploads put after.png --pr 3827 --meta path=/settings --state after --caption "Saved settings toast"
uploads put chat.png --pr 3827 --app ios --screen "Chat" --state after

No CLI? With the Uploads MCP, call sign_upload_url for files on disk (or put) with repo, pr: 3827 and the same screen, state and caption fields.

This comment updates with each upload, so you don't need to post the images yourself. A shot or two in the PR description is still welcome. Check what's attached with uploads list --pr 3827. More in the github-screenshots skill or the agent docs.

Workspace admins can turn this comment off in Settings → GitHub · docs

@schlessera

Copy link
Copy Markdown
Owner Author

Collision report for head 88e5805b77ab822b72f51452be274f59ea99c392 (bun scripts/collisions.ts --json --pr 3827):

Whichever lands second rebases and re-proves. No lock is implied.

@schlessera schlessera changed the title fix(ui-server): contain a safety-recording failure to what it puts at risk and recover automatically (#3812, #3810) CONTRACT: fix(ui-server): contain a safety-recording failure to what it puts at risk and recover automatically (#3812, #3810) Nov 10, 2026
schlessera and others added 5 commits November 10, 2026 07:52
A tool result already exists when its safety record is written, and a
runtime may keep it in its own session: the installed Claude runtime
replays a result whose PostToolUse hook stopped the turn on the next
resumed request. Treating a refused result reservation as "before
delivery" therefore left the chat normal and complete while the model
had seen the untrusted output.

Only begin(), which the backend awaits before the tool runs, may now
take the pre-delivery shortcut. Result records are no longer tagged
beforeDelivery, so a failed reservation is contained at chat scope by
the writer and the collector records the loss on the chat as well.

The new installed-Claude test proves the replay and the permanent gap;
the Pi writer-loss test again requires the loss to stay with its chat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d cause, and say what frees spent room (#3812, #3810)

- Automatic recovery now waits until every producer that predates the
  latch has ended, failed or not. Only turns begun restricted run
  beside it; a failed producer's durable or in-memory loss no longer
  exempts it from the drain.
- /api/status `safetyRecording.cause` falls back to the cause this
  process holds while its notice cannot commit, marked
  `durable: false`; a committed latch cause carries `durable: true`.
- Every capacity refusal names what it spent (`turn`, `chat` or
  `brain`). A turn refused for spent chat or brain room ends with the
  additive failure classes `safety_recording_chat_full` (start a new
  chat) or `safety_recording_brain_full` (retrying won't help), and the
  PWA no longer asks the owner to try again.

Additive: one optional field on the status cause and two failure
classes, documented in docs/integration-contract/http.md and wire.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the pinned browser (#3812)

The real Chat page in the pinned Chromium talks to the real app and its
own safety recorder. The first chat's search result reaches the runtime
and its record is refused, so that chat keeps a permanent recording gap;
a second chat, started from the page's New chat, sends twice and is
answered under normal policy, and the brain never latches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…sult the host cannot record (#3812)

Second review of #3827 at 511e94a.

P1: result() checked the turn's liveness before its try, so a turn
stopped as its result arrived skipped both the record and safetyFail(),
while the installed Claude runtime replays that result on resume. A
result that reaches the host is now recorded whatever happened to the
turn: stopping refuses new tools, never the record of one that ran. Any
failure while recording still leaves the chat a permanent gap.

Audit of every exit between a tool running and its result's record,
in both backends. Also fixed:
- a result queued behind a failed begin() inherited its refusal;
- a result for a call whose begin() failed partway recorded nothing for
  the unrecorded input (the call is now not admitted: gap);
- the Pi host refused a stopped turn's safetyResult before recording it
  (now recorded, then the post-record live check refuses the worker);
- a malformed or replayed Pi safetyResult left no gap (new internal
  inputSafety.lost);
- the Pi worker skipped the report when the session's own afterToolCall
  failed.

P2a: a latch records the safety revision it was set at (durable and in
process). Automatic recovery exempts only turns begun restricted after
it; one begun restricted under an earlier latch drains first.

P2c: unbound room (count and both byte checks) is brain-full only when
ended unbound collections alone fill it; room an open first turn or a
pending write holds is a retryable refusal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…corded (#3812)

A turn stopped while a tool runs reaches neither Claude result hook, yet
the runtime keeps the call in its session and may replay its output on
resume. The collector only gapped a chat when a delivered hook failed, so
a Grep stopped mid-run left its chat normal and complete.

Every call `begin()` admits is now an obligation, recorded before the tool
runs (`safety_obligations`, migration 085). It is discharged only when its
result is durably recorded, or when the backend refuses the call, which
proves it never ran: a rejected `begin()`, a Claude PreToolUse or
`canUseTool` deny, or a Pi permission answer other than allow. A
collection that ends owing one, however it ended, and an obligation still
open at boot, give the chat a permanent `recording_failed` gap naming the
call. Nothing depends on the runtime delivering a hook.

A fully observed result of a stopped turn is still recorded as an
occurrence, with no gap. A refused call stays refused, so a parallel hook
cannot reopen it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
schlessera and others added 4 commits November 10, 2026 10:21
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d, and discharge it with that record (#3812)

A refusal proved a call never ran only until the backend let it run. A
later permission request for the same Pi call id, rejected as a replay,
refused for a stopped turn or denied, discharged the obligation of a call
that had already run, and its chat ended normal and complete. Backends now
tell the collector when they let a call run (the Pi dispatcher's allow,
the Pi gate's pass, Claude's permission callback allow); from then on a
refusal or a rejected begin() for that id discharges nothing, and only the
call's recorded result does. An allow the collector can no longer note is
refused instead.

A result's last exposure now commits with its call's discharge in one
transaction, so neither a collection's end nor a restart can find the
record durable and the call still owed. A collection's end also waits,
bounded, for a result record already under way: stopping a turn refuses
new tools, never the record of one that ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d re-anchor citations into the files it touches (#3812)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
schlessera and others added 2 commits November 10, 2026 11:59
…own tests do

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eclared endpoints (#3810)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@schlessera

Copy link
Copy Markdown
Owner Author

Review follow-up, second and first rounds, moved here from the PR body, which is at GitHub's size limit. The text is unchanged.

Second review, at 511e94a

One blocking finding and two medium ones. Each fix has a failing-first run on 511e94a's sources and a mutation receipt. The first round's fixes are unchanged and still pass (below).

  • P1 (security), fixed: a stopped turn skipped its result's record. result() checked the turn's liveness outside its try, so a cancellation as the result arrived skipped both the record and safetyFail(), while the installed Claude runtime replayed the real Grep output on resume. A result is now recorded whatever happened to the turn: stopping refuses new tools, never the record of one that already ran. Any failure while recording still leaves the chat a permanent gap. Recording rather than gapping is the narrower containment: the chat is restricted by an unresolved, reviewable occurrence instead of a permanent gap, and a stop no longer costs a chat its coverage.
  • P1 audit: every early return or throw between "tool executed" and "result durably recorded", in both backends (table below). Four more paths could skip both the record and the gap, and are fixed.
  • P2a, fixed: a latch now records the safety revision at which it was set (safety_latch.revision, plus the in-process latch's revision). Automatic recovery exempts only collections begun restricted after that revision. A turn begun restricted under an earlier, recovered latch must drain first.
  • P2c, fixed: the unbound ceilings (count, and the same bug class in both byte checks) are brain-full only when ended unbound collections alone leave no room. Room that an open first turn or a pending write holds is a retryable refusal.

Exit-path audit. Each path between a tool running and its result's record now records the result or leaves the chat a permanent gap.

Backend Path 511e94a Now Test
Collector Turn stopped before result() (liveness check outside its try) Neither: no record, no gap Recorded safety-result-retention "a turn stopped as its result arrives…" (installed Claude, real resume)
Collector Turn stopped and its collection ended before the result Neither Record refused (ended) → gap safety-result-exits "…stopped and ended…"
Collector Liveness check after a recorded result Gap on top of a record Record only (proportionate) SAFETY_CANCELLED_RECORDED_RESULT_IS_NO_GAP
Collector Result queued behind a begin() that failed Rejected with begin's error: neither Runs; call not admitted → gap safety-result-exits "…refused before delivery…: queued"
Collector Result for a call whose begin() failed partway Recorded nothing for the unrecorded input (once the queue was clear) Not admitted → gap safety-result-exits "…refused before delivery…: after"
Collector Queue capacity, segment capacity, unknown/conflicting call Gap Gap unchanged code path (no dedicated test)
Collector record() refusal for a stopped producer, reservation or commit failure Gap (chat, else brain, else in process) Same existing (safety-containment, safety-ledger)
Collector Turn begun restricted Gap committed before delivery Same safety-containment (SAFETY_BRAIN_RESTRICTION_RUNS_NEW_TURNS)
Collector Chat retired No chat left to restrict Same unchanged code path
Claude PostToolUse/PostToolUseFailure hook, every tool (no matcher) result() Same; refusal returns continue: false safety-result-retention (both cases)
Claude A sibling hook (finishNativeFile) throws Not measured Probe on installed 2.1.293: the safety hook still records (tool_search_output); not committed scratch probe
Claude Host process dies before the hook Restart gaps every open collection (host_restart_unknown) Same, plus each owed call's own gap (boot-obligation, third review) safety-ledger, safety-result-exits "…still owed when the host dies…"
Pi host safetyResult while the turn is stopped (live() refusal) Neither Recorded, then the post-record live() refuses the worker safety-result-exits "a Pi result reaching a stopped turn…"
Pi host Malformed safetyResult Neither Gap (inputSafety.lost) …refused before its record…: malformed
Pi host Replayed RPC id Neither Gap …refused before its record…: replayed
Pi host result() itself fails Gap Same safety-pi-delivery writer-loss
Pi host No bridge: the turn has ended Refused Same; pi-agent-core 0.99.2 finalizeExecutedToolCall replaces the result with the thrown error, so the output never enters the session n/a
Pi worker Session's own afterToolCall throws Result never reported Reported, then the failure stops the worker …session's own after-hook fails
Pi worker Report cannot be sent (pipe gone) Same error substitution; worker ends Same n/a

inputSafety.lost is a new @internal member of BackendBridge.inputSafety, so the API report is unchanged.

Failing-first (511e94a sources, new tests):

Test 511e94a now
safety-result-retention "a turn stopped as its result arrives…" (installed Claude) SAFETY_CANCELLED_RESULT_IS_RECORDED: expected [{detector: "tool_search_output"}], received [], after SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT passed pass
safety-result-exits "…stopped and ended…" SAFETY_LATE_RESULT_IS_A_DURABLE_GAP: received null pass
safety-result-exits "…refused before delivery…" (after, queued) SAFETY_RESULT_AFTER_REFUSED_BEGIN_IS_A_GAP: received null pass
safety-result-exits "a Pi result reaching a stopped turn…" SAFETY_PI_STOPPED_RESULT_IS_RECORDED pass
safety-result-exits "…refused before its record…" (malformed, replayed) SAFETY_PI_REFUSED_REPORT_IS_A_DURABLE_GAP: received null pass
safety-result-exits "…session's own after-hook fails" SAFETY_PI_RESULT_SURVIVES_A_FAILED_AFTER_HOOK pass
safety-containment "a turn begun restricted under an earlier latch…" (retained, durable) SAFETY_LATER_LATCH_DRAINS_AN_EARLIER_RESTRICTED_TURN: expected false, received true pass
safety-containment "room for turns not yet in a chat…" SAFETY_UNBOUND_ROOM_A_RUNNING_TURN_FREES_IS_RETRYABLE: received the brain-full refusal pass
safety-containment "unbound byte room a running first turn holds…" SAFETY_UNBOUND_BYTES_A_RUNNING_TURN_HOLDS_ARE_RETRYABLE pass

Mutations (each restored; every one fails its named test):

Mutation Fails
Liveness check before result()'s try (= 511e94a) SAFETY_CANCELLED_RESULT_IS_RECORDED, SAFETY_LATE_RESULT_IS_A_DURABLE_GAP
Liveness check inside the try (the reviewer's control: gap instead of record) SAFETY_CANCELLED_RESULT_IS_RECORDED
Trailing liveness check after a recorded result restored SAFETY_CANCELLED_RECORDED_RESULT_IS_NO_GAP
Result accepted for a partly begun call SAFETY_RESULT_AFTER_REFUSED_BEGIN_IS_A_GAP (after, queued)
Result inherits a queued begin()'s refusal SAFETY_RESULT_AFTER_REFUSED_BEGIN_IS_A_GAP (queued)
Pi dispatcher refuses a stopped turn's result before recording SAFETY_PI_STOPPED_RESULT_IS_RECORDED
Pi refused report keeps no loss SAFETY_PI_REFUSED_REPORT_IS_A_DURABLE_GAP (malformed, replayed)
Pi worker skips the result when the session after-hook fails SAFETY_PI_RESULT_SURVIVES_A_FAILED_AFTER_HOOK
Every restricted-begun producer exempt from the drain (= 511e94a) SAFETY_LATER_LATCH_DRAINS_AN_EARLIER_RESTRICTED_TURN (retained, durable)
In-process latch dated before every producer SAFETY_LATER_LATCH_DRAINS_AN_EARLIER_RESTRICTED_TURN (retained)
Unbound ceiling always a full brain (= 511e94a) SAFETY_UNBOUND_ROOM_A_RUNNING_TURN_FREES_IS_RETRYABLE, SAFETY_UNBOUND_BYTES_A_RUNNING_TURN_HOLDS_ARE_RETRYABLE
Open unbound collections counted as permanent same two

A test note: Bun's expect(pending).rejects waits synchronously and never sees the write worker's reply, so the new tests settle promises with .then(…, error => error), as the existing safety tests do.

Runs after the second follow-up (exit codes read from each command):

  • Focused: every safety-* suite in ui-server (incl. the new safety-result-exits, installed Claude retention and Pi delivery), session-safety-boundaries, approval-scope-isolation, http-supported-mounts, live-safety-admission, owner-safety-review, host-publication-safety, no-console; ui-backend-pi worker-rpc, extension-inspection, worker-session, worker-session-units; ui-backend-claude permission-wiring-units, follow-up, characterization-permissions; ui-react render/turn-failure; root first-party-failure-classes: 569/569 across 30 files, exit 0.
  • Provider history (ui-backend-claude and ui-backend-pi provider-history): 33/33, exit 0.
  • tsc --noEmit (12 GB heap): exit 0. bun run lint: exit 0. bun run api-report: exit 0, no diff (lost is @internal).
  • bun run check:pr --base origin/main at e162f73: exit 0 (receipt below).

First review, at 88e5805

Independent review at 88e5805 found one blocking and four further issues. Each fix has a failing-first run on 88e5805's sources and a mutation receipt.

  • P1 (security), fixed: a tool result whose record was refused was treated as "before delivery", so its chat stayed normal and complete while the Claude runtime replayed the result on resume. Result records are no longer pre-delivery, and only begin() may skip the gap; Claude and Pi both keep the loss on the chat.
  • P2a, fixed: automatic recovery waits until every producer that predates the latch has ended, failed or not; only turns begun restricted run beside it.
  • P2b, fixed: /api/status shows the in-memory cause (durable: false) while its notice cannot commit.
  • P2c, fixed: capacity refusals carry what they spent (turn/chat/brain); a full chat says "start a new chat", a full brain says retrying won't help, and neither is offered as retryable.
  • Missing browser proof, added: safety-gap.layout.tsx on the pinned image, against the real app.

Failing-first (88e5805 sources, new tests):

Test 88e5805 now
safety-result-retention.test.ts (installed Claude, real resume) SAFETY_REFUSED_RESULT_RESTRICTS_ITS_CHAT: expected restricted, received normal, after SAFETY_RUNTIME_REPLAYS_THE_REFUSED_RESULT passed pass
safety-pi-delivery.test.ts writer-loss SAFETY_PI_REFUSED_RESULT_KEEPS_ITS_LOSS: expected false, received true pass
safety-gap.layout.tsx (pinned browser) BROWSER_FIRST_CHAT_KEEPS_A_RECORDING_GAP: received normal/complete/no gap pass
automatic recovery waits for every producer that predates the latch… (retained, durable) SAFETY_AUTOMATIC_RECOVERY_DRAINS_FAILED_PRODUCERS: expected false, received true pass
status shows the cause this process holds… SAFETY_STATUS_SHOWS_THE_RETAINED_CAUSE: cause null pass
spent safety room says what to do… SAFETY_EPOCH_CEILING_IS_A_FULL_CHAT: received undefined pass
room held only by pending writes stays a retryable refusal SAFETY_PENDING_ROOM_IS_RETRYABLE pass

Mutations (each restored):

Mutation Fails
Result records tagged beforeDelivery and result failures take the held shortcut (= 88e5805) SAFETY_REFUSED_RESULT_RESTRICTS_ITS_CHAT
Only result records tagged beforeDelivery passes: the collector still records the loss (defence in depth)
Only result failures take the held shortcut passes: the writer still contains the reservation failure at chat scope
Exempt producers with a durable failure from the drain SAFETY_AUTOMATIC_RECOVERY_DRAINS_FAILED_PRODUCERS (durable)
Exempt producers with an in-memory loss from the drain SAFETY_AUTOMATIC_RECOVERY_DRAINS_FAILED_PRODUCERS (retained)
Drop the in-memory status cause SAFETY_STATUS_SHOWS_THE_RETAINED_CAUSE
Ignore the capacity scope SAFETY_EPOCH_CEILING_IS_A_FULL_CHAT, SAFETY_FULL_OUTRANKS_PAUSED
Browser: a chat-scope loss latches the brain instead BROWSER_FIRST_CHAT_KEEPS_A_RECORDING_GAP (available: false)

Runs after the follow-up. 19 focused files: every safety-* suite in ui-server (incl. installed Claude and Pi delivery), session-safety-boundaries, approval-scope-isolation, http-supported-mounts, no-console, ui-react render/turn-failure, root first-party-failure-classes: 354/354, exit 0. ui-react render/worker-host-notice and root browser-command-activation: green. Pinned browser outgoing-snapshots.offline (now with the full-chat copy) and safety-gap.layout: 10/10, exit 0. tsc --noEmit exit 0; bun run lint exit 0; bun run api-report regenerated (ui-sdk.txt, the two classes) and unchanged after merging origin/main.

schlessera and others added 3 commits November 10, 2026 17:21
…mission (#3812)

The Claude backend counted admissions per hook, keyed by call id alone.
When a different tool reused an id, its hooks were not the ones that had
seen the id. A Bash call reusing an auto-allowed Grep's id reached the
mutating hook first, which had never seen that id, so its count did not
pass the maximum. Its denial then found one admission and discharged the
Grep's obligation before the shared hook counted the Bash call. The chat
ended normal and complete, although the search had run.

Admissions are now counted per (tool name, id). For one tool name, the
same hooks run on every admission, so whichever hook starts first counts
it. Backends report the tool name with each admission. The collector
keeps the tool names seen for each id. A refusal discharges an obligation
only when the id was admitted exactly once, under one tool name, and was
never allowed.

Also brings three comments that still described the superseded
no-refusal rule in line with the narrowed rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@schlessera
schlessera marked this pull request as ready for review November 10, 2026 22:14
#3812)

The browser dispatch audit pins inbound.ts by hash. It now also imports
refusalReason from lib/turn-failure.ts, which imports only protocol
types and constants; inbound.ts still takes only runStateForFrame from
the chat handlers and never reaches chatFrameHandlers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: ui-react React chat/files/voice components, stores, WebSocket transport. area: ui-server Hono app factory: turn coordinator, auth, session catalog, routes, cron. contract Touches the integration contract: CONTRACT: commit, contract doc updated in the same commit. type: fix Something is broken and must behave the way it is documented.

Projects

None yet

1 participant