From c21abe4e8110b4c165029111c69f5e3f7f942324 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 02:16:50 +0000 Subject: [PATCH 1/8] CONTRACT: feat(safety): revalidate live authority at final admission --- .changeset/live-effective-safety.md | 8 + api-report/ui-sdk.txt | 8 +- api-report/ui-server.txt | 11 + docs/decisions/apify-capability.md | 2 +- docs/decisions/async-collaboration.md | 6 +- docs/decisions/backend-authoring-toolkit.md | 8 +- .../decisions/claude-2.1.287-compatibility.md | 2 +- docs/decisions/governed-writable-workers.md | 44 +- docs/decisions/live-conversation.md | 2 +- docs/decisions/voice-permission.md | 16 +- docs/hosting/agent-workers.md | 2 +- docs/http-api-coverage.md | 4 +- docs/http-api.md | 3 +- docs/integration-contract/http.md | 41 +- docs/integration-contract/package-api.md | 26 ++ .../live-conversation-investigation.md | 4 +- .../plans/async-collaboration-requirements.md | 6 +- docs/plans/async-collaboration.md | 8 +- docs/plans/chat-history-deletion.md | 2 +- docs/plans/reviewable-session-safety.md | 6 +- .../ui-backend-claude/src/permission-hooks.ts | 36 +- packages/ui-backend-pi/src/file-tools.ts | 6 + packages/ui-backend-pi/src/permission-gate.ts | 18 +- packages/ui-backend-pi/src/tool-admission.ts | 29 ++ packages/ui-backend-pi/src/worker-entry.ts | 1 + packages/ui-backend-pi/src/worker-protocol.ts | 2 +- packages/ui-backend-pi/src/worker-rpc.ts | 25 +- .../ui-backend-pi/tests/worker-rpc.test.ts | 2 +- packages/ui-sdk/src/internal.ts | 4 +- .../ui-sdk/src/server/admission-safety.ts | 39 ++ packages/ui-sdk/src/server/backend.ts | 6 + packages/ui-sdk/src/server/egress-proxy.ts | 30 +- packages/ui-sdk/src/server/inference-relay.ts | 1 + packages/ui-sdk/src/server/outward-policy.ts | 23 +- packages/ui-sdk/src/server/permission-gate.ts | 10 +- packages/ui-sdk/src/server/provider-relay.ts | 2 + packages/ui-sdk/src/turn-journal.ts | 2 +- .../083_effective_taint.journal.sql | 3 + packages/ui-server/src/brain/compute-host.ts | 5 +- .../ui-server/src/brain/journal-governance.ts | 6 +- packages/ui-server/src/brain/journal-store.ts | 20 +- packages/ui-server/src/brain/turn-egress.ts | 23 +- packages/ui-server/src/brain/turn-journal.ts | 4 +- .../src/governance/effective-safety.ts | 43 ++ .../ui-server/src/governance/event-writes.ts | 7 +- packages/ui-server/src/governance/events.ts | 9 + .../ui-server/src/governance/safety-queue.ts | 11 +- .../src/ws/bridge-capabilities/permissions.ts | 31 ++ packages/ui-server/src/ws/bridge.ts | 15 + packages/ui-server/src/ws/host.ts | 8 + .../ui-server/tests/governance-events.test.ts | 1 + .../tests/live-safety-admission.test.ts | 383 ++++++++++++++++++ .../tests/provider-relay-taint.test.ts | 3 + .../ui-server/tests/shell-taint-proxy.test.ts | 5 + packages/ui-server/tests/turn-egress.test.ts | 2 +- packages/ui-server/tests/turn-journal.test.ts | 3 +- 56 files changed, 915 insertions(+), 112 deletions(-) create mode 100644 .changeset/live-effective-safety.md create mode 100644 packages/ui-backend-pi/src/tool-admission.ts create mode 100644 packages/ui-sdk/src/server/admission-safety.ts create mode 100644 packages/ui-server/migrations/083_effective_taint.journal.sql create mode 100644 packages/ui-server/src/governance/effective-safety.ts create mode 100644 packages/ui-server/tests/live-safety-admission.test.ts diff --git a/.changeset/live-effective-safety.md b/.changeset/live-effective-safety.md new file mode 100644 index 0000000000..9ca6e7bc94 --- /dev/null +++ b/.changeset/live-effective-safety.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-backend-claude": minor +"@schlessera/brain-backend-pi": minor +--- + +Breaking before 1.0: revalidate effective safety at dispatch after waits, restore later policy allowances only after complete individual review, and attribute new journal changes to current evidence while preserving historical facts. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 06333cc410..dc3ceaf483 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1119,6 +1119,8 @@ export "./client" (./src/client/index.ts) export "./internal" (./src/internal.ts) AGENT_INFERENCE_CREDENTIAL_ENV ANTHROPIC_INFERENCE_ROUTES + type AdmissionSafety + type AdmissionSafetySnapshot BRAIN_INTERACTION_GUIDANCE BRAIN_SCRATCH_DIR BRAIN_WORKSPACES_DIR @@ -1182,6 +1184,7 @@ export "./internal" (./src/internal.ts) RTK_WORKER_ENV type RemovalRun type Reservation + STALE_SAFETY_ADMISSION SUBPROCESS_ENV type SessionPromptFacts type SessionRetirement @@ -1241,6 +1244,7 @@ export "./internal" (./src/internal.ts) claudeMaskFilename claudeReportedMaskPath combineRemovalOutcomes + commitOutwardPlan compileWorkerCommandPolicy conversationOrientation createLimitTracker @@ -1327,6 +1331,8 @@ export "./internal" (./src/internal.ts) rewriteWorkerRtk runMaintenanceWorker runMaintenanceWorkerSync + safetyAdmissionRefusal + sameSafetyAdmission sessionPromptContext sessionPromptContextLocation sessionReplay @@ -17635,7 +17641,7 @@ signatures (every public export and the types it is made of) registerToolRenderers (packages/ui-sdk/src/client/renderers.ts) export function registerToolRenderers(pack: RendererPack): void; requestToolPermission (packages/ui-sdk/src/server/permission-gate.ts) - export function requestToolPermission(bridge: Pick | null | undefined, request: PermissionRequest, options?: RequestToolPermissionOptions): Promise; + export function requestToolPermission(bridge: Pick | null | undefined, request: PermissionRequest, options?: RequestToolPermissionOptions): Promise; resolutionEffectSchema (packages/ui-sdk/src/schemas.ts) const resolutionEffectSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ approvedBy: z.ZodOptional; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index e9bb1abb69..1c304c2f47 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -965,6 +965,16 @@ signatures (every public export and the types it is made of) }, z.core.$strict>; version: number; }; + readonly safety_admission_expired: { + payload: z.ZodObject<{ + authorityEpoch: z.ZodString; + evidenceRevision: z.ZodString; + reason: z.ZodLiteral<"safety_changed">; + toolUseId: z.ZodString; + trustRevision: z.ZodString; + }, z.core.$strict>; + version: number; + }; readonly scope_cap: { payload: z.ZodObject<{ cap: z.ZodEnum<{ @@ -1017,6 +1027,7 @@ signatures (every public export and the types it is made of) path: z.ZodString; sequence: z.ZodNumber; taintSourceEventId: z.ZodNullable; + tainted: z.ZodOptional>; }, z.core.$strict>; version: number; }; diff --git a/docs/decisions/apify-capability.md b/docs/decisions/apify-capability.md index cedd0b212f..288458697c 100644 --- a/docs/decisions/apify-capability.md +++ b/docs/decisions/apify-capability.md @@ -35,7 +35,7 @@ egress, outward rules and recipient restrictions, but no discovery or Actor gran fields (`GovernancePolicySchema`, `packages/common/src/governance-policy.ts:101-130`). Name-based permission admission cannot distinguish different Actors supplied to one execution tool (`decideToolPermission`, -`packages/ui-sdk/src/server/permission-gate.ts:62-92`). Provider accounting is +`packages/ui-sdk/src/server/permission-gate.ts:63-93`). Provider accounting is already attributed and settled on the host (`observeProvider`, `packages/ui-server/src/brain/turn-budgets.ts:223-237`). diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index a036da94d1..fa92556cd3 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:636`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:660`). These are permission primitives, +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, 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:102-131`). Removing four curated +`packages/ui-backend-pi/src/permission-gate.ts:103-134`). 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. @@ -204,7 +204,7 @@ permission and unwinds the turn. Already completed side effects are not undone by an abort. Attempt staging and cleanup therefore need idempotent recovery, with filesystem compensation outside SQLite transactions. Ordinary permission parking still exists (`requestPermission: (req) => {`, -`packages/ui-server/src/ws/bridge-capabilities/permissions.ts:17-123`); it is not a durable Action store. +`packages/ui-server/src/ws/bridge-capabilities/permissions.ts:18-154`); it is not a durable Action store. Resolution validates the stored effect again, checks current authority, records one resolution and applies the guarded state transition in one transaction. diff --git a/docs/decisions/backend-authoring-toolkit.md b/docs/decisions/backend-authoring-toolkit.md index 87b4a78676..bd1e180d21 100644 --- a/docs/decisions/backend-authoring-toolkit.md +++ b/docs/decisions/backend-authoring-toolkit.md @@ -62,11 +62,11 @@ by the package-wide inventory in [the public export boundary](public-export-boun sharing a server entry point with the toolkit does not classify them implicitly. The public permission implementation is the gate (`decideToolPermission`, -`packages/ui-sdk/src/server/permission-gate.ts:62-96`), request construction -(`createToolPermissionRequest`, `packages/ui-sdk/src/server/permission-gate.ts:205-219`), -bridge operation (`requestToolPermission`, `packages/ui-sdk/src/server/permission-gate.ts:254-292`) +`packages/ui-sdk/src/server/permission-gate.ts:63-97`), request construction +(`createToolPermissionRequest`, `packages/ui-sdk/src/server/permission-gate.ts:206-220`), +bridge operation (`requestToolPermission`, `packages/ui-sdk/src/server/permission-gate.ts:255-298`) and edited-input check (`checkEditedApproval`, -`packages/ui-sdk/src/server/permission-gate.ts:148-180`). Pattern compilation is +`packages/ui-sdk/src/server/permission-gate.ts:149-181`). Pattern compilation is shared (`compileConfirmPatterns`, `packages/ui-sdk/src/server/confirm-patterns.ts:97-134`). ## Mask fallback containment diff --git a/docs/decisions/claude-2.1.287-compatibility.md b/docs/decisions/claude-2.1.287-compatibility.md index 44798f5f1b..01575fddaa 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:665-668`). +(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:687-690`). `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/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 79230c2bd9..4b7aef2b84 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1398,7 +1398,7 @@ classification: `Write`/`Edit`/`NotebookEdit` disallow is lifted (`disallowedTools`, `packages/ui-backend-claude/src/sdk-options.ts:405`). In pi, the direct tools and a `bash` whose working directory is the brain root - return (`export function bashTool`, `packages/ui-backend-pi/src/file-tools.ts:151`). + return (`export function bashTool`, `packages/ui-backend-pi/src/file-tools.ts:152`). - **Approvals do not change.** Confirmation patterns and destructive-operation approvals still run in the permission hooks. The journal adds the ability to undo; it removes no approval. @@ -2249,7 +2249,7 @@ reports which applies as `governed.egress`. Making the relay work without managed storage is follow-up work. Each connection is recorded as a governance event, and a recording failure ends the turn. Without a governance recorder the policy still applies and only the records are absent (`prepareTurnEgress`, -`packages/ui-server/src/brain/turn-egress.ts:82-190`). The note says egress is +`packages/ui-server/src/brain/turn-egress.ts:83-203`). The note says egress is recorded only when the backend actually routed the worker through the proxy. API-key Claude profiles (2026-10-22) and pi turns (2026-10-23) are routed too. A pi turn whose credential the relay cannot carry is refused rather than @@ -3845,7 +3845,7 @@ outward host skips the card only while every classified call in progress is a visible read, or an approved outward action that names that host. A GitHub write names the GitHub API hosts, and a push or HTTP write names its target's host. Any unknown or opaque call in progress withholds the exception -(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:58-80`). +(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:59-81`). A background process left by an earlier call can still connect inside such a window; the proxy records it either way. @@ -3859,7 +3859,7 @@ listen on other ports: `gmail.googleapis.com`, `graph.microsoft.com`, `smtp.sendgrid.net`, `api.mailgun.net`, `api.eu.mailgun.net`, `smtp.mailgun.org`, `smtp.eu.mailgun.org`, `api.postmarkapp.com`, `smtp.postmarkapp.com`, `api.resend.com` and `smtp.resend.com` -(`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:18-21`). +(`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:19-22`). Microsoft Graph and Exchange Online carry more than mail, so their reads by an opaque script also wait on the card. The coordinator chose this list for #1665; the maintainer may override it. @@ -3895,6 +3895,18 @@ HTTP endpoint or review capability is enabled here. Live admission integration remains a separate slice; this changes neither existing provider prefixes nor the independent outward/credential/egress controls below. +**Live admission supersession — 2026-11-06 (#3602).** Effective evidence is +re-read after asynchronous approval, lock, index and recording waits at the +last host-controlled dispatch point. Only complete coverage and zero unresolved +committed evidence can restore normal policy. Standing allowances are recomputed; +completed per-use approvals retain their exact scope. Stale cards receive a +durable terminal withdrawal, without replay. New journal attribution reads the +current unresolved source; all prior journal/egress/approval facts and provider +prefixes remain unchanged. Live trust input accepts only a host revision and +notification; publication and source matching remain separate work. Ordinary +admitted governance, credentials, provider routing, outward and voice controls +remain independently enforced. + A session becomes **tainted** the first time a turn ingests content it did not author: @@ -3948,7 +3960,7 @@ every signal. A write that fails stops the turn rather than leaving its outward rules loose. Binding, duplicate checks and the write share a SQLite transaction (`recordFirstTaint`, `packages/ui-server/src/governance/session-taint.ts:21-27`). The hosted server runs that transaction on its write worker -(`insertGovernanceEvent`, `packages/ui-server/src/governance/events.ts:367`; +(`insertGovernanceEvent`, `packages/ui-server/src/governance/events.ts:376`; [#2850](https://github.com/schlessera/brain-kit/issues/2850)). A taint counts for admission from the moment it is submitted, and a connection's first byte waits for its taint's commit. @@ -3973,7 +3985,7 @@ charges only after admission); otherwise it is refused and recorded as an `egress_denial` with reason `taint_allowlist` (an interactive turn asks first since 2026-11-03, see [below](#tainted-destinations-ask)). The taint list narrows and never widens: deny and `allowlist` mode still apply first (`prepareTurnEgress`, -`packages/ui-server/src/brain/turn-egress.ts:82-215`). Hosts without managed +`packages/ui-server/src/brain/turn-egress.ts:83-229`). Hosts without managed native storage have no proxy, so the Bash classifier remains their shell rule and nothing narrows their egress. @@ -4018,18 +4030,18 @@ turn's connection passes deny, `allowlist` mode and the byte ceiling but matches neither `taint.egress.allow` nor a contacted host, the proxy asks through the turn's tool-permission card (`toolName: "Network"`, `kind: "command"`, never remembered as a tool grant) before refusing -(`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:192-197`). The +(`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:198-203`). The card names the destination, the session's first taint source and the consequence of allowing it -(`taintedDestinationDescription`, `packages/ui-server/src/brain/turn-egress.ts:37-42`). +(`taintedDestinationDescription`, `packages/ui-server/src/brain/turn-egress.ts:38-43`). Concurrent connections to the same host share one card. An allowed connection's admission adds its host to the turn's contacted hosts, and its charged `egress_connection` record carries the host into the session's later turns, so it is not asked for again; a different host still asks -(`const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:164-175`). +(`const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:167-178`). A decline refuses: the record stays an `egress_denial` with reason `taint_allowlist`, and the 403 carries a short reason the tool can print (`function describeRefusal`, -`packages/ui-sdk/src/server/egress-proxy.ts:83-99`). Stopping the turn while the +`packages/ui-sdk/src/server/egress-proxy.ts:88-104`). Stopping the turn while the card is pending cancels the connection, and a late allow admits nothing. Voice turns, which have no grant surface, and autonomous turns, which have no turn proxy, refuse without a card as before; deny and `allowlist` mode still refuse first. Maintainer @@ -4049,8 +4061,8 @@ with a status text and a body that name it: the deny list, `allowlist` mode, the byte ceiling, an unapproved outward host, or a tainted session's host outside its allow-list, with the session's first taint source and what the user can do (`function describeRefusal`, -`packages/ui-sdk/src/server/egress-proxy.ts:83-99`; the source wording, -`cause: () =>`, `packages/ui-server/src/brain/turn-egress.ts:181`). The status +`packages/ui-sdk/src/server/egress-proxy.ts:88-104`; the source wording, +`cause: () =>`, `packages/ui-server/src/brain/turn-egress.ts:194`). The status line carries the reason because `curl -v`, `git` and `egress-connect` print only that line for a refused CONNECT. The provider relay passes the proxy's reason through as the refusal body's `error.message` and an additive @@ -4151,11 +4163,11 @@ authorization, the byte ceilings, budget admission, cancellation and accounting. It keeps its own `egress_connection` record, which carries `provider: true` and never `inference: true`. The exemption belongs to the operation, never to a hostname. Only the relay's validated routes reach the proxy's provider -admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:322`), and +admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:338`), and worker HTTP and `CONNECT` traffic cannot claim it, even to a provider's host -(`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:190`). Turn egress +(`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:196`). Turn egress records neither a taint nor a contacted host for the operation -(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:151-154`). So in a +(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:154-157`). So in a tainted session, the worker's own traffic stays narrowed away from the provider's host. @@ -4163,7 +4175,7 @@ A later turn rebuilds its contacted hosts from the session's earlier `egress_connection` records, and a provider record there would look like a worker's. So the maintainer added the optional `provider: true` tag, mirroring `inference: true`, on the record of every validated provider-relay operation -(`finish`, `packages/ui-sdk/src/server/egress-proxy.ts:153-160`). The rebuild +(`finish`, `packages/ui-sdk/src/server/egress-proxy.ts:159-166`). The rebuild excludes those records (`contactedHosts`, `packages/ui-server/src/governance/session-taint.ts:34-40`), so a provider request never gives the worker's own `CONNECT` a contacted-host pass, in the diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index f921e44e15..4c670833e4 100644 --- a/docs/decisions/live-conversation.md +++ b/docs/decisions/live-conversation.md @@ -82,7 +82,7 @@ tool admission and execution, permissions, cancellation, terminal state and resynchronization. Engine task requests are advisory until mapped to committed user input. No native search, code-execution or alternate permission loop is enabled. Both adapters can delegate through the existing `AgentBackend` -(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:778-821`); +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:784-827`); the host serializes work in a session and uses capability-checked follow-ups. The [voice-permission decision](voice-permission.md) binds this interface. diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index d17f020355..21eb13941e 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -58,7 +58,7 @@ which is the largest thing this answer changes. ## The question The permission bridge asks the user to approve a tool call before it runs -(`requestToolPermission`, `packages/ui-sdk/src/server/permission-gate.ts:254-292`). +(`requestToolPermission`, `packages/ui-sdk/src/server/permission-gate.ts:255-298`). In chat the user is looking at a card: the transcript copy in (`export function ToolPermissionCard`, @@ -341,7 +341,7 @@ the matched pattern's effect, so the same words are already on the card. they are exhaustive.** A kind-`tool` request has no pattern at all — the description is the SDK's own (`canUseTool` passes `description: opts.description` straight through to `createToolPermissionRequest`, -`permission-hooks.ts:387-397`) and is not +`permission-hooks.ts:392-402`) and is not written to be heard. And `ClaudeBackendOptions.confirmBashPatterns` (`Regex sources`, `packages/ui-backend-claude/src/options.ts:55-65`) lets a deployment supply its own patterns, which have no phrase when given as @@ -436,7 +436,7 @@ A microphone is a reflex surface with worse recognition than a keyboard. This costs nothing measurable: the server already refuses `always` for kind `command` requests (the block computing `remembers`, `tool-permission.ts:86-92`, and the lookup computing -`remembered`, `ws/bridge-capabilities/permissions.ts:28-48`), and 192 of 192 measured +`remembered`, `ws/bridge-capabilities/permissions.ts:29-49`), and 192 of 192 measured approvals were kind `command`. ### When the announcement actually fires @@ -493,7 +493,7 @@ the request kind, and it patches the span (`onApprovalDecision`, `packages/ui-server/src/activity/recorder.ts:715-730`), fed from the bridge's `recorded()` wrapper -(`const recorded`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:66-81`). +(`const recorded`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:68-84`). One thing is missing and is a follow-up: **the event does not record the modality.** A denial decided by a phrase a microphone heard and one decided by a @@ -620,7 +620,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. **Closed, by #141 (`42a4d86`), which closed #124.** A turn now declares `StartTurnRequest.enforceAllowedTools` -(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:636`) +(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:642`) — the declaration this record asked for, by that name — and under it: - The input-rewrite hooks no longer grant. `createAgentHook` and `createRtkHook` @@ -628,7 +628,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. without granting (`RewriteHookOptions`, `packages/ui-backend-claude/src/input-rewrite-hooks.ts:17-31`; `!mayGrant`, `:70-78`; wired at their `agentHook`/`rtkHook` constructions, - `const agentHook`, `permission-hooks.ts:610-631`). + `const agentHook`, `permission-hooks.ts:632-653`). The premise the old grant rested on was measured false in the process: `permissionDecision: "allow"` was never what made `updatedInput` take effect, so the grant was a side effect and it is the @@ -638,7 +638,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. purpose, so a grant that exists and is deliberately not applied can be logged — but refuses to answer from it or add to it for a tool the enforced allowlist left out (the lookup computing `remembered`, - `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:28-48`, + `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:29-49`, and the block computing `remembers`, `packages/ui-server/src/ws/handlers/tool-permission.ts:86-92`). The evaluation happens @@ -719,7 +719,7 @@ before permission evaluation and evaluates the confirm patterns against `commandAllowed`, which adds `Bash` back unconditionally (`commandAllowed`, `permission-hooks.ts:90-92`, and the call in `mutatingHook` that reads it, -`decideToolPermission`, `:485-492`). So a +`decideToolPermission`, `:497-504`). So a destructive shell command in a voice turn raises a `command` request — and parks — before the tool grant is ever considered. A fail-closed rule written only for kind `tool` would leave exactly the calls this whole record is about diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 9e2a1ae29d..de2440b766 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -86,7 +86,7 @@ The explicitly prepared ordinary egress proxy follows that same helper selection. Its directory and socket remain owned by the server and use its shared primary group, with exact `0750`/`0660` modes; a setgid temporary parent cannot choose another IPC group (`const separateIdentity`, -`packages/ui-sdk/src/server/egress-proxy.ts:127-133`). Without a helper they retain +`packages/ui-sdk/src/server/egress-proxy.ts:132-138`). Without a helper they retain owner-only `0700`/`0600` modes. Before mounting the proxy, the launcher checks canonical paths, server ownership, the expected helper group, exact modes and socket type. Missing entries, symlinks and widened permissions refuse before diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index 2d5267f0e4..b1f8e4616d 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -386,8 +386,8 @@ the additive `query_activity` scope carries the supported agent contract. - `governance events filter by session, turn and kind, and page in id order` ([source](../packages/ui-server/tests/governance-events-http.test.ts)), (`governance events filter by session, turn and kind, and page in id order`, `packages/ui-server/tests/governance-events-http.test.ts:48-71`) - `governance events refuse malformed parameters` ([source](../packages/ui-server/tests/governance-events-http.test.ts)), (`governance events refuse malformed parameters`, `packages/ui-server/tests/governance-events-http.test.ts:73-82`) - `a governance event storage failure is a 500` ([source](../packages/ui-server/tests/governance-events-http.test.ts)), (`a governance event storage failure is a 500`, `packages/ui-server/tests/governance-events-http.test.ts:84-91`) -- `events survive the Activity span-detail prune` ([source](../packages/ui-server/tests/governance-events.test.ts)), (`events survive the Activity span-detail prune`, `packages/ui-server/tests/governance-events.test.ts:184-198`) -- `deleting a session deletes its events and only its events` ([source](../packages/ui-server/tests/governance-events.test.ts)), (`deleting a session deletes its events and only its events`, `packages/ui-server/tests/governance-events.test.ts:200-209`) +- `events survive the Activity span-detail prune` ([source](../packages/ui-server/tests/governance-events.test.ts)), (`events survive the Activity span-detail prune`, `packages/ui-server/tests/governance-events.test.ts:185-199`) +- `deleting a session deletes its events and only its events` ([source](../packages/ui-server/tests/governance-events.test.ts)), (`deleting a session deletes its events and only its events`, `packages/ui-server/tests/governance-events.test.ts:201-210`) **N — Speech grants.** diff --git a/docs/http-api.md b/docs/http-api.md index 1ad09c351e..3a61cec7c1 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -1449,8 +1449,9 @@ read by any authenticated principal. | Kind | Version | Fields | Meaning | | --- | --- | --- | --- | +| `safety_admission_expired` | 1 | `toolUseId`, `evidenceRevision`, `trustRevision`, `authorityEpoch`, `reason` | A pending safety-bound approval was withdrawn before dispatch. The server commits this terminal fact before settling the backend wait or publishing the coordinator's `expired` result. Revisions describe the card's original host snapshot; `reason` is `safety_changed`. This grants no replay and changes no historical approval. | | `egress_connection` | 1 | `connectionId` (optional), `host`, `port`, `method`, `path` (optional), `bytes`, `accounting`, `durationMs`, `outcome`, `inference` (optional), `provider` (optional, #3246), `reason` (optional) | A completed, denied, failed or cancelled proxy connection. HTTP has a path and conservative wire accounting; opaque CONNECT has no path or plaintext claim. Only the concrete inference relay sets `inference: true`, and only a validated provider-relay operation sets `provider: true`; a record never carries both. Neither relay's record makes its host a contacted one for a tainted session's worker traffic. Headers, query strings and content are absent. | -| `steering_change` | 1 | `path`, `sequence`, `beforeHash`, `afterHash`, `taintSourceEventId`, `overlappingTurnIds` | One observed steering change, attributed to its turn. Hashes identify retained regular-file versions or are `null`; the source is an existing prior taint event or `null`. Shared windows remain shared, not exclusive writer claims. | +| `steering_change` | 1 | `path`, `sequence`, `beforeHash`, `afterHash`, `taintSourceEventId`, `overlappingTurnIds`, `tainted` (optional) | One observed steering change, attributed to its turn. Hashes identify retained regular-file versions or are `null`; the source is the current unresolved taint event or `null`. New observations may carry `tainted: true` for effective restriction, including unknown coverage without an attributable source. Historical rows retain their original attribution. Shared windows remain shared, not exclusive writer claims. | | `policy_change` | 1 | `requestId`, `baseHash`, `proposedHash`, `sections`, `outcome` | Explicit user-approved policy publication. Actor is `user`; outcome is `updated`; hashes identify the exact reviewed and written bytes. | | `scratch_overage` | 1 | `bytes`, `pinnedFiles`, `pinnedBytes`, `overageBytes` | Scratch remains above its cap after a prune that preserved retained links. Counts are remaining bytes and pinned files/bytes; `overageBytes` is the excess. A background pass has actor `server` and no session or turn; unbound retention applies. | | `promotion` | 1 | `source`, `destination`, `bytes`, `originalLink`, `rewrittenLink` | A linked turn-temp file was copied into `.brain/scratch/turns//` and its link rewritten. `destination` is brain-relative. | diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index e12d2eec94..29466abaf2 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -378,12 +378,38 @@ trust enforcement or safety capability is enabled; the reviewed public safety-history DTOs remain prospective. Older clients continue under host restrictions without new mutation controls. +**Live admission supersession (breaking before 1.0, #3602).** Proxy dispatch, +both first-party backend gates, outward policy allowances and new journal +attribution use the current effective aggregate. The host reads +`(evidenceRevision, trustRevision, authorityEpoch)` with the exact turn/session +generation and frozen ordinary policy hash after its last asynchronous wait, +in the continuation that dispatches. Pi also rechecks after its post-permission +RTK and lock waits, with an exact-input, one-use final worker admission. New/pending input, recording loss and +unknown coverage remain restrictive; pending/failed verdicts never clear them. +A proxy may exclude only its own newly retained input from that request's +first-byte test when it was otherwise normal. A concurrent connection cannot +borrow that authority. Contacted-host legacy grants begin only at dispatch; +validated provider relays remain excluded from those grants. + +A completed per-use outward approval is distinct from standing policy authority. +An earlier standing allowance is recomputed at dispatch; a stale pending card +is claimed/withdrawn through the coordinator, with a durable +`safety_admission_expired` governance event before the backend wait settles. +Its existing tool-resolution outcome is `expired`. No denied or interrupted +operation replays automatically. Receipt-storage failure stops the turn rather +than reporting successful withdrawal. Ordinary budgets, commands, profiles, +egress configuration, credential routing and outward/voice controls keep their +existing independent, turn-bound meanings. No persistent source matching, +Settings publication, scoped-network capability or owner review route is enabled +by this admission slice. Historical journal/egress/approval facts and provider +prefixes are unchanged; only later decisions and new journal attribution use +the live state. + **Individual verdict persistence (breaking before 1.0, #3601).** The host-only writer now prepares one selected finalized occurrence and atomically commits its immutable `safe` decision, revision and terminal request receipt on the FULL SQLite write worker. This implements the dated -[G6 ruling](../decisions/session-safety-reviews.md); live admission revalidation -and owner-authenticated HTTP/wire operations are separate implementation slices. +[G6 ruling](../decisions/session-safety-reviews.md); owner-authenticated HTTP/wire operations remain a separate implementation slice. No endpoint or capability is added by this persistence layer. Host identity arguments do not establish human authorization. @@ -812,16 +838,17 @@ with actor `user`. ### Steering observations (additive, #1658) -Journal details may add `tainted: true` and `taintSourceEventId` to a steering -change only when an existing taint record preceded the observation in that -session or turn. The ID is retained with the change; replay never derives it -from later events. A missing flag is not a claim that untrusted-input coverage +Journal details may add `tainted: true` and an optional `taintSourceEventId` to a steering +change. New observations capture effective restriction, including unknown +coverage without an attributable source. An available ID names the current +unresolved event. Older rows retain their original attribution; replay never +derives it from later events or verdicts. A missing flag is not a claim that untrusted-input coverage is complete. Policy changes remain class `policy`, with user attribution, and are excluded from `steeringFiles`. The governance event API accepts/returns `steering_change`, version 1, with `path`, journal `sequence`, nullable `beforeHash`/`afterHash`, nullable -`taintSourceEventId`, and `overlappingTurnIds`. It records an observation, not +`taintSourceEventId`, `overlappingTurnIds` and optional `tainted: true`. New observations retain effective restriction even when unknown coverage has no attributable source; older rows and events are unchanged. It records an observation, not an exclusive writer or per-write interception. Configuration inventory that cannot identify a retained local input is named in journal `missing` with `configuration_inputs_not_fully_identified`; raw-version availability remains diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 01371b043a..0da44faefc 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4858,3 +4858,29 @@ count, byte and omission limits are in [disclose the additional data](wire.md#observed-content-map-disclosure-additive-3630) before Start; this adds no execution seam or startup host task. This is an additive minor SDK change, without a model-obedience or acoustic guarantee. + + +## Live safety admission (additive host input, #3602) + +`BackendBridge` accepts an optional internal `admissionSafety` host callback with +synchronous `read()` and invalidation subscription. Its snapshot binds decimal +`evidenceRevision`, `trustRevision`, `authorityEpoch`, the host's turn/session +scope, frozen ordinary `policyHash`, effective restriction, recorder health and +current authority. `PermissionRequest.admissionSnapshot` is host-only metadata; +it is never a wire field, worker initialization input or provider content. +The shared `requestToolPermission` snapshots and rechecks the live input after +approval waits. First-party backend gates additionally revalidate in their +final dispatch continuations after locks, index barriers and occurrence writes. +Absent input retains the existing taint callback fallback and grants no new +capability. The live trust input is revision/notification only; matching and +publication have separate implementations. See the [effective admission +contract](http.md#governance-events-additive-1651) and +[the ruling](../decisions/session-safety-reviews.md). + +Pi's internal worker pipe also has an `admission` request for the exact +host-held permission input. The worker sends it after RTK and lock waits, +immediately before spawning bash. It consumes the host's one-use admission +ticket and cannot approve, widen or replay a call. In-process bash uses the +same revalidation at that point. The internal `commitToolAdmission` bridge +callback transports that check; it carries no provider-facing data or new +public tool. Lock and native observation RPCs also recheck current host safety. diff --git a/docs/investigations/live-conversation-investigation.md b/docs/investigations/live-conversation-investigation.md index 51e695236d..2151177da5 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:547-644`). +(`export interface StartTurnRequest`, `packages/ui-sdk/src/server/backend.ts:553-650`). 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:778-821`). +(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:784-827`). 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 580774eb0e..6afe81e90b 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -43,7 +43,7 @@ session. Three consequences: 1. **Background work cannot ask.** Cron runs (`sync`, `validate`, `maintain`, module jobs) have no human attached. `bridge.requestPermission` parks a promise that nobody will - resolve (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:17-123`), so autonomous work is confined to + resolve (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:18-154`), so autonomous work is confined to whatever is pre-approved, and anything requiring judgment is not attempted. 2. **Inbound material has no path.** A forwarded email, a shared link, a captured note has nowhere to land that the agent will act on later. The PWA share target stages into @@ -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:547-637`); ordinary Claude turns create an SDK session, emit + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:553-643`); 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 @@ -263,7 +263,7 @@ Stated before the requirements because five of them derive from it. threshold (~20s of the 30s lock budget). Below it nothing yields; above it the holder checkpoints/unwinds/releases. Test both edges and independent paths. - R26. **Abort-and-redo needs a checkpoint primitive.** `requestPermission` parks a bare - promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:62-122`) — while blocked on it the model cannot write anything, so + promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:63-153`) — while blocked on it the model cannot write anything, so "writes its findings, then aborts" has nowhere to run. The autonomous bridge must, in one server-side step: capture the checkpoint, create the Action and block the item, unwind without a live approval promise, preserving the tested timeout path's abort-then-drain order (`abortController.abort();`, `packages/ui-server/src/ws/session-run/admission.ts:55-57`). Aborting does **not** undo completed tool side diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 8679a1df4f..0e31fcc9d1 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -28,7 +28,7 @@ than last. ## Problem Frame Collaboration is synchronous-only: background work cannot ask (`requestPermission` parks a -promise nobody resolves — (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:17-123`)), inbound material +promise nobody resolves — (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:18-154`)), inbound material has no path that survives until the user is present, and no decision accumulates into standing authority. See origin for the full frame. @@ -134,7 +134,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. - **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1015`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. -- **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:17-123`). Timeout unwind is +- **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:18-154`). Timeout unwind is (`abortController.abort();`, `packages/ui-server/src/ws/session-run/admission.ts:55-57`). Durable escalation must checkpoint before unwinding; the existing ordinary bridge does not do that. - **Tool enforcement:** (`export function enforcementHookFor`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`) closes measured bypasses. @@ -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:102-131`). Built-ins are disabled, + (`export function createPermissionGate(`, `packages/ui-backend-pi/src/permission-gate.ts:103-134`). Built-ins are disabled, but ambient resources/extensions and in-process execution still need containment. - **Cost timing:** (`store.rollupRun(runId);`, `packages/ui-server/src/activity/recorder.ts:787`) settles after execution; (`export function sumEffectiveCost(`, `packages/ui-server/src/activity/store.ts:179-194`) explicitly counts unpriced runs. @@ -1189,7 +1189,7 @@ and a server-selected tool policy. **Files:** - Modify: `packages/ui-sdk/src/server/backend.ts` (the additive `StartTurnRequest.autonomous` mode carries persistence, origin, tool policy and prompt configuration — - (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:547-637`)) + (`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:553-643`)) - 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 cda952b49f..7f73ee311f 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:759-802`). A storage root +(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:765-808`). A storage root is not removal authority. Future supported package/HTTP/wire changes need their actual contract assessment and a CONTRACT commit; additive capability negotiation ships in a minor. The approved retention exception is recorded before runtime diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index b8cdd1f131..d053046e71 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -36,11 +36,11 @@ public design or its fixtures. Fictional examples use the Odysseus world. never prove finalized delivery or complete coverage. - The turn proxy records each admitted non-provider connection and terminal exposure observation (`prepareTurnEgress`, - `packages/ui-server/src/brain/turn-egress.ts:82-241`). A raw CONNECT reveals + `packages/ui-server/src/brain/turn-egress.ts:83-242`). A raw CONNECT reveals only an authority and opaque bytes, not a repository path or inner protocol - (`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:119-354`). + (`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:124-359`). - Outward decisions read session taint at admission (`prepareOutwardPlan`, - `packages/ui-sdk/src/server/outward-policy.ts:46-73`). Existing historical + `packages/ui-sdk/src/server/outward-policy.ts:47-94`). Existing historical steering attribution must remain attribution at the time of a write. - Governance policy is protected Markdown, validated by a strict schema (`GovernancePolicySchema`, `packages/common/src/governance-policy.ts:101-130`). diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts index 7bc2fbe312..e269b873ec 100644 --- a/packages/ui-backend-claude/src/permission-hooks.ts +++ b/packages/ui-backend-claude/src/permission-hooks.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import { relative, resolve } from "node:path"; import { createWorkerFileObserver, NativeFileVersions, WORKER_AREA_ROOT, type ObservedWorkerFile } from "@schlessera/brain-ui-sdk/internal"; import type { HookCallback, Options, PermissionResult } from "@anthropic-ai/claude-agent-sdk"; -import { type CompiledWorkerCommandPolicy, compileWorkerCommandPolicy, denyWorkerCommand, requestPolicyPermission, prepareOutwardPlan, observeOutwardPlan, OUTWARD_VOICE_REFUSAL } from "@schlessera/brain-ui-sdk/internal"; +import { type CompiledWorkerCommandPolicy, compileWorkerCommandPolicy, denyWorkerCommand, requestPolicyPermission, prepareOutwardPlan, commitOutwardPlan, safetyAdmissionRefusal, observeOutwardPlan, OUTWARD_VOICE_REFUSAL } from "@schlessera/brain-ui-sdk/internal"; import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; import { checkEditedApproval, @@ -187,7 +187,7 @@ export function createPermissionContext(options: PermissionWiringOptions, native const commandPolicy: CompiledWorkerCommandPolicy = compileWorkerCommandPolicy(req.autonomous ? undefined : req.workerSandbox?.commandPolicy); const confirmPatterns = [...options.confirmPatterns, ...commandPolicy.confirm]; const outward = (toolName: string, input: unknown) => prepareOutwardPlan({ toolName, shellToolName: "Bash", input, - allow: req.workerSandbox?.commandPolicy?.outwardAllow, taint: req.workerSandbox?.commandPolicy?.taint, autonomous: Boolean(req.autonomous), voice: req.posture === "voice", + allow: req.workerSandbox?.commandPolicy?.outwardAllow, taint: req.workerSandbox?.commandPolicy?.taint, safety: req.bridge.admissionSafety, autonomous: Boolean(req.autonomous), voice: req.posture === "voice", configurationRoot: options.configurationRoot?.() ?? (req.workerSandbox?.profile === "governed" ? brainPath : undefined), maskPaths: req.workerSandbox?.maskPaths, maintenance: options.maintenance }); const observe = (plan: ReturnType, toolName: string, input: unknown, toolUseId: string, decision: Parameters[1]["decision"]) => observeOutwardPlan(plan, { bridge: req.bridge, toolName, input, toolUseId, decision }); @@ -289,6 +289,7 @@ export function createPermissionContext(options: PermissionWiringOptions, native export function enforcementHookFor(ctx: PermissionContext): HookCallback { const { req, allowed, enforced } = ctx; return async (hookInput) => { + const snapshot = req.bridge.admissionSafety?.read(); if (hookInput.hook_event_name === "PreToolUse") { const unavailable = toolAvailabilityRefusal(req, hookInput.tool_name); if (unavailable) return { continue: true, hookSpecificOutput: { @@ -305,17 +306,20 @@ export function enforcementHookFor(ctx: PermissionContext): HookCallback { } // An index reader runs only once the host has indexed every application // committed before it; a failed update refuses it rather than serve stale results. - if (hookInput.hook_event_name === "PreToolUse" && req.bridge.awaitIndex) { + const mutating = hookInput.hook_event_name === "PreToolUse" && !ctx.routed(hookInput.tool_name) && new RegExp(MUTATING_TOOL_MATCHER).test(hookInput.tool_name); + if (hookInput.hook_event_name === "PreToolUse" && !mutating && req.bridge.awaitIndex) { try { await req.bridge.awaitIndex(hookInput.tool_name, hookInput.tool_input as Record | undefined); } catch (error) { return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: error instanceof Error ? error.message : "The search index could not be brought up to date." } }; } } - if(hookInput.hook_event_name==="PreToolUse"&&req.bridge.inputSafety){ + if(hookInput.hook_event_name==="PreToolUse"&&!mutating&&req.bridge.inputSafety){ try { await req.bridge.inputSafety.begin(hookInput.tool_use_id,hookInput.tool_name,hookInput.tool_input as Record); } catch(error){return {continue:true,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:error instanceof Error?error.message:"Safety recording unavailable"}};} } + const stale = safetyAdmissionRefusal(req.bridge.admissionSafety, snapshot); + if (stale) return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: stale } }; if ( hookInput.hook_event_name !== "PreToolUse" || !outsideEnforcedAllowlist(enforced, allowed, hookInput.tool_name) @@ -357,6 +361,7 @@ export function canUseToolFor(ctx: PermissionContext): NonNullable);} catch(error){turnLock.releaseForTool(hookInput.tool_use_id);return {continue:true,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:error instanceof Error?error.message:"Safety recording unavailable"}};} + if (req.bridge.awaitIndex) { + try { await req.bridge.awaitIndex(hookInput.tool_name, finalInput as Record); } + catch (error) { turnLock.releaseForTool(hookInput.tool_use_id); return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: String(error) } }; } + } + const finalPlan = outward(hookInput.tool_name, finalInput); + const approved = outwardPlan.needsApproval && approval?.kind === "command"; + const refusal = commitOutwardPlan(finalPlan, { bridge: req.bridge, before: snapshot, approved, signal: req.signal }); + observe(finalPlan, hookInput.tool_name, finalInput, hookInput.tool_use_id, refusal ? "refused" : { behavior: "allow" }); + if (refusal) { turnLock.releaseForTool(hookInput.tool_use_id); return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: refusal } }; } + if (approved) shownOutward.set(hookInput.tool_use_id, JSON.stringify(finalInput)); if (edited !== undefined) { // Applied by returning `updatedInput` with NO permissionDecision. A // PreToolUse hook's rewrite takes effect without one — measured for #124 @@ -589,6 +609,8 @@ function createRewriteHooks(ctx: PermissionContext, options: PermissionWiringOpt // rewrite's auto-allow must not re-admit an already completed effect. const restrictRewrite = (hook: HookCallback, toolName: string): HookCallback => async (...args) => { const output = await hook(...args); + const admissionRefusal = safetyAdmissionRefusal(req.bridge.admissionSafety); + if (admissionRefusal) return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: admissionRefusal } }; if (req.signal.aborted) return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: "Turn cancelled during input rewrite.", } }; diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index af9f962356..320f4500c5 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -16,6 +16,7 @@ import { RTK_WORKER_ENV, execWrapperSpawnOptions, WORKER_DATA_ROOT, WORKER_EGRES import { resolveEnabledWebSearchEnvNames, ambientExecConfig, subprocessEnv } from "./config/env.js"; import { clip, MAX_READ_BYTES, textResult, type BrainToolKit } from "./tool-kit.js"; +import { revalidatePiAdmission } from "./tool-admission.js"; /** `read_file`: one repo-contained UTF-8 file, remembered as a same-turn base. */ export function readFileTool(kit: BrainToolKit): ToolDefinition { @@ -180,6 +181,11 @@ export function bashTool(kit: BrainToolKit): ToolDefinition { // sibling tool calls in one message. return lock.withKey(bashLockKey(params.command), async () => { if (signal?.aborted) throw new DOMException("Tool cancelled before subprocess execution", "AbortError"); + if (turn.bridge?.commitToolAdmission) await turn.bridge.commitToolAdmission(_id, "bash", params); + else { + const stale = revalidatePiAdmission(turn, "bash", _id, params, true); + if (stale) throw new Error(stale); + } const exec = deps.exec ?? ambientExecConfig(); // Not a login shell (#2960): `-l` sourced /etc/profile and the first // profile under HOME before every command, so their output reached diff --git a/packages/ui-backend-pi/src/permission-gate.ts b/packages/ui-backend-pi/src/permission-gate.ts index 5122523a3d..07bd1477f1 100644 --- a/packages/ui-backend-pi/src/permission-gate.ts +++ b/packages/ui-backend-pi/src/permission-gate.ts @@ -42,10 +42,11 @@ import { isCompletedAutonomousToolCall, } from "@schlessera/brain-ui-sdk/server"; -import { compileWorkerCommandPolicy, denyWorkerCommand, requestPolicyPermission, prepareOutwardPlan, observeOutwardPlan, OUTWARD_VOICE_REFUSAL } from "@schlessera/brain-ui-sdk/internal"; +import { compileWorkerCommandPolicy, denyWorkerCommand, requestPolicyPermission, prepareOutwardPlan, commitOutwardPlan, safetyAdmissionRefusal, observeOutwardPlan, OUTWARD_VOICE_REFUSAL } from "@schlessera/brain-ui-sdk/internal"; import type { PermissionDecision } from "@schlessera/brain-ui-sdk/server"; import type { TurnContext } from "./turn-context.js"; import { PI_BRAIN_UPDATE_TOOL_NAME } from "./tools.js"; +import { rememberPiAdmission } from "./tool-admission.js"; export interface PermissionGateOptions { /** The session's turn holder — the gate reads the CURRENT turn's bridge. */ @@ -113,7 +114,9 @@ export function createPermissionGate(options: PermissionGateOptions): InlineExte // The server route rechecks the exact operation, live principal, // membership and approval. Avoid a second runtime approval card. if (turn.bridge?.applyBrain && ["brain_add", "brain_update", "brain_archive", "write_file", "edit_file", "apply_staged_changes"].includes(event.toolName)) { - await turn.bridge.inputSafety?.begin(event.toolCallId,event.toolName,event.input??{});return undefined; + await turn.bridge.inputSafety?.begin(event.toolCallId,event.toolName,event.input??{}); + const unavailable = safetyAdmissionRefusal(turn.bridge.admissionSafety); + return unavailable ? { block: true, reason: unavailable } : undefined; } const decision = await decidePiToolPermission(options, event.toolName, (event.input ?? {}) as Record, event.toolCallId); if (decision.behavior === "deny") return { block: true, reason: decision.message || `Permission denied for ${event.toolName}.` }; @@ -143,12 +146,14 @@ export async function decidePiToolPermission(options: PermissionGateOptions, too if (unavailable) return { behavior: "deny", message: unavailable }; const policy = compileWorkerCommandPolicy(turn.autonomous ? undefined : turn.commandPolicy); const outward = (value: unknown) => prepareOutwardPlan({ toolName, shellToolName: "bash", input: value, - allow: turn.commandPolicy?.outwardAllow, taint: turn.commandPolicy?.taint, autonomous: Boolean(turn.autonomous), voice: turn.posture === "voice", configurationRoot: turn.configurationRoot, maintenance: turn.maintenance }); + allow: turn.commandPolicy?.outwardAllow, taint: turn.commandPolicy?.taint, safety: turn.bridge?.admissionSafety, autonomous: Boolean(turn.autonomous), voice: turn.posture === "voice", configurationRoot: turn.configurationRoot, maintenance: turn.maintenance }); const observe = (value: unknown, decision: Parameters[1]["decision"]) => observeOutwardPlan(outward(value), { bridge: turn.bridge, toolName, input: value, toolUseId, decision }); const denied = denyWorkerCommand(policy, { bridge: turn.bridge, toolName, shellToolName: "bash", input, toolUseId }); if (denied) { observeOutwardPlan(prepareOutwardPlan({ toolName, shellToolName: "bash", input, taint: turn.commandPolicy?.taint, autonomous: Boolean(turn.autonomous) }), { bridge: turn.bridge, toolName, input, toolUseId, decision: "refused" }); return { behavior: "deny", message: denied }; } if (turn.signal?.aborted) return { behavior: "deny", message: "Turn cancelled before tool admission." }; const outwardPlan = outward(input); + const snapshot = turn.bridge?.admissionSafety?.read(); + let outwardApproved = false; const confirmPatterns = [...options.confirmPatterns, ...policy.confirm, ...(outwardPlan.pattern ? [outwardPlan.pattern] : [])]; if (outwardPlan.voiceRefusal) { observe(input, "refused"); return { behavior: "deny", message: OUTWARD_VOICE_REFUSAL }; } let effective = input; @@ -168,6 +173,7 @@ export async function decidePiToolPermission(options: PermissionGateOptions, too const decision = await requestPolicyPermission(policy, { bridge: turn.bridge, request, shellToolName: "bash", permission: { noGrantSurface: turn.noGrantSurface }, signal: turn.signal }); if (decision.behavior === "deny") { observe(original, decision); return decision; } + if (approval.kind === "command" && outwardPlan.needsApproval) outwardApproved = true; if (decision.updatedInput !== undefined) { const refusal = denyWorkerCommand(policy, { bridge: turn.bridge, toolName, shellToolName: "bash", input: decision.updatedInput, toolUseId }) || checkEditedApproval({ toolName, shellToolName: "bash", updateToolName: PI_BRAIN_UPDATE_TOOL_NAME, @@ -189,6 +195,10 @@ export async function decidePiToolPermission(options: PermissionGateOptions, too } try{await turn.bridge?.inputSafety?.begin(toolUseId,toolName,effective);} catch(error){return {behavior:"deny",message:error instanceof Error?error.message:"Safety collection unavailable"};} - observe(effective, { behavior: "allow" }); + const finalPlan = outward(effective); + const stale = commitOutwardPlan(finalPlan, { bridge: turn.bridge, before: snapshot, approved: outwardApproved, signal: turn.signal }); + observeOutwardPlan(finalPlan, { bridge: turn.bridge, toolName, input: effective, toolUseId, decision: stale ? "refused" : { behavior: "allow" } }); + if (stale) return { behavior: "deny", message: stale }; + rememberPiAdmission(turn, toolName, toolUseId, effective, snapshot, outwardApproved); return effective === input ? { behavior: "allow" } : { behavior: "allow", updatedInput: effective }; } diff --git a/packages/ui-backend-pi/src/tool-admission.ts b/packages/ui-backend-pi/src/tool-admission.ts new file mode 100644 index 0000000000..2ecdabc775 --- /dev/null +++ b/packages/ui-backend-pi/src/tool-admission.ts @@ -0,0 +1,29 @@ +/** Host-only per-use provenance retained across rewrite and lock waits. */ +import { commitOutwardPlan, prepareOutwardPlan, STALE_SAFETY_ADMISSION, type AdmissionSafetySnapshot } from "@schlessera/brain-ui-sdk/internal"; +import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import type { TurnContext } from "./turn-context.js"; + +type Admission = { input: string; before?: AdmissionSafetySnapshot; approved: boolean }; +const admissions = new WeakMap }>(); +const key = (tool: string, id: string) => JSON.stringify([tool, id]); + +export function rememberPiAdmission(turn: TurnContext, tool: string, id: string, input: unknown, before: AdmissionSafetySnapshot | undefined, approved: boolean): void { + let state = admissions.get(turn); + if (!state || state.bridge !== turn.bridge) { state = { bridge: turn.bridge, calls: new Map() }; admissions.set(turn, state); } + const identity = key(tool, id); + if (!state.calls.has(identity) && state.calls.size >= 2000) throw new Error("Pi tool admission capacity exceeded"); + state.calls.set(identity, { input: JSON.stringify(input), before, approved }); +} + +/** No approval or replay: re-evaluate only the authority this exact call already obtained. */ +export function revalidatePiAdmission(turn: TurnContext, tool: string, id: string, input: unknown, consume = false): string | null { + const state = admissions.get(turn), admitted = state?.calls.get(key(tool, id)); + if (state?.bridge !== turn.bridge || !admitted || admitted.input !== JSON.stringify(input)) + return turn.bridge?.admissionSafety ? STALE_SAFETY_ADMISSION : null; + const plan = prepareOutwardPlan({ toolName: tool, shellToolName: "bash", input, allow: turn.commandPolicy?.outwardAllow, + taint: turn.commandPolicy?.taint, safety: turn.bridge?.admissionSafety, autonomous: !!turn.autonomous, + voice: turn.posture === "voice", configurationRoot: turn.configurationRoot, maintenance: turn.maintenance }); + const refused = commitOutwardPlan(plan, { bridge: turn.bridge, before: admitted.before, approved: admitted.approved, signal: turn.signal }); + if (!refused && consume) state!.calls.delete(key(tool, id)); + return refused; +} diff --git a/packages/ui-backend-pi/src/worker-entry.ts b/packages/ui-backend-pi/src/worker-entry.ts index db46b8471b..1b629446fa 100644 --- a/packages/ui-backend-pi/src/worker-entry.ts +++ b/packages/ui-backend-pi/src/worker-entry.ts @@ -188,6 +188,7 @@ async function initialize(init: Init): Promise { turn.turnContext.bridge = { emit() { throw new Error("Workers cannot emit privileged bridge frames"); }, requestPermission() { throw new Error("Use the server permission RPC"); }, + commitToolAdmission: async (id, name, input) => { await rpc("admission", name, id, input); }, applyBrain: input => rpc("apply", toolScope.getStore()?.name ?? "", toolScope.getStore()?.id ?? "", input as unknown as Record), readBrainBase: path => rpc("readBase", "brain_read_base", toolScope.getStore()?.id ?? "", { path }), }; diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index 26fd35b4ac..9a953ad870 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -78,7 +78,7 @@ export const piWorkerMessage = z.discriminatedUnion("type", [ z.object({ type: z.literal("ready"), sessionId: z.string().uuid(), append: z.string().optional(), model: input.optional(), thinkingLevel: text.optional(), levels: z.array(text), cost: usageNumber }).strict(), z.object({ type: z.literal("event"), event: piWorkerEvent }).strict(), - z.object({ type: z.literal("rpc"), id, method: z.enum(["permission", "bridge", "apply", "readBase", "syncAuth", "lock", "unlock", "fileObservation", "safetyResult", "safetyUnavailable"]), + z.object({ type: z.literal("rpc"), id, method: z.enum(["permission", "admission", "bridge", "apply", "readBase", "syncAuth", "lock", "unlock", "fileObservation", "safetyResult", "safetyUnavailable"]), toolCallId: text, toolName: text, input }).strict(), z.object({ type: z.literal("snapshot"), entries: z.array(transcriptEntry) }).strict(), z.object({ type: z.literal("done"), cost: usageNumber, error: text.optional() }).strict(), diff --git a/packages/ui-backend-pi/src/worker-rpc.ts b/packages/ui-backend-pi/src/worker-rpc.ts index 1144071400..86f0e5e78a 100644 --- a/packages/ui-backend-pi/src/worker-rpc.ts +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -14,6 +14,8 @@ import type { LaunchedWorker, NativeFileVersions, WorkerSandbox } from "@schless import type { SessionCaps } from "./backend-options.js"; import { createPiBridgeTools, REQUEST_IMAGE_MASK_INPUT_SCHEMA } from "./bridge-tools.js"; import { decidePiToolPermission } from "./permission-gate.js"; +import { revalidatePiAdmission } from "./tool-admission.js"; +import { safetyAdmissionRefusal } from "@schlessera/brain-ui-sdk/internal"; import { syncPiAuth } from "./session-storage.js"; import type { TurnContext } from "./turn-context.js"; import type { PiWorkerMessage } from "./worker-protocol.js"; @@ -85,7 +87,11 @@ async function lock(msg: PiWorkerRpc, _bridge: BackendBridge, context: PiWorkerR : fileTool ? target && `path:${target}` : BRAIN_LOCK_KEY; if (typeof key !== "string" || msg.input.key !== key || Object.keys(msg.input).length !== 1) throw new Error("Pi worker lock does not match the authorized operation"); const release = await workerLock.acquire(key, { signal: turnContext.signal ?? undefined }); - try { live(); } catch (error) { release(); throw error; } + try { + live(); + const stale = revalidatePiAdmission(turnContext, msg.toolName, msg.toolCallId, input); + if (stale) { grants.delete(msg.toolCallId); throw new Error(stale); } + } catch (error) { release(); throw error; } const lockId = randomUUID(); releases.set(lockId, release); executed(msg).lock = true; return { lockId }; } @@ -111,6 +117,8 @@ async function fileObservation(msg: PiWorkerRpc, _bridge: BackendBridge, context await nativeVersions.beginWrite(observed.key); } else await nativeVersions.finishWrite(observed.key, observed.version); executed(msg).phases.add(phase as string); + const unavailable = safetyAdmissionRefusal(context.turn.bridge?.admissionSafety); + if (unavailable) throw new Error(unavailable); return { ok: true }; } @@ -137,11 +145,18 @@ async function permission(msg: PiWorkerRpc, bridge: BackendBridge, context: PiWo if (application && bridge.applyBrain) { // 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" }; } 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) }); return decision; } @@ -229,6 +244,14 @@ async function apply(msg: PiWorkerRpc, bridge: BackendBridge, context: PiWorkerR /** One handler per worker RPC method. */ export const PI_WORKER_RPC_HANDLERS: Readonly> = { unlock, lock, fileObservation, syncAuth, permission, bridge: bridgeCall, readBase, apply, + admission: async (msg, _bridge, context) => { + const grant = context.grants.get(msg.toolCallId); + if (msg.toolName !== "bash" || !grant || grant.name !== msg.toolName || grant.input !== JSON.stringify(msg.input)) throw new Error("Pi final admission has no exact permission grant"); + const stale = revalidatePiAdmission(context.turn, msg.toolName, msg.toolCallId, msg.input, true); + if (stale) { context.grants.delete(msg.toolCallId); throw new Error(stale); } + context.grants.delete(msg.toolCallId); + return { ok: true }; + }, safetyUnavailable: async(msg,bridge)=>{ if(msg.toolName||msg.toolCallId||Object.keys(msg.input).length)throw new Error("Malformed safety unavailable notice"); await bridge.inputSafety?.unavailable?.(); diff --git a/packages/ui-backend-pi/tests/worker-rpc.test.ts b/packages/ui-backend-pi/tests/worker-rpc.test.ts index b9c0779579..50f5311632 100644 --- a/packages/ui-backend-pi/tests/worker-rpc.test.ts +++ b/packages/ui-backend-pi/tests/worker-rpc.test.ts @@ -64,7 +64,7 @@ function harness(overrides: Partial = {}, bridge: Partial { expect(Object.keys(PI_WORKER_RPC_HANDLERS).sort()) - .toEqual(["apply", "bridge", "fileObservation", "lock", "permission", "readBase", "safetyResult", "safetyUnavailable", "syncAuth", "unlock"]); + .toEqual(["admission", "apply", "bridge", "fileObservation", "lock", "permission", "readBase", "safetyResult", "safetyUnavailable", "syncAuth", "unlock"]); }); test("a method without a handler is refused, including inherited object keys", async () => { diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index f4ae5714b6..0964b9d252 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -59,8 +59,10 @@ export { compileWorkerCommandPolicy, denyWorkerCommand, requestPolicyPermission, workerCommandPolicyNote } from "./server/command-policy.js"; export type { CompiledWorkerCommandPolicy, WorkerCommandPolicy } from "./server/command-policy.js"; -export { prepareOutwardPlan, observeOutwardPlan, OUTWARD_VOICE_REFUSAL, workerOutwardNote } from "./server/outward-policy.js"; +export { prepareOutwardPlan, commitOutwardPlan, observeOutwardPlan, OUTWARD_VOICE_REFUSAL, workerOutwardNote } from "./server/outward-policy.js"; export type { OutwardPlan } from "./server/outward-policy.js"; +export { sameSafetyAdmission, safetyAdmissionRefusal, STALE_SAFETY_ADMISSION } from "./server/admission-safety.js"; +export type { AdmissionSafety, AdmissionSafetySnapshot } from "./server/admission-safety.js"; export { NativeFileVersions, nativeFileVersion } from "./server/native-file-versions.js"; export { createWorkerFileObserver } from "./server/worker-file-observer.js"; export type { ObservedWorkerFile } from "./server/worker-file-observer.js"; diff --git a/packages/ui-sdk/src/server/admission-safety.ts b/packages/ui-sdk/src/server/admission-safety.ts new file mode 100644 index 0000000000..5c9c8c6e60 --- /dev/null +++ b/packages/ui-sdk/src/server/admission-safety.ts @@ -0,0 +1,39 @@ +/** Host-only state. Never serialized into worker initialization or provider history. */ +export interface AdmissionSafetySnapshot { + readonly evidenceRevision: string; + readonly trustRevision: string; + readonly authorityEpoch: string; + readonly scope: string; + readonly policyHash: string | null; + readonly restricted: boolean; + readonly recordingAvailable: boolean; + readonly authorityCurrent: boolean; +} + +export interface AdmissionSafety { + read(): AdmissionSafetySnapshot; + /** Invalidation is a hint; every commit still reads synchronously. */ + subscribe(changed: () => void): () => void; +} + +export const STALE_SAFETY_ADMISSION = "Safety or authority changed before admission. Nothing ran; a fresh attempt needs a fresh decision."; + +export function sameSafetyAdmission(a: AdmissionSafetySnapshot, b: AdmissionSafetySnapshot): boolean { + return a.evidenceRevision === b.evidenceRevision && a.trustRevision === b.trustRevision && a.authorityEpoch === b.authorityEpoch + && a.scope === b.scope && a.policyHash === b.policyHash && a.restricted === b.restricted + && a.recordingAvailable === b.recordingAvailable && a.authorityCurrent === b.authorityCurrent; +} + +/** Call in the dispatching continuation, after its last await. */ +export function safetyAdmissionRefusal(safety: AdmissionSafety | undefined, before?: AdmissionSafetySnapshot): string | null { + if (!safety) return null; + try { + return safetySnapshotRefusal(safety.read(), before); + } catch { return STALE_SAFETY_ADMISSION; } +} + +export function safetySnapshotRefusal(now: AdmissionSafetySnapshot | undefined, before?: AdmissionSafetySnapshot): string | null { + if (now && (!now.authorityCurrent || !now.recordingAvailable || before && + (now.scope !== before.scope || now.policyHash !== before.policyHash || now.authorityEpoch !== before.authorityEpoch))) return STALE_SAFETY_ADMISSION; + return null; +} diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index 6d7be712d4..ad835edc0a 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -113,6 +113,8 @@ export type PermissionDecision = | { behavior: "deny"; message: string }; export interface PermissionRequest { + /** @internal Host snapshot for withdrawing stale cards; never client authority. */ + admissionSnapshot?: import("./admission-safety.js").AdmissionSafetySnapshot; toolUseId: string; toolName: string; input: Record; @@ -171,6 +173,10 @@ export interface LocationFix { * @experimental Part of the `AgentBackend` seam. */ export interface BackendBridge { + /** @internal Worker-to-host final admission after local rewrite/lock waits. Never an approval surface. */ + commitToolAdmission?(toolUseId: string, toolName: string, input: Record): Promise; + /** @internal Live host state, never sent to a worker or model provider. */ + admissionSafety?: import("./admission-safety.js").AdmissionSafety; /** @internal Host-owned versioned input collection. Await before executing a * tool and before returning its result to the provider. Never a grant. */ inputSafety?: { diff --git a/packages/ui-sdk/src/server/egress-proxy.ts b/packages/ui-sdk/src/server/egress-proxy.ts index 98f876fca3..6f0e4c7210 100644 --- a/packages/ui-sdk/src/server/egress-proxy.ts +++ b/packages/ui-sdk/src/server/egress-proxy.ts @@ -5,6 +5,7 @@ import { chmodSync, chownSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { workerIdentityHelper } from "./worker-identity.js"; import { join } from "node:path"; +import { safetyAdmissionRefusal, type AdmissionSafety, type AdmissionSafetySnapshot } from "./admission-safety.js"; export const WORKER_EGRESS_DIR = "/run/brain-egress"; export const WORKER_EGRESS_SOCKET = `${WORKER_EGRESS_DIR}/proxy.sock`; @@ -31,6 +32,8 @@ export interface EgressRecord { reason?: string; } export interface EgressProxyOptions { + /** Host-owned effective state. No request header or concurrent operation supplies authority. */ + admissionSafety?: AdmissionSafety; mode: "record" | "allowlist"; /** Exact DNS names/IPs or *.suffix; deny always wins. */ allow: readonly string[]; @@ -50,7 +53,7 @@ export interface EgressProxyOptions { * asks before refusing a narrowed destination (#3430); absent, or resolving * anything but `true`, refuses. */ - taint?: { allow: readonly string[]; tainted(): boolean; contacted(host: string): boolean; + taint?: { allow: readonly string[]; tainted(connectionId?: string): boolean; contacted(host: string): boolean; approve?(destination: { host: string; port: number; method: string }, signal: AbortSignal): Promise; /** What tainted the session, as "it …" completes it, for a refusal's message (#3431). */ cause?(): string | null }; @@ -60,6 +63,8 @@ export interface EgressProxyOptions { * before any byte flows; its rejection refuses the connection. */ admitted?(destination: { host: string; port: number; method: string; inference: boolean; provider: boolean; connectionId: string; protocol?: string }): unknown; + /** Synchronous notification only after final admission, immediately before dispatch. */ + committed?(destination: { host: string; connectionId: string; inference: boolean; provider: boolean }): void; signal?: AbortSignal; } const hostname = (value: string) => value.toLowerCase().replace(/\.$/, ""); @@ -147,6 +152,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { function operation(method: string, url: URL, relay?: "inference" | "provider") { const inference = relay === "inference", provider = relay === "provider"; const connectionId = crypto.randomUUID(); + let snapshot: AdmissionSafetySnapshot | undefined; const started = performance.now(); const controller = new AbortController(); controllers.add(controller); const host = hostname(url.hostname), port = Number(url.port || (url.protocol === "https:" ? "443" : "80")); @@ -188,7 +194,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { let granted = false; // Checked again after an approval wait, during which another connection may taint the session. // Neither host relay is narrowed by taint (G6; #3246 for the provider relay). - const narrowed = () => !granted && !relay && options.taint?.tainted() && !matches(host, options.taint.allow) && !options.taint.contacted(host); + const narrowed = (final = false) => !granted && !relay && options.taint?.tainted(final ? connectionId : undefined) && !matches(host, options.taint.allow) && !options.taint.contacted(host); const narrowing = async () => { if (!narrowed()) return true; if (options.taint?.approve) granted = await approval(options.taint.approve.bind(options.taint)); @@ -196,6 +202,8 @@ export async function startEgressProxy(options: EgressProxyOptions) { return granted; }; const admit = async () => { + snapshot = options.admissionSafety?.read(); + if (safetyAdmissionRefusal(options.admissionSafety, snapshot)) { finish("denied", "safety_changed"); return false; } if (stopped || options.signal?.aborted) { finish("cancelled", "turn_cancelled"); return false; } if (matches(host, options.deny) || options.mode === "allowlist" && !matches(host, options.allow)) { finish("denied", "destination_not_allowed"); return false; } if (usedBytes >= options.maxBytes) { finish("denied", "max_bytes_per_turn"); return false; } @@ -209,6 +217,14 @@ export async function startEgressProxy(options: EgressProxyOptions) { if (stopped || controller.signal.aborted) { finish("cancelled", "turn_cancelled"); return false; } return true; }; + // No await may intervene between this check and connect/request/fetch. + const commit = () => { + if (stopped || controller.signal.aborted || safetyAdmissionRefusal(options.admissionSafety, snapshot)) { finish("denied", "safety_changed"); return false; } + if (usedBytes >= options.maxBytes) { finish("denied", "max_bytes_per_turn"); return false; } + if (narrowed(true)) { finish("denied", "taint_not_allowed"); return false; } + options.committed?.({ host, connectionId, inference, provider }); + return true; + }; /** Why this connection was refused, for the tool that made it; undefined while admitted or for a bare refusal. */ const refusal = () => { if (finalOutcome !== "denied") return undefined; @@ -216,7 +232,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { if (finalReason === "taint_not_allowed") try { cause = options.taint?.cause?.(); } catch { /* The message names no cause. */ } return describeRefusal(finalReason, host, matches(host, options.deny), cause); }; - return { finish, charge, admit, refusal, signal: controller.signal, outcome: () => finalOutcome, reason: () => finalReason }; + return { finish, charge, admit, commit, refusal, signal: controller.signal, outcome: () => finalOutcome, reason: () => finalReason }; } server.on("connect", (request, client, head) => { client.on("error", () => {}); @@ -230,7 +246,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { let connected = false; client.once("close", () => op.finish(stopped || !connected ? "cancelled" : "completed")); void (async () => { - if (!await op.admit() || client.destroyed) { + if (!await op.admit() || client.destroyed || !op.commit()) { const declined = refusalHead(op.refusal(), op.reason()); client.end(declined ? `HTTP/1.1 403 ${declined.status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${Buffer.byteLength(declined.body)}\r\nConnection: close\r\n\r\n${declined.body}` : "HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"); @@ -267,7 +283,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { else { response.writeHead(403); response.end(); } }; void (async () => { - if (!await op.admit() || response.destroyed) { refuse(); return; } + if (!await op.admit() || response.destroyed || !op.commit()) { refuse(); return; } const outgoingHeaders = { ...headers(request), host: target.host, connection: "close" }; // Include the complete observable target and headers: a body-only cap // would allow uncharged exfiltration in query strings or header values. @@ -335,7 +351,9 @@ export async function startEgressProxy(options: EgressProxyOptions) { signal.addEventListener("abort", abort, { once: true }); if (signal.aborted) abort(); return { charge: op.charge, signal: op.signal, outcome: op.outcome, refusal: op.refusal, - admit: async () => !op.signal.aborted && await op.admit(), + admit: async () => !op.signal.aborted && await op.admit() && op.commit(), + /** The concrete relay calls this again after its own final async waits. */ + commit: op.commit, finish(outcome: EgressRecord["outcome"], reason?: string) { signal.removeEventListener("abort", abort); op.finish(outcome, reason); }, diff --git a/packages/ui-sdk/src/server/inference-relay.ts b/packages/ui-sdk/src/server/inference-relay.ts index a2d9318f1e..3215f53a5e 100644 --- a/packages/ui-sdk/src/server/inference-relay.ts +++ b/packages/ui-sdk/src/server/inference-relay.ts @@ -189,6 +189,7 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe // Body/credential waits may have crossed an input-recording failure. // Re-enter the concrete host admission at the last dispatch boundary. if(operation&&!await operation.admit())return denied("inference_admission_refused"); + if(operation&&!operation.commit())return denied("inference_admission_refused"); let response: Response; try { // Never follow a redirect: the upstream must not choose another host. diff --git a/packages/ui-sdk/src/server/outward-policy.ts b/packages/ui-sdk/src/server/outward-policy.ts index e8dac6a10a..64dd85f46c 100644 --- a/packages/ui-sdk/src/server/outward-policy.ts +++ b/packages/ui-sdk/src/server/outward-policy.ts @@ -3,6 +3,7 @@ import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { realpathSync } from "node:fs"; import { dirname } from "node:path"; import type { BackendBridge, PermissionDecision } from "./backend.js"; +import { safetySnapshotRefusal, STALE_SAFETY_ADMISSION, type AdmissionSafety, type AdmissionSafetySnapshot } from "./admission-safety.js"; import { bashCommand, type CompiledConfirmPattern } from "./confirm-patterns.js"; import { runMaintenanceWorkerSync, type MaintenanceHost } from "./maintenance-worker.js"; import { classifyOutwardCall, outwardTarget, type OutwardClassification, type VisibleOutwardAction } from "./outward-actions.js"; @@ -48,9 +49,10 @@ export function prepareOutwardPlan(options: { autonomous?: boolean; voice?: boolean; configurationRoot?: string; maskPaths?: readonly string[]; maintenance?: MaintenanceHost; /** Read at admission: a session that ingested untrusted input asks for every outward action (G6). */ taint?: () => WorkerSessionTaint | null; + safety?: AdmissionSafety; }): OutwardPlan { const classification = options.autonomous ? { kind: "unknown" as const, actions: [] } : classifyOutwardCall(options.toolName, options.shellToolName, options.input); - const tainted = classification.actions.length > 0 && options.taint?.() != null; + const tainted = classification.actions.length > 0 && (options.safety ? options.safety.read().restricted : options.taint?.() != null); const rules = classification.actions.map(action => { // Unknown preceding code can alter a named destination before the push. // A visible action still asks; opaque segments never borrow an allow rule. @@ -70,6 +72,25 @@ export function prepareOutwardPlan(options: { const pattern = needsApproval && command ? Object.assign(new RegExp(`^${escape(command)}$`, "i"), { effect: `Outward action: ${reason}.${untrusted}` }) : undefined; return { classification, rules, tainted, needsApproval, voiceRefusal, ...(pattern ? { pattern } : {}) }; } +/** Recompute standing authority at the last host-controlled dispatch boundary. + * A completed per-use outward card is authority for its exact input, not a rule. */ +export function commitOutwardPlan(plan: OutwardPlan, options: { + bridge?: BackendBridge | null; before?: AdmissionSafetySnapshot; approved: boolean; signal?: AbortSignal | null; +}): string | null { + let now: AdmissionSafetySnapshot | undefined; + try { now = options.bridge?.admissionSafety?.read(); } catch { return STALE_SAFETY_ADMISSION; } + const unavailable = safetySnapshotRefusal(now, options.before); + if (unavailable || options.signal?.aborted) return unavailable ?? STALE_SAFETY_ADMISSION; + // Remote resolution can itself block while another writer commits. The + // final snapshot, not a taint read made before that lookup, decides. + if (now?.restricted && plan.classification.actions.length) { + plan.tainted = true; plan.rules = plan.rules.map(() => null); plan.needsApproval = true; + } + if (plan.voiceRefusal) return OUTWARD_VOICE_REFUSAL; + if (plan.needsApproval && !options.approved) return STALE_SAFETY_ADMISSION; + if (options.approved) plan.rules = plan.rules.map(() => null); + return null; +} function bounded(text: string, limit: number): string { const suffix = "… [truncated]"; return text.length <= limit ? text : text.slice(0, limit - suffix.length) + suffix; } diff --git a/packages/ui-sdk/src/server/permission-gate.ts b/packages/ui-sdk/src/server/permission-gate.ts index 97d63273e7..8a42352c92 100644 --- a/packages/ui-sdk/src/server/permission-gate.ts +++ b/packages/ui-sdk/src/server/permission-gate.ts @@ -3,6 +3,7 @@ import type { PermissionDecision, PermissionRequest, } from "./backend.js"; +import { sameSafetyAdmission, STALE_SAFETY_ADMISSION } from "./admission-safety.js"; import { ARCHIVING_UPDATE_REASON, archivesDocument, @@ -252,7 +253,7 @@ function noGrantSurfaceMessage(request: PermissionRequest): string { * @experimental */ export function requestToolPermission( - bridge: Pick | null | undefined, + bridge: Pick | null | undefined, request: PermissionRequest, options: RequestToolPermissionOptions = {} ): Promise { @@ -288,7 +289,12 @@ export function requestToolPermission( message: `No active turn to approve ${request.toolName}.`, }); } - return bridge.requestPermission(request).then((decision) => snapshotEdit(request, decision)); + const guarded = bridge.admissionSafety ? { ...request, admissionSnapshot: bridge.admissionSafety.read() } : request; + return bridge.requestPermission(guarded).then((decision) => { + if (bridge.admissionSafety && guarded.admissionSnapshot && !sameSafetyAdmission(guarded.admissionSnapshot, bridge.admissionSafety.read())) + return { behavior: "deny", message: STALE_SAFETY_ADMISSION }; + return snapshotEdit(request, decision); + }); } /** diff --git a/packages/ui-sdk/src/server/provider-relay.ts b/packages/ui-sdk/src/server/provider-relay.ts index e0da9b1cf8..6d1e734249 100644 --- a/packages/ui-sdk/src/server/provider-relay.ts +++ b/packages/ui-sdk/src/server/provider-relay.ts @@ -503,6 +503,7 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider operation?.finish("denied", "budget_exceeded"); return refuse(403, "budget_exceeded", now.message); } + if (operation && !operation.commit()) return denied("provider_admission_refused"); const attemptId = crypto.randomUUID(); let reported = false; const observe = (outcome: ProviderRelayReceipt["outcome"], status: number, usage: ProviderUsage | null): void => { @@ -674,6 +675,7 @@ export function startProviderRelay(options: ProviderRelayOptions = {}): Provider catch { /* The host's own accounting reports its failure. */ } }; observe("dispatched", 0); + if (operation && !operation.commit()) return; try { const response = await fetch(target, { method: "DELETE", headers, redirect: "manual", signal }); await response.body?.cancel().catch(() => {}); diff --git a/packages/ui-sdk/src/turn-journal.ts b/packages/ui-sdk/src/turn-journal.ts index 7fd2de1c82..8bea3d6f9f 100644 --- a/packages/ui-sdk/src/turn-journal.ts +++ b/packages/ui-sdk/src/turn-journal.ts @@ -92,7 +92,7 @@ export interface TurnJournalChange { before: JournalVersion | null; after: JournalVersion | null; overlappingTurnIds: string[]; - /** Present only when an existing same-session/turn taint event preceded this observation. */ + /** Effective restriction at this observation; unknown coverage may have no source event. Historical attribution is unchanged. */ tainted?: true; taintSourceEventId?: number; /** At least two distinct retained after-versions observed in one shared window. */ diff --git a/packages/ui-server/migrations/083_effective_taint.journal.sql b/packages/ui-server/migrations/083_effective_taint.journal.sql new file mode 100644 index 0000000000..a9054b5a9d --- /dev/null +++ b/packages/ui-server/migrations/083_effective_taint.journal.sql @@ -0,0 +1,3 @@ +-- Historical rows retain their original attribution. Only new observations +-- capture effective restriction, including unknown coverage with no source row. +ALTER TABLE journal.turn_journal_changes ADD COLUMN effective_taint INTEGER CHECK (effective_taint IN (0,1)); diff --git a/packages/ui-server/src/brain/compute-host.ts b/packages/ui-server/src/brain/compute-host.ts index 374b4be363..a79661be2b 100644 --- a/packages/ui-server/src/brain/compute-host.ts +++ b/packages/ui-server/src/brain/compute-host.ts @@ -53,7 +53,7 @@ import type { ActivityRuntime } from "../activity/runtime.js"; import { COMPUTE_RUN_PREFIX } from "../activity/stream.js"; import type { SpanOutcome } from "../activity/store.js"; import type { GovernanceEventInput } from "../governance/events.js"; -import { queryGovernanceEvents } from "../governance/events.js"; +import { sessionTaint } from "../governance/session-taint.js"; import { ProviderMaskRefusedError } from "./provider-mask-refusal.js"; import type { TurnBudgets } from "./turn-budgets.js"; @@ -699,8 +699,7 @@ export function createComputeHost(options: ComputeHostOptions): ComputeHost { // The conversation's earlier turns, and this turn's events not yet bound to its session. const tainted = (session: string) => { try { - return queryGovernanceEvents(db, { sessionId: session, kinds: ["taint"], limit: 1 }).length > 0 - || queryGovernanceEvents(db, { turnId: ctx.turnId, kinds: ["taint"], limit: 1 }).length > 0; + return sessionTaint(db, ctx.turnId, session) !== null; } catch { return true; } }; const canAsk = () => !ctx.autonomous && ctx.posture !== "voice" && !ctx.noGrantSurface && ctx.hasClient(); diff --git a/packages/ui-server/src/brain/journal-governance.ts b/packages/ui-server/src/brain/journal-governance.ts index 6e5e6f6008..8b510e03a6 100644 --- a/packages/ui-server/src/brain/journal-governance.ts +++ b/packages/ui-server/src/brain/journal-governance.ts @@ -4,7 +4,7 @@ import { GovernanceEventError, recordGovernanceEvent } from "../governance/event type SteeringRow = { turn_id: string; sequence: number; path: string; scope: string; before_json: string | null; after_json: string | null; actor: string; - overlaps: string; taint_source_event_id: number | null; session_id: string | null; turn_actor: "interactive" | "voice" | "user"; + overlaps: string; effective_taint: number | null; taint_source_event_id: number | null; session_id: string | null; turn_actor: "interactive" | "voice" | "user"; model: string | null; profile: "strict" | "governed"; at: number; }; @@ -17,7 +17,7 @@ type SteeringRow = { * Returns how many events it recorded. */ export function replaySteeringEvents(db: Database): number { - const rows = db.query(`SELECT c.turn_id, c.sequence, c.path, c.scope, c.before_json, c.after_json, c.actor, c.overlaps, c.taint_source_event_id, + const rows = db.query(`SELECT c.turn_id, c.sequence, c.path, c.scope, c.before_json, c.after_json, c.actor, c.overlaps, c.taint_source_event_id, c.effective_taint, t.session_id, t.actor AS turn_actor, t.model, t.profile, coalesce(t.ended_at, t.started_at) AS at FROM turn_journal_changes c JOIN turn_journal_turns t ON t.turn_id = c.turn_id WHERE c.class = 'steering' AND NOT EXISTS (SELECT 1 FROM governance_events g @@ -32,7 +32,7 @@ export function replaySteeringEvents(db: Database): number { actor: row.scope !== "claude_memory" && row.actor === "user" ? "user" : row.turn_actor, dedupeKey: `${row.turn_id}:${row.sequence}`, payload: { path: row.path, sequence: row.sequence, beforeHash: hash(row.before_json), afterHash: hash(row.after_json), - taintSourceEventId: row.taint_source_event_id, overlappingTurnIds: JSON.parse(row.overlaps) as string[] }, + ...(row.effective_taint === 1 ? { tainted: true as const } : {}), taintSourceEventId: row.taint_source_event_id, overlappingTurnIds: JSON.parse(row.overlaps) as string[] }, }).recorded); } catch (error) { // A row the event schema refuses could never have been recorded either. diff --git a/packages/ui-server/src/brain/journal-store.ts b/packages/ui-server/src/brain/journal-store.ts index 867d48e48c..31187bb246 100644 --- a/packages/ui-server/src/brain/journal-store.ts +++ b/packages/ui-server/src/brain/journal-store.ts @@ -10,6 +10,7 @@ import type { JournalObservationReference, JournalVersion } from "@schlessera/br import type { WireError, WriteProcedures } from "../db/write-worker.js"; import { recordGovernanceEvent } from "../governance/events.js"; +import { sessionTaint } from "../governance/session-taint.js"; import { createJournalAccounting, JournalStorageUnavailable } from "./journal-accounting.js"; import { configurationSet, recordedConfigurationSet } from "./journal-configuration-sets.js"; import { createJournalObjects, JournalCapacityError, type JournalObjectReservation } from "./journal-objects.js"; @@ -131,8 +132,7 @@ export function setup(db: Database, options: JournalStoreOptions): WriteProcedur const purgeState = () => (db.query("SELECT index_purge FROM turn_journal_allocation WHERE id=1").get() as { index_purge: number }).index_purge; const turnContext = (turnId: string) => { const row = db.query("SELECT * FROM turn_journal_turns WHERE turn_id=?").get(turnId) as TurnRow; - const taint = db.query("SELECT id FROM governance_events WHERE kind='taint' AND (turn_id=? OR (? IS NOT NULL AND session_id=?)) ORDER BY id LIMIT 1") - .get(turnId, row.session_id, row.session_id) as { id: number } | null; + const taint = sessionTaint(db, turnId, row.session_id); return { row, taint }; }; return { @@ -248,13 +248,14 @@ export function setup(db: Database, options: JournalStoreOptions): WriteProcedur const approvedPolicy = record.userPolicy && item.path === "context/policies/governance.md"; const classification = approvedPolicy ? "policy" : steering.has(item.path) ? "steering" : "content"; const actor = approvedPolicy || metadata.kind === "revert" ? "user" : "agent"; - const source = classification === "steering" && actor === "agent" && taint ? taint.id : null; + const restricted = classification === "steering" && actor === "agent" && taint !== null; + const source = restricted && taint!.eventId > 0 ? taint!.eventId : null; const overlappingTurnIds = record.overlaps.filter(id => id !== turnId); - db.query("INSERT INTO turn_journal_changes (turn_id,sequence,path,scope,before_json,after_json,class,actor,overlaps,taint_source_event_id) VALUES (?,?,?,?,?,?,?,?,?,?)") - .run(turnId, sequence, item.path, item.scope, item.before ? JSON.stringify(item.before) : null, item.after ? JSON.stringify(item.after) : null, classification, actor, JSON.stringify(overlappingTurnIds), source); + db.query("INSERT INTO turn_journal_changes (turn_id,sequence,path,scope,before_json,after_json,class,actor,overlaps,taint_source_event_id,effective_taint) VALUES (?,?,?,?,?,?,?,?,?,?,?)") + .run(turnId, sequence, item.path, item.scope, item.before ? JSON.stringify(item.before) : null, item.after ? JSON.stringify(item.after) : null, classification, actor, JSON.stringify(overlappingTurnIds), source, restricted ? 1 : 0); if (classification === "steering") recordGovernanceEvent(db, { kind: "steering_change", sessionId: metadata.session_id, turnId, actor: actor === "user" ? "user" : metadata.actor, model: metadata.model, profile: metadata.profile, at, dedupeKey: `${turnId}:${sequence}`, - payload: { path: item.path, sequence, beforeHash: item.before?.hash ?? null, afterHash: item.after?.hash ?? null, taintSourceEventId: source, overlappingTurnIds } }); + payload: { path: item.path, sequence, beforeHash: item.before?.hash ?? null, afterHash: item.after?.hash ?? null, taintSourceEventId: source, overlappingTurnIds, ...(restricted ? { tainted: true } : {}) } }); pin(turnId, item.before); pin(turnId, item.after); const observed = db.query("SELECT sequence,after_json,overlaps FROM turn_journal_changes WHERE turn_id=? AND path=? ORDER BY sequence").all(turnId, item.path) as {sequence:number;after_json:string|null;overlaps:string}[]; const participants = new Set(observed.flatMap(row => JSON.parse(row.overlaps) as string[])); @@ -304,12 +305,13 @@ export function setup(db: Database, options: JournalStoreOptions): WriteProcedur const { row: metadata, taint: found } = turnContext(turnId); const actor = metadata.actor === "user" ? "user" : "agent"; const taint = actor === "agent" ? found : null; - db.query("INSERT INTO turn_journal_changes (turn_id,sequence,path,scope,before_json,after_json,class,actor,overlaps,taint_source_event_id) VALUES (?,?,?,?,?,?,'steering',?,'[]',?)") - .run(turnId, sequence, path, "claude_memory", before ? JSON.stringify(before) : null, after ? JSON.stringify(after) : null, actor, taint?.id ?? null); + const source = taint && taint.eventId > 0 ? taint.eventId : null; + db.query("INSERT INTO turn_journal_changes (turn_id,sequence,path,scope,before_json,after_json,class,actor,overlaps,taint_source_event_id,effective_taint) VALUES (?,?,?,?,?,?,'steering',?,'[]',?,?)") + .run(turnId, sequence, path, "claude_memory", before ? JSON.stringify(before) : null, after ? JSON.stringify(after) : null, actor, source, taint ? 1 : 0); db.query("INSERT OR REPLACE INTO turn_journal_claude_memory VALUES (?,?,?,?,?,?,?,?,?)").run(turnId, path, target.directory, target.device, target.inode, target.note, before ? JSON.stringify(before) : null, after ? JSON.stringify(after) : null, "saved"); pin(turnId, before); pin(turnId, after); recordGovernanceEvent(db, { kind: "steering_change", sessionId: metadata.session_id, turnId, actor: metadata.actor, model: metadata.model, profile: metadata.profile, at, dedupeKey: `${turnId}:${sequence}`, - payload: { path, sequence, beforeHash: before?.hash ?? null, afterHash: after?.hash ?? null, taintSourceEventId: taint?.id ?? null, overlappingTurnIds: [] } }); + payload: { path, sequence, beforeHash: before?.hash ?? null, afterHash: after?.hash ?? null, taintSourceEventId: source, overlappingTurnIds: [], ...(taint ? { tainted: true } : {}) } }); }); }, /** False when the turn has no record to mark. */ diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index fcc51a1cc9..8337dc66f2 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -7,6 +7,7 @@ import { occurrence, type Occurrence } from "../governance/occurrence.js"; import type { GovernanceEventInput } from "../governance/events.js"; import { contactedHosts, recordFirstTaint, sessionTaint, type TaintSource } from "../governance/session-taint.js"; import type { GovernanceWrites } from "../governance/event-writes.js"; +import { safetyProjection } from "../governance/safety-store.js"; type Classification = Extract["classification"]; const GITHUB_API_HOSTS = ["api.github.com", "uploads.github.com"] as const; @@ -96,7 +97,7 @@ export async function prepareTurnEgress(options: { * before that commit lands (#2850). Absent: the taint commits on * `governanceDb` through `record`. */ - governanceWrites?: Pick & Partial>; + governanceWrites?: Pick & Partial>; }) { const calls = createOutwardCalls(); let recordingFailure: Error | undefined; @@ -112,6 +113,7 @@ export async function prepareTurnEgress(options: { const contacted = new Set(db ? contactedHosts(db, options.sessionId()) : []); const collectionEpoch = (db?.query("SELECT id FROM safety_collections WHERE turn_id=?").get(options.turnId) as {id:string}|null)?.id??crypto.randomUUID(); const exposures = new Map(); + const normalBefore = new Set(); const base = () => ({ turnId: options.turnId, sessionId: options.sessionId(), model: options.model(), actor: options.origin, profile: options.profile }); const fail = () => { @@ -130,6 +132,7 @@ export async function prepareTurnEgress(options: { const exposure = record.connectionId ? exposures.get(record.connectionId) : undefined; if (exposure) { exposures.delete(record.connectionId!); + normalBefore.delete(record.connectionId!); // A clean HTTP completion proves bounded input ended. A tunnel close // or cancellation alone cannot prove all opaque delivery completed. track(options.record({ ...base(), kind: "taint_exposure", dedupeKey: exposure.id, @@ -175,7 +178,17 @@ export async function prepareTurnEgress(options: { }; const taint = db ? { allow: options.policy.taint.egress.allow, - tainted: () => firstTaint() !== null, + tainted: (connectionId?: string) => { + if (connectionId && normalBefore.has(connectionId)) { + const projection = options.governanceWrites?.safety?.(options.turnId, options.sessionId()) ?? safetyProjection(db, options.turnId, options.sessionId()); + // Only this request's own newly recorded input may be excluded from + // its first-byte check. A second connection gets no such authority. + if (projection.coverage.state === "complete" && projection.unresolvedCount === 1 && + projection.earliestUnresolvedId === exposures.get(connectionId)?.id && + projection.reasons.every(reason => reason === "unresolved")) return false; + } + return firstTaint() !== null; + }, contacted: (host: string) => contacted.has(host), // A refusal names what tainted the session, as the card does (#3431). cause: () => { const source = firstTaint()?.source; return source ? TAINT_SOURCE_WORDING[source] : null; }, @@ -194,7 +207,7 @@ export async function prepareTurnEgress(options: { if(writes?.recordingAvailable&&!writes.recordingAvailable(options.turnId,options.sessionId())){fail();throw new Error("Input recording unavailable before provider dispatch");} return; } - contacted.add(destination.host); + if (firstTaint() === null) normalBefore.add(destination.connectionId); if (!writes) return; const exposure = occurrence(collectionEpoch, "proxy_input", destination.connectionId, "open"); exposure.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; @@ -211,10 +224,12 @@ export async function prepareTurnEgress(options: { /** Settles once every record submitted so far has committed or failed; `recordingFailure()` is final after it. */ const settled = async () => { while (recording.size) await Promise.all([...recording]); }; const proxy = await startEgressProxy({ mode: options.policy.egress.mode, allow: options.policy.egress.allow, + ...(options.bridge.admissionSafety ? { admissionSafety: options.bridge.admissionSafety } : {}), deny: options.policy.egress.deny, maxBytes: options.policy.egress.max_bytes_per_turn ?? Number.MAX_SAFE_INTEGER, outwardHosts: [...new Set([...GITHUB_API_HOSTS, ...MAIL_SUBMISSION_HOSTS, ...options.policy.outward.hosts])], outwardPorts: MAIL_SUBMISSION_PORTS, - signal: options.controller.signal, observe: report, admitted, ...(taint ? { taint } : {}), + signal: options.controller.signal, observe: report, admitted, + committed: destination => { if (!destination.inference && !destination.provider) contacted.add(destination.host); }, ...(taint ? { taint } : {}), approveOutward: async (destination, signal) => { if (calls.covers(destination.host)) return !signal.aborted; const decision = await requestToolPermission(options.bridge, { toolUseId: crypto.randomUUID(), toolName: "Network", diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 254ac7ce58..3d37da396b 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -52,7 +52,7 @@ const KEPT_CHANGE = `NOT (path IN (SELECT value FROM json_each(?)) OR path GLOB const storageError = (error: unknown): Error => error instanceof JournalCapacityError || error instanceof JournalStorageUnavailable ? error : new JournalStorageUnavailable(error instanceof Error ? error.message : String(error)); type TurnRow = { turn_id: string; session_id: string | null; actor: "interactive" | "voice" | "user"; kind: "turn" | "revert"; source_turn_id: string | null; model: string | null; profile: "strict" | "governed"; policy_hash: string | null; started_at: number; ended_at: number | null; state: TurnJournalSummary["state"]; summary: string | null; missing: string; steering_inventory_missing: string; configuration_set: string | null; failure: string }; -type ChangeRow = { sequence: number; path: string; scope: string; before_json: string | null; after_json: string | null; class: "content" | "steering" | "policy"; actor: "agent" | "user"; taint_source_event_id: number | null; conflict_observations: string; overlaps: string }; +type ChangeRow = { sequence: number; path: string; scope: string; before_json: string | null; after_json: string | null; class: "content" | "steering" | "policy"; actor: "agent" | "user"; taint_source_event_id: number | null; effective_taint: number | null; conflict_observations: string; overlaps: string }; const statement = (sql: string, ...params: SQLQueryBindings[]): JournalStatement => ({ sql, params }); const version = (entry: JournalSnapshotEntry | undefined): JournalVersion | null => entry ? { kind: entry.kind, mode: entry.mode, bytes: entry.bytes, ignored: entry.ignored, @@ -737,7 +737,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const row = db.query("SELECT * FROM turn_journal_turns WHERE turn_id=? AND session_id=?").get(turnId, sessionId) as TurnRow | null; if (!row) return null; const changes = (db.query("SELECT * FROM turn_journal_changes WHERE turn_id=? ORDER BY sequence,path").all(turnId) as ChangeRow[]).map(item => ({ sequence: item.sequence, path: item.path, scope: item.scope, class: item.class, actor: item.actor, - before: presented(item.path, item.before_json), after: presented(item.path, item.after_json), overlappingTurnIds: JSON.parse(item.overlaps) as string[], ...(item.taint_source_event_id ? { tainted: true as const, taintSourceEventId: item.taint_source_event_id } : {}), + before: presented(item.path, item.before_json), after: presented(item.path, item.after_json), overlappingTurnIds: JSON.parse(item.overlaps) as string[], ...(item.effective_taint === 1 || item.taint_source_event_id ? { tainted: true as const } : {}), ...(item.taint_source_event_id ? { taintSourceEventId: item.taint_source_event_id } : {}), ...(JSON.parse(item.conflict_observations).length && !journalMetadataOnlyPath(item.path) ? { conflict: { versions: JSON.parse(item.conflict_observations) as JournalObservationReference[], latest: { turnId, sequence: (db.query("SELECT max(sequence) AS sequence FROM turn_journal_changes WHERE turn_id=? AND path=?").get(turnId,item.path) as {sequence:number}).sequence, side:"after" as const } } } : {}) })); const failure = failures.get(turnId) ?? row.failure.trim(); diff --git a/packages/ui-server/src/governance/effective-safety.ts b/packages/ui-server/src/governance/effective-safety.ts new file mode 100644 index 0000000000..afcb3014fc --- /dev/null +++ b/packages/ui-server/src/governance/effective-safety.ts @@ -0,0 +1,43 @@ +/** One live read for enforcement; ordinary governance remains turn-bound. */ +import type { AdmissionSafety } from "@schlessera/brain-ui-sdk/internal"; +import type { Database } from "bun:sqlite"; +import type { GovernanceWrites } from "./event-writes.js"; +import { safetyProjection } from "./safety-store.js"; +import { safetyQueue } from "./safety-queue.js"; + +/** Concrete input from the host's future trust publisher, not a policy loader or matcher. */ +export interface LiveTrustRevision { + revision(): string; + subscribe(changed: () => void): () => void; +} + +export function createEffectiveSafety(db: Database, options: { + turnId: string; sessionId: () => string | null; policyHash: string | null; + brain?: string; + writes?: Pick; + authority(): { current: boolean; epoch: string }; + trust?: LiveTrustRevision; + signal?: AbortSignal; +}): AdmissionSafety { + return { + read() { + const projection = options.writes?.safety(options.turnId, options.sessionId()) ?? safetyProjection(db, options.turnId, options.sessionId()); + const authority = options.authority(), trustRevision = options.trust?.revision() ?? "0"; + for (const revision of [trustRevision, authority.epoch]) { + if (!/^(0|[1-9][0-9]{0,19})$/.test(revision) || BigInt(revision) > 18446744073709551615n) throw new Error("Invalid live safety revision"); + } + return { evidenceRevision: projection.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)), + authorityCurrent: authority.current }; + }, + subscribe(changed) { + const listeners = safetyQueue(db).listeners; + listeners.add(changed); + const release = options.trust?.subscribe(changed); + options.signal?.addEventListener("abort", changed, { once: true }); + return () => { listeners.delete(changed); release?.(); options.signal?.removeEventListener("abort", changed); }; + }, + }; +} diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index c529229312..e61fffe5de 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -6,7 +6,7 @@ * writes. An event the journal records inside its own transaction stays * there (`brain/journal-store.ts`). */ -import { retainSafetyLoss, safetyQueue } from "./safety-queue.js"; +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, type SafetyCollectionInput, type SafetyProjection } from "./safety-store.js"; @@ -94,7 +94,7 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov const shared=safetyQueue(db),pendingTaints=shared.pending; const call:typeof invoke=(name:string,...args:unknown[])=>{ shared.inflight++; - return invoke(name,...args).finally(()=>{shared.inflight--;}); + return invoke(name,...args).finally(()=>{shared.inflight--;notifySafetyChanged(db);}); }; const safetyFail=(turnId:string|null):Promise=>{ if(!turnId||!db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(turnId))retainSafetyLoss(db,turnId); @@ -113,10 +113,11 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov } 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; }); + .finally(() => { pendingTaints.delete(pending); shared.bytes -= bytes; notifySafetyChanged(db); }); }; return { record, diff --git a/packages/ui-server/src/governance/events.ts b/packages/ui-server/src/governance/events.ts index 234e4bae9e..0e272da954 100644 --- a/packages/ui-server/src/governance/events.ts +++ b/packages/ui-server/src/governance/events.ts @@ -63,6 +63,14 @@ function kind(version: number, payload: T) { * docs/http-api.md ("Governance events"); keep the two in step. */ export const GOVERNANCE_EVENT_SCHEMAS = { + /** Durable withdrawal of a pending card, before its operation can retry. */ + safety_admission_expired: kind(1, z.strictObject({ + toolUseId: z.string().min(1).max(200), + evidenceRevision: z.string().regex(/^(0|[1-9][0-9]{0,19})$/), + trustRevision: z.string().regex(/^(0|[1-9][0-9]{0,19})$/), + authorityEpoch: z.string().regex(/^(0|[1-9][0-9]{0,19})$/), + reason: z.literal("safety_changed"), + })), /** Completed or refused connection, using the proxy's actual visibility. */ egress_connection: kind(1, z.strictObject({ connectionId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(), @@ -73,6 +81,7 @@ export const GOVERNANCE_EVENT_SCHEMAS = { inference: z.literal(true).optional(), provider: z.literal(true).optional(), reason: z.string().max(200).optional(), })), steering_change: kind(1, z.strictObject({ path, sequence: count, + tainted: z.literal(true).optional(), beforeHash: policyHash, afterHash: policyHash, taintSourceEventId: z.number().int().positive().nullable(), overlappingTurnIds: z.array(z.string().min(1).max(200)).max(1000) })), policy_change: kind(1, z.strictObject({ requestId: z.string().min(1).max(200), diff --git a/packages/ui-server/src/governance/safety-queue.ts b/packages/ui-server/src/governance/safety-queue.ts index c8c21f6ca3..8df0772e15 100644 --- a/packages/ui-server/src/governance/safety-queue.ts +++ b/packages/ui-server/src/governance/safety-queue.ts @@ -3,17 +3,24 @@ 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}>(); + lostTurns:Set;unscopedLoss:boolean;listeners:Set<()=>void>}>(); 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};queues.set(db,queue);} + if(!queue){queue={pending:new Set(),bytes:0,failed:false,inflight:0,lostTurns:new Set(),unscopedLoss:false,listeners:new Set()};queues.set(db,queue);} return queue; } +export function notifySafetyChanged(db:Database):void { + for(const listener of [...safetyQueue(db).listeners]) { + try { listener(); } catch { /* The synchronous dispatch read still fails closed. */ } + } +} + /** 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; else queue.lostTurns.add(turnId); + notifySafetyChanged(db); } diff --git a/packages/ui-server/src/ws/bridge-capabilities/permissions.ts b/packages/ui-server/src/ws/bridge-capabilities/permissions.ts index 879dc71c95..f78c6b63d1 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/permissions.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/permissions.ts @@ -1,6 +1,7 @@ import { PROPOSE_POLICY_CHANGE_TOOL_NAME, type PolicyChangeInput } from "@schlessera/brain-ui-sdk/tool-contracts"; import type { ApprovalChannel } from "@schlessera/brain-ui-sdk/protocol"; import type { BackendBridge, PermissionDecision } from "@schlessera/brain-ui-sdk/server"; +import { sameSafetyAdmission, STALE_SAFETY_ADMISSION } from "@schlessera/brain-ui-sdk/internal"; import { approvalRequestFrame, withTurnScope } from "../frames.js"; import type { BridgeContext, BridgeSlice } from "./context.js"; @@ -60,6 +61,7 @@ export function createPermissions(ctx: BridgeContext, self: () => BackendBridge) return Promise.resolve({ behavior: "allow" }); } return new Promise((resolve) => { + let unsubscribe: (() => void) | undefined; // The decision stamps the wait/execution boundary on the tool span // (grant) or lands the denied outcome (deny) before the backend's // own error tool_result can mislabel it — write-once protects it. @@ -67,6 +69,7 @@ export function createPermissions(ctx: BridgeContext, self: () => BackendBridge) decision: PermissionDecision, response?: { principalId: string; always?: boolean; channel?: ApprovalChannel } ) => { + unsubscribe?.(); unsubscribe = undefined; recorder?.onApprovalDecision( req.toolUseId, decision.behavior === "deny" @@ -92,6 +95,34 @@ export function createPermissions(ctx: BridgeContext, self: () => BackendBridge) resolve({ behavior: "deny", message: "Duplicate tool-approval id" }); return; } + const safety = self().admissionSafety, snapshot = req.admissionSnapshot; + const invalidate = () => { + let current = false; + try { current = !!safety && !!snapshot && sameSafetyAdmission(snapshot, safety.read()); } catch { /* Refuse unavailable state. */ } + if (current) return; + const claimed = coordinator.claimApproval(req.toolUseId, p => p.turn === turn && p.request === req); + if (!claimed) return; + unsubscribe?.(); unsubscribe = undefined; + const writes = host.activity?.governanceWrites; + // Claim first to fence a simultaneous answer, then retain the terminal + // fact before publishing it or settling the backend's pending wait. + const committed = writes && snapshot ? Promise.resolve().then(() => writes.record({ kind: "safety_admission_expired", turnId, + sessionId: turn.sessionId ?? null, actor: "server", model: null, profile: null, + payload: { toolUseId: req.toolUseId, evidenceRevision: snapshot.evidenceRevision, + trustRevision: snapshot.trustRevision, authorityEpoch: snapshot.authorityEpoch, reason: "safety_changed" } })) : Promise.resolve(); + void committed.then(() => { + coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId: turn.sessionId, reason: STALE_SAFETY_ADMISSION }); + claimed.resolve({ behavior: "deny", message: STALE_SAFETY_ADMISSION }); + }, error => { + turn.abortController.abort(error); + claimed.resolve({ behavior: "deny", message: "Safety withdrawal could not be retained; the turn was stopped." }); + }); + }; + if (safety && snapshot) { + unsubscribe = safety.subscribe(invalidate); + invalidate(); + if (!coordinator.pendingApprovals.has(req.toolUseId)) { unsubscribe?.(); unsubscribe = undefined; return; } + } if (!host.clients.hasClients()) { // Not a failure — the card is parked and re-delivered on reconnect // (see resendPendingInteractive) — but the wait was invisible before diff --git a/packages/ui-server/src/ws/bridge.ts b/packages/ui-server/src/ws/bridge.ts index 4c6aaafcdf..638a8e077e 100644 --- a/packages/ui-server/src/ws/bridge.ts +++ b/packages/ui-server/src/ws/bridge.ts @@ -13,6 +13,7 @@ import { createPolicyProposal } from "./bridge-capabilities/policy-proposal.js"; import { createApplication } from "./bridge-capabilities/application.js"; import { createScratch } from "./bridge-capabilities/scratch.js"; import { createAttachmentRead } from "./bridge-capabilities/attachments.js"; +import { createEffectiveSafety } from "../governance/effective-safety.js"; export { emitTurnError } from "./bridge-capabilities/turn-error.js"; @@ -73,6 +74,20 @@ export async function makeBridge(host: WsHost, turn: RunningTurn, options: MakeB Object.assign(bridge, createAttachmentRead(ctx, transcript)); guardMaskedRecords(ctx, bridge); if (ctx.backendId === "claude" || ctx.backendId === "pi") applyLiveAuthority(ctx, bridge); + if (host.activity?.governanceDb) { + let epoch = 0n, previous = ctx.current(); + bridge.admissionSafety = createEffectiveSafety(host.activity.governanceDb, { + brain: host.brainPath, turnId: ctx.turnId, sessionId: () => turn.sessionId ?? null, policyHash: options.governance?.policy.hash ?? null, + writes: host.activity.governanceWrites, trust: host.safetyTrust, signal: ctx.signal, + authority: () => { + // Journal/scope holds retain their existing wait semantics; they are + // not principal revocation and do not mint a new authority epoch. + const current = ctx.current(); + if (current !== previous) { epoch++; previous = current; } + return { current, epoch: String(epoch) }; + }, + }); + } return bridge; } diff --git a/packages/ui-server/src/ws/host.ts b/packages/ui-server/src/ws/host.ts index 1ad0c352f4..3bcc2a2541 100644 --- a/packages/ui-server/src/ws/host.ts +++ b/packages/ui-server/src/ws/host.ts @@ -17,6 +17,7 @@ import type { ActivityStream } from "../activity/stream.js"; import type { AwaitablePushSender } from "../activity/push-sender.js"; import type { RuntimeStatus } from "../activity/runtime-status.js"; import type { GovernanceEventInput } from "../governance/events.js"; +import { notifySafetyChanged } from "../governance/safety-queue.js"; import type { Principal } from "../db/principals.js"; import type { createInboxBridgeTools } from "../inbox/bridge-tools.js"; import type { InboxStream } from "../inbox/stream.js"; @@ -69,6 +70,8 @@ export { } from "./limits.js"; export interface WsHostOptions { + /** @internal Live trust publication input; no matching or publication authority. */ + safetyTrust?: import("../governance/effective-safety.js").LiveTrustRevision; /** @internal Concrete user history service mounted by this host, not agent authority. */ turnReverts?: import("../brain/turn-revert.js").TurnReverts; /** @internal The brain/git lock the host shares, when the app built a service that needs it first. */ @@ -233,6 +236,8 @@ export interface ToolPermissions { * modules (#1053; docs/decisions/public-export-boundary.md). */ export class WsHost { + /** @internal Live trust revision supplied by the concrete host publisher. */ + readonly safetyTrust?: import("../governance/effective-safety.js").LiveTrustRevision; /** @internal Concrete user history service mounted by this host, not agent authority. */ readonly turnReverts?: import("../brain/turn-revert.js").TurnReverts; /** Explicit local chat deletion (#3230); present when the host answers `POST /api/chat-deletions`. */ @@ -353,6 +358,7 @@ export class WsHost { private readonly historyReads = new Set<{ sessionId: string; changed: boolean; resultTurnId?: string }>(); constructor(options: WsHostOptions) { + this.safetyTrust = options.safetyTrust; this.turnReverts = options.turnReverts; this.workerLock = options.workerLock ?? createKeyedLock(); this.journal = options.journal; @@ -375,6 +381,7 @@ export class WsHost { this.askUserFormLimits = resolveAskUserFormLimits(options.askUserFormLimits); this.clients = new ClientSet(options.wsMaxConnections, (principalIds) => { this.coordinator.invalidateAuthorizations(principalIds); + if (this.activity?.governanceDb) notifySafetyChanged(this.activity.governanceDb); }); this.registry = options.registry; this.catalog = options.catalog; @@ -799,6 +806,7 @@ export class WsHost { const revoked = new Set(principalIds); if (revoked.size === 0) return; const affectedRunning = this.coordinator.revokePrincipals(revoked); + if (this.activity?.governanceDb) notifySafetyChanged(this.activity.governanceDb); const unbinding: Promise[] = []; for (const principalId of revoked) { this.clients.closeFor(principalId, code, reason); diff --git a/packages/ui-server/tests/governance-events.test.ts b/packages/ui-server/tests/governance-events.test.ts index 5456d58a60..7e5a9c21ae 100644 --- a/packages/ui-server/tests/governance-events.test.ts +++ b/packages/ui-server/tests/governance-events.test.ts @@ -27,6 +27,7 @@ const DAY = 24 * 60 * 60 * 1000; /** One valid v1 payload per kind, in the Odysseus world. */ const SAMPLE_PAYLOADS: { [K in GovernanceEventKind]: GovernanceEventPayload } = { + safety_admission_expired: { toolUseId: "ithaca-card", evidenceRevision: "1", trustRevision: "0", authorityEpoch: "0", reason: "safety_changed" }, taint_exposure: { occurrenceId: "ithaca-exposure", state: "interrupted_unknown" }, egress_connection: { host: "ithaca.invalid", port: 443, method: "CONNECT", bytes: 100, accounting: "opaque_bytes", durationMs: 5, outcome: "completed" }, policy_change: { requestId: "policy-ithaca", baseHash: null, proposedHash: "a".repeat(64), sections: ["profiles.interactive"], outcome: "updated" }, diff --git a/packages/ui-server/tests/live-safety-admission.test.ts b/packages/ui-server/tests/live-safety-admission.test.ts new file mode 100644 index 0000000000..907e943dbf --- /dev/null +++ b/packages/ui-server/tests/live-safety-admission.test.ts @@ -0,0 +1,383 @@ +/** Real FULL SQLite writers, loopback transport and backend permission bindings. */ +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { request } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resolveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import type { BackendActivityEvent, BackendBridge, PermissionRequest } from "@schlessera/brain-ui-sdk/server"; +import { createPermissionWiring } from "../../ui-backend-claude/src/permission-hooks"; +import { MUTATING_TOOL_MATCHER } from "../../ui-backend-claude/src/tool-policy"; +import { decidePiToolPermission } from "../../ui-backend-pi/src/permission-gate"; +import { createTurnContext } from "../../ui-backend-pi/src/turn-context"; +import { createBrainAccess } from "../../ui-backend-pi/src/brain-access"; +import { createBrainToolKit } from "../../ui-backend-pi/src/tool-kit"; +import { bashTool } from "../../ui-backend-pi/src/file-tools"; +import { createPiWorkerRpcDispatcher, type PiWorkerRpcContext } from "../../ui-backend-pi/src/worker-rpc"; +import { bashLockKey } from "@schlessera/brain-ui-sdk/server"; +import { createUiDb } from "../src/db/client"; +import { createPrincipal } from "../src/db/principals"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createGovernanceWrites } from "../src/governance/event-writes"; +import { createEffectiveSafety } from "../src/governance/effective-safety"; +import { createSafetyCollector } from "../src/governance/safety-collector"; +import { safetyCatalogCreated, safetyRecords } from "../src/governance/safety-store"; +import { occurrence } from "../src/governance/occurrence"; +import { queryGovernanceEvents } from "../src/governance/events"; +import { prepareTurnEgress } from "../src/brain/turn-egress"; +import * as probe from "./fixtures/write-worker-probe"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { createActivityStore } from "../src/activity/store"; +import { createActivityStream } from "../src/activity/stream"; +import { WsHost } from "../src/ws/host"; +import { runSession } from "../src/ws/run-session"; +import { createSessionCatalog } from "../src/ws/session-catalog"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import { testAuthorization } from "./helpers/principal"; +import { requestToolPermission } from "@schlessera/brain-ui-sdk/server"; +import { createNativeJournalFixture } from "./helpers/native-journal-fixture"; +import { createTurnJournal } from "../src/brain/turn-journal"; + +async function fixture() { + const root = mkdtempSync(join(tmpdir(), "odysseus-live-safety-")), db = createUiDb(join(root, "ui.db")); + const writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer), bindingId = crypto.randomUUID(); + const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: principal.id, backendId: "claude", at: 0 }); + db.query("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('ithaca',0,0,'claude')").run(); + db.query("INSERT INTO chat_session_owners VALUES('ithaca',?,0)").run(principal.id); + safetyCatalogCreated(db, "ithaca", principal.id, "voyage"); await writes.bind("voyage", "ithaca"); + const controller = new AbortController(); + const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, sessionId: () => "ithaca", backendId: "claude", + signal: controller.signal, shellProxied: () => true, brainPath: root }); + await collector.ready("claude", 1); + const state = () => writes.safety("voyage", "ithaca"); + const actor = { principalId: principal.id, channel: "owner_history" as const }; + const add = async (name: string, finalized = true) => { + await collector.begin(name, "WebFetch", { url: "https://ithaca.invalid/notice" }); + if (finalized) await collector.result(name, "WebFetch", "The harbour is open.", true); + return safetyRecords(db, "ithaca").filter(r => r.kind === "occurrence").at(-1)!.id; + }; + const review = async (id: string) => { + const projection = state(), body = { version: 1 as const, session: projection.session!, occurrenceId: id, + expectedEvidenceRevision: projection.evidenceRevision, verdict: "safe" as const }; + const prepared = await writes.safetyPrepareReview(body, actor); + return writes.safetyCommitReview(prepared.requestId!, body, actor); + }; + let trustRevision = "0", authorityCurrent = true, authorityEpoch = "0"; + const listeners = new Set<() => void>(); + const safety = createEffectiveSafety(db, { turnId: "voyage", sessionId: () => "ithaca", policyHash: null, writes, + authority: () => ({ current: authorityCurrent, epoch: authorityEpoch }), + trust: { revision: () => trustRevision, subscribe: changed => { listeners.add(changed); return () => { listeners.delete(changed); }; } } }); + const remove = () => { trustRevision = String(BigInt(trustRevision) + 1n); for (const listener of [...listeners]) listener(); }; + const revoke = () => { authorityCurrent = false; authorityEpoch = "1"; for (const listener of [...listeners]) listener(); }; + return { root, db, writer, writes, bindingId, principal, controller, collector, state, add, review, safety, remove, revoke, + async close() { await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } }; +} + +type Fixture = Awaited>; +const command = "git push https://github.com/odysseus/voyage.git main"; +const allow = [{ command: "^git push ", remotes: ["github.com/odysseus/*"], index: 0 }]; +type Binding = "claude-hook" | "claude-callback" | "pi"; +async function execute(f: Fixture, binding: Binding, options: { + phase?: "approval" | "input" | "index" | "lock"; interleave?: () => Promise; explicit?: boolean; +}) { + let interleaved = false; + const pause = async (phase: typeof options.phase) => { + if (options.phase === phase && !interleaved) { interleaved = true; await options.interleave?.(); } + }; + const requests: PermissionRequest[] = [], events: BackendActivityEvent[] = []; + const bridge: BackendBridge = { emit() {}, admissionSafety: f.safety, activity: e => { events.push(e); }, + async requestPermission(req) { requests.push(req); await pause("approval"); return { behavior: "allow" }; }, + async awaitIndex() { await pause("index"); }, + inputSafety: { ...f.collector, async begin(id, tool, input) { await f.collector.begin(id, tool, input); await pause("input"); } } }; + const policy = { hash: null, deny: [], confirm: options.phase === "approval" && binding === "claude-hook" && !options.explicit + ? [{ pattern: "^git push ", reason: "Review this command", index: 0 }] : [], outwardAllow: options.explicit ? [] : allow, + taint: () => f.writes.taint("voyage", "ithaca") }; + const id = crypto.randomUUID(), input = { command }; + let allowed = false; + if (binding === "pi") { + const decision = await decidePiToolPermission({ turn: { ...createTurnContext(), bridge, signal: f.controller.signal, commandPolicy: policy }, + allowedTools: new Set(options.phase === "approval" && !options.explicit ? [] : ["bash"]), confirmPatterns: [] }, "bash", input, id); + allowed = decision.behavior === "allow"; + } else { + const wiring = createPermissionWiring({ req: { prompt: "Return to Ithaca", bridge, signal: f.controller.signal, + workerSandbox: { brain: f.root, profile: "governed", commandPolicy: policy } as never }, allowedTools: ["Bash"], confirmPatterns: [], brainPath: f.root, + turnLock: { async acquireForTool() { await pause("lock"); return { ok: true }; }, releaseForTool() {} } as never, + childEnv: {}, log() {} }); + if (binding === "claude-callback") { + const result = await wiring.canUseTool!("Bash", input, { toolUseID: id, signal: f.controller.signal } as never); + allowed = result?.behavior === "allow"; + } else { + const hook = wiring.hooks!.PreToolUse!.find(group => group.matcher === MUTATING_TOOL_MATCHER)!.hooks[0]!; + const result = await hook({ hook_event_name: "PreToolUse", tool_name: "Bash", tool_input: input, tool_use_id: id } as never, id, { signal: f.controller.signal }); + allowed = !("hookSpecificOutput" in result && result.hookSpecificOutput?.hookEventName === "PreToolUse" && result.hookSpecificOutput.permissionDecision === "deny"); + } + } + // An actual process effect is the oracle; no external Git/network executes. + const bin = join(f.root, "bin"), marker = join(f.root, "executed"); mkdirSync(bin, { recursive: true }); + writeFileSync(join(bin, "git"), `#!/bin/sh\nprintf 'Ithaca\\n' >> '${marker}'\n`, { mode: 0o755 }); + const before = existsSync(marker) ? readFileSync(marker, "utf8") : ""; + if (allowed) { + const child = Bun.spawn(["/bin/sh", "-c", command], { cwd: f.root, env: { PATH: bin }, stdout: "pipe", stderr: "pipe" }); + expect(await child.exited, await new Response(child.stderr).text()).toBe(0); + } + return { allowed, requests, events, interleaved, executed: (existsSync(marker) ? readFileSync(marker, "utf8") : "") !== before }; +} + +for (const mode of ["in-process-lock", "rpc-lock", "rpc-final"] as const) for (const explicit of [false, true]) { + test(`Pi ${mode}: final post-permission admission preserves ${explicit ? "per-use approval" : "standing-rule restrictions"}`, async () => { + const f = await fixture(), bin = join(f.root, "bin"), marker = join(f.root, "effect"); mkdirSync(bin); + writeFileSync(join(bin, "git"), `#!/bin/sh\nprintf 'Ithaca\\n' >> '${marker}'\n`, { mode: 0o755 }); + const saved = Object.getOwnPropertyDescriptor(process.env, "PATH"); process.env.PATH = `${bin}:/usr/bin:/bin`; + const bridge: BackendBridge = { emit() {}, admissionSafety: f.safety, inputSafety: f.collector, requestPermission: async () => ({ behavior: "allow" }) }; + const turn = { ...createTurnContext(), bridge, signal: f.controller.signal, commandPolicy: { hash: null, deny: [], confirm: [], outwardAllow: explicit ? [] : allow } }; + const id = "post-permission", input = { command }; + let refused: unknown; + const interleave = () => f.add("post-gate-input"); + try { + if (mode === "in-process-lock") { + expect((await decidePiToolPermission({ turn, allowedTools: new Set(["bash"]), confirmPatterns: [] }, "bash", input, id)).behavior).toBe("allow"); + const tool = bashTool(createBrainToolKit({ brain: createBrainAccess(f.root), turn, exec: {}, lock: { async withKey(_key, body) { await interleave(); return body(); } } })); + try { await tool.execute(id, input, f.controller.signal, undefined, {} as never); } catch (error) { refused = error; } + } else { + const context = { brainPath: f.root, turn, live() {}, grants: new Map(), releases: new Map(), admitTool() {}, + autonomous: false, workerSandbox: undefined, allowedTools: new Set(["bash"]), confirmPatterns: [], + workerLock: { async acquire() { if (mode === "rpc-lock") await interleave(); return () => {}; } }, + executed: () => ({ name: "bash", lock: false, host: false, phases: new Set() }) } as unknown as PiWorkerRpcContext; + const dispatch = createPiWorkerRpcDispatcher(context); + const message = (n: number, method: "permission" | "lock" | "admission", value: Record) => ({ type: "rpc" as const, id: n, method, toolName: "bash", toolCallId: id, input: value }); + expect(await dispatch(message(1, "permission", input))).toEqual({ behavior: "allow" }); + try { + await dispatch(message(2, "lock", { key: bashLockKey(command) })); + if (mode === "rpc-final") await interleave(); + await dispatch(message(3, "admission", input)); + const child = Bun.spawn(["/bin/sh", "-c", command], { env: { PATH: `${bin}:/usr/bin:/bin` }, stdout: "pipe", stderr: "pipe" }); + expect(await child.exited, await new Response(child.stderr).text()).toBe(0); + await expect(dispatch(message(4, "admission", input)), "LIVE_PI_FINAL_TICKET_CANNOT_REPLAY").rejects.toThrow("no exact permission grant"); + } catch (error) { refused = error; } + for (const release of context.releases.values()) release(); + } + expect(existsSync(marker), "LIVE_PI_POST_GATE_WAITS_REVALIDATE_BEFORE_PROCESS_EFFECT").toBe(explicit); + if (explicit) expect(refused).toBeUndefined(); else expect(String(refused)).toContain("Safety or authority changed"); + } finally { + if (saved) Object.defineProperty(process.env, "PATH", saved); else delete process.env.PATH; + await f.close(); + } + }); +} + +for (const binding of ["claude-hook", "claude-callback", "pi"] as const) { + test(`${binding}: A/B/C individual verdicts change later admissions without rewriting prior facts`, async () => { + const f = await fixture(); try { + const [a, b, c] = [await f.add("A"), await f.add("B"), await f.add("C")]; + const original = JSON.stringify(queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["taint", "taint_exposure"], limit: 100 })); + await f.review(a); expect(f.state().unresolvedCount).toBe(2); + expect((await execute(f, binding, {})).requests.some(r => r.kind === "command"), "LIVE_A_VERDICT_CANNOT_CLEAR_B_OR_C_ADMISSION").toBe(true); + await f.review(b); expect(f.state().unresolvedCount).toBe(1); + expect((await execute(f, binding, {})).requests.some(r => r.kind === "command"), "LIVE_B_VERDICT_CANNOT_CLEAR_SAME_SOURCE_C_ADMISSION").toBe(true); + await f.review(c); expect(f.state().restriction).toBe("normal"); + const normal = await execute(f, binding, {}); + expect(normal.executed, "LIVE_SAFE_ZERO_RESTORES_LATER_POLICY_ALLOW").toBe(true); + expect(normal.requests.filter(r => r.kind === "command")).toEqual([]); + const open = await f.add("D", false); + expect((await f.review(open)).reason).toBe("not_finalized"); + const restricted = await execute(f, binding, {}); + expect(restricted.requests.some(r => r.kind === "command"), "LIVE_OPEN_INPUT_CANNOT_BORROW_SAFE_VERDICT").toBe(true); + expect(JSON.stringify(queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["taint", "taint_exposure"], limit: 100 })).startsWith(original.slice(0, -1)), "LIVE_RETAINED_OCCURRENCES_UNCHANGED").toBe(true); + } finally { await f.close(); } + }); + for (const phase of binding === "claude-hook" ? ["approval", "lock", "input", "index"] as const : binding === "pi" ? ["approval", "input", "index"] as const : ["approval", "lock", "input"] as const) { + test(`${binding}: a new trigger during ${phase} cannot dispatch under an earlier outward allowance`, async () => { + const f = await fixture(); try { + const result = await execute(f, binding, { phase, interleave: () => f.add("B") }); + expect(result.interleaved, "LIVE_TEST_REACHES_ASYNC_BOUNDARY").toBe(true); + expect(result.executed, "LIVE_FINAL_GATE_REJECTS_STALE_STANDING_ALLOW").toBe(false); + expect(f.state().unresolvedCount).toBe(1); + } finally { await f.close(); } + }); + } + for (const change of ["remove", "revoke"] as const) test(`${binding}: live ${change} during a per-use approval never dispatches`, async () => { + const f = await fixture(); try { + const result = await execute(f, binding, { explicit: true, phase: "approval", interleave: async () => { f[change](); } }); + expect(result.interleaved).toBe(true); + expect(result.executed, "LIVE_APPROVAL_WAITS_RECHECK_REVISION_AND_AUTHORITY").toBe(false); + } finally { await f.close(); } + }); + test(`${binding}: a completed explicit outward approval stays distinct from a removed standing rule`, async () => { + const f = await fixture(); try { + const result = await execute(f, binding, { explicit: true, phase: "input", interleave: async () => { f.remove(); } }); + expect(result.executed, "LIVE_COMPLETED_PER_USE_IS_NOT_STANDING_AUTHORITY").toBe(true); + expect(result.events.find(e => e.kind === "outward_action")).toMatchObject({ payload: { decision: "approved", rule: null } }); + } finally { await f.close(); } + }); + test(`${binding}: another facade's recorder loss during the last input wait fences dispatch`, async () => { + const f = await fixture(); try { + const result = await execute(f, binding, { explicit: true, phase: "input", interleave: () => createGovernanceWrites(f.db, f.writer).safetyFail("other-turn") }); + expect(result.interleaved).toBe(true); + expect(result.executed, "LIVE_BACKEND_RECHECKS_SHARED_RECORDER_HEALTH").toBe(false); + } finally { await f.close(); } + }); +} + +const get = (socketPath: string, target: string) => new Promise((resolve, reject) => { + const req = request({ socketPath, path: target }, res => { res.resume(); res.once("end", () => resolve(res.statusCode!)); res.once("error", reject); }); + req.once("error", reject); req.end(); +}); + +test("an independent connection cannot borrow another request's own-input authority; dispatched legacy grants still work", async () => { + const f = await fixture(); let reached = 0, admissions = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { reached++; return new Response("Ithaca"); } }); + const entered = Promise.withResolvers(), release = Promise.withResolvers(); + const asked = Promise.withResolvers<"asked">(), borrowed = Promise.withResolvers<"borrowed">(); + const proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), + bridge: { emit() {}, admissionSafety: f.safety, requestPermission: async () => { asked.resolve("asked"); return { behavior: "deny", message: "Odysseus declines" }; } }, controller: f.controller, + turnId: "voyage", sessionId: () => "ithaca", model: () => null, profile: "governed", origin: "interactive", governanceDb: f.db, + governanceWrites: { ...f.writes, async firstTaint(event) { + if (++admissions > 1) borrowed.resolve("borrowed"); + await f.writes.firstTaint(event); entered.resolve(); await release.promise; return true; + } }, record: event => f.writes.record(event) }); + let first: Promise | undefined, second: Promise | undefined; + try { + first = get(proxy.socketPath, origin.url.href); await entered.promise; + second = get(proxy.socketPath, origin.url.href); + expect(await Promise.race([asked.promise, borrowed.promise]), "LIVE_UNRELATED_CONNECTION_CANNOT_BORROW_OWN_INPUT_AUTHORITY").toBe("asked"); + expect(await second).toBe(403); expect(reached).toBe(0); + release.resolve(); expect(await first).toBe(200); + await proxy.settled(); + expect(await get(proxy.socketPath, origin.url.href), "LIVE_DISPATCHED_LEGACY_CONTACT_GRANT_REMAINS_AVAILABLE").toBe(200); + expect(reached).toBe(2); + expect(safetyRecords(f.db, "ithaca").filter(r => r.kind === "occurrence")).toHaveLength(2); + } finally { release.resolve(); proxy.stop(); await Promise.allSettled([first, second]); await proxy.settled(); origin.stop(true); await f.close(); } +}); + +for (const change of ["healthy", "new-input", "other-recorder-loss", "revoke"] as const) test(`loopback proxy final occurrence-write wait revalidates ${change}`, async () => { + const f = await fixture(); let reached = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { reached++; return new Response("Ithaca"); } }); + const entered = Promise.withResolvers(), release = Promise.withResolvers(); + const proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), + bridge: { emit() {}, admissionSafety: f.safety, requestPermission: async () => ({ behavior: "allow" }) }, controller: f.controller, + turnId: "voyage", sessionId: () => "ithaca", model: () => null, profile: "governed", origin: "interactive", governanceDb: f.db, + governanceWrites: { ...f.writes, async firstTaint(event) { await f.writes.firstTaint(event); entered.resolve(); await release.promise; return true; } }, + record: event => f.writes.record(event) }); + try { + const pending = get(proxy.socketPath, origin.url.href); await entered.promise; + if (change === "new-input") await f.add("B"); + if (change === "other-recorder-loss") await f.writes.safetyFail("unrelated-turn"); + if (change === "revoke") f.revoke(); + release.resolve(); + expect(await pending, "LIVE_PROXY_CHECKS_AFTER_OCCURRENCE_COMMIT_WAIT").toBe(change === "healthy" ? 200 : 403); + expect(reached, "LIVE_PROXY_NEVER_DISPATCHES_STALE_AUTHORITY").toBe(change === "healthy" ? 1 : 0); + } finally { release.resolve(); proxy.stop(); await proxy.settled(); origin.stop(true); await f.close(); } +}); + +test("FULL writer pending input restricts every facade before reservation commit, and queued safe verdict never loosens", async () => { + const f = await fixture(); try { + const a = await f.add("A"); + const projection = f.state(), body = { version: 1 as const, session: projection.session!, occurrenceId: a, + expectedEvidenceRevision: projection.evidenceRevision, verdict: "safe" as const }; + const actor = { principalId: f.principal.id, channel: "owner_history" as const }; + const prepared = await f.writes.safetyPrepareReview(body, actor); + expect(prepared.stage).toBe("prepared"); + const channel = f.writer.channel(probe, { table: "live_hold" }); await channel.ready; + expect(await channel.call("level")).toBe(2); + const entered = new Int32Array(new SharedArrayBuffer(4)), held = channel.call("slow", "Ithaca", 200, entered); + const waiting = Atomics.waitAsync(entered, 0, 0, 5000); if (waiting.async) await waiting.value; + expect(Atomics.load(entered, 0)).toBe(1); + const safe = f.writes.safetyCommitReview(prepared.requestId!, body, actor); + expect(f.safety.read().restricted, "LIVE_QUEUED_SAFE_VERDICT_REMAINS_RESTRICTIVE").toBe(true); + await held; expect((await safe).stage).toBe("verdict_committed"); + const enteredAgain = new Int32Array(new SharedArrayBuffer(4)), second = channel.call("slow", "Troy", 200, enteredAgain); + const next = Atomics.waitAsync(enteredAgain, 0, 0, 5000); if (next.async) await next.value; + const pending = f.writes.firstTaint({ kind: "taint", turnId: "voyage", sessionId: "ithaca", actor: "interactive", model: null, profile: null, + payload: { source: "web_fetch", tool: "WebFetch", detail: null, occurrence: occurrence(f.bindingId, "tool_web_input", "B", "finalized") } }); + expect(f.safety.read().recordingAvailable, "LIVE_PENDING_INPUT_FENCES_BEFORE_FULL_COMMIT").toBe(false); + expect(createGovernanceWrites(f.db, f.writer).taint("voyage", "ithaca")).not.toBeNull(); + await second; await pending; + expect(f.state().unresolvedCount).toBe(1); + } finally { await f.close(); } +}); + +for (const change of ["review", "new-input", "remove", "revoke"] as const) test(`real bridge withdraws a stale ${change} card only with a durable terminal receipt and never replays it`, async () => { + const f = await fixture(), trigger = await f.add("A"); + const raised = Promise.withResolvers(), completed = Promise.withResolvers(); + const decisions: string[] = [], frames: { type: string; outcome?: string }[] = []; + const backend = makeFakeBackend({ id: "claude", async startTurn(req) { + await req.bridge.inputSafety!.ready("claude", 1); + req.bridge.emit({ type: "session_info", sessionId: "ithaca", isNew: false }); + const result = await requestToolPermission(req.bridge, { toolUseId: "ithaca-card", toolName: "Network", kind: "command", input: { target: "troy.invalid:443" } }); + decisions.push(result.behavior); + // The wait cannot settle until its terminal receipt has committed. + expect(queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["safety_admission_expired"], limit: 100 }), "LIVE_WITHDRAWAL_COMMITS_BEFORE_BACKEND_SETTLES").toHaveLength(1); + req.bridge.emit({ type: "result", sessionId: "ithaca", isError: false, durationMs: 1, numTurns: 1 }); + completed.resolve(); + } }); + const store = createActivityStore(f.db); + let principalCurrent = true; + const host = new WsHost({ brainPath: f.root, registry: createStaticBackendRegistry([backend], "claude"), catalog: createSessionCatalog(() => f.db), + isPrincipalAuthorized: id => principalCurrent && id === f.principal.id, + safetyTrust: { revision: () => f.safety.read().trustRevision, subscribe: callback => f.safety.subscribe(callback) }, + activity: { store, stream: createActivityStream(store), governanceDb: f.db, governanceWrites: f.writes } }); + host.clients.add({ send(text) { const frame = JSON.parse(text); frames.push(frame); if (frame.type === "tool_approval_request") raised.resolve(); } }, f.principal.id); + try { + const run = runSession(host, { authorization: testAuthorization(f.principal.id), text: "Return to Ithaca", attachments: [], sessionId: "ithaca" }); + await Promise.race([raised.promise, run.then(() => { throw new Error(`Bridge ended before opening its card: ${JSON.stringify(frames)}`); })]); + if (change === "review") expect((await f.review(trigger)).stage).toBe("verdict_committed"); + if (change === "new-input") await f.add("B"); + if (change === "remove") f.remove(); + if (change === "revoke") { principalCurrent = false; await host.revokePrincipals([f.principal.id], 1008, "Revoked"); } + await Promise.race([completed.promise, run]); await run; + expect(frames.filter(frame => frame.type === "error"), JSON.stringify(frames)).toEqual([]); + expect(decisions, "LIVE_STALE_CARD_NEVER_AUTOMATICALLY_REPLAYS").toEqual(["deny"]); + expect(host.coordinator.claimApproval("ithaca-card"), "LIVE_LATE_CARD_REPLY_HAS_NO_AUTHORITY").toBeUndefined(); + expect(host.coordinator.resolvedApprovals.get("ithaca-card")).toMatchObject({ outcome: "expired" }); + expect(frames.filter(frame => frame.type === "tool_approval_request")).toHaveLength(1); + expect(f.db.query("SELECT payload FROM governance_events WHERE kind='safety_admission_expired'").all()).toHaveLength(1); + } finally { host.close(); await f.close(); } +}); + +test("only new journal steering attribution uses effective evidence; original facts remain identical", async () => { + const f = await fixture(), brain = join(f.root, "brain"); mkdirSync(brain); + writeFileSync(join(brain, "AGENTS.md"), "Original harbour instructions\n"); + const native = createNativeJournalFixture(brain, f.root); + const journal = createTurnJournal(f.db, { nativeManager: native.manager, brainPath: brain, dbPath: join(f.root, "ui.db"), objectsRoot: join(f.root, "objects") }); + const observe = async (id: string, text: string) => { + await journal.begin(id, { sessionId: "ithaca", actor: "interactive", model: null, profile: "governed", policyHash: null }, error => { throw error; }); + writeFileSync(join(brain, "AGENTS.md"), text); await journal.finish(id); + return journal.details("ithaca", id)!.changes.find(change => change.path === "AGENTS.md")!; + }; + try { + await journal.ready; + const a = await f.add("A"), first = await observe("journal-a", "The first harbour instructions\n"); + expect(first, "LIVE_JOURNAL_RECORDS_ORIGINAL_TAINT").toMatchObject({ tainted: true }); + const retained = JSON.stringify(journal.details("ithaca", "journal-a")); + await f.review(a); + expect(await observe("journal-b", "Reviewed harbour instructions\n"), "LIVE_NEW_JOURNAL_DOES_NOT_REUSE_RESOLVED_FIRST_SOURCE").not.toHaveProperty("tainted"); + const b = await f.add("B"); + const third = await observe("journal-c", "Another harbour instruction\n"); + expect(third).toMatchObject({ tainted: true }); + expect(third.taintSourceEventId, "LIVE_NEW_JOURNAL_NAMES_CURRENT_UNRESOLVED_SOURCE").not.toBe(first.taintSourceEventId); + await f.review(b); + await f.writes.safetyBegin({ turnId: "unknown-journal-epoch", bindingId: crypto.randomUUID(), sessionId: "ithaca", principalId: f.principal.id, backendId: "unknown", at: 0 }); + const unknown = await observe("journal-d", "Instructions from unknown retained context\n"); + expect(unknown, "LIVE_JOURNAL_RETAINS_UNKNOWN_RESTRICTION_WITHOUT_INVENTING_SOURCE").toHaveProperty("tainted", true); + expect(unknown).not.toHaveProperty("taintSourceEventId"); + expect(JSON.stringify(journal.details("ithaca", "journal-a")), "LIVE_HISTORICAL_JOURNAL_IS_BYTE_IDENTICAL").toBe(retained); + } finally { await journal.close(); await native.close(); await f.close(); } +}); + +test("zero reviewed triggers cannot clear unknown coverage or waive ordinary deny and byte controls", async () => { + const f = await fixture(); + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca") }); + try { + await f.review(await f.add("A")); + await f.writes.safetyBegin({ turnId: "unknown-epoch", bindingId: crypto.randomUUID(), sessionId: "ithaca", principalId: f.principal.id, backendId: "unknown", at: 0 }); + expect(f.state().unresolvedCount).toBe(0); expect(f.safety.read().restricted, "LIVE_ZERO_WITH_UNKNOWN_HISTORY_STAYS_RESTRICTED").toBe(true); + for (const egress of [{ mode: "record" as const, deny: ["127.0.0.1"] }, { mode: "allowlist" as const, allow: [] }, { mode: "record" as const, max_bytes_per_turn: 0 }]) { + const proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1, egress }), + bridge: { emit() {}, admissionSafety: f.safety, requestPermission: async () => ({ behavior: "allow" }) }, controller: new AbortController(), + turnId: "voyage", sessionId: () => "ithaca", model: () => null, profile: "governed", origin: "interactive", governanceDb: f.db, governanceWrites: f.writes, record: event => f.writes.record(event) }); + try { expect(await get(proxy.socketPath, origin.url.href), "LIVE_INDEPENDENT_EGRESS_CONTROLS_STILL_REFUSE").toBe(403); } + finally { proxy.stop(); await proxy.settled(); } + } + } finally { origin.stop(true); await f.close(); } +}); diff --git a/packages/ui-server/tests/provider-relay-taint.test.ts b/packages/ui-server/tests/provider-relay-taint.test.ts index 3d6132bc29..b2f7add97d 100644 --- a/packages/ui-server/tests/provider-relay-taint.test.ts +++ b/packages/ui-server/tests/provider-relay-taint.test.ts @@ -18,6 +18,7 @@ import {connectedSafetySession} from "./helpers/connected-safety"; import { createUiDb } from "../src/db/client.js"; import { queryGovernanceEvents, recordGovernanceEvent } from "../src/governance/events.js"; import { prepareTurnEgress } from "../src/brain/turn-egress.js"; +import { beginSafetyCollection, acknowledgeSafety } from "../src/governance/safety-store.js"; const HOST_KEY = "odysseus-host-gemini-key"; const RERANK = "/v1beta/models/gemini-2.5-flash:generateContent"; @@ -58,6 +59,8 @@ const bridge = { requestPermission: async () => ({ behavior: "deny", message: "O async function turn(db: Database, sessionId: string, turnId: string, policy: GovernancePolicyInput = { schema_version: 1 }, relayOptions: Partial = {}) { const controller = new AbortController(); + beginSafetyCollection(db, { turnId, bindingId: crypto.randomUUID(), sessionId, principalId: "odysseus", backendId: "claude", at: 0 }); + acknowledgeSafety(db, turnId, "claude", 1); const egress = await prepareTurnEgress({ controller, policy: resolveGovernancePolicy(policy), turnId, sessionId: () => sessionId, model: () => "claude-haiku-4-5", profile: "governed", origin: "interactive", bridge, record: event => recordGovernanceEvent(db, event), governanceDb: db }); diff --git a/packages/ui-server/tests/shell-taint-proxy.test.ts b/packages/ui-server/tests/shell-taint-proxy.test.ts index cc0fe967eb..fdef7ca63e 100644 --- a/packages/ui-server/tests/shell-taint-proxy.test.ts +++ b/packages/ui-server/tests/shell-taint-proxy.test.ts @@ -13,6 +13,7 @@ import { createActivityStore } from "../src/activity/store"; import { prepareTurnEgress } from "../src/brain/turn-egress"; import {connectedSafetySession} from "./helpers/connected-safety"; import { createUiDb } from "../src/db/client"; +import { beginSafetyCollection, acknowledgeSafety } from "../src/governance/safety-store"; import { queryGovernanceEvents, recordGovernanceEvent } from "../src/governance/events"; const BRAIN = "/srv/ithaca"; @@ -27,6 +28,10 @@ function fixture() { else db.query("INSERT INTO sessions (id,title,created_at,last_active_at) VALUES (?, 'Voyage', 1, 1)").run(sessionId); sessions.add(sessionId); } + if (connected) { + beginSafetyCollection(db, { turnId: `${sessionId}-turn`, bindingId: crypto.randomUUID(), sessionId, principalId: "odysseus", backendId: "claude", at: 0 }); + acknowledgeSafety(db, `${sessionId}-turn`, "claude", 1); + } const value = createTurnRecorder({ store, governanceDb: db, brainPath: BRAIN, governance: event => { recordGovernanceEvent(db, event); } }, { turnId: `${sessionId}-turn`, sessionId, profile: "governed" }); if (proxied) value.setEgressProxied(); diff --git a/packages/ui-server/tests/turn-egress.test.ts b/packages/ui-server/tests/turn-egress.test.ts index a9a9d08bdf..d05d44d5fb 100644 --- a/packages/ui-server/tests/turn-egress.test.ts +++ b/packages/ui-server/tests/turn-egress.test.ts @@ -295,7 +295,7 @@ test("a governed turn whose runtime sends only relayed inference stays untainted // A validated provider-relay request is a host relay's operation: it never taints (G6, #3246). expect(events("taint"), "PROVIDER_RELAY_NEVER_TAINTS").toEqual([]); // WebFetch's own target, reached first in a fresh turn of a clean session. - connectedSafetySession(db,"calypso","turn-calypso"); + connectedSafetySession(db,"calypso","turn-fetch"); const fresh = await prepareTurnEgress({ ...inputs(new AbortController()), turnId: "turn-fetch", sessionId: () => "calypso", record: event => recordGovernanceEvent(db, event), governanceDb: db }); try { diff --git a/packages/ui-server/tests/turn-journal.test.ts b/packages/ui-server/tests/turn-journal.test.ts index 8d0fe0e346..577d9fc44f 100644 --- a/packages/ui-server/tests/turn-journal.test.ts +++ b/packages/ui-server/tests/turn-journal.test.ts @@ -1,4 +1,5 @@ import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; +import { connectedSafetySession } from "./helpers/connected-safety.js"; import { Database } from "bun:sqlite"; import { createHash } from "node:crypto"; import { expect, test } from "bun:test"; @@ -456,7 +457,7 @@ test("actual journal classifies steering and local transitive configuration sepa test("steering retains only taint recorded before observation, including sticky session evidence and overlap", async () => { const f = fixture(); try { - f.db.query("INSERT INTO sessions (id,title,created_at,last_active_at) VALUES ('ithaca','Ithaca',0,0)").run(); + connectedSafetySession(f.db, "ithaca", "untainted"); writeFileSync(join(f.brain, "AGENTS.md"), "Original instructions\n"); await f.begin("untainted"); writeFileSync(join(f.brain, "AGENTS.md"), "First instructions\n"); await f.journal.finish("untainted"); const source = recordGovernanceEvent(f.db, { kind: "taint", sessionId: "ithaca", turnId: "prior-turn", actor: "interactive", model: null, profile: "governed", payload: { source: "web_fetch", tool: "WebFetch", detail: "Odysseus reads a harbour notice." } }); From 4d9150acfeccc6612c149508b5aecb6a6e999b4e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 03:03:52 +0000 Subject: [PATCH 2/8] CONTRACT: fix(safety): fence parallel hooks and retain approval lifecycle --- .changeset/live-effective-safety.md | 2 + api-report/ui-server.txt | 6 +- .../decisions/claude-2.1.287-compatibility.md | 2 +- docs/decisions/live-conversation.md | 2 +- docs/decisions/voice-permission.md | 16 +- docs/http-api.md | 2 +- docs/integration-contract/http.md | 11 +- docs/integration-contract/package-api.md | 10 +- .../live-conversation-investigation.md | 2 +- .../plans/async-collaboration-requirements.md | 2 +- .../ui-backend-claude/src/permission-hooks.ts | 42 +++- packages/ui-sdk/src/server/permission-gate.ts | 20 +- packages/ui-server/src/governance/events.ts | 2 +- .../src/ws/bridge-capabilities/permissions.ts | 75 ++++-- .../src/ws/handlers/tool-permission.ts | 13 +- packages/ui-server/src/ws/turns.ts | 46 +++- .../tests/live-safety-admission.test.ts | 236 ++++++++++++++++++ 17 files changed, 429 insertions(+), 60 deletions(-) diff --git a/.changeset/live-effective-safety.md b/.changeset/live-effective-safety.md index 9ca6e7bc94..e308197dbe 100644 --- a/.changeset/live-effective-safety.md +++ b/.changeset/live-effective-safety.md @@ -6,3 +6,5 @@ --- Breaking before 1.0: revalidate effective safety at dispatch after waits, restore later policy allowances only after complete individual review, and attribute new journal changes to current evidence while preserving historical facts. + +Fence parallel Claude hook waits and direct host approvals, and retain claimed-card ownership through grant persistence with explicit terminal receipts. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 1c304c2f47..1d59be16b5 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -969,7 +969,11 @@ signatures (every public export and the types it is made of) payload: z.ZodObject<{ authorityEpoch: z.ZodString; evidenceRevision: z.ZodString; - reason: z.ZodLiteral<"safety_changed">; + reason: z.ZodEnum<{ + grant_storage_failed: "grant_storage_failed"; + safety_changed: "safety_changed"; + turn_ended: "turn_ended"; + }>; toolUseId: z.ZodString; trustRevision: z.ZodString; }, z.core.$strict>; diff --git a/docs/decisions/claude-2.1.287-compatibility.md b/docs/decisions/claude-2.1.287-compatibility.md index 01575fddaa..c1a650722f 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:687-690`). +(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:715-718`). `scripts/measure-claude-enforcement.ts` runs `createClaudeBackend().startTurn()` and forwards to the SDK resolved from that backend. Its query wrapper only diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index 4c670833e4..4cdebecd99 100644 --- a/docs/decisions/live-conversation.md +++ b/docs/decisions/live-conversation.md @@ -92,7 +92,7 @@ posture. A speech provider cannot reinterpret a visual grant, widen an allowlist, or settle an approval because it generated an answer. The host resolves pending exchanges when a turn ends -(`drainPendingForTurn`, `packages/ui-server/src/ws/turns.ts:1030-1053`). The +(`drainPendingForTurn`, `packages/ui-server/src/ws/turns.ts:1064-1085`). The conversation integration must also reconcile client cards and audible claims; that server method is not proof of a client receipt. Completion requires host terminal state plus local playback drained or discarded. Provider generation diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 21eb13941e..ea49bfb9e5 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -426,7 +426,7 @@ exchange over a security decision is a second chance for noise to produce a grant. **"Always allow" cannot be given by voice.** It is a persistent policy change -(the block computing `remembers`, `packages/ui-server/src/ws/handlers/tool-permission.ts:86-92`) +(the block computing `remembers`, `packages/ui-server/src/ws/handlers/tool-permission.ts:87-93`) and it is the one decision on the card with no keyboard shortcut, by D37's ruling 5, and the reason given there is exactly the one that applies here: *"a letter that grants standing @@ -435,8 +435,8 @@ permission by reflex is the one footgun in the vocabulary"* A microphone is a reflex surface with worse recognition than a keyboard. This costs nothing measurable: the server already refuses `always` for kind `command` requests -(the block computing `remembers`, `tool-permission.ts:86-92`, and the lookup computing -`remembered`, `ws/bridge-capabilities/permissions.ts:29-49`), and 192 of 192 measured +(the block computing `remembers`, `tool-permission.ts:87-93`, and the lookup computing +`remembered`, `ws/bridge-capabilities/permissions.ts:54-74`), and 192 of 192 measured approvals were kind `command`. ### When the announcement actually fires @@ -493,7 +493,7 @@ the request kind, and it patches the span (`onApprovalDecision`, `packages/ui-server/src/activity/recorder.ts:715-730`), fed from the bridge's `recorded()` wrapper -(`const recorded`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:68-84`). +(`const recorded`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:96-112`). One thing is missing and is a follow-up: **the event does not record the modality.** A denial decided by a phrase a microphone heard and one decided by a @@ -505,7 +505,7 @@ provenance. The wire needs nothing new: a spoken refusal is an ordinary `tool_denial` (its handler `handleToolDenial`, -`packages/ui-server/src/ws/handlers/tool-permission.ts:128-141`) with a message naming the +`packages/ui-server/src/ws/handlers/tool-permission.ts:137-150`) with a message naming the phrase that produced it. ## Containment: shared with #51, deliberately not identical @@ -628,7 +628,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. without granting (`RewriteHookOptions`, `packages/ui-backend-claude/src/input-rewrite-hooks.ts:17-31`; `!mayGrant`, `:70-78`; wired at their `agentHook`/`rtkHook` constructions, - `const agentHook`, `permission-hooks.ts:632-653`). + `const agentHook`, `permission-hooks.ts:638-659`). The premise the old grant rested on was measured false in the process: `permissionDecision: "allow"` was never what made `updatedInput` take effect, so the grant was a side effect and it is the @@ -638,9 +638,9 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. purpose, so a grant that exists and is deliberately not applied can be logged — but refuses to answer from it or add to it for a tool the enforced allowlist left out (the lookup computing `remembered`, - `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:29-49`, + `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:54-74`, and the block computing `remembers`, - `packages/ui-server/src/ws/handlers/tool-permission.ts:86-92`). + `packages/ui-server/src/ws/handlers/tool-permission.ts:87-93`). The evaluation happens before the lookup, which is what this record asked for. diff --git a/docs/http-api.md b/docs/http-api.md index 3a61cec7c1..bbee2b3d91 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -1449,7 +1449,7 @@ read by any authenticated principal. | Kind | Version | Fields | Meaning | | --- | --- | --- | --- | -| `safety_admission_expired` | 1 | `toolUseId`, `evidenceRevision`, `trustRevision`, `authorityEpoch`, `reason` | A pending safety-bound approval was withdrawn before dispatch. The server commits this terminal fact before settling the backend wait or publishing the coordinator's `expired` result. Revisions describe the card's original host snapshot; `reason` is `safety_changed`. This grants no replay and changes no historical approval. | +| `safety_admission_expired` | 1 | `toolUseId`, `evidenceRevision`, `trustRevision`, `authorityEpoch`, `reason` | A waiting or claimed safety-bound approval was withdrawn before dispatch. The server commits this terminal fact before settling the backend wait or publishing the coordinator's `expired` result. Revisions describe the card's original host snapshot; `reason` is `safety_changed`, `turn_ended` or `grant_storage_failed`. Storage failure stops the turn with an explicit failed terminal outcome, without claiming durable withdrawal. This grants no replay and changes no historical approval. | | `egress_connection` | 1 | `connectionId` (optional), `host`, `port`, `method`, `path` (optional), `bytes`, `accounting`, `durationMs`, `outcome`, `inference` (optional), `provider` (optional, #3246), `reason` (optional) | A completed, denied, failed or cancelled proxy connection. HTTP has a path and conservative wire accounting; opaque CONNECT has no path or plaintext claim. Only the concrete inference relay sets `inference: true`, and only a validated provider-relay operation sets `provider: true`; a record never carries both. Neither relay's record makes its host a contacted one for a tainted session's worker traffic. Headers, query strings and content are absent. | | `steering_change` | 1 | `path`, `sequence`, `beforeHash`, `afterHash`, `taintSourceEventId`, `overlappingTurnIds`, `tainted` (optional) | One observed steering change, attributed to its turn. Hashes identify retained regular-file versions or are `null`; the source is the current unresolved taint event or `null`. New observations may carry `tainted: true` for effective restriction, including unknown coverage without an attributable source. Historical rows retain their original attribution. Shared windows remain shared, not exclusive writer claims. | | `policy_change` | 1 | `requestId`, `baseHash`, `proposedHash`, `sections`, `outcome` | Explicit user-approved policy publication. Actor is `user`; outcome is `updated`; hashes identify the exact reviewed and written bytes. | diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 29466abaf2..3b050f9693 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -396,8 +396,15 @@ An earlier standing allowance is recomputed at dispatch; a stale pending card is claimed/withdrawn through the coordinator, with a durable `safety_admission_expired` governance event before the backend wait settles. Its existing tool-resolution outcome is `expired`. No denied or interrupted -operation replays automatically. Receipt-storage failure stops the turn rather -than reporting successful withdrawal. Ordinary budgets, commands, profiles, +operation replays automatically. Direct host permission callers have the same +host-owned snapshot and withdrawal behavior. An answer claimed by a handler +stays under coordinator ownership while its legacy grant write waits; safety +invalidation, cancellation and grant-write failure settle it exactly once and +cannot dispatch a stale grant. Terminal event reasons are `safety_changed`, +`turn_ended` and `grant_storage_failed`. A successfully persisted legacy grant +remains its independent historical fact and cannot revive the expired call. +Receipt-storage failure stops the turn and emits an explicit failed terminal +outcome, without claiming durable withdrawal. Ordinary budgets, commands, profiles, egress configuration, credential routing and outward/voice controls keep their existing independent, turn-bound meanings. No persistent source matching, Settings publication, scoped-network capability or owner review route is enabled diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 0da44faefc..7da87973cb 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4869,8 +4869,14 @@ scope, frozen ordinary `policyHash`, effective restriction, recorder health and current authority. `PermissionRequest.admissionSnapshot` is host-only metadata; it is never a wire field, worker initialization input or provider content. The shared `requestToolPermission` snapshots and rechecks the live input after -approval waits. First-party backend gates additionally revalidate in their -final dispatch continuations after locks, index barriers and occurrence writes. +approval waits. The host's `requestPermission` boundary also owns its initial +snapshot and final revalidation for direct application, policy, compute and +actor callers; caller metadata cannot opt out. Claimed answers remain under +coordinator ownership through grant storage and may expire during that wait. +First-party backend gates additionally revalidate in their final dispatch +continuations after locks, index barriers and occurrence writes. Every Claude +pre-tool hook fences its own final asynchronous wait, including parallel +rewrites and native file observations. Absent input retains the existing taint callback fallback and grants no new capability. The live trust input is revision/notification only; matching and publication have separate implementations. See the [effective admission diff --git a/docs/investigations/live-conversation-investigation.md b/docs/investigations/live-conversation-investigation.md index 2151177da5..91423df40e 100644 --- a/docs/investigations/live-conversation-investigation.md +++ b/docs/investigations/live-conversation-investigation.md @@ -302,7 +302,7 @@ Never add a spoken approve or always-allow path. On the evidence date the denial handler removed/resolved a matched request but provided no dedicated denial receipt at that branch; #957 added one -(`handleToolDenial`, `packages/ui-server/src/ws/handlers/tool-permission.ts:128-141`). The +(`handleToolDenial`, `packages/ui-server/src/ws/handlers/tool-permission.ts:137-150`). The integration therefore needs host-authoritative resolution/replay: denied, already granted, expired, or unknown/disconnected. Speak a denial confirmation only for a confirmed denied outcome. A visual grant winning the race remains diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 6afe81e90b..1e31a9d3cf 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -263,7 +263,7 @@ Stated before the requirements because five of them derive from it. threshold (~20s of the 30s lock budget). Below it nothing yields; above it the holder checkpoints/unwinds/releases. Test both edges and independent paths. - R26. **Abort-and-redo needs a checkpoint primitive.** `requestPermission` parks a bare - promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:63-153`) — while blocked on it the model cannot write anything, so + promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:91-186`) — while blocked on it the model cannot write anything, so "writes its findings, then aborts" has nowhere to run. The autonomous bridge must, in one server-side step: capture the checkpoint, create the Action and block the item, unwind without a live approval promise, preserving the tested timeout path's abort-then-drain order (`abortController.abort();`, `packages/ui-server/src/ws/session-run/admission.ts:55-57`). Aborting does **not** undo completed tool side diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts index e269b873ec..792397c9d5 100644 --- a/packages/ui-backend-claude/src/permission-hooks.ts +++ b/packages/ui-backend-claude/src/permission-hooks.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import { relative, resolve } from "node:path"; import { createWorkerFileObserver, NativeFileVersions, WORKER_AREA_ROOT, type ObservedWorkerFile } from "@schlessera/brain-ui-sdk/internal"; import type { HookCallback, Options, PermissionResult } from "@anthropic-ai/claude-agent-sdk"; -import { type CompiledWorkerCommandPolicy, compileWorkerCommandPolicy, denyWorkerCommand, requestPolicyPermission, prepareOutwardPlan, commitOutwardPlan, safetyAdmissionRefusal, observeOutwardPlan, OUTWARD_VOICE_REFUSAL } from "@schlessera/brain-ui-sdk/internal"; +import { type AdmissionSafetySnapshot, type CompiledWorkerCommandPolicy, compileWorkerCommandPolicy, denyWorkerCommand, requestPolicyPermission, prepareOutwardPlan, commitOutwardPlan, safetyAdmissionRefusal, observeOutwardPlan, OUTWARD_VOICE_REFUSAL } from "@schlessera/brain-ui-sdk/internal"; import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; import { checkEditedApproval, @@ -608,6 +608,7 @@ function createRewriteHooks(ctx: PermissionContext, options: PermissionWiringOpt // contain the foreground/RTK rewrite, so restrict that final form too: a // rewrite's auto-allow must not re-admit an already completed effect. const restrictRewrite = (hook: HookCallback, toolName: string): HookCallback => async (...args) => { + const snapshot = req.bridge.admissionSafety?.read(); const output = await hook(...args); const admissionRefusal = safetyAdmissionRefusal(req.bridge.admissionSafety); if (admissionRefusal) return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: admissionRefusal } }; @@ -626,6 +627,11 @@ function createRewriteHooks(ctx: PermissionContext, options: PermissionWiringOpt if (refusal) return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: refusal } }; try{await req.bridge.inputSafety?.begin(args[0].tool_use_id,toolName,output.hookSpecificOutput.updatedInput as Record);} catch(error){return {continue:true,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:error instanceof Error?error.message:"Safety recording unavailable"}};} + // Recording the rewritten input is another wait. Recompute its standing + // authority afterwards; parallel hooks only checked the original input. + const finalPlan = outward(toolName, output.hookSpecificOutput.updatedInput); + const finalRefusal = commitOutwardPlan(finalPlan, { bridge: req.bridge, before: snapshot, approved: false, signal: req.signal }); + if (finalRefusal) return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: finalRefusal } }; } return output; }; @@ -663,6 +669,28 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick HookCallback = hook => async (...args) => { + let snapshot: AdmissionSafetySnapshot | undefined; + let output: Awaited>; + try { + snapshot = req.bridge.admissionSafety?.read(); + output = await hook(...args); + } catch (error) { + if (args[0].hook_event_name === "PreToolUse") turnLock.releaseForTool(args[0].tool_use_id); + return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", + permissionDecisionReason: error instanceof Error ? error.message : "Host tool admission is unavailable." } }; + } + const refusal = safetyAdmissionRefusal(req.bridge.admissionSafety, snapshot) + ?? (req.signal.aborted || args[2].signal.aborted ? "Turn cancelled before tool admission." : null); + if (refusal) { + if (args[0].hook_event_name === "PreToolUse") turnLock.releaseForTool(args[0].tool_use_id); + return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: refusal } }; + } + return output; + }; const safetyResult: HookCallback = async input => { 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; @@ -684,12 +712,12 @@ export function createPermissionWiring(options: PermissionWiringOptions): Pick { - if (bridge.admissionSafety && guarded.admissionSnapshot && !sameSafetyAdmission(guarded.admissionSnapshot, bridge.admissionSafety.read())) - return { behavior: "deny", message: STALE_SAFETY_ADMISSION }; + try { + if (bridge.admissionSafety && guarded.admissionSnapshot) { + const current = bridge.admissionSafety.read(); + if (safetySnapshotRefusal(current) || !sameSafetyAdmission(guarded.admissionSnapshot, current)) + return { behavior: "deny", message: STALE_SAFETY_ADMISSION }; + } + } catch { return { behavior: "deny", message: STALE_SAFETY_ADMISSION }; } return snapshotEdit(request, decision); }); } diff --git a/packages/ui-server/src/governance/events.ts b/packages/ui-server/src/governance/events.ts index 0e272da954..e573243ac1 100644 --- a/packages/ui-server/src/governance/events.ts +++ b/packages/ui-server/src/governance/events.ts @@ -69,7 +69,7 @@ export const GOVERNANCE_EVENT_SCHEMAS = { evidenceRevision: z.string().regex(/^(0|[1-9][0-9]{0,19})$/), trustRevision: z.string().regex(/^(0|[1-9][0-9]{0,19})$/), authorityEpoch: z.string().regex(/^(0|[1-9][0-9]{0,19})$/), - reason: z.literal("safety_changed"), + reason: z.enum(["safety_changed", "turn_ended", "grant_storage_failed"]), })), /** Completed or refused connection, using the proxy's actual visibility. */ egress_connection: kind(1, z.strictObject({ diff --git a/packages/ui-server/src/ws/bridge-capabilities/permissions.ts b/packages/ui-server/src/ws/bridge-capabilities/permissions.ts index f78c6b63d1..1422f4b38d 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/permissions.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/permissions.ts @@ -1,7 +1,7 @@ import { PROPOSE_POLICY_CHANGE_TOOL_NAME, type PolicyChangeInput } from "@schlessera/brain-ui-sdk/tool-contracts"; import type { ApprovalChannel } from "@schlessera/brain-ui-sdk/protocol"; import type { BackendBridge, PermissionDecision } from "@schlessera/brain-ui-sdk/server"; -import { sameSafetyAdmission, STALE_SAFETY_ADMISSION } from "@schlessera/brain-ui-sdk/internal"; +import { sameSafetyAdmission, safetyAdmissionRefusal, STALE_SAFETY_ADMISSION, type AdmissionSafetySnapshot } from "@schlessera/brain-ui-sdk/internal"; import { approvalRequestFrame, withTurnScope } from "../frames.js"; import type { BridgeContext, BridgeSlice } from "./context.js"; @@ -16,6 +16,31 @@ export function createPermissions(ctx: BridgeContext, self: () => BackendBridge) const { coordinator } = host; return { requestPermission: (req) => { + // Retain the coordinator's original terminal reason for a late request; + // cancellation must not replace it with a new safety diagnosis. + const drained = coordinator.drainedReason(turn, turnId); + if (drained !== undefined) { + coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId: turn.sessionId, reason: drained }); + recorder?.onApprovalDecision(req.toolUseId, "deny", req.kind ?? "tool"); + return Promise.resolve({ behavior: "deny", message: drained }); + } + // This is the common boundary for SDK tools AND host-internal callers + // (applications, policy publication, compute and actors). Caller metadata + // cannot opt a card out of withdrawal or supply its authority. + const safety = self().admissionSafety; + let snapshot: AdmissionSafetySnapshot | undefined; + try { snapshot = safety?.read(); } + catch { return Promise.resolve({ behavior: "deny", message: STALE_SAFETY_ADMISSION }); } + const revalidate = (): string | null => { + if (ctx.signal.aborted || (safety || ctx.backendId === "claude" || ctx.backendId === "pi") && !ctx.current()) return STALE_SAFETY_ADMISSION; + try { + if (safetyAdmissionRefusal(safety, snapshot) || safety && snapshot && !sameSafetyAdmission(snapshot, safety.read())) return STALE_SAFETY_ADMISSION; + } catch { return STALE_SAFETY_ADMISSION; } + return null; + }; + if (revalidate() || safety && snapshot && req.admissionSnapshot && !sameSafetyAdmission(req.admissionSnapshot, snapshot)) + return Promise.resolve({ behavior: "deny", message: STALE_SAFETY_ADMISSION }); + if (snapshot) req = { ...req, admissionSnapshot: snapshot }; // A native permission checkpoint delegates this particular operation to // the host validator. Invalid input never raises a generic approval card. // Its handler later reads the SAME request receipt, without another write. @@ -23,7 +48,7 @@ export function createPermissions(ctx: BridgeContext, self: () => BackendBridge) const bridge = self(); if (!bridge.proposePolicyChange) return Promise.resolve({ behavior: "deny", message: "Policy proposals are unavailable in this turn." }); return bridge.proposePolicyChange(req.toolUseId, req.input as PolicyChangeInput) - .then(review => review.state === "updated" ? { behavior: "allow" as const } : { behavior: "deny" as const, message: review.message }, + .then(review => review.state === "updated" && !revalidate() ? { behavior: "allow" as const } : { behavior: "deny" as const, message: revalidate() ?? review.message }, error => ({ behavior: "deny" as const, message: error instanceof Error ? error.message : "Invalid policy proposal." })); } // A remembered "always allow" answers grantable tool requests without @@ -58,7 +83,10 @@ export function createPermissions(ctx: BridgeContext, self: () => BackendBridge) }); } if (remembered && !req.outsideEnforcedAllowlist) { - return Promise.resolve({ behavior: "allow" }); + return Promise.resolve().then(() => { + const refusal = revalidate(); + return refusal ? { behavior: "deny", message: refusal } : { behavior: "allow" }; + }); } return new Promise((resolve) => { let unsubscribe: (() => void) | undefined; @@ -91,33 +119,38 @@ export function createPermissions(ctx: BridgeContext, self: () => BackendBridge) recorded({ behavior: "deny", message: drained }); return; } - if (!coordinator.openApproval(req.toolUseId, { turn, turnId, request: req, resolve: recorded })) { - resolve({ behavior: "deny", message: "Duplicate tool-approval id" }); - return; - } - const safety = self().admissionSafety, snapshot = req.admissionSnapshot; - const invalidate = () => { - let current = false; - try { current = !!safety && !!snapshot && sameSafetyAdmission(snapshot, safety.read()); } catch { /* Refuse unavailable state. */ } - if (current) return; - const claimed = coordinator.claimApproval(req.toolUseId, p => p.turn === turn && p.request === req); - if (!claimed) return; + const expire = (reason: string, cause: "safety_changed" | "turn_ended" | "grant_storage_failed") => { unsubscribe?.(); unsubscribe = undefined; const writes = host.activity?.governanceWrites; - // Claim first to fence a simultaneous answer, then retain the terminal - // fact before publishing it or settling the backend's pending wait. + const sessionId = turn.sessionId; + // Coordinator ownership has already been removed from both waiting + // and in-flight answers. Retain exactly one terminal fact before + // publishing the outcome or settling the backend wait. const committed = writes && snapshot ? Promise.resolve().then(() => writes.record({ kind: "safety_admission_expired", turnId, - sessionId: turn.sessionId ?? null, actor: "server", model: null, profile: null, + sessionId: sessionId ?? null, actor: "server", model: null, profile: null, payload: { toolUseId: req.toolUseId, evidenceRevision: snapshot.evidenceRevision, - trustRevision: snapshot.trustRevision, authorityEpoch: snapshot.authorityEpoch, reason: "safety_changed" } })) : Promise.resolve(); + trustRevision: snapshot.trustRevision, authorityEpoch: snapshot.authorityEpoch, reason: cause } })) + : snapshot ? Promise.reject(new Error("Safety withdrawal storage is unavailable")) : Promise.resolve(); void committed.then(() => { - coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId: turn.sessionId, reason: STALE_SAFETY_ADMISSION }); - claimed.resolve({ behavior: "deny", message: STALE_SAFETY_ADMISSION }); + coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId, reason }); + recorded({ behavior: "deny", message: reason }); }, error => { + // No successful durable-withdrawal claim on storage failure, but + // cleanup and the backend still receive one explicit terminal. + const failed = "Safety withdrawal could not be retained; the turn was stopped."; + coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId, reason: failed }); + recorded({ behavior: "deny", message: failed }); turn.abortController.abort(error); - claimed.resolve({ behavior: "deny", message: "Safety withdrawal could not be retained; the turn was stopped." }); }); }; + if (!coordinator.openApproval(req.toolUseId, { turn, turnId, request: req, resolve: recorded, revalidate, ...(snapshot ? { expire } : {}) })) { + resolve({ behavior: "deny", message: "Duplicate tool-approval id" }); + return; + } + const invalidate = () => { + if (!revalidate()) return; + coordinator.expireApproval(req.toolUseId, STALE_SAFETY_ADMISSION, "safety_changed", p => p.turn === turn && p.request === req); + }; if (safety && snapshot) { unsubscribe = safety.subscribe(invalidate); invalidate(); diff --git a/packages/ui-server/src/ws/handlers/tool-permission.ts b/packages/ui-server/src/ws/handlers/tool-permission.ts index dbe9bf3061..456091de66 100644 --- a/packages/ui-server/src/ws/handlers/tool-permission.ts +++ b/packages/ui-server/src/ws/handlers/tool-permission.ts @@ -67,7 +67,8 @@ export const handleToolApproval: ClientMessageHandler<"tool_approval"> = async ( ); return; } - coordinator.claimApproval(msg.toolUseId); + const claimed = coordinator.claimApproval(msg.toolUseId, p => p === pending); + if (!claimed) return; // Remember-on-approve. Kind "command" never persists (the client // hides the option, but the wire is not trusted to enforce policy). // Neither does an approval given under an enforced allowlist that @@ -89,7 +90,15 @@ export const handleToolApproval: ClientMessageHandler<"tool_approval"> = async ( !pending.request.outsideEnforcedAllowlist; const actorAlways = pending.request.kind === "actor" && !pending.request.outsideEnforcedAllowlist && msg.always === true; if (msg.always && remembers) { - await store.add(pending.request.toolName); + try { await store.add(pending.request.toolName); } + catch (error) { + host.log.emit({ severityText: "ERROR", body: "tool grant storage failed", + attributes: { "tool.name": pending.request.toolName, "toolUse.id": msg.toolUseId, + error: error instanceof Error ? error.message : String(error) } }); + coordinator.expireApproval(msg.toolUseId, "The tool grant could not be retained. Nothing ran; request a fresh decision.", + "grant_storage_failed", p => p === claimed); + return; + } } else if (msg.always && !actorAlways) { // The user asked for something the host will not do. Recorded for // the same reason the bridge records a grant it declines to apply: diff --git a/packages/ui-server/src/ws/turns.ts b/packages/ui-server/src/ws/turns.ts index 1f47183d1a..4b19c4b20e 100644 --- a/packages/ui-server/src/ws/turns.ts +++ b/packages/ui-server/src/ws/turns.ts @@ -292,6 +292,10 @@ export interface PendingApproval { * locks; an approval must survive that and reappear, not silently die. */ request: PermissionRequest; + /** Final synchronous revalidation, including after a grant-store wait. */ + revalidate?: () => string | null; + /** Retain the terminal fact before resolving a safety-aware backend wait. */ + expire?: (reason: string, cause: "safety_changed" | "turn_ended" | "grant_storage_failed") => void; resolve: ( decision: PermissionDecision, response?: { principalId: string; always?: boolean; channel?: ApprovalChannel } @@ -464,6 +468,9 @@ export class TurnCoordinator { readonly #startingBySession = new Map(); readonly #unorderedSessions = new Set(); readonly #pendingApprovals = new Map(); + /** A client owns the answer, but invalidation/teardown still own its lifetime. */ + readonly #claimedApprovals = new Map(); + readonly #expiringApprovals = new Set(); readonly #resolvedApprovals = new Map(); readonly #asks = new Map(); readonly #pendingLocation = new Map(); @@ -779,22 +786,40 @@ export class TurnCoordinator { /** Open a permission request unless another turn holds its id; says whether it opened. */ openApproval(toolUseId: string, entry: PendingApproval): boolean { + if (this.#claimedApprovals.has(toolUseId) || this.#expiringApprovals.has(toolUseId)) return false; if (this.collides(this.#pendingApprovals.get(toolUseId), toolUseId, entry.turn)) return false; this.#pendingApprovals.set(toolUseId, entry); return true; } /** - * Remove a pending permission request that `accepts` matches, so no other - * path can settle it, and return it. Settle it with `settleApproval`. + * Transfer a pending answer to one handler. Keep it owned through any + * storage wait so invalidation/teardown can still expire it exactly once. */ claimApproval(toolUseId: string, accepts: (p: PendingApproval) => boolean = () => true): PendingApproval | undefined { const p = this.#pendingApprovals.get(toolUseId); if (!p || !accepts(p)) return undefined; this.#pendingApprovals.delete(toolUseId); + this.#claimedApprovals.set(toolUseId, p); return p; } + /** Expire a waiting or claimed answer; late handlers can no longer settle it. */ + expireApproval(toolUseId: string, reason: string, cause: "safety_changed" | "turn_ended" | "grant_storage_failed", + accepts: (p: PendingApproval) => boolean = () => true): boolean { + const p = this.#pendingApprovals.get(toolUseId) ?? this.#claimedApprovals.get(toolUseId); + if (!p || !accepts(p)) return false; + this.#pendingApprovals.delete(toolUseId); + this.#claimedApprovals.delete(toolUseId); + this.#expiringApprovals.add(toolUseId); + if (p.expire) p.expire(reason, cause); + else { + this.recordApprovalOutcome(toolUseId, { outcome: "expired", turnId: p.turnId, sessionId: p.turn.sessionId, reason }); + p.resolve({ behavior: "deny", message: reason }); + } + return true; + } + /** Answer a claimed permission request and record its outcome. */ settleApproval( toolUseId: string, @@ -802,13 +827,20 @@ export class TurnCoordinator { decision: PermissionDecision, response: { principalId: string; always?: boolean; channel?: ApprovalChannel } ): void { - claimed.resolve(decision, response); + if (this.#claimedApprovals.get(toolUseId) !== claimed) return; + const refusal = decision.behavior === "allow" ? claimed.revalidate?.() : null; + if (refusal) { + this.expireApproval(toolUseId, refusal, "safety_changed", p => p === claimed); + return; + } + this.#claimedApprovals.delete(toolUseId); this.recordApprovalOutcome(toolUseId, { outcome: decision.behavior === "deny" ? "denied" : "granted", turnId: claimed.turnId, sessionId: claimed.turn.sessionId, ...(response.channel ? { channel: response.channel } : {}), }); + claimed.resolve(decision, response); } /** Open a location request unless another turn holds its id; says whether it opened. */ @@ -963,6 +995,7 @@ export class TurnCoordinator { for (const turn of [...this.#running]) this.cancelTurn(turn, reason); const orphaned = new Set(); for (const p of this.#pendingApprovals.values()) orphaned.add(p.turn); + for (const p of this.#claimedApprovals.values()) orphaned.add(p.turn); for (const p of this.#asks.values()) orphaned.add(p.entry.turn); for (const p of this.#pendingLocation.values()) orphaned.add(p.turn); for (const p of this.#pendingMask.values()) orphaned.add(p.turn); @@ -993,6 +1026,7 @@ export class TurnCoordinator { /** Record a settled permission outcome and tell the host. */ recordApprovalOutcome(toolUseId: string, record: ToolResolutionRecord): void { + this.#expiringApprovals.delete(toolUseId); this.#resolvedApprovals.delete(toolUseId); this.#resolvedApprovals.set(toolUseId, record); while (this.#resolvedApprovals.size > MAX_RESOLVED_APPROVALS) { @@ -1032,13 +1066,11 @@ export class TurnCoordinator { // caller aborts first. The first one's reason is the one kept. if (turn.abortController?.signal.aborted && this.#drained.get(turn)?.turnId !== turn.turnId) this.#drained.set(turn, { turnId: turn.turnId, reason }); - for (const [id, p] of this.#pendingApprovals) { + for (const [id, p] of [...this.#pendingApprovals, ...this.#claimedApprovals]) { if (p.turn !== turn) continue; - p.resolve({ behavior: "deny", message: reason }); - this.#pendingApprovals.delete(id); // A terminal turn settles its own cards: no tool_result is coming, and // a client must be able to clear the card without waiting for one. - this.recordApprovalOutcome(id, { outcome: "expired", turnId: p.turnId, sessionId: p.turn.sessionId, reason }); + this.expireApproval(id, reason, "turn_ended", entry => entry === p); } // Kind by kind, in the order the per-kind maps were once drained. for (const kind of ASK_KINDS) { diff --git a/packages/ui-server/tests/live-safety-admission.test.ts b/packages/ui-server/tests/live-safety-admission.test.ts index 907e943dbf..ea876e9872 100644 --- a/packages/ui-server/tests/live-safety-admission.test.ts +++ b/packages/ui-server/tests/live-safety-admission.test.ts @@ -35,6 +35,12 @@ import { createSessionCatalog } from "../src/ws/session-catalog"; import { makeFakeBackend } from "./helpers/fake-backend"; import { testAuthorization } from "./helpers/principal"; import { requestToolPermission } from "@schlessera/brain-ui-sdk/server"; +import { NativeFileVersions } from "@schlessera/brain-ui-sdk/internal"; +import { handleToolApproval, handleToolDenial } from "../src/ws/handlers/tool-permission"; +import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { createSettingsWrites } from "../src/db/settings-writes"; +import { getAutoAllowedTools } from "../src/db/settings"; +import { retireChat, resolveChat } from "../src/ws/chat-lifecycle"; import { createNativeJournalFixture } from "./helpers/native-journal-fixture"; import { createTurnJournal } from "../src/brain/turn-journal"; @@ -381,3 +387,233 @@ test("zero reviewed triggers cannot clear unknown coverage or waive ordinary den } } finally { origin.stop(true); await f.close(); } }); + + +// Each hook sees the original input concurrently. The last hook must fence its +// own final wait even when every other hook already returned an allow/continue. +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 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(); }; + writeFileSync(join(f.root, "notice.md"), "Ithaca"); + let finished = 0; + const name = last === "agent" ? "Agent" : last === "native-read" || last === "index" ? "Read" : "Bash"; + const input = name === "Bash" ? { command: "echo Ithaca" } : name === "Agent" ? { prompt: "Return to Ithaca" } : { file_path: "notice.md" }; + const bridge: BackendBridge = { emit() {}, admissionSafety: f.safety, requestPermission: async () => ({ behavior: "allow" }), + inputSafety: { ...f.collector, async begin(id, tool, value) { + await f.collector.begin(id, tool, value); + if (last === "rtk" && value.command === "printf Ithaca" || last === "agent" && value.run_in_background === false) await wait(); + } }, ...(last === "index" ? { awaitIndex: async () => { await wait(); } } : {}) }; + const wiring = createPermissionWiring({ req: { prompt: "Return to Ithaca", bridge, signal: f.controller.signal, + workerSandbox: { brain: f.root, profile: "governed" } as never }, allowedTools: [name], confirmPatterns: [], brainPath: f.root, + turnLock: { async acquireForTool() { return { ok: true }; }, releaseForTool() {} } as never, + ...(last === "native-read" ? { fileVersions: versions } : {}), childEnv: {}, rewriteRtk: async () => "printf Ithaca", log() {} }); + 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; })); + try { + await entered.promise; + await new Promise(resolve => setImmediate(resolve)); + 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(); + if (change === "cancel") f.controller.abort(); + release.resolve(); + const outputs = await Promise.all(calls); + const denied = outputs.some(output => "hookSpecificOutput" in output && output.hookSpecificOutput?.hookEventName === "PreToolUse" && output.hookSpecificOutput.permissionDecision === "deny"); + const marker = join(f.root, "parallel-effect"); + let delivered: string | null = null; + if (!denied) { + if (name === "Read") delivered = readFileSync(join(f.root, "notice.md"), "utf8"); + else { + const command = name === "Bash" ? "printf Ithaca" : "printf Odyssey"; + const child = Bun.spawn(["/bin/sh", "-c", command], { stdout: Bun.file(marker), stderr: "pipe" }); + expect(await child.exited, await new Response(child.stderr).text()).toBe(0); + } + } + expect(name === "Read" ? delivered !== null : existsSync(marker), "PARALLEL_LAST_WAIT_MUST_FENCE_REAL_DELIVERY").toBe(change === "healthy"); + } finally { release.resolve(); await Promise.allSettled(calls); await f.close(); } + }); + } +} + +for (const kind of ["tool", "command", "policy", "actor"] as const) for (const change of ["healthy", "remove"] as const) { + test(`direct host ${kind} approval: host-owned snapshot fences ${change}`, async () => { + const f = await fixture(), raised = Promise.withResolvers(); + let reached = 0, decision: string | undefined, run: Promise | undefined; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { reached++; return new Response("Ithaca"); } }); + const backend = makeFakeBackend({ id: "claude", async startTurn(req) { + await req.bridge.inputSafety!.ready("claude", 1); + req.bridge.emit({ type: "session_info", sessionId: "ithaca", isNew: false }); + // Application, policy, compute and Apify callers all use this boundary. + const result = await req.bridge.requestPermission({ toolUseId: "direct-card", toolName: "OdysseyTool", kind, input: {} }); + decision = result.behavior; + if (result.behavior === "allow") await fetch(origin.url); + req.bridge.emit({ type: "result", sessionId: "ithaca", isError: false, durationMs: 1, numTurns: 1 }); + } }); + const store = createActivityStore(f.db); + const host = new WsHost({ brainPath: f.root, registry: createStaticBackendRegistry([backend], "claude"), catalog: createSessionCatalog(() => f.db), + isPrincipalAuthorized: id => id === f.principal.id, + safetyTrust: { revision: () => f.safety.read().trustRevision, subscribe: changed => f.safety.subscribe(changed) }, + activity: { store, stream: createActivityStream(store), governanceDb: f.db, governanceWrites: f.writes } }); + const frames: ServerMessage[] = []; + const ws = { send(text: string) { const frame = JSON.parse(text) as ServerMessage; frames.push(frame); if (frame.type === "tool_approval_request") raised.resolve(); } }; + host.clients.add(ws, f.principal.id); + host.clients.setCapabilities(ws, { toolResolution: true }); + try { + run = runSession(host, { authorization: testAuthorization(f.principal.id), text: "Return to Ithaca", attachments: [], sessionId: "ithaca" }); + await raised.promise; + const pending = host.coordinator.pendingApprovals.get("direct-card")!; + if (change === "remove") f.remove(); + // A simultaneous answer must neither revive nor grant a withdrawn card. + await handleToolApproval({ host, ws, requireEcho: true, connection: { principal: f.principal, + authorization: testAuthorization(f.principal.id), capabilities: { toolResolution: true } } }, + { type: "tool_approval", toolUseId: "direct-card", turnId: pending.turnId, channel: "card" }); + await run; + expect(reached, "DIRECT_HOST_STALE_CARD_CANNOT_DISPATCH_LOOPBACK").toBe(change === "healthy" ? 1 : 0); + expect(decision).toBe(change === "healthy" ? "allow" : "deny"); + expect(queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["safety_admission_expired"], limit: 100 })).toHaveLength(change === "healthy" ? 0 : 1); + expect(host.coordinator.resolvedApprovals.get("direct-card")?.outcome).toBe(change === "healthy" ? "granted" : "expired"); + expect(frames.filter(frame => frame.type === "tool_resolution" && frame.outcome === (change === "healthy" ? "granted" : "expired"))).toHaveLength(1); + } finally { host.close(); await run; origin.stop(true); await f.close(); } + }); +} + +for (const failStore of [false, true]) for (const change of ["healthy", "remove", "revoke", "cancel", "shutdown", "silent-remove", "retire"] as const) { + test(`claimed approval grant-storage ${failStore ? "failure" : "success"}: ${change} settles once without stale dispatch`, async () => { + const f = await fixture(), raised = Promise.withResolvers(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + let decision: string | undefined, reached = 0, adds = 0, run: Promise | undefined, answer: Promise | undefined; + let trust = "0", principalCurrent = true; + const grants = createSettingsWrites(f.db, f.writer); + const flush = f.writer.channel(probe, { table: "approval_flush" }); await flush.ready; + expect(await flush.call("level")).toBe(2); + let pendingCard: import("../src/ws/turns").PendingApproval | undefined; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { reached++; return new Response("Ithaca"); } }); + const backend = makeFakeBackend({ id: "claude", async startTurn(req) { + await req.bridge.inputSafety!.ready("claude", 1); + req.bridge.emit({ type: "session_info", sessionId: "ithaca", isNew: false }); + const result = await requestToolPermission(req.bridge, { toolUseId: "stored-card", toolName: "OdysseyTool", kind: "tool", input: {} }); + decision = result.behavior; + if (result.behavior === "allow") await fetch(origin.url); + req.bridge.emit({ type: "result", sessionId: "ithaca", isError: false, durationMs: 1, numTurns: 1 }); + } }); + const store = createActivityStore(f.db); + const host = new WsHost({ brainPath: f.root, registry: createStaticBackendRegistry([backend], "claude"), catalog: createSessionCatalog(() => f.db), + isPrincipalAuthorized: id => principalCurrent && id === f.principal.id, + safetyTrust: { revision: () => change === "silent-remove" ? trust : f.safety.read().trustRevision, subscribe: changed => f.safety.subscribe(changed) }, + toolPermissions: { isAutoAllowed: () => false, async add(name) { adds++; entered.resolve(); await release.promise; if (failStore) throw new Error("injected grant write failure"); await grants.addAutoAllowedTool(name); } }, + activity: { store, stream: createActivityStream(store), governanceDb: f.db, governanceWrites: f.writes } }); + const frames: ServerMessage[] = []; + const ws = { send(text: string) { const frame = JSON.parse(text) as ServerMessage; frames.push(frame); if (frame.type === "tool_approval_request") raised.resolve(); } }; + host.clients.add(ws, f.principal.id); + host.clients.setCapabilities(ws, { toolResolution: true }); + const ctx = { host, ws, requireEcho: true, connection: { principal: f.principal, authorization: testAuthorization(f.principal.id) } }; + try { + run = runSession(host, { authorization: testAuthorization(f.principal.id), text: "Return to Ithaca", attachments: [], sessionId: "ithaca" }); + await raised.promise; + const pending = host.coordinator.pendingApprovals.get("stored-card")!; + pendingCard = pending; + const reply = { type: "tool_approval" as const, toolUseId: "stored-card", turnId: pending.turnId, always: true, channel: "card" as const }; + answer = Promise.resolve(handleToolApproval(ctx, reply)); + // Observe handler errors without masking the eventual success assertion. + void answer.catch(() => {}); + await entered.promise; + expect(host.coordinator.pendingApprovals.has("stored-card")).toBe(false); + expect(host.chatBusy({ sessions: ["ithaca"], dialogueOwners: [], conversations: [], tasks: [], requests: [], nativeTasks: [] }), + "CLAIMED_CARD_KEEPS_CHAT_BUSY_BEFORE_RETIREMENT").toBe(true); + await handleToolApproval(ctx, reply); + handleToolDenial(ctx, { type: "tool_denial", toolUseId: "stored-card", turnId: pending.turnId, message: "Late denial", channel: "card" }); + expect(adds, "CLAIMED_CARD_HAS_ONE_GRANT_STORE_WRITER").toBe(1); + if (change === "remove") f.remove(); + if (change === "silent-remove") trust = "1"; + if (change === "revoke") { principalCurrent = false; await host.revokePrincipals([f.principal.id], 1008, "Revoked"); } + if (change === "cancel") host.coordinator.cancelTurn(pending.turn, "Odysseus cancelled"); + if (change === "shutdown") host.close(); + if (change === "retire") { + // Simulate a separate lifecycle writer; the public deletion path above + // refuses busy work, and must keep doing so. + const chat = resolveChat(f.db, { sessionId: "ithaca" }); + if ("refused" in chat) throw new Error(chat.refused); + expect(retireChat(f.db, { operationId: "retire-stored-card", principalId: f.principal.id, target: { sessionId: "ithaca" }, + expected: { backendId: chat.backendId, generation: chat.generation }, removableBackends: ["claude"], at: Date.now() }).status).toBe("retired"); + } + if (["remove", "revoke", "cancel", "shutdown"].includes(change)) { + await Promise.resolve(); // Let the invalidation enqueue its durable terminal first. + await flush.call("level"); + await new Promise(resolve => setImmediate(resolve)); + expect(decision, "INVALIDATION_SETTLES_BACKEND_WHILE_GRANT_STORE_STILL_WAITS").toBe("deny"); + } + release.resolve(); + await answer.catch(() => {}); + // Drain the real FULL writer and settlement continuations, without a timeout oracle. + await Promise.resolve(); + await flush.call("level"); + await new Promise(resolve => setImmediate(resolve)); + const expired = queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["safety_admission_expired"], limit: 100 }); + const allowed = change === "healthy" && !failStore; + if (allowed) await run; + expect(expired, "CLAIMED_CARD_RETAINS_EXACTLY_ONE_DURABLE_TERMINAL").toHaveLength(allowed || change === "retire" ? 0 : 1); + if (change === "retire") { + expect(host.coordinator.resolvedApprovals.get("stored-card")?.reason).toContain("could not be retained"); + expect(pending.turn.abortController.signal.aborted).toBe(true); + expect(f.db.query("SELECT generation FROM chat_lifecycles WHERE operation_id='retire-stored-card'").get()).toEqual({ generation: 2 }); + } + expect(decision, "GRANT_FAILURE_OR_WITHDRAWAL_NEVER_ORPHANS_BACKEND").toBe(allowed ? "allow" : "deny"); + expect(reached, "CLAIMED_CARD_CANNOT_DISPATCH_STALE_GRANT").toBe(allowed ? 1 : 0); + expect(host.coordinator.resolvedApprovals.get("stored-card")?.outcome).toBe(allowed ? "granted" : "expired"); + expect(frames.filter(frame => frame.type === "tool_resolution")).toHaveLength(change === "revoke" ? 0 : 1); + // The already-requested legacy standing grant is independent of whether + // this operation expired; it must never revive that operation. + expect(getAutoAllowedTools(f.db)).toEqual(failStore ? [] : ["OdysseyTool"]); + await run; + await answer; + } finally { + release.resolve(); + if (decision === undefined) pendingCard?.resolve({ behavior: "deny", message: "Probe cleanup" }); + host.close(); + await answer?.catch(() => {}); + await run; + origin.stop(true); await f.close(); + } + }); +} + + +test("withdrawal receipt storage failure explicitly terminates and stops the backend without dispatch", async () => { + const f = await fixture(), raised = Promise.withResolvers(); + let decision: string | undefined, aborted = false, reached = 0, run: Promise | undefined; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { reached++; return new Response("Ithaca"); } }); + const backend = makeFakeBackend({ id: "claude", async startTurn(req) { + await req.bridge.inputSafety!.ready("claude", 1); + req.bridge.emit({ type: "session_info", sessionId: "ithaca", isNew: false }); + const result = await req.bridge.requestPermission({ toolUseId: "failed-terminal", toolName: "OdysseyTool", kind: "command", input: {} }); + decision = result.behavior; aborted = req.signal.aborted; + if (result.behavior === "allow") await fetch(origin.url); + } }); + const store = createActivityStore(f.db); + const host = new WsHost({ brainPath: f.root, registry: createStaticBackendRegistry([backend], "claude"), catalog: createSessionCatalog(() => f.db), + isPrincipalAuthorized: id => id === f.principal.id, + safetyTrust: { revision: () => f.safety.read().trustRevision, subscribe: changed => f.safety.subscribe(changed) }, + activity: { store, stream: createActivityStream(store), governanceDb: f.db, governanceWrites: f.writes } }); + const frames: ServerMessage[] = []; + const ws = { send(text: string) { const frame = JSON.parse(text) as ServerMessage; frames.push(frame); if (frame.type === "tool_approval_request") raised.resolve(); } }; + host.clients.add(ws, f.principal.id); host.clients.setCapabilities(ws, { toolResolution: true }); + try { + run = runSession(host, { authorization: testAuthorization(f.principal.id), text: "Return to Ithaca", attachments: [], sessionId: "ithaca" }); + await raised.promise; + f.db.exec("CREATE TRIGGER fail_terminal BEFORE INSERT ON governance_events WHEN NEW.kind='safety_admission_expired' BEGIN SELECT RAISE(FAIL,'injected terminal storage failure'); END"); + f.remove(); await run; + expect(decision, "FAILED_WITHDRAWAL_STILL_SETTLES_BACKEND").toBe("deny"); + expect(aborted, "FAILED_WITHDRAWAL_STOPS_PROVIDER_CONTINUATION").toBe(true); + expect(reached, "FAILED_WITHDRAWAL_CANNOT_DISPATCH").toBe(0); + expect(host.coordinator.resolvedApprovals.get("failed-terminal")).toMatchObject({ outcome: "expired", reason: "Safety withdrawal could not be retained; the turn was stopped." }); + expect(frames.filter(frame => frame.type === "tool_resolution")).toHaveLength(1); + expect(queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["safety_admission_expired"], limit: 100 })).toHaveLength(0); + } finally { + host.close(); await run; origin.stop(true); await f.close(); + } +}); From affd94c2b166df5ce59f6d6536bdda010074249f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 04:14:09 +0000 Subject: [PATCH 3/8] CONTRACT: fence host publication on recording health --- .changeset/live-effective-safety.md | 2 + docs/decisions/governed-writable-workers.md | 2 +- docs/integration-contract/package-api.md | 8 + .../src/ws/bridge-capabilities/application.ts | 7 +- .../src/ws/bridge-capabilities/context.ts | 15 +- .../ws/bridge-capabilities/policy-proposal.ts | 4 +- .../tests/fixtures/held-publication-writer.ts | 14 ++ .../tests/host-publication-safety.test.ts | 203 ++++++++++++++++++ 8 files changed, 247 insertions(+), 8 deletions(-) create mode 100644 packages/ui-server/tests/fixtures/held-publication-writer.ts create mode 100644 packages/ui-server/tests/host-publication-safety.test.ts diff --git a/.changeset/live-effective-safety.md b/.changeset/live-effective-safety.md index e308197dbe..5e87724ef0 100644 --- a/.changeset/live-effective-safety.md +++ b/.changeset/live-effective-safety.md @@ -8,3 +8,5 @@ Breaking before 1.0: revalidate effective safety at dispatch after waits, restore later policy allowances only after complete individual review, and attribute new journal changes to current evidence while preserving historical facts. Fence parallel Claude hook waits and direct host approvals, and retain claimed-card ownership through grant persistence with explicit terminal receipts. + +Fence host publication after application/policy locks and related effect waits, while preserving principal epochs, completed per-use approvals and frozen ordinary policy. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 4b7aef2b84..bcfb2b0684 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -176,7 +176,7 @@ still holds. **Voice.** Ruling 1 makes voice `governed` too. Voice keeps its narrower membership (`VOICE_ALLOWED_TOOLS`, `packages/ui-backend-claude/src/tool-policy.ts:120`): no Bash, no raw `Write`/`Edit`, no archive, and approval returns false -(`const apply = createBrainApplication`, `packages/ui-server/src/ws/bridge-capabilities/application.ts:24-37`). +(`const apply = createBrainApplication`, `packages/ui-server/src/ws/bridge-capabilities/application.ts:25-38`). A voice turn therefore writes only through curated capture and update, now with a journal behind it. The writable mount gives voice no tool it lacked. Pi still refuses voice turns. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 7da87973cb..8296260b1d 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4877,6 +4877,14 @@ First-party backend gates additionally revalidate in their final dispatch continuations after locks, index barriers and occurrence writes. Every Claude pre-tool hook fences its own final asynchronous wait, including parallel rewrites and native file observations. +Host publication also checks qualified recording after its own lock/hold waits. +Application, image-mask, inbox and compute effects share that final host health +predicate; policy publication checks health independently of its own journal +observation, and share completion retains it through its final submission. +Recorder health remains separate from principal lifetime and does not rotate +the authority epoch or reload ordinary policy. Completed per-use approvals +retain their existing scope; pending input or recording loss cannot authorize +a new irreversible publication. Absent input retains the existing taint callback fallback and grants no new capability. The live trust input is revision/notification only; matching and publication have separate implementations. See the [effective admission diff --git a/packages/ui-server/src/ws/bridge-capabilities/application.ts b/packages/ui-server/src/ws/bridge-capabilities/application.ts index 6400c1b1b6..4f83b71fa9 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/application.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/application.ts @@ -18,9 +18,10 @@ function operationToolNames(backendId: string) { */ export function createApplication(ctx: BridgeContext, self: () => BackendBridge, root: string, applicationPolicy: BrainApplicationPolicy, options: Pick): { slice: BridgeSlice<"readBrainBase" | "applyBrain"> & Partial>; indexBatch: IndexBatch } { - const { host, turn, turnId, principalId, authorization, signal, work, backendId, recorder, maskGuard, toolName, isAuthorized, hold, afterHolds, current } = ctx; + const { host, turn, turnId, principalId, authorization, signal, work, backendId, recorder, maskGuard, toolName, isAuthorized, recordingAvailable, hold, afterHolds, current } = ctx; const { protectedPaths, turnData } = options; const operationTools = operationToolNames(backendId); + const effectCurrent = () => current() && recordingAvailable(); const apply = createBrainApplication({ root, principalId, turnId, signal, policy: applicationPolicy, protectedPaths, @@ -50,11 +51,11 @@ export function createApplication(ctx: BridgeContext, self: () => BackendBridge, // The application waits for holds itself, so its refusals are recorded. applyBrain: input => afterHolds(() => { const execute = () => apply({ principalId, turnId, input }); - return host.inboxTools?.shares ? host.inboxTools.shares.apply(principalId, turnId, turn.sessionId ?? undefined, current, input, execute) : execute(); + return host.inboxTools?.shares ? host.inboxTools.shares.apply(principalId, turnId, turn.sessionId ?? undefined, effectCurrent, input, execute) : execute(); }, false), }; if (host.inboxTools?.shares && work?.posture !== "voice") slice.completeShare = input => afterHolds(() => { - return host.inboxTools!.shares!.complete(principalId, turnId, turn.sessionId ?? undefined, current, input, async () => { + return host.inboxTools!.shares!.complete(principalId, turnId, turn.sessionId ?? undefined, effectCurrent, input, async () => { const decision = await self().requestPermission({ toolUseId: `share-completion-${crypto.randomUUID()}`, toolName: toolName("complete_share"), input, kind: "command", description: "Complete this share and discard only these exact originals after verified filing." }); return decision.behavior === "allow" && decision.updatedInput === undefined; }, applicationPolicy.lock, maskGuard ? paths => maskGuard.assert(toolName("complete_share"), paths) : undefined); diff --git a/packages/ui-server/src/ws/bridge-capabilities/context.ts b/packages/ui-server/src/ws/bridge-capabilities/context.ts index ae8972624f..283dc1652c 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/context.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/context.ts @@ -7,6 +7,7 @@ import { AUTHORITY_HOLD_WAIT_MS, waitForAuthority, waitWhile, type AuthorityHold import type { TurnRecorder } from "../../activity/recorder.js"; import type { RunningTurn } from "../turns.js"; import type { WsHost } from "../host.js"; +import { createEffectiveSafety } from "../../governance/effective-safety.js"; /** What one turn's bridge is built from, besides its host and turn (#2516). */ export interface MakeBridgeOptions { @@ -68,6 +69,8 @@ export interface BridgeContext { readonly queryActivity: NonNullable["query"] | undefined; /** The turn's own authority: its identity, authorization and principal are current. */ principalIsAuthorized(): boolean; + /** Final host effects require qualified input recording independently of principal authority. */ + recordingAvailable(): boolean; scopePaused(): boolean; isAuthorized(): boolean; holdOf(held: () => boolean): AuthorityHold; @@ -94,11 +97,19 @@ export function createBridgeContext(host: WsHost, turn: RunningTurn, options: Ma const work = turn.work; const principalIsAuthorized = () => turn.turnId === turnId && turn.startedAt !== undefined && authorization.valid && authorization.expiresAt > Date.now() && !turn.cancelled && host.isPrincipalAuthorized(principalId); + const safety = host.activity?.governanceDb ? createEffectiveSafety(host.activity.governanceDb, { + brain: host.brainPath, turnId, sessionId: () => turn.sessionId ?? null, policyHash: null, + writes: host.activity.governanceWrites, trust: host.safetyTrust, + authority: () => ({ current: principalIsAuthorized(), epoch: "0" }), + }) : undefined; + const recordingAvailable = () => { + try { return safety?.read().recordingAvailable ?? true; } catch { return false; } + }; // A journal observation or a scope pause stops host effects for a while but // revokes nothing (#2853). An effect waits for one, bounded, and checks again; // `isAuthorized` stays false while one is active, so nothing commits under it. const scopePaused = () => !!host.scope?.isPaused(turnId); - const isAuthorized = () => principalIsAuthorized() && !host.journal?.isHeld() && !scopePaused(); + const isAuthorized = () => principalIsAuthorized() && recordingAvailable() && !host.journal?.isHeld() && !scopePaused(); // A pause ends with the user's answer, which has no event here; the wait rechecks it. const holdOf = (held: () => boolean): AuthorityHold => ({ waitMs: AUTHORITY_HOLD_WAIT_MS, active: () => !signal.aborted && principalIsAuthorized() && held(), @@ -133,7 +144,7 @@ export function createBridgeContext(host: WsHost, turn: RunningTurn, options: Ma return { host, turn, backendId, turnId, requestId: turn.requestId, principalId, authorization, signal, work, recorder, mainModel, workerProfile, queryActivity: host.activity?.query, - principalIsAuthorized, scopePaused, isAuthorized, holdOf, hold, assertAuthority, afterHolds, + principalIsAuthorized, recordingAvailable, scopePaused, isAuthorized, holdOf, hold, assertAuthority, afterHolds, current: () => !signal.aborted && principalIsAuthorized(), toolName: (name: string) => backendId === "claude" ? `mcp__brain-ui__${name}` : name, maskGuard, diff --git a/packages/ui-server/src/ws/bridge-capabilities/policy-proposal.ts b/packages/ui-server/src/ws/bridge-capabilities/policy-proposal.ts index 7c59f581b9..c1c5d9455e 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/policy-proposal.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/policy-proposal.ts @@ -10,7 +10,7 @@ import type { BridgeContext, BridgeSlice } from "./context.js"; * `requestPermission`, live-authority wrapper included. */ export function createPolicyProposal(ctx: BridgeContext, self: () => BackendBridge): Partial> { - const { host, turn, turnId, principalId, signal, work, backendId, maskGuard, toolName, principalIsAuthorized, scopePaused, holdOf } = ctx; + const { host, turn, turnId, principalId, signal, work, backendId, maskGuard, toolName, principalIsAuthorized, recordingAvailable, scopePaused, holdOf } = ctx; if (!host.policyProposals || work?.posture === "voice") return {}; return { proposePolicyChange: async (requestId, input) => { @@ -18,7 +18,7 @@ export function createPolicyProposal(ctx: BridgeContext, self: () => BackendBrid maskGuard?.assert(toolName(PROPOSE_POLICY_CHANGE_TOOL_NAME), [GOVERNANCE_POLICY_PATH]); return host.policyProposals!.propose({ // Publication runs inside its own journal observation, so only a scope pause holds it. - principalId, turnId, sessionId: () => turn.sessionId, signal, isAuthorized: () => principalIsAuthorized() && !scopePaused(), + principalId, turnId, sessionId: () => turn.sessionId, signal, isAuthorized: () => principalIsAuthorized() && recordingAvailable() && !scopePaused(), hold: holdOf(scopePaused), isAvailable: () => work?.posture !== "voice", approve: async review => { const decision = await self().requestPermission({ toolUseId: requestId, diff --git a/packages/ui-server/tests/fixtures/held-publication-writer.ts b/packages/ui-server/tests/fixtures/held-publication-writer.ts new file mode 100644 index 0000000000..a5a5caba21 --- /dev/null +++ b/packages/ui-server/tests/fixtures/held-publication-writer.ts @@ -0,0 +1,14 @@ +import type { Database } from "bun:sqlite"; +export const url = import.meta.url; +export function setup(db: Database) { + return { + level() { return (db.query("PRAGMA synchronous").get() as { synchronous: number }).synchronous; }, + hold(entered: Int32Array, release: Int32Array) { + return db.transaction(() => { + Atomics.store(entered, 0, 1); Atomics.notify(entered, 0); + if (Atomics.wait(release, 0, 0, 5000) === "timed-out") throw new Error("Publication fixture release timed out"); + return true; + }).immediate(); + }, + }; +} diff --git a/packages/ui-server/tests/host-publication-safety.test.ts b/packages/ui-server/tests/host-publication-safety.test.ts new file mode 100644 index 0000000000..74acf6992e --- /dev/null +++ b/packages/ui-server/tests/host-publication-safety.test.ts @@ -0,0 +1,203 @@ +/** Actual authoritative-file effects after healthy backend admission. */ +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createKeyedLock, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { createPermissionWiring } from "../../ui-backend-claude/src/permission-hooks"; +import { createTurnContext } from "../../ui-backend-pi/src/turn-context"; +import { createPermissionGate } from "../../ui-backend-pi/src/permission-gate"; +import { createUiDb } from "../src/db/client"; +import { createPrincipal } from "../src/db/principals"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createGovernanceWrites } from "../src/governance/event-writes"; +import { createEffectiveSafety } from "../src/governance/effective-safety"; +import { createSafetyCollector } from "../src/governance/safety-collector"; +import { safetyCatalogCreated } from "../src/governance/safety-store"; +import { occurrence } from "../src/governance/occurrence"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { createActivityStore } from "../src/activity/store"; +import { createActivityStream } from "../src/activity/stream"; +import { WsHost } from "../src/ws/host"; +import { createSessionCatalog } from "../src/ws/session-catalog"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import { createBridgeContext } from "../src/ws/bridge-capabilities/context"; +import { createPermissions } from "../src/ws/bridge-capabilities/permissions"; +import { createApplication } from "../src/ws/bridge-capabilities/application"; +import type { RunningTurn } from "../src/ws/turns"; +import { makeBridge } from "../src/ws/bridge"; +import { createPolicyProposals } from "../src/brain/policy-proposal"; +import { handleToolApproval } from "../src/ws/handlers/tool-permission"; +import * as heldWriter from "./fixtures/held-publication-writer"; + +async function fixture(backendId: "claude" | "pi" = "claude") { + const root = mkdtempSync(join(tmpdir(), "odysseus-publication-safety-")), db = createUiDb(join(root, "ui.db")); + const writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer), bindingId = crypto.randomUUID(); + const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: principal.id, backendId, at: 0 }); + db.query("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('ithaca',0,0,?)").run(backendId); + db.query("INSERT INTO chat_session_owners VALUES('ithaca',?,0)").run(principal.id); + safetyCatalogCreated(db, "ithaca", principal.id, "voyage"); await writes.bind("voyage", "ithaca"); + const controller = new AbortController(); + const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, sessionId: () => "ithaca", backendId, + signal: controller.signal, shellProxied: () => true, brainPath: root }); + await collector.ready(backendId, 1); + const safety = createEffectiveSafety(db, { turnId: "voyage", sessionId: () => "ithaca", policyHash: null, writes, + authority: () => ({ current: true, epoch: "0" }) }); + return { root, db, writer, writes, bindingId, principal, controller, collector, safety, + async close() { await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } }; +} + +for (const adverse of [false, true]) test(`extra: direct application final lock wait fences shared recorder loss (${adverse})`, async () => { + const f=await fixture(); + const entered=Promise.withResolvers(), release=Promise.withResolvers(); + const backend=makeFakeBackend({id:"claude"}); + const store=createActivityStore(f.db); + const host=new WsHost({brainPath:f.root,registry:createStaticBackendRegistry([backend],"claude"),catalog:createSessionCatalog(()=>f.db), + isPrincipalAuthorized:id=>id===f.principal.id, + applicationPlanner:{async planAdd(){throw new Error("not used");},async index(){}}, + activity:{store,stream:createActivityStream(store),governanceDb:f.db,governanceWrites:f.writes}}); + const authorization=host.coordinator.openAuthorization({principalId:f.principal.id,valid:true,expiresAt:Number.MAX_SAFE_INTEGER}); + const turn={turnId:"voyage",principalId:f.principal.id,authorization,startedAt:1,sessionId:"ithaca",abortController:f.controller,queue:[]} as unknown as RunningTurn; + const ctx=createBridgeContext(host,turn,{promptText:"Return to Ithaca",backendId:"claude"}); + const bridge={emit(){},admissionSafety:f.safety} as unknown as BackendBridge; + Object.assign(bridge,createPermissions(ctx,()=>bridge)); + const app=createApplication(ctx,()=>bridge,f.root,{available:["write"],autoAllowed:["write"], + lock:{async withLock(_key:any,body:any){entered.resolve();await release.promise;return body();}} as never},{}); + Object.assign(bridge,app.slice); + let work:Promise|undefined; + try { + // The backend gate and collector have completed in the healthy state. + await f.collector.begin("application-call","mcp__brain-ui__write_file",{path:"notes/raft.md"}); + expect(f.safety.read().recordingAvailable).toBe(true); + work=bridge.applyBrain!({operation:"write",path:"notes/raft.md",content:"Odysseus returns to Ithaca.\n",expectedBaseHash:null}); + await entered.promise; + if(adverse) await createGovernanceWrites(f.db,f.writer).safetyFail("another-turn"); + expect(f.safety.read().recordingAvailable).toBe(!adverse); + release.resolve(); const result=await work; + expect(existsSync(join(f.root,"notes/raft.md")),"DIRECT_APPLICATION_LAST_WAIT_MUST_FENCE_SHARED_RECORDER_LOSS").toBe(!adverse); + expect(result.ok).toBe(!adverse); + } finally {release.resolve();await work;authorization.release();host.close();await f.close();} +}); + + +for(const backendId of ["claude","pi"] as const) for(const adverse of [false,true]) test(`extra composed ${backendId}: application post-gate lock health (${adverse})`,async()=>{ + const f=await fixture(backendId), entered=Promise.withResolvers(), release=Promise.withResolvers(); + const backend=makeFakeBackend({id:backendId}),store=createActivityStore(f.db); + const host=new WsHost({brainPath:f.root,registry:createStaticBackendRegistry([backend],backendId),catalog:createSessionCatalog(()=>f.db), + isPrincipalAuthorized:id=>id===f.principal.id, + applicationPlanner:{async planAdd(){throw new Error("not used");},async index(){}}, + activity:{store,stream:createActivityStream(store),governanceDb:f.db,governanceWrites:f.writes}}); + const authorization=host.coordinator.openAuthorization({principalId:f.principal.id,valid:true,expiresAt:Number.MAX_SAFE_INTEGER}); + const turn={turnId:"voyage",principalId:f.principal.id,authorization,startedAt:1,sessionId:"ithaca",abortController:f.controller,queue:[]} as unknown as RunningTurn; + const lock=host.workerLock; + (host as any).workerLock=Object.assign(Object.create(lock),{withLock:async(key:any,body:any,options:any)=>lock.withLock(key,async()=>{entered.resolve();await release.promise;return body();},options)}); + const bridge=await makeBridge(host,turn,{promptText:"Return to Ithaca",backendId,applicationPolicy:{available:["write"],autoAllowed:["write"],lock}}); + bridge.inputSafety=f.collector; + const input={operation:"write" as const,path:"notes/composed-raft.md",content:"Odysseus repairs the raft.\n",expectedBaseHash:null}; + const name=backendId==="claude"?"mcp__brain-ui__write_file":"write_file"; + let work:Promise|undefined; + try { + if(backendId==="claude") { + const wiring=createPermissionWiring({req:{prompt:"Return to Ithaca",bridge,signal:f.controller.signal,workerSandbox:{brain:f.root,profile:"governed"} as never}, + allowedTools:[name],confirmPatterns:[],brainPath:f.root,turnLock:{async acquireForTool(){return {ok:true};},releaseForTool(){}} as never,childEnv:{},log(){}}); + const outputs=await Promise.all(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:"composed-application"} as never,"composed-application",{signal:f.controller.signal}))); + expect(outputs.some(o=>"hookSpecificOutput" in o&&o.hookSpecificOutput&&"permissionDecision" in o.hookSpecificOutput&&o.hookSpecificOutput.permissionDecision==="deny")).toBe(false); + } else { + let gate:any;const extension=createPermissionGate({turn:{...createTurnContext(),bridge,signal:f.controller.signal},allowedTools:new Set([name]),confirmPatterns:[]}); + const factory=typeof extension==="function"?extension:extension.factory;await factory({on(_event:any,fn:any){gate=fn;}} as never); + expect(await gate({toolName:name,toolCallId:"composed-application",input})).toBeUndefined(); + } + expect(bridge.admissionSafety!.read().recordingAvailable).toBe(true); + const authorityEpoch = bridge.admissionSafety!.read().authorityEpoch; + work=bridge.applyBrain!(input);await entered.promise; + if(adverse)await createGovernanceWrites(f.db,f.writer).safetyFail("another-turn"); + expect(bridge.admissionSafety!.read().recordingAvailable).toBe(!adverse); + expect(bridge.admissionSafety!.read().authorityEpoch, "RECORDING_HEALTH_DOES_NOT_ROTATE_PRINCIPAL_EPOCH").toBe(authorityEpoch); + expect(f.controller.signal.aborted).toBe(false); + release.resolve();const result=await work; + expect(existsSync(join(f.root,input.path)),"COMPOSED_APPLICATION_POST_GATE_LOCK_MUST_FENCE_SHARED_HEALTH").toBe(!adverse); + expect(result.ok).toBe(!adverse); + }finally{release.resolve();await work;authorization.release();host.close();await f.close();} +}); + +for(const backendId of ["claude","pi"] as const) for(const adverse of [true]) test(`extra composed ${backendId}: application post-gate pending input (${adverse})`,async()=>{ + const f=await fixture(backendId), entered=Promise.withResolvers(), release=Promise.withResolvers(); + const backend=makeFakeBackend({id:backendId}),store=createActivityStore(f.db); + const host=new WsHost({brainPath:f.root,registry:createStaticBackendRegistry([backend],backendId),catalog:createSessionCatalog(()=>f.db), + isPrincipalAuthorized:id=>id===f.principal.id, + applicationPlanner:{async planAdd(){throw new Error("not used");},async index(){}}, + activity:{store,stream:createActivityStream(store),governanceDb:f.db,governanceWrites:f.writes}}); + const authorization=host.coordinator.openAuthorization({principalId:f.principal.id,valid:true,expiresAt:Number.MAX_SAFE_INTEGER}); + const turn={turnId:"voyage",principalId:f.principal.id,authorization,startedAt:1,sessionId:"ithaca",abortController:f.controller,queue:[]} as unknown as RunningTurn; + const lock=host.workerLock; + (host as any).workerLock=Object.assign(Object.create(lock),{withLock:async(key:any,body:any,options:any)=>lock.withLock(key,async()=>{entered.resolve();await release.promise;return body();},options)}); + const bridge=await makeBridge(host,turn,{promptText:"Return to Ithaca",backendId,applicationPolicy:{available:["write"],autoAllowed:["write"],lock}}); + bridge.inputSafety=f.collector; + const input={operation:"write" as const,path:"notes/composed-raft.md",content:"Odysseus repairs the raft.\n",expectedBaseHash:null}; + const name=backendId==="claude"?"mcp__brain-ui__write_file":"write_file"; + let work:Promise|undefined, held:Promise|undefined, pending:Promise|undefined; const writerRelease=new Int32Array(new SharedArrayBuffer(4)); + try { + if(backendId==="claude") { + const wiring=createPermissionWiring({req:{prompt:"Return to Ithaca",bridge,signal:f.controller.signal,workerSandbox:{brain:f.root,profile:"governed"} as never}, + allowedTools:[name],confirmPatterns:[],brainPath:f.root,turnLock:{async acquireForTool(){return {ok:true};},releaseForTool(){}} as never,childEnv:{},log(){}}); + const outputs=await Promise.all(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:"composed-application"} as never,"composed-application",{signal:f.controller.signal}))); + expect(outputs.some(o=>"hookSpecificOutput" in o&&o.hookSpecificOutput&&"permissionDecision" in o.hookSpecificOutput&&o.hookSpecificOutput.permissionDecision==="deny")).toBe(false); + } else { + let gate:any;const extension=createPermissionGate({turn:{...createTurnContext(),bridge,signal:f.controller.signal},allowedTools:new Set([name]),confirmPatterns:[]}); + const factory=typeof extension==="function"?extension:extension.factory;await factory({on(_event:any,fn:any){gate=fn;}} as never); + expect(await gate({toolName:name,toolCallId:"composed-application",input})).toBeUndefined(); + } + expect(bridge.admissionSafety!.read().recordingAvailable).toBe(true); + const authorityEpoch = bridge.admissionSafety!.read().authorityEpoch; + work=bridge.applyBrain!(input);await entered.promise; + const channel=f.writer.channel(heldWriter,{});await channel.ready; + expect(await channel.call("level")).toBe(2); + const writerEntered=new Int32Array(new SharedArrayBuffer(4));held=channel.call("hold",writerEntered,writerRelease); + const waiting=Atomics.waitAsync(writerEntered,0,0,5000);if(waiting.async)await waiting.value;expect(Atomics.load(writerEntered,0)).toBe(1); + pending=f.writes.firstTaint({kind:"taint",turnId:"voyage",sessionId:"ithaca",actor:"interactive",model:null,profile:null, + payload:{source:"web_fetch",tool:"WebFetch",detail:null,occurrence:occurrence(f.bindingId,"tool_web_input","queued-input","finalized")}}); + expect(bridge.admissionSafety!.read().recordingAvailable).toBe(!adverse); + expect(bridge.admissionSafety!.read().authorityEpoch, "RECORDING_HEALTH_DOES_NOT_ROTATE_PRINCIPAL_EPOCH").toBe(authorityEpoch); + expect(f.controller.signal.aborted).toBe(false); + release.resolve();const result=await work; + expect(existsSync(join(f.root,input.path)),"COMPOSED_APPLICATION_POST_GATE_LOCK_MUST_FENCE_PENDING_INPUT").toBe(!adverse); + expect(result.ok).toBe(!adverse); + }finally{release.resolve();Atomics.store(writerRelease,0,1);Atomics.notify(writerRelease,0);await Promise.allSettled([held,pending]);await work;authorization.release();host.close();await f.close();} +}); + +for(const adverse of [false,true]) test(`extra composed policy: final publication lock health (${adverse})`,async()=>{ + const f=await fixture(),entered=Promise.withResolvers(),release=Promise.withResolvers(),raised=Promise.withResolvers(); + const path=join(f.root,"context/policies/governance.md"),original="---\nschema_version: 1\nprofiles:\n interactive: governed\n---\nOdysseus reviews the policy.\n",proposed=original.replace("interactive: governed","interactive: strict"); + mkdirSync(join(f.root,"context/policies"),{recursive:true});writeFileSync(path,original); + const keyLock=createKeyedLock(); + const service=createPolicyProposals({root:f.root,db:f.db,writer:f.writer, + lock:{withLock:(key,body,options)=>keyLock.withLock(key,async()=>{entered.resolve();await release.promise;return body();},options)}, + observeUserPolicy:(_id,write)=>write(),recordEvent:(review,turn)=>f.writes.record({kind:"policy_change",turnId:turn.turnId,sessionId:turn.sessionId(),actor:"user",model:null,profile:null, + payload:{requestId:review.requestId,baseHash:review.baseHash,proposedHash:review.proposedHash,sections:review.sections,outcome:"updated"}})}); + const backend=makeFakeBackend({id:"claude"}),store=createActivityStore(f.db); + const host=new WsHost({brainPath:f.root,registry:createStaticBackendRegistry([backend],"claude"),catalog:createSessionCatalog(()=>f.db),isPrincipalAuthorized:id=>id===f.principal.id, + policyProposals:service,activity:{store,stream:createActivityStream(store),governanceDb:f.db,governanceWrites:f.writes}}); + const authorization=host.coordinator.openAuthorization({principalId:f.principal.id,valid:true,expiresAt:Number.MAX_SAFE_INTEGER}); + const turn={turnId:"voyage",principalId:f.principal.id,authorization,startedAt:1,sessionId:"ithaca",abortController:f.controller,queue:[]} as unknown as RunningTurn; + const ws={send(text:string){if(JSON.parse(text).type==="tool_approval_request")raised.resolve();}};host.clients.add(ws,f.principal.id); + const bridge=await makeBridge(host,turn,{promptText:"Return to Ithaca",backendId:"claude"});bridge.inputSafety=f.collector; + let work:Promise|undefined; + try{ + await f.collector.begin("policy-health","mcp__brain-ui__propose_policy_change",{content:proposed,rationale:"Use strict from the next turn."}); + expect(bridge.admissionSafety!.read().recordingAvailable).toBe(true); + const authorityEpoch = bridge.admissionSafety!.read().authorityEpoch; + work=bridge.proposePolicyChange!("policy-health",{content:proposed,rationale:"Use strict from the next turn."}); + await Promise.race([raised.promise,work.then(result=>{throw new Error(`Policy completed without a card: ${JSON.stringify(result)}`);})]); + await handleToolApproval({host,ws,requireEcho:true,connection:{principal:f.principal,authorization}} as never,{type:"tool_approval",toolUseId:"policy-health",turnId:"voyage",channel:"card"}); + await Promise.race([entered.promise,work.then(result=>{throw new Error(`Policy completed before lock: ${JSON.stringify(result)}`);})]); + if(adverse)await f.writes.safetyFail("another-turn"); + expect(bridge.admissionSafety!.read().recordingAvailable).toBe(!adverse); + expect(bridge.admissionSafety!.read().authorityEpoch, "RECORDING_HEALTH_DOES_NOT_ROTATE_PRINCIPAL_EPOCH").toBe(authorityEpoch); + release.resolve();const result=await work; + expect(readFileSync(path,"utf8")===proposed,"POLICY_FINAL_LOCK_MUST_FENCE_SHARED_RECORDER_LOSS").toBe(!adverse); + expect(result.state).toBe(adverse ? "refused" : "updated"); + }finally{release.resolve();host.close();await work;authorization.release();await f.close();} +}); From ed6f20497dda1c38794fa3ad0fa6cda2a44df573 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 06:01:32 +0000 Subject: [PATCH 4/8] CONTRACT: settle initial session binding before approval snapshots --- .changeset/live-effective-safety.md | 2 + docs/decisions/async-collaboration.md | 4 +- docs/decisions/governed-writable-workers.md | 2 +- docs/decisions/session-handoff.md | 2 +- docs/decisions/voice-permission.md | 6 +- docs/integration-contract/package-api.md | 5 + .../plans/async-collaboration-requirements.md | 4 +- docs/plans/async-collaboration.md | 4 +- .../src/ws/bridge-capabilities/context.ts | 4 +- .../src/ws/bridge-capabilities/emission.ts | 16 + .../src/ws/bridge-capabilities/permissions.ts | 335 +++++++++--------- packages/ui-server/src/ws/session-catalog.ts | 6 +- .../tests/approval-session-binding.test.ts | 95 +++++ 13 files changed, 312 insertions(+), 173 deletions(-) create mode 100644 packages/ui-server/tests/approval-session-binding.test.ts diff --git a/.changeset/live-effective-safety.md b/.changeset/live-effective-safety.md index 5e87724ef0..95f2205120 100644 --- a/.changeset/live-effective-safety.md +++ b/.changeset/live-effective-safety.md @@ -10,3 +10,5 @@ Breaking before 1.0: revalidate effective safety at dispatch after waits, restor Fence parallel Claude hook waits and direct host approvals, and retain claimed-card ownership through grant persistence with explicit terminal receipts. Fence host publication after application/policy locks and related effect waits, while preserving principal epochs, completed per-use approvals and frozen ordinary policy. + +Wait for initial session identity binding before capturing an approval card's safety snapshot; recheck recorder health and authority after that bounded wait. diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index fa92556cd3..4d31f70758 100644 --- a/docs/decisions/async-collaboration.md +++ b/docs/decisions/async-collaboration.md @@ -203,8 +203,8 @@ code atomically creates the Action and blocks its Queue item, then denies the permission and unwinds the turn. Already completed side effects are not undone by an abort. Attempt staging and cleanup therefore need idempotent recovery, with filesystem compensation outside SQLite transactions. Ordinary permission -parking still exists (`requestPermission: (req) => {`, -`packages/ui-server/src/ws/bridge-capabilities/permissions.ts:18-154`); it is not a durable Action store. +parking still exists (`const requestPermission`, +`packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`); it is not a durable Action store. Resolution validates the stored effect again, checks current authority, records one resolution and applies the guarded state transition in one transaction. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index bcfb2b0684..bf83f7e982 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1466,7 +1466,7 @@ from worker transcripts, and no extension of the observed-shell guarantee. **Where the next request waited.** The bridge never awaits an observation: it starts one per result and carries on -(`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:256`). +(`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:272`). The wait is the observation's hold. `held` takes it synchronously, before it queues the capture (`function held`, `packages/ui-server/src/brain/turn-journal.ts:240-261`), diff --git a/docs/decisions/session-handoff.md b/docs/decisions/session-handoff.md index ea27ac1994..28c2f27b22 100644 --- a/docs/decisions/session-handoff.md +++ b/docs/decisions/session-handoff.md @@ -160,7 +160,7 @@ its distinct retry treatment. Nothing archives, purges or automatically sends. The notice's presentation and actions are (`StateRoomNotice`, `packages/ui-react/src/components/chat/state-room-notice.tsx:22-100`); the host keeps the measurement and first quiet event (`const onResult`, -`packages/ui-server/src/ws/bridge-capabilities/emission.ts:187-212`). +`packages/ui-server/src/ws/bridge-capabilities/emission.ts:203-228`). ### Historical state directories remain untouched diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index ea49bfb9e5..f9ac08c236 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -436,7 +436,7 @@ A microphone is a reflex surface with worse recognition than a keyboard. This costs nothing measurable: the server already refuses `always` for kind `command` requests (the block computing `remembers`, `tool-permission.ts:87-93`, and the lookup computing -`remembered`, `ws/bridge-capabilities/permissions.ts:54-74`), and 192 of 192 measured +`remembered`, `ws/bridge-capabilities/permissions.ts:68-88`), and 192 of 192 measured approvals were kind `command`. ### When the announcement actually fires @@ -493,7 +493,7 @@ the request kind, and it patches the span (`onApprovalDecision`, `packages/ui-server/src/activity/recorder.ts:715-730`), fed from the bridge's `recorded()` wrapper -(`const recorded`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:96-112`). +(`const recorded`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:97-114`). One thing is missing and is a follow-up: **the event does not record the modality.** A denial decided by a phrase a microphone heard and one decided by a @@ -638,7 +638,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. purpose, so a grant that exists and is deliberately not applied can be logged — but refuses to answer from it or add to it for a tool the enforced allowlist left out (the lookup computing `remembered`, - `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:54-74`, + `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:68-88`, and the block computing `remembers`, `packages/ui-server/src/ws/handlers/tool-permission.ts:87-93`). The evaluation happens diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index f2e042b8a0..089f517005 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4873,6 +4873,11 @@ approval waits. The host's `requestPermission` boundary also owns its initial snapshot and final revalidation for direct application, policy, compute and actor callers; caller metadata cannot opt out. Claimed answers remain under coordinator ownership through grant storage and may expire during that wait. +On initial session naming, the host waits for its catalog/governance identity +binding before taking the first card snapshot. This wait is bounded and +cancellable; health and authority are checked again afterward. A healthy +first card therefore survives its own binding, while later changes still +withdraw stale authority. First-party backend gates additionally revalidate in their final dispatch continuations after locks, index barriers and occurrence writes. Every Claude pre-tool hook fences its own final asynchronous wait, including parallel diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index f023015d14..4f47e86034 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -43,7 +43,7 @@ session. Three consequences: 1. **Background work cannot ask.** Cron runs (`sync`, `validate`, `maintain`, module jobs) have no human attached. `bridge.requestPermission` parks a promise that nobody will - resolve (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:18-154`), so autonomous work is confined to + resolve (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`), so autonomous work is confined to whatever is pre-approved, and anything requiring judgment is not attempted. 2. **Inbound material has no path.** A forwarded email, a shared link, a captured note has nowhere to land that the agent will act on later. The PWA share target stages into @@ -263,7 +263,7 @@ Stated before the requirements because five of them derive from it. threshold (~20s of the 30s lock budget). Below it nothing yields; above it the holder checkpoints/unwinds/releases. Test both edges and independent paths. - R26. **Abort-and-redo needs a checkpoint primitive.** `requestPermission` parks a bare - promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:91-186`) — while blocked on it the model cannot write anything, so + promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:92-187`) — while blocked on it the model cannot write anything, so "writes its findings, then aborts" has nowhere to run. The autonomous bridge must, in one server-side step: capture the checkpoint, create the Action and block the item, unwind without a live approval promise, preserving the tested timeout path's abort-then-drain order (`abortController.abort();`, `packages/ui-server/src/ws/session-run/admission.ts:55-57`). Aborting does **not** undo completed tool side diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 98b0c332f1..17508354a9 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -28,7 +28,7 @@ than last. ## Problem Frame Collaboration is synchronous-only: background work cannot ask (`requestPermission` parks a -promise nobody resolves — (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:18-154`)), inbound material +promise nobody resolves — (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`)), inbound material has no path that survives until the user is present, and no decision accumulates into standing authority. See origin for the full frame. @@ -134,7 +134,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. - **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1019`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. -- **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:18-154`). Timeout unwind is +- **Permission parking:** (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`). Timeout unwind is (`abortController.abort();`, `packages/ui-server/src/ws/session-run/admission.ts:55-57`). Durable escalation must checkpoint before unwinding; the existing ordinary bridge does not do that. - **Tool enforcement:** (`export function enforcementHookFor`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`) closes measured bypasses. diff --git a/packages/ui-server/src/ws/bridge-capabilities/context.ts b/packages/ui-server/src/ws/bridge-capabilities/context.ts index 283dc1652c..7f0e062029 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/context.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/context.ts @@ -67,6 +67,8 @@ export interface BridgeContext { readonly workerProfile: WorkerProfileBinding | undefined; /** Read when the bridge is built, like the identity above. */ readonly queryActivity: NonNullable["query"] | undefined; + /** This bridge's announced session identity must commit before its first approval snapshot. */ + readonly sessionBinding: { pending?: Promise; failed: boolean }; /** The turn's own authority: its identity, authorization and principal are current. */ principalIsAuthorized(): boolean; /** Final host effects require qualified input recording independently of principal authority. */ @@ -143,7 +145,7 @@ export function createBridgeContext(host: WsHost, turn: RunningTurn, options: Ma payload: { ...refusal, policyHash: providerMasks.policy.hash } }) }) : undefined; return { host, turn, backendId, turnId, requestId: turn.requestId, principalId, authorization, signal, work, - recorder, mainModel, workerProfile, queryActivity: host.activity?.query, + recorder, mainModel, workerProfile, queryActivity: host.activity?.query, sessionBinding: { failed: false }, principalIsAuthorized, recordingAvailable, scopePaused, isAuthorized, holdOf, hold, assertAuthority, afterHolds, current: () => !signal.aborted && principalIsAuthorized(), toolName: (name: string) => backendId === "claude" ? `mcp__brain-ui__${name}` : name, diff --git a/packages/ui-server/src/ws/bridge-capabilities/emission.ts b/packages/ui-server/src/ws/bridge-capabilities/emission.ts index d1b9c2a15d..7b9a8d0748 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/emission.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/emission.ts @@ -144,6 +144,22 @@ export function createEmission(ctx: BridgeContext, transcript: TurnTranscript, catalog.persistSessionStub(msg.sessionId, promptText, turn.providerId, backendId, creator,creator?turnId:undefined); // Governance events recorded before the row existed join it now (#1651). catalog.bindGovernanceEvents?.(turnId, msg.sessionId); + // A backend can ask immediately after this synchronous announcement. + // Its approval must snapshot the committed identity, not the provisional + // identity that this announcement is still reconciling on the writer. + const pending = catalog.settled?.(); + if (pending) { + ctx.sessionBinding.failed = false; + ctx.sessionBinding.pending = pending; + void pending.then(() => { + if (ctx.sessionBinding.pending === pending) delete ctx.sessionBinding.pending; + }, () => { + if (ctx.sessionBinding.pending === pending) { + delete ctx.sessionBinding.pending; + ctx.sessionBinding.failed = true; + } + }); + } // Submitted after the catalog row; every share read/effect joins this queue. void host.inboxTools?.shares?.bind(turnId, msg.sessionId).catch(error => { turn.abortController.abort(error); emitTurnError(host, turn, error); diff --git a/packages/ui-server/src/ws/bridge-capabilities/permissions.ts b/packages/ui-server/src/ws/bridge-capabilities/permissions.ts index 1422f4b38d..a8600de761 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/permissions.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/permissions.ts @@ -4,6 +4,8 @@ import type { BackendBridge, PermissionDecision } from "@schlessera/brain-ui-sdk import { sameSafetyAdmission, safetyAdmissionRefusal, STALE_SAFETY_ADMISSION, type AdmissionSafetySnapshot } from "@schlessera/brain-ui-sdk/internal"; import { approvalRequestFrame, withTurnScope } from "../frames.js"; import type { BridgeContext, BridgeSlice } from "./context.js"; +import { waitWhile } from "../../brain/authority-hold.js"; +import { STORAGE_SETTLEMENT_MS } from "../../db/settlement.js"; /** * Permission requests: a remembered grant, a policy proposal's checkpoint, or @@ -14,176 +16,189 @@ import type { BridgeContext, BridgeSlice } from "./context.js"; export function createPermissions(ctx: BridgeContext, self: () => BackendBridge): BridgeSlice<"requestPermission"> { const { host, turn, turnId, recorder } = ctx; const { coordinator } = host; - return { - requestPermission: (req) => { - // Retain the coordinator's original terminal reason for a late request; - // cancellation must not replace it with a new safety diagnosis. + const requestPermission: BackendBridge["requestPermission"] = (req) => { + // Retain the coordinator's original terminal reason for a late request; + // cancellation must not replace it with a new safety diagnosis. + const drained = coordinator.drainedReason(turn, turnId); + if (drained !== undefined) { + coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId: turn.sessionId, reason: drained }); + recorder?.onApprovalDecision(req.toolUseId, "deny", req.kind ?? "tool"); + return Promise.resolve({ behavior: "deny", message: drained }); + } + // This is the common boundary for SDK tools AND host-internal callers + // (applications, policy publication, compute and actors). Caller metadata + // cannot opt a card out of withdrawal or supply its authority. + const safety = self().admissionSafety; + let snapshot: AdmissionSafetySnapshot | undefined; + try { snapshot = safety?.read(); } + catch { return Promise.resolve({ behavior: "deny", message: STALE_SAFETY_ADMISSION }); } + const revalidate = (): string | null => { + if (ctx.signal.aborted || (safety || ctx.backendId === "claude" || ctx.backendId === "pi") && !ctx.current()) return STALE_SAFETY_ADMISSION; + try { + if (safetyAdmissionRefusal(safety, snapshot) || safety && snapshot && !sameSafetyAdmission(snapshot, safety.read())) return STALE_SAFETY_ADMISSION; + } catch { return STALE_SAFETY_ADMISSION; } + return null; + }; + if (revalidate() || safety && snapshot && req.admissionSnapshot && !sameSafetyAdmission(req.admissionSnapshot, snapshot)) + return Promise.resolve({ behavior: "deny", message: STALE_SAFETY_ADMISSION }); + if (snapshot) req = { ...req, admissionSnapshot: snapshot }; + // A native permission checkpoint delegates this particular operation to + // the host validator. Invalid input never raises a generic approval card. + // Its handler later reads the SAME request receipt, without another write. + if (req.kind !== "policy" && [PROPOSE_POLICY_CHANGE_TOOL_NAME, `mcp__brain-ui__${PROPOSE_POLICY_CHANGE_TOOL_NAME}`].includes(req.toolName)) { + const bridge = self(); + if (!bridge.proposePolicyChange) return Promise.resolve({ behavior: "deny", message: "Policy proposals are unavailable in this turn." }); + return bridge.proposePolicyChange(req.toolUseId, req.input as PolicyChangeInput) + .then(review => review.state === "updated" && !revalidate() ? { behavior: "allow" as const } : { behavior: "deny" as const, message: revalidate() ?? review.message }, + error => ({ behavior: "deny" as const, message: error instanceof Error ? error.message : "Invalid policy proposal." })); + } + // A remembered "always allow" answers grantable tool requests without + // a card. NEVER for kind "command" — those are destructive-pattern + // confirmations for tools that are already auto-allowed, and + // remembering them would silently disable the seatbelt. NEVER either + // when the backend says the turn's enforced allowlist left this tool + // out: the grant was given under a wider posture and answering with it + // would make the narrower one decoration. + // + // The store is still READ for such a request, and only read: a grant + // that exists and is deliberately not applied is the thing worth a + // record, and there is nothing to record without looking. What the + // enforced posture forbids is answering from the store (here) and + // adding to it (dispatch.ts) — not knowing what is in it. + const remembered = + req.kind !== "actor" && req.kind !== "command" && req.kind !== "policy" && host.toolPermissions?.isAutoAllowed(req.toolName) === true; + if (remembered && req.outsideEnforcedAllowlist) { + // Body stays constant and the reason rides as an attribute, matching + // the refusal dispatch.ts records on the write side. A reason spliced + // into the body reads better in a terminal and aggregates worse: two + // halves of one policy would not group, and neither would two reasons + // for the same half. + host.log.emit({ + severityText: "INFO", + body: "remembered tool grant not applied", + attributes: { + "tool.name": req.toolName, + "toolUse.id": req.toolUseId, + reason: "outside this turn's enforced allowlist", + }, + }); + } + if (remembered && !req.outsideEnforcedAllowlist) { + return Promise.resolve().then(() => { + const refusal = revalidate(); + return refusal ? { behavior: "deny", message: refusal } : { behavior: "allow" }; + }); + } + return new Promise((resolve) => { + let unsubscribe: (() => void) | undefined; + // The decision stamps the wait/execution boundary on the tool span + // (grant) or lands the denied outcome (deny) before the backend's + // own error tool_result can mislabel it — write-once protects it. + const recorded = ( + decision: PermissionDecision, + response?: { principalId: string; always?: boolean; channel?: ApprovalChannel } + ) => { + unsubscribe?.(); unsubscribe = undefined; + recorder?.onApprovalDecision( + req.toolUseId, + decision.behavior === "deny" + ? "deny" + : response?.always + ? "always_allow" + : "allow", + req.kind ?? "tool", + response?.principalId, + response?.channel + ); + resolve(decision); + }; + // A request raised after the turn's drain is expired the way the + // drain expires one, or it would never settle (#3553). const drained = coordinator.drainedReason(turn, turnId); if (drained !== undefined) { coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId: turn.sessionId, reason: drained }); - recorder?.onApprovalDecision(req.toolUseId, "deny", req.kind ?? "tool"); - return Promise.resolve({ behavior: "deny", message: drained }); + recorded({ behavior: "deny", message: drained }); + return; + } + const expire = (reason: string, cause: "safety_changed" | "turn_ended" | "grant_storage_failed") => { + unsubscribe?.(); unsubscribe = undefined; + const writes = host.activity?.governanceWrites; + const sessionId = turn.sessionId; + // Coordinator ownership has already been removed from both waiting + // and in-flight answers. Retain exactly one terminal fact before + // publishing the outcome or settling the backend wait. + const committed = writes && snapshot ? Promise.resolve().then(() => writes.record({ kind: "safety_admission_expired", turnId, + sessionId: sessionId ?? null, actor: "server", model: null, profile: null, + payload: { toolUseId: req.toolUseId, evidenceRevision: snapshot.evidenceRevision, + trustRevision: snapshot.trustRevision, authorityEpoch: snapshot.authorityEpoch, reason: cause } })) + : snapshot ? Promise.reject(new Error("Safety withdrawal storage is unavailable")) : Promise.resolve(); + void committed.then(() => { + coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId, reason }); + recorded({ behavior: "deny", message: reason }); + }, error => { + // No successful durable-withdrawal claim on storage failure, but + // cleanup and the backend still receive one explicit terminal. + const failed = "Safety withdrawal could not be retained; the turn was stopped."; + coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId, reason: failed }); + recorded({ behavior: "deny", message: failed }); + turn.abortController.abort(error); + }); + }; + if (!coordinator.openApproval(req.toolUseId, { turn, turnId, request: req, resolve: recorded, revalidate, ...(snapshot ? { expire } : {}) })) { + resolve({ behavior: "deny", message: "Duplicate tool-approval id" }); + return; } - // This is the common boundary for SDK tools AND host-internal callers - // (applications, policy publication, compute and actors). Caller metadata - // cannot opt a card out of withdrawal or supply its authority. - const safety = self().admissionSafety; - let snapshot: AdmissionSafetySnapshot | undefined; - try { snapshot = safety?.read(); } - catch { return Promise.resolve({ behavior: "deny", message: STALE_SAFETY_ADMISSION }); } - const revalidate = (): string | null => { - if (ctx.signal.aborted || (safety || ctx.backendId === "claude" || ctx.backendId === "pi") && !ctx.current()) return STALE_SAFETY_ADMISSION; - try { - if (safetyAdmissionRefusal(safety, snapshot) || safety && snapshot && !sameSafetyAdmission(snapshot, safety.read())) return STALE_SAFETY_ADMISSION; - } catch { return STALE_SAFETY_ADMISSION; } - return null; + const invalidate = () => { + if (!revalidate()) return; + coordinator.expireApproval(req.toolUseId, STALE_SAFETY_ADMISSION, "safety_changed", p => p.turn === turn && p.request === req); }; - if (revalidate() || safety && snapshot && req.admissionSnapshot && !sameSafetyAdmission(req.admissionSnapshot, snapshot)) - return Promise.resolve({ behavior: "deny", message: STALE_SAFETY_ADMISSION }); - if (snapshot) req = { ...req, admissionSnapshot: snapshot }; - // A native permission checkpoint delegates this particular operation to - // the host validator. Invalid input never raises a generic approval card. - // Its handler later reads the SAME request receipt, without another write. - if (req.kind !== "policy" && [PROPOSE_POLICY_CHANGE_TOOL_NAME, `mcp__brain-ui__${PROPOSE_POLICY_CHANGE_TOOL_NAME}`].includes(req.toolName)) { - const bridge = self(); - if (!bridge.proposePolicyChange) return Promise.resolve({ behavior: "deny", message: "Policy proposals are unavailable in this turn." }); - return bridge.proposePolicyChange(req.toolUseId, req.input as PolicyChangeInput) - .then(review => review.state === "updated" && !revalidate() ? { behavior: "allow" as const } : { behavior: "deny" as const, message: revalidate() ?? review.message }, - error => ({ behavior: "deny" as const, message: error instanceof Error ? error.message : "Invalid policy proposal." })); + if (safety && snapshot) { + unsubscribe = safety.subscribe(invalidate); + invalidate(); + if (!coordinator.pendingApprovals.has(req.toolUseId)) { unsubscribe?.(); unsubscribe = undefined; return; } } - // A remembered "always allow" answers grantable tool requests without - // a card. NEVER for kind "command" — those are destructive-pattern - // confirmations for tools that are already auto-allowed, and - // remembering them would silently disable the seatbelt. NEVER either - // when the backend says the turn's enforced allowlist left this tool - // out: the grant was given under a wider posture and answering with it - // would make the narrower one decoration. - // - // The store is still READ for such a request, and only read: a grant - // that exists and is deliberately not applied is the thing worth a - // record, and there is nothing to record without looking. What the - // enforced posture forbids is answering from the store (here) and - // adding to it (dispatch.ts) — not knowing what is in it. - const remembered = - req.kind !== "actor" && req.kind !== "command" && req.kind !== "policy" && host.toolPermissions?.isAutoAllowed(req.toolName) === true; - if (remembered && req.outsideEnforcedAllowlist) { - // Body stays constant and the reason rides as an attribute, matching - // the refusal dispatch.ts records on the write side. A reason spliced - // into the body reads better in a terminal and aggregates worse: two - // halves of one policy would not group, and neither would two reasons - // for the same half. + if (!host.clients.hasClients()) { + // Not a failure — the card is parked and re-delivered on reconnect + // (see resendPendingInteractive) — but the wait was invisible before + // this line existed, and it is bounded only by the turn timeout. host.log.emit({ - severityText: "INFO", - body: "remembered tool grant not applied", - attributes: { - "tool.name": req.toolName, - "toolUse.id": req.toolUseId, - reason: "outside this turn's enforced allowlist", - }, + severityText: "WARN", + body: "approval requested with no client connected; holding for reconnect", + attributes: { "tool.name": req.toolName, "toolUse.id": req.toolUseId }, }); } - if (remembered && !req.outsideEnforcedAllowlist) { - return Promise.resolve().then(() => { - const refusal = revalidate(); - return refusal ? { behavior: "deny", message: refusal } : { behavior: "allow" }; - }); + host.sendToClients( + withTurnScope( + approvalRequestFrame(req, host.toolPermissions !== null), + turn, + turnId + ) + ); + host.sendToClients( + withTurnScope( + { type: "status", status: "tool_executing", detail: `Waiting for approval: ${req.toolName}` }, + turn, + turnId + ) + ); + if (turn.sessionId) { + host.conversations?.approvalRaised({ sessionId: turn.sessionId, turnId, toolUseId: req.toolUseId, toolName: req.toolName }); } - return new Promise((resolve) => { - let unsubscribe: (() => void) | undefined; - // The decision stamps the wait/execution boundary on the tool span - // (grant) or lands the denied outcome (deny) before the backend's - // own error tool_result can mislabel it — write-once protects it. - const recorded = ( - decision: PermissionDecision, - response?: { principalId: string; always?: boolean; channel?: ApprovalChannel } - ) => { - unsubscribe?.(); unsubscribe = undefined; - recorder?.onApprovalDecision( - req.toolUseId, - decision.behavior === "deny" - ? "deny" - : response?.always - ? "always_allow" - : "allow", - req.kind ?? "tool", - response?.principalId, - response?.channel - ); - resolve(decision); - }; - // A request raised after the turn's drain is expired the way the - // drain expires one, or it would never settle (#3553). - const drained = coordinator.drainedReason(turn, turnId); - if (drained !== undefined) { - coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId: turn.sessionId, reason: drained }); - recorded({ behavior: "deny", message: drained }); - return; - } - const expire = (reason: string, cause: "safety_changed" | "turn_ended" | "grant_storage_failed") => { - unsubscribe?.(); unsubscribe = undefined; - const writes = host.activity?.governanceWrites; - const sessionId = turn.sessionId; - // Coordinator ownership has already been removed from both waiting - // and in-flight answers. Retain exactly one terminal fact before - // publishing the outcome or settling the backend wait. - const committed = writes && snapshot ? Promise.resolve().then(() => writes.record({ kind: "safety_admission_expired", turnId, - sessionId: sessionId ?? null, actor: "server", model: null, profile: null, - payload: { toolUseId: req.toolUseId, evidenceRevision: snapshot.evidenceRevision, - trustRevision: snapshot.trustRevision, authorityEpoch: snapshot.authorityEpoch, reason: cause } })) - : snapshot ? Promise.reject(new Error("Safety withdrawal storage is unavailable")) : Promise.resolve(); - void committed.then(() => { - coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId, reason }); - recorded({ behavior: "deny", message: reason }); - }, error => { - // No successful durable-withdrawal claim on storage failure, but - // cleanup and the backend still receive one explicit terminal. - const failed = "Safety withdrawal could not be retained; the turn was stopped."; - coordinator.recordApprovalOutcome(req.toolUseId, { outcome: "expired", turnId, sessionId, reason: failed }); - recorded({ behavior: "deny", message: failed }); - turn.abortController.abort(error); - }); - }; - if (!coordinator.openApproval(req.toolUseId, { turn, turnId, request: req, resolve: recorded, revalidate, ...(snapshot ? { expire } : {}) })) { - resolve({ behavior: "deny", message: "Duplicate tool-approval id" }); - return; - } - const invalidate = () => { - if (!revalidate()) return; - coordinator.expireApproval(req.toolUseId, STALE_SAFETY_ADMISSION, "safety_changed", p => p.turn === turn && p.request === req); - }; - if (safety && snapshot) { - unsubscribe = safety.subscribe(invalidate); - invalidate(); - if (!coordinator.pendingApprovals.has(req.toolUseId)) { unsubscribe?.(); unsubscribe = undefined; return; } - } - if (!host.clients.hasClients()) { - // Not a failure — the card is parked and re-delivered on reconnect - // (see resendPendingInteractive) — but the wait was invisible before - // this line existed, and it is bounded only by the turn timeout. - host.log.emit({ - severityText: "WARN", - body: "approval requested with no client connected; holding for reconnect", - attributes: { "tool.name": req.toolName, "toolUse.id": req.toolUseId }, - }); - } - host.sendToClients( - withTurnScope( - approvalRequestFrame(req, host.toolPermissions !== null), - turn, - turnId - ) - ); - host.sendToClients( - withTurnScope( - { type: "status", status: "tool_executing", detail: `Waiting for approval: ${req.toolName}` }, - turn, - turnId - ) - ); - if (turn.sessionId) { - host.conversations?.approvalRaised({ sessionId: turn.sessionId, turnId, toolUseId: req.toolUseId, toolName: req.toolName }); - } - }); + }); + }; + return { + requestPermission: req => { + if (coordinator.drainedReason(turn, turnId) !== undefined) return requestPermission(req); + if (ctx.sessionBinding.failed) return Promise.resolve({ behavior: "deny", message: STALE_SAFETY_ADMISSION }); + if (!ctx.sessionBinding.pending) return requestPermission(req); + // One bounded identity wait, before capturing any approval snapshot. + // Actual permission/health/authority checks remain in the continuation. + return waitWhile(() => !!ctx.sessionBinding.pending && ctx.current(), + () => ctx.sessionBinding.pending!, ctx.signal, Date.now() + STORAGE_SETTLEMENT_MS).then(settled => { + if (!settled || ctx.sessionBinding.failed || ctx.sessionBinding.pending && ctx.current()) + return { behavior: "deny" as const, message: STALE_SAFETY_ADMISSION }; + return requestPermission(req); + }); }, }; } diff --git a/packages/ui-server/src/ws/session-catalog.ts b/packages/ui-server/src/ws/session-catalog.ts index ed1b679f79..0a03ff53ea 100644 --- a/packages/ui-server/src/ws/session-catalog.ts +++ b/packages/ui-server/src/ws/session-catalog.ts @@ -602,7 +602,11 @@ export function createSessionCatalog(db: () => Database, log?: Logger, scratchPi }, bindGovernanceEvents(turnId, sessionId) { - try { governance().bind(turnId, sessionId).catch((err: unknown) => reportWriteFailure(sessionId, err)); } + try { + const bound = governance().bind(turnId, sessionId); + settle(bound); + void bound.catch((err: unknown) => reportWriteFailure(sessionId, err)); + } catch (err) { reportWriteFailure(sessionId, err); } }, diff --git a/packages/ui-server/tests/approval-session-binding.test.ts b/packages/ui-server/tests/approval-session-binding.test.ts new file mode 100644 index 0000000000..aeabef463e --- /dev/null +++ b/packages/ui-server/tests/approval-session-binding.test.ts @@ -0,0 +1,95 @@ +/** A first approval snapshots the durable identity of its own announced session. */ +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import type { PermissionDecision } from "@schlessera/brain-ui-sdk/server"; +import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { createUiDb } from "../src/db/client"; +import { createPrincipal } from "../src/db/principals"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createGovernanceWrites } from "../src/governance/event-writes"; +import { createActivityStore } from "../src/activity/store"; +import { createActivityStream } from "../src/activity/stream"; +import { createModelPricing } from "../src/pricing/model-pricing"; +import { resolveStandalonePricingConfig } from "../src/config/env"; +import { createSessionCatalog } from "../src/ws/session-catalog"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { WsHost } from "../src/ws/host"; +import { makeBridge } from "../src/ws/bridge"; +import type { RunningTurn } from "../src/ws/turns"; +import { handleToolApproval } from "../src/ws/handlers/tool-permission"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import * as heldWriter from "./fixtures/held-publication-writer"; + +for (const mode of ["healthy", "recording loss", "revocation", "cancellation"] as const) { + test(`first approval joins its own FULL-writer binding: ${mode}`, async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-approval-binding-")), db = createUiDb(join(root, "ui.db")); + const writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer), store = createActivityStore(db); + const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const backend = makeFakeBackend({ id: "scripted-binding" }); + const catalog = createSessionCatalog(() => db, undefined, undefined, { + writer, store, governance: writes, pricing: createModelPricing(resolveStandalonePricingConfig()), + }); + const host = new WsHost({ brainPath: root, registry: createStaticBackendRegistry([backend], backend.id), catalog, + isPrincipalAuthorized: id => id === principal.id, + activity: { store, stream: createActivityStream(store), governanceDb: db, governanceWrites: writes } }); + const authorization = host.coordinator.openAuthorization({ principalId: principal.id, valid: true, expiresAt: Number.MAX_SAFE_INTEGER }); + const controller = new AbortController(); + const turn = { turnId: "voyage", principalId: principal.id, authorization, startedAt: 1, + abortController: controller, queue: [] } as unknown as RunningTurn; + const frames: ServerMessage[] = [], raised = Promise.withResolvers(); + const ws = { send(text: string) { + const frame = JSON.parse(text) as ServerMessage; frames.push(frame); + if (frame.type === "tool_approval_request") raised.resolve(); + } }; + host.clients.add(ws, principal.id); + const release = new Int32Array(new SharedArrayBuffer(4)); + let held: Promise | undefined, loss: Promise | undefined, decision: Promise | undefined; + try { + await writes.safetyBegin({ turnId: "voyage", bindingId: "binding-voyage", sessionId: null, + principalId: principal.id, backendId: backend.id, at: 0 }); + const bridge = await makeBridge(host, turn, { promptText: "Return to Ithaca", backendId: backend.id }); + const channel = writer.channel(heldWriter, {}); await channel.ready; + expect(await channel.call("level")).toBe(2); + const entered = new Int32Array(new SharedArrayBuffer(4)); held = channel.call("hold", entered, release); + const waiting = Atomics.waitAsync(entered, 0, 0, 5000); if (waiting.async) await waiting.value; + expect(Atomics.load(entered, 0)).toBe(1); + bridge.emit({ type: "session_info", sessionId: "ithaca", isNew: true }); + expect(bridge.admissionSafety!.read().recordingAvailable).toBe(true); + const before = bridge.admissionSafety!.read(); + decision = bridge.requestPermission({ toolUseId: "raft-write", toolName: "Write", kind: "command", + input: { file_path: "notes/raft.md", content: "Odysseus repairs the raft." } }); + expect(frames.some(frame => frame.type === "tool_approval_request"), "FIRST_CARD_WAITS_FOR_OWN_BINDING").toBe(false); + if (mode === "recording loss") { + loss = writes.safetyFail("another-turn"); + expect(controller.signal.aborted).toBe(false); + } else if (mode === "revocation") authorization.valid = false; + else if (mode === "cancellation") controller.abort(); + Atomics.store(release, 0, 1); Atomics.notify(release, 0); await held; await writer.idle(); + if (mode === "healthy") { + const deadline = setTimeout(() => raised.reject(new Error("Bound approval did not appear")), 2000); + try { await raised.promise; } finally { clearTimeout(deadline); } + expect(host.coordinator.pendingApprovals.has("raft-write"), "HEALTHY_FIRST_CARD_SURVIVES_OWN_BINDING").toBe(true); + const current = bridge.admissionSafety!.read(); + expect(current.scope).not.toBe(before.scope); + expect(host.coordinator.pendingApprovals.get("raft-write")!.request.admissionSnapshot).toEqual(current); + await handleToolApproval({ host, ws, requireEcho: true, connection: { principal, authorization } } as never, + { type: "tool_approval", toolUseId: "raft-write", turnId: "voyage", channel: "card" }); + } + const result = await decision; + if (result.behavior === "allow") { + mkdirSync(join(root, "notes")); writeFileSync(join(root, "notes/raft.md"), "Odysseus repairs the raft."); + } + expect(result.behavior).toBe(mode === "healthy" ? "allow" : "deny"); + expect(existsSync(join(root, "notes/raft.md")), "POST_BINDING_LOSS_OR_REVOCATION_RUNS_NOTHING").toBe(mode === "healthy"); + if (mode !== "healthy") expect(frames.some(frame => frame.type === "tool_approval_request")).toBe(false); + // The scripted backend did not claim detector completeness. + expect(writes.safety("voyage", "ithaca").restriction).toBe("restricted"); + } finally { + Atomics.store(release, 0, 1); Atomics.notify(release, 0); controller.abort(); + await host.close(); await Promise.allSettled([held, loss, decision]); authorization.release(); + await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); + } + }); +} From b869be30be0fe477fdba3494125e1153264a0a80 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 06:30:02 +0000 Subject: [PATCH 5/8] CONTRACT: settle turn proxy records before relay admission --- .changeset/live-effective-safety.md | 2 + docs/integration-contract/package-api.md | 6 + docs/plans/reviewable-session-safety.md | 4 +- packages/ui-server/src/brain/turn-egress.ts | 22 +++- .../tests/relay-recording-settlement.test.ts | 116 ++++++++++++++++++ 5 files changed, 148 insertions(+), 2 deletions(-) create mode 100644 packages/ui-server/tests/relay-recording-settlement.test.ts diff --git a/.changeset/live-effective-safety.md b/.changeset/live-effective-safety.md index 95f2205120..4fa4815ac8 100644 --- a/.changeset/live-effective-safety.md +++ b/.changeset/live-effective-safety.md @@ -12,3 +12,5 @@ Fence parallel Claude hook waits and direct host approvals, and retain claimed-c Fence host publication after application/policy locks and related effect waits, while preserving principal epochs, completed per-use approvals and frozen ordinary policy. Wait for initial session identity binding before capturing an approval card's safety snapshot; recheck recorder health and authority after that bounded wait. + +Let inference and provider relay admission join their own turn proxy's submitted terminal records before reading fresh safety state. Keep that wait cancellable and continue refusing independent pending input, recorder loss and revoked authority. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 089f517005..94444e955c 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4890,6 +4890,12 @@ Recorder health remains separate from principal lifetime and does not rotate the authority epoch or reload ordinary policy. Completed per-use approvals retain their existing scope; pending input or recording loss cannot authorize a new irreversible publication. +Inference and provider relays wait for their turn proxy's already submitted +egress records before taking a fresh admission snapshot. This cancellable +settlement prevents a completed connection's pending exposure commit from +spuriously refusing the next model request. It excludes no occurrence and +grants no authority: independent pending input, recorder loss and revoked +authority still refuse, with final dispatch checks after later waits. Absent input retains the existing taint callback fallback and grants no new capability. The live trust input is revision/notification only; matching and publication have separate implementations. See the [effective admission diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index ea88ef5d5b..e616f90c3c 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -36,7 +36,9 @@ public design or its fixtures. Fictional examples use the Odysseus world. never prove finalized delivery or complete coverage. - The turn proxy records each admitted non-provider connection and terminal exposure observation (`prepareTurnEgress`, - `packages/ui-server/src/brain/turn-egress.ts:83-242`). A raw CONNECT reveals + `packages/ui-server/src/brain/turn-egress.ts:83-269`). Relay admissions join + this proxy's submitted terminal observations before reading fresh safety, + without excluding independent pending input. A raw CONNECT reveals only an authority and opaque bytes, not a repository path or inner protocol (`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:124-359`). - Outward decisions read session taint at admission (`prepareOutwardPlan`, diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index 8337dc66f2..dcd4156036 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -245,5 +245,25 @@ export async function prepareTurnEgress(options: { emit(message) { calls.emitted(message); original.emit(message); }, activity(event) { calls.activity(event); original.activity?.(event); }, }; - return { ...proxy, bridge, recordingFailure: () => recordingFailure, settled }; + const relayOperation = (kind: "inference" | "relayed", method: string, target: URL, signal: AbortSignal) => { + const operation = proxy[kind](method, target, signal); + return { ...operation, async admit() { + // A completed worker connection may still be committing its terminal + // exposure. Join only this turn proxy's submitted records before taking + // a fresh admission snapshot; independent pending input still refuses. + if (operation.signal.aborted) return false; + let abort: (() => void) | undefined; + try { + const ready = await Promise.race([settled().then(() => true), new Promise(resolve => { + abort = () => resolve(false); + operation.signal.addEventListener("abort", abort, { once: true }); + if (operation.signal.aborted) resolve(false); + })]); + return ready && !operation.signal.aborted && await operation.admit(); + } finally { if (abort) operation.signal.removeEventListener("abort", abort); } + } }; + }; + return { ...proxy, bridge, recordingFailure: () => recordingFailure, settled, + inference: (method: string, target: URL, signal: AbortSignal) => relayOperation("inference", method, target, signal), + relayed: (method: string, target: URL, signal: AbortSignal) => relayOperation("relayed", method, target, signal) }; } diff --git a/packages/ui-server/tests/relay-recording-settlement.test.ts b/packages/ui-server/tests/relay-recording-settlement.test.ts new file mode 100644 index 0000000000..fe0b070161 --- /dev/null +++ b/packages/ui-server/tests/relay-recording-settlement.test.ts @@ -0,0 +1,116 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { request } from "node:http"; +import { resolveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import { startInferenceRelay, startProviderRelay } from "@schlessera/brain-ui-sdk/internal"; +import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { prepareTurnEgress } from "../src/brain/turn-egress"; +import { createUiDb } from "../src/db/client"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createEffectiveSafety } from "../src/governance/effective-safety"; +import { createGovernanceWrites } from "../src/governance/event-writes"; +import { occurrence } from "../src/governance/occurrence"; +import { queryGovernanceEvents } from "../src/governance/events"; +import { connectedSafetySession } from "./helpers/connected-safety"; +import * as heldWriter from "./fixtures/held-publication-writer"; + +function exchange(socketPath: string, path: string, method = "GET", headers: Record = {}, body = "") { + return new Promise((resolve, reject) => { + const child = request({ socketPath, path, method, headers }, response => { + response.resume(); response.once("end", () => resolve(response.statusCode!)); response.once("error", reject); + }); + child.once("error", reject); child.end(body); + }); +} + +for (const kind of ["inference", "provider"] as const) { + for (const mode of ["healthy", "shared loss", "independent pending", "revocation", "cancellation"] as const) { + test(`${kind} joins its own completed egress recording before admission: ${mode}`, async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-relay-settlement-")), db = createUiDb(join(root, "ui.db")); + connectedSafetySession(db, "ithaca", "voyage"); + const writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer), controller = new AbortController(); + const channel = writer.channel(heldWriter, {}); await channel.ready; + expect(await channel.call("level")).toBe(2); + const entered = new Int32Array(new SharedArrayBuffer(4)), release = new Int32Array(new SharedArrayBuffer(4)); + const otherEntered = new Int32Array(new SharedArrayBuffer(4)), otherRelease = new Int32Array(new SharedArrayBuffer(4)); + const binding = (db.query("SELECT id FROM safety_collections WHERE turn_id='voyage'").get() as { id: string }).id; + const submitted = Promise.withResolvers(); + let held: Promise | undefined, otherHeld: Promise | undefined, pending: Promise | undefined, authority = true, upstream = 0; + const safety = createEffectiveSafety(db, { turnId: "voyage", sessionId: () => "ithaca", policyHash: null, writes, + authority: () => ({ current: authority, epoch: authority ? "0" : "1" }) }); + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { + if (request.method === "POST") { upstream++; await request.arrayBuffer(); return Response.json({ candidates: [] }); } + return new Response("Ithaca"); + } }); + const proxy = await prepareTurnEgress({ controller, policy: resolveGovernancePolicy({ schema_version: 1 }), + turnId: "voyage", sessionId: () => "ithaca", model: () => null, profile: "governed", origin: "interactive", + bridge: { admissionSafety: safety, emit() {}, requestPermission: async () => ({ behavior: "deny" }) } as unknown as BackendBridge, + governanceDb: db, governanceWrites: writes, record(event) { + // Hold the real FULL transaction just before terminal exposure storage, + // after the worker has received its HTTP body, as in the native failure. + if (event.kind === "taint_exposure" && !held) { + held = channel.call("hold", entered, release); + const result = writes.record(event).then(value => { + if (mode === "independent pending") { + // This separate ingestion stays held after the proxy's own + // exposure has committed. It is outside proxy.settled(). + otherHeld = channel.call("hold", otherEntered, otherRelease); + pending = writes.firstTaint({ turnId: "voyage", sessionId: "ithaca", actor: "interactive", model: null, profile: "governed", + kind: "taint", payload: { source: "web_fetch", tool: "WebFetch", detail: null, + occurrence: occurrence(binding, "tool_web_input", "other-input", "open") } }); + } + return value; + }); + submitted.resolve(); return result; + } + return writes.record(event); + } }); + const path = kind === "inference" ? "/v1/messages" : "/v1beta/models/gemini-2.5-flash:generateContent"; + const relay = kind === "inference" + ? startInferenceRelay({ upstream: origin.url.origin, routes: [path], credentials: { "x-api-key": "odysseus-host-key" }, egress: proxy }) + : startProviderRelay({ egress: proxy, credential: name => name === "GEMINI_API_KEY" ? "odysseus-host-key" : undefined, + origins: new Map([["GEMINI_API_KEY", [origin.url.origin]]]) }); + let dispatch: Promise | undefined; + try { + expect(await exchange(proxy.socketPath, origin.url.href)).toBe(200); + await submitted.promise; + const waiting = Atomics.waitAsync(entered, 0, 0, 5000); if (waiting.async) await waiting.value; + expect(Atomics.load(entered, 0)).toBe(1); + expect(safety.read().recordingAvailable).toBe(false); + const body = JSON.stringify({ contents: [{ parts: [{ text: "Rank the harbours of Ithaca." }] }] }); + const headers = { "content-type": "application/json", "content-length": String(Buffer.byteLength(body)), + ...(kind === "provider" ? { "x-brain-provider": "gemini", "x-brain-provider-key": "GEMINI_API_KEY", "x-brain-provider-origin": origin.url.origin } : {}) }; + let completed = false; + dispatch = exchange(relay.socketPath, path, "POST", headers, body).then(status => { completed = true; return status; }); + await Bun.sleep(30); + expect(completed, "RELAY_WAITS_FOR_OWN_EGRESS_RECORDING").toBe(false); + expect(upstream).toBe(0); + if (mode === "shared loss") pending = writes.safetyFail("other-turn"); + else if (mode === "revocation") authority = false; + else if (mode === "cancellation") controller.abort(); + if (mode === "cancellation") { + const status = await Promise.race([dispatch, Bun.sleep(1000).then(() => { throw new Error("Relay cancellation waited for SQLite"); })]); + expect(status).toBe(499); + } + Atomics.store(release, 0, 1); Atomics.notify(release, 0); + await held; + const status = await dispatch; + expect(status, "SETTLED_HEALTHY_RELAY_CONTINUES_WITHOUT_RETRY").toBe(mode === "healthy" ? 200 : mode === "cancellation" ? 499 : 403); + expect(upstream, "ADVERSE_RELAY_RUNS_NOTHING").toBe(mode === "healthy" ? 1 : 0); + if (mode === "independent pending") expect(safety.read().recordingAvailable).toBe(false); + Atomics.store(otherRelease, 0, 1); Atomics.notify(otherRelease, 0); + await otherHeld; await pending; await proxy.settled(); + expect(writes.safety("voyage", "ithaca").restriction).toBe("restricted"); + expect(queryGovernanceEvents(db, { kinds: ["taint_exposure"], limit: 10 }).map(row => row.payload), + "RELAY_SETTLEMENT_PRESERVES_EXPOSURE").toMatchObject([{ state: "finalized" }]); + } finally { + Atomics.store(release, 0, 1); Atomics.notify(release, 0); controller.abort(); + Atomics.store(otherRelease, 0, 1); Atomics.notify(otherRelease, 0); + await relay.stop(); proxy.stop(); await Promise.allSettled([held, otherHeld, pending, dispatch]); + await proxy.settled(); origin.stop(true); await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); + } + }); + } +} From aae9a89cb7ce0defcc0ccc290a694738f112e9aa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 07:04:29 +0000 Subject: [PATCH 6/8] test: run matching Claude hooks in application fixture --- .../tests/brain-application-adapters.test.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/ui-server/tests/brain-application-adapters.test.ts b/packages/ui-server/tests/brain-application-adapters.test.ts index e2fa05bc38..7adb918803 100644 --- a/packages/ui-server/tests/brain-application-adapters.test.ts +++ b/packages/ui-server/tests/brain-application-adapters.test.ts @@ -8,6 +8,8 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { createKeyedLock, type BackendBridge, type BrainApplicationResult } from "@schlessera/brain-ui-sdk/server"; import { createClaudeBackend } from "../../ui-backend-claude/src/backend.js"; import { createClaudeSdkTurn } from "../../ui-backend-claude/src/sdk-options.js"; +import { createTurnLockBinding } from "../../ui-backend-claude/src/turn-lock.js"; +import { runToolCall } from "../../ui-backend-claude/tests/helpers/run-tool-call.js"; import { DEFAULT_ALLOWED_TOOLS, VOICE_ALLOWED_TOOLS } from "../../ui-backend-claude/src/tool-policy.js"; import { createPiBackend } from "../../ui-backend-pi/src/backend.js"; import { createBrainTools, toolLockFromKeyed } from "../../ui-backend-pi/src/tools.js"; @@ -91,23 +93,23 @@ async function adapter(kind: "claude" | "pi", voice = false) { awaitIndex: async name => { if (!readsIndex(name)) return; if (index.pending()) indexRuns++; await index.barrier(); } }; const search = async (query: string) => (await createBrainAccess(root).search({ query, limit: 50 })).results.map(result => result.path); if (kind === "claude") { + const turnLock = createTurnLockBinding({ turn: { ended: false, pendingReleases: new Map() }, + writeLock: createKeyedLock(), lockWaitMs: 1000, log() {} }); + closes.push(async () => turnLock.close()); const { options } = createClaudeSdkTurn({ backend: { brainPath: root }, req: { prompt: "Odysseus repairs a raft", signal: new AbortController().signal, bridge, ...(voice ? { posture: "voice", noGrantSurface: true, enforceAllowedTools: true } : {}) }, profile: { requiredEnvKeys: [], buildEnv: () => ({}) } as never, abortController: new AbortController(), allowedTools: voice ? VOICE_ALLOWED_TOOLS : DEFAULT_ALLOWED_TOOLS, - confirmPatterns: [], turnLock: { acquire: () => {}, release: () => {} } as never, log: () => {} }); + confirmPatterns: [], turnLock, log: () => {} }); const client = new Client({ name: "hosted-application", version: "0.1.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const server = options.mcpServers!["brain-ui"] as { instance: { connect(t: unknown): Promise } }; await server.instance.connect(serverTransport); await client.connect(clientTransport); closes.push(() => client.close()); - // The runtime's admission of a tool: every unmatched PreToolUse hook, as the SDK runs them. + // The runtime runs all matching PreToolUse hooks in parallel, including + // the brain MCP hook that owns the final index barrier after its lock wait. const admit = async (name: string) => { - for (const matcher of options.hooks!.PreToolUse!.filter(entry => !entry.matcher)) for (const hook of matcher.hooks) { - const output = await hook({ hook_event_name: "PreToolUse", tool_name: name, tool_input: { query: "raft" }, tool_use_id: `admit-${name}`, - session_id: "hosted", transcript_path: "", cwd: root } as never, `admit-${name}`, { signal: new AbortController().signal }) as { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string } }; - if (output.hookSpecificOutput?.permissionDecision === "deny") return { allowed: false, message: output.hookSpecificOutput.permissionDecisionReason }; - } - return { allowed: true }; + const result = await runToolCall(options, name, { query: "raft" }, `admit-${name}`); + return result.executed ? { allowed: true } : { allowed: false, message: result.message }; }; return { options, approvals, receipts, indexFailure, admit, search, indexRuns: () => indexRuns, tools: (await client.listTools()).tools.map(t => t.name), call: async (name: string, input: Record) => { From 3bccc96c9b6d1d4c4adea82d411ce5dc3a3b2ff0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 15:23:54 +0000 Subject: [PATCH 7/8] CONTRACT: isolate admission revisions to canonical session evidence --- .changeset/live-effective-safety.md | 2 + docs/decisions/session-safety-reviews.md | 7 + docs/integration-contract/package-api.md | 9 + .../src/governance/effective-safety.ts | 49 ++++-- .../ui-server/src/governance/event-writes.ts | 50 ++++-- .../ui-server/src/governance/safety-store.ts | 48 +++-- .../tests/approval-scope-isolation.test.ts | 164 ++++++++++++++++++ .../ui-server/tests/safety-ledger.test.ts | 15 ++ .../ui-server/tests/safety-reviews.test.ts | 49 +++++- 9 files changed, 353 insertions(+), 40 deletions(-) create mode 100644 packages/ui-server/tests/approval-scope-isolation.test.ts diff --git a/.changeset/live-effective-safety.md b/.changeset/live-effective-safety.md index 4fa4815ac8..cf13040133 100644 --- a/.changeset/live-effective-safety.md +++ b/.changeset/live-effective-safety.md @@ -14,3 +14,5 @@ Fence host publication after application/policy locks and related effect waits, Wait for initial session identity binding before capturing an approval card's safety snapshot; recheck recorder health and authority after that bounded wait. Let inference and provider relay admission join their own turn proxy's submitted terminal records before reading fresh safety state. Keep that wait cancellable and continue refusing independent pending input, recorder loss and revoked authority. + +Keep pending approvals stable across unrelated sessions by scoping host admission revisions to canonical safety evidence. Continue withdrawing on same-cursor history adoption, exposure appends, provisional pending input and shared recorder loss; preserve brain-wide history/review cursors and existing capacity limits. diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index 9627292b2a..6332f1bb63 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -114,6 +114,13 @@ irreversible dispatch, after every async wait. Pending input restricts immediately; pending verdict never loosens before commit. Preserve original journal/egress facts and historical approvals. +Admission's evidence revision follows the canonical session scope. Brain-wide +history/review revision changes from unrelated sessions retain pending authority. +Read the scoped aggregate, immutable append sequence and membership together; +history adoption and local pending/loss changes advance admission even when the +global cursor does not. Pending-input overlays and capacity grouping use the +same retained aliases. The history/review cursor keeps its existing meaning. + Only effective taint and the trust slice update live. Ordinary governance budgets, profiles and commands keep turn-bound semantics. Trust removal fences new active-turn dispatch before its enforcing receipt; ongoing input must split diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index c6e1ccb1d5..98b45ab63b 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4894,6 +4894,15 @@ binding before taking the first card snapshot. This wait is bounded and cancellable; health and authority are checked again afterward. A healthy first card therefore survives its own binding, while later changes still withdraw stale authority. +Admission evidence revisions are monotonic within the host's canonical safety +scope, independently of the brain-wide history/review cursor. Unrelated sessions +do not withdraw a pending approval. Own immutable lifecycle appends, canonical +history adoption, locally pending input and shared recorder loss still invalidate +it, including changes that leave the unresolved aggregate or global cursor +unchanged. Projection, membership and latest scoped sequence are read from one +SQLite snapshot; revision exhaustion refuses admission. Pending-input reads and +capacity checks include retained provisional aliases before their SQL reservation +commits. HTTP/WS history cursors and review request revisions remain brain-wide. First-party backend gates additionally revalidate in their final dispatch continuations after locks, index barriers and occurrence writes. Every Claude pre-tool hook fences its own final asynchronous wait, including parallel diff --git a/packages/ui-server/src/governance/effective-safety.ts b/packages/ui-server/src/governance/effective-safety.ts index afcb3014fc..cec94b1bec 100644 --- a/packages/ui-server/src/governance/effective-safety.ts +++ b/packages/ui-server/src/governance/effective-safety.ts @@ -1,8 +1,8 @@ /** One live read for enforcement; ordinary governance remains turn-bound. */ import type { AdmissionSafety } from "@schlessera/brain-ui-sdk/internal"; -import type { Database } from "bun:sqlite"; +import { Database } from "bun:sqlite"; import type { GovernanceWrites } from "./event-writes.js"; -import { safetyProjection } from "./safety-store.js"; +import { safetyEvidenceSequence, safetyProjection, safetyScopeTurns } from "./safety-store.js"; import { safetyQueue } from "./safety-queue.js"; /** Concrete input from the host's future trust publisher, not a policy loader or matcher. */ @@ -19,18 +19,43 @@ export function createEffectiveSafety(db: Database, options: { trust?: LiveTrustRevision; signal?: AbortSignal; }): AdmissionSafety { + let observed: string | undefined, evidenceRevision = "0", lastGlobalRevision = 0n; + const read = () => { + const sessionId = options.sessionId(); + const projection = options.writes?.safety(options.turnId, sessionId) ?? safetyProjection(db, options.turnId, sessionId); + const sequence = safetyEvidenceSequence(db, options.turnId, sessionId); + const membership = safetyScopeTurns(db, options.turnId, sessionId).size; + const authority = options.authority(), trustRevision = options.trust?.revision() ?? "0"; + for (const revision of [projection.evidenceRevision, sequence, trustRevision, authority.epoch]) { + if (!/^(0|[1-9][0-9]{0,19})$/.test(revision) || BigInt(revision) > 18446744073709551615n) throw new Error("Invalid live safety revision"); + } + const global = BigInt(projection.evidenceRevision); + if (global < lastGlobalRevision) throw new Error("Safety evidence revision moved backwards"); + // The history cursor is brain-wide. Admission advances only when this + // bounded canonical scope changes, including same-aggregate appends from + // another FULL writer. Local pending/failure flags remain in the marker; + // shared recorder loss therefore still withdraws unrelated approvals. + const evidence = { ...projection, evidenceRevision: undefined }; + const marker = JSON.stringify([evidence, sequence, membership]); + if (marker !== observed) { + // Durable alias adoption and local pending/loss overlays can change this + // scope without changing the history cursor. Keep a separate monotonic + // admission revision; it is never a history/review cursor. + const next = observed === undefined ? global : (global > BigInt(evidenceRevision) ? global : BigInt(evidenceRevision) + 1n); + if (next > 18446744073709551615n) throw new Error("Safety admission revision exhausted"); + evidenceRevision = next.toString(); observed = marker; + } + lastGlobalRevision = global; + 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)), + authorityCurrent: authority.current }; + }; return { read() { - const projection = options.writes?.safety(options.turnId, options.sessionId()) ?? safetyProjection(db, options.turnId, options.sessionId()); - const authority = options.authority(), trustRevision = options.trust?.revision() ?? "0"; - for (const revision of [trustRevision, authority.epoch]) { - if (!/^(0|[1-9][0-9]{0,19})$/.test(revision) || BigInt(revision) > 18446744073709551615n) throw new Error("Invalid live safety revision"); - } - return { evidenceRevision: projection.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)), - authorityCurrent: authority.current }; + // Projection and immutable sequence must describe one SQLite snapshot. + return db.inTransaction ? read() : Database.prototype.transaction.call(db, read).deferred() as ReturnType; }, subscribe(changed) { const listeners = safetyQueue(db).listeners; diff --git a/packages/ui-server/src/governance/event-writes.ts b/packages/ui-server/src/governance/event-writes.ts index e61fffe5de..7df1c8e203 100644 --- a/packages/ui-server/src/governance/event-writes.ts +++ b/packages/ui-server/src/governance/event-writes.ts @@ -9,8 +9,8 @@ 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, type SafetyCollectionInput, type SafetyProjection } from "./safety-store.js"; -import type { Database } from "bun:sqlite"; + ensureSafetyEventCollection, latchSafety, SafetyUnavailable, safetyScopeTurns, type SafetyCollectionInput, type SafetyProjection } from "./safety-store.js"; +import { Database } from "bun:sqlite"; import {assertLive,ChatRetiredError} from "../ws/chat-lifecycle.js"; import { procedureCaller, type SqliteWriter, type WriteProcedures } from "../db/write-worker.js"; @@ -92,6 +92,12 @@ export interface GovernanceWrites { export function createGovernanceWrites(db: Database, writer?: SqliteWriter): GovernanceWrites { const invoke = procedureCaller(db, { url, setup }, undefined, writer); const shared=safetyQueue(db),pendingTaints=shared.pending; + const snapshot=(read:()=>T):T=>db.inTransaction?read():Database.prototype.transaction.call(db,read).deferred() as T; + const pendingInScope=(turnId:string|null,sessionId:string|null)=>{ + if(!pendingTaints.size)return []; + const turns=safetyScopeTurns(db,turnId,sessionId); + return [...pendingTaints].filter(p=>(p.turnId!==null&&turns.has(p.turnId))||(sessionId!==null&&p.sessionId===sessionId)); + }; const call:typeof invoke=(name:string,...args:unknown[])=>{ shared.inflight++; return invoke(name,...args).finally(()=>{shared.inflight--;notifySafetyChanged(db);}); @@ -105,7 +111,8 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov 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 bytes = Buffer.byteLength(JSON.stringify(row))+1024; - const session = [...pendingTaints].filter(p => row.sessionId !== null ? p.sessionId === row.sessionId : p.turnId === row.turnId); + 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(()=>{}); @@ -122,33 +129,42 @@ export function createGovernanceWrites(db: Database, writer?: SqliteWriter): Gov return { record, safetyPrepareReview: (body,actor)=>call("safetyPrepareReview",body,actor), - safetyCommitReview: (id,body,actor)=>call("safetyCommitReview",id,body,actor,[...pendingTaints].some(p=>p.sessionId===body.session.sessionId),shared.failed), + safetyCommitReview(id,body,actor){ + let pending=true; + try {pending=snapshot(()=>pendingInScope(null,body.session.sessionId).length>0);} + 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);}, safetyReady: (turnId,backendId,version)=>call("safetyReady",turnId,backendId,version), safetyEnd: turnId=>call("safetyEnd",turnId,shared.unscopedLoss||shared.lostTurns.has(turnId)), safetyFail, - safety: (turnId,sessionId)=>{ + safety: (turnId,sessionId)=>snapshot(()=>{ const projection=safetyProjection(db,turnId,sessionId); - const local=[...pendingTaints].filter(p=>(turnId!==null&&p.turnId===turnId)||(sessionId!==null&&p.sessionId===sessionId)).length; + const local=pendingInScope(turnId,sessionId).length; if(local||shared.failed){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");}} return projection; - }, + }), recordingAvailable(turnId,sessionId){ - if(shared.failed||[...pendingTaints].some(p=>(turnId!==null&&p.turnId===turnId)||(sessionId!==null&&p.sessionId===sessionId)))return false; - const state=safetyProjection(db,turnId,sessionId); - return !state.reasons.some(reason=>["recording_failed","recording_pending","capacity"].includes(reason)); + return snapshot(()=>{ + if(shared.failed||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), taint(turnId, sessionId) { - if (shared.failed) return { eventId: 0, source: "legacy_unknown" }; - const committed = sessionTaint(db, turnId, sessionId); - if (committed && committed.eventId>0) return committed; - for (const pending of pendingTaints) { - if ((turnId !== null && pending.turnId === turnId) || (sessionId !== null && pending.sessionId === sessionId)) return { eventId: 0, source: pending.source }; - } - return committed; + return snapshot(()=>{ + if (shared.failed) 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]; + if(pending)return {eventId:0,source:pending.source}; + return committed; + }); }, bind: async (turnId, sessionId) => { const bound = await call("bind", turnId, sessionId); diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index fbbc7058e0..750aa6a54c 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -51,11 +51,12 @@ function live(db:Database,c:Collection,reserved=false):void { } function capacity(db:Database,c:Collection,rows:number,bytes:number):void { const all=meta(db); + const {scope,args}=safetyScope(db,c.turn_id,c.session_id); const used=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 (? IS NOT NULL AND c.session_id=?) OR c.id=?`,c.session_id,c.session_id,c.id); + FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE ${scope}`,...args); 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 x ON x.id=p.collection_id WHERE (? IS NOT NULL AND x.session_id=?) OR x.id=?`,c.session_id,c.session_id,c.id); + FROM safety_pending p JOIN safety_collections c ON c.id=p.collection_id WHERE ${scope}`,...args); if(all.used_rows+all.scope_rows+pending.rows+rows>SAFETY_LIMITS.brainRows||all.used_bytes+all.scope_bytes+pending.bytes+bytes>SAFETY_LIMITS.brainBytes ||used.rows+localPending.rows+rows>SAFETY_LIMITS.sessionRows||used.bytes+localPending.bytes+bytes>SAFETY_LIMITS.sessionBytes) throw new SafetyUnavailable("Safety ledger capacity exhausted"); @@ -148,13 +149,14 @@ export function bindSafetyCollection(db:Database,turnId:string,sessionId:string) const owner=d?.id??retained?.id??s.history_owner_id,gen=d?actualGeneration(d.generation):retained?actualGeneration(retained.generation):s.generation; if(retained&&actualGeneration(retained.generation)!==c.generation)throw new SafetyUnavailable("Safety history generation changed"); assertLive(db,[["session",sessionId],["dialogue_owner",owner]]); - const epochs=one<{n:number}>(db,"SELECT COUNT(*) n FROM safety_collections WHERE session_id=? OR id=?",sessionId,c.id); + 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"); 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 c.session_id=? OR c.id=?`,sessionId,c.id); + 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 c.session_id=? OR c.id=?`,sessionId,c.id); + 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"); const previous=one<{session_id:string;history_owner_id:string;generation:string}|null>(db,"SELECT * FROM safety_bindings WHERE turn_id=?",turnId); @@ -233,14 +235,39 @@ export function safetyProjection(db:Database,turnId:string|null,sessionId:string if(db.inTransaction)return readSafetyProjection(db,turnId,sessionId); return Database.prototype.transaction.call(db,()=>readSafetyProjection(db,turnId,sessionId)).deferred() as SafetyProjection; } -function readSafetyProjection(db:Database,turnId:string|null,sessionId:string|null):SafetyProjection { +function safetyScope(db:Database,turnId:string|null,sessionId:string|null) { const s=sessionId?one(db,"SELECT * FROM safety_sessions WHERE session_id=?",sessionId):null; const target=turnId?collection(db,turnId):null; - const owner=s?.history_owner_id??target?.history_owner_id??null,generation=s?.generation??target?.generation??"1"; - assertLive(db,[["session",sessionId],["dialogue_owner",owner]]); + const retainedOwner=s?.history_owner_id??target?.history_owner_id??null,generation=s?.generation??target?.generation??"1"; + const owner=retainedOwner?one<{owner_id:string}|null>(db,"SELECT owner_id FROM dialogue_aliases WHERE id=?",retainedOwner)?.owner_id??retainedOwner:null; + assertLive(db,[["session",sessionId],["dialogue_owner",retainedOwner],["dialogue_owner",owner]]); const scope=`((? IS NOT NULL AND c.session_id=?) OR c.turn_id=? OR (? IS NOT NULL AND c.generation=? AND (c.history_owner_id=? OR c.history_owner_id IN (SELECT id FROM dialogue_aliases WHERE owner_id=?))))`; const args=[sessionId,sessionId,turnId,owner,generation,owner,owner]; + return {s,scope,args}; +} +/** Pending input uses the aggregate's durable canonical membership, even before + * its own reservation commits. Include an unbound turn with no collection yet. */ +export function safetyScopeTurns(db:Database,turnId:string|null,sessionId:string|null):Set { + const {scope,args}=safetyScope(db,turnId,sessionId); + const turns=new Set(db.query<{turn_id:string},(string|null)[]>(`SELECT c.turn_id FROM safety_collections c WHERE ${scope}`).all(...args).map(c=>c.turn_id)); + if(turnId!==null)turns.add(turnId); + return turns; +} +/** Last immutable append in the same canonical scope as the aggregate. */ +export function safetyEvidenceSequence(db:Database,turnId:string|null,sessionId:string|null):string { + const {scope,args}=safetyScope(db,turnId,sessionId); + return one<{sequence:string}|null>(db,`SELECT sequence FROM ( + SELECT r.sequence FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE ${scope} + UNION ALL SELECT d.sequence FROM safety_decisions d JOIN safety_records r ON r.id=d.occurrence_id + JOIN safety_collections c ON c.id=r.collection_id WHERE ${scope} + UNION ALL SELECT b.sequence FROM safety_bindings b JOIN safety_collections c ON c.id=b.binding_id WHERE ${scope} + UNION ALL SELECT c.start_revision FROM safety_collections c WHERE ${scope} + UNION ALL SELECT c.end_revision FROM safety_collections c WHERE ${scope} AND c.end_revision IS NOT NULL + ) ORDER BY length(sequence) DESC,sequence DESC LIMIT 1`,...args,...args,...args,...args,...args)?.sequence??"0"; +} +function readSafetyProjection(db:Database,turnId:string|null,sessionId:string|null):SafetyProjection { + const {s,scope,args}=safetyScope(db,turnId,sessionId); const cs=db.query(`SELECT c.* FROM safety_collections c WHERE ${scope} ORDER BY c.rowid`).all(...args) as Collection[]; const epochs=cs.slice(0,128).map(c=>{ const acknowledged=JSON.parse(c.acknowledged) as string[]; @@ -293,8 +320,9 @@ export function reserveSafetyWrite(db:Database,turnId:string,requestId:string,by if(terminalOccurrenceId&&!db.query("SELECT 1 FROM safety_records WHERE id=? AND collection_id=? AND kind='occurrence'").get(terminalOccurrenceId,c.id))throw new SafetyUnavailable("Safety terminal reservation identity mismatch"); const prior=one<{bytes:number}|null>(db,"SELECT bytes FROM safety_pending WHERE id=?",requestId);if(prior){if(prior.bytes!==bytes)throw new SafetyUnavailable("Conflicting safety reservation");return;} const global=one<{n:number;bytes:number}>(db,"SELECT COUNT(*) n,COALESCE(SUM(bytes),0) bytes FROM safety_pending"); - const local=one<{n:number;bytes:number}>(db,`SELECT COUNT(*) n,COALESCE(SUM(p.bytes),0) bytes FROM safety_pending p JOIN safety_collections x ON x.id=p.collection_id - WHERE (? IS NOT NULL AND x.session_id=?) OR x.id=?`,c.session_id,c.session_id,c.id); + const {scope,args}=safetyScope(db,turnId,c.session_id); + 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"); const rows=terminalOccurrenceId?0:4,reserved=terminalOccurrenceId?0:bytes+VERDICT_BYTES+2*TERMINAL_BYTES; diff --git a/packages/ui-server/tests/approval-scope-isolation.test.ts b/packages/ui-server/tests/approval-scope-isolation.test.ts new file mode 100644 index 0000000000..0affaafa2c --- /dev/null +++ b/packages/ui-server/tests/approval-scope-isolation.test.ts @@ -0,0 +1,164 @@ +/** Pending cards follow their canonical safety scope; real FULL writers and replies. */ +import { expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { PermissionDecision } from "@schlessera/brain-ui-sdk/server"; +import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { createUiDb } from "../src/db/client"; +import { createPrincipal } from "../src/db/principals"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { createGovernanceWrites } from "../src/governance/event-writes"; +import { occurrence } from "../src/governance/occurrence"; +import { queryGovernanceEvents } from "../src/governance/events"; +import { createActivityStore } from "../src/activity/store"; +import { createActivityStream } from "../src/activity/stream"; +import { createModelPricing } from "../src/pricing/model-pricing"; +import { resolveStandalonePricingConfig } from "../src/config/env"; +import { createSessionCatalog } from "../src/ws/session-catalog"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { WsHost } from "../src/ws/host"; +import { makeBridge } from "../src/ws/bridge"; +import type { RunningTurn } from "../src/ws/turns"; +import { handleToolApproval } from "../src/ws/handlers/tool-permission"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import * as heldWriter from "./fixtures/held-publication-writer"; +import { openDialogue, bindDialogue } from "../src/ws/dialogue-storage"; +import { createEffectiveSafety } from "../src/governance/effective-safety"; +import { safetyAdmissionRefusal, STALE_SAFETY_ADMISSION } from "@schlessera/brain-ui-sdk/internal"; + +for (const mode of ["backward cursor", "exhausted admission"] as const) test(`admission revisions fail closed: ${mode}`, async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-scope-revision-")), db = createUiDb(join(root, "ui.db")); + const writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); + let loss: Promise | undefined; + try { + db.exec("UPDATE safety_meta SET revision='18446744073709551615'"); + const safety = createEffectiveSafety(db, { turnId: "voyage", sessionId: () => null, policyHash: null, writes, + authority: () => ({ current: true, epoch: "0" }) }); + expect(safety.read().evidenceRevision).toBe("18446744073709551615"); + if (mode === "backward cursor") db.exec("UPDATE safety_meta SET revision='0'"); + else loss = writes.safetyFail("voyage"); + expect(() => safety.read()).toThrow(mode === "backward cursor" ? "moved backwards" : "revision exhausted"); + expect(safetyAdmissionRefusal(safety), "INVALID_REVISION_NEVER_AUTHORIZES_DISPATCH").toBe(STALE_SAFETY_ADMISSION); + } 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) { + 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); + const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const backend = makeFakeBackend({ id: "scripted-scope" }); + const catalog = createSessionCatalog(() => db, undefined, undefined, { writer, store, governance: writes, + pricing: createModelPricing(resolveStandalonePricingConfig()) }); + const host = new WsHost({ brainPath: root, registry: createStaticBackendRegistry([backend], backend.id), catalog, + isPrincipalAuthorized: id => id === principal.id, + activity: { store, stream: createActivityStream(store), governanceDb: db, governanceWrites: writes } }); + const authorization = host.coordinator.openAuthorization({ principalId: principal.id, valid: true, expiresAt: Number.MAX_SAFE_INTEGER }); + const controller = new AbortController(); + const turn = { sessionId: null, turnId: "voyage", principalId: principal.id, authorization, startedAt: 1, + abortController: controller, queue: [] } as unknown as RunningTurn; + const frames: ServerMessage[] = [], raised = Promise.withResolvers(); + const ws = { send(text: string) { const frame = JSON.parse(text) as ServerMessage; frames.push(frame); + if (frame.type === "tool_approval_request") raised.resolve(); } }; + host.clients.add(ws, principal.id); + let decision: Promise | undefined, externalDb: Database | undefined; + let externalWriter: ReturnType | undefined; + const release = new Int32Array(new SharedArrayBuffer(4)); + let held: Promise | undefined, pending: Promise | undefined; + const add = (target: "voyage" | "other", sessionId: string | null = target === "voyage" ? "ithaca" : "pylos") => writes.firstTaint({ turnId: target, sessionId, + actor: "interactive", model: null, profile: "governed", kind: "taint", payload: { source: "web_fetch", tool: "WebFetch", detail: null, + occurrence: occurrence(`binding-${target}`, "tool_web_input", `notice-${target}`, "open") } }); + const other = async () => { + await writes.safetyBegin({ turnId: "other", bindingId: "binding-other", sessionId: null, + principalId: principal.id, backendId: backend.id, at: 0 }); + const otherTurn = { ...turn, sessionId: null, turnId: "other", queue: [] } as RunningTurn; + const bridge = await makeBridge(host, otherTurn, { promptText: "Nestor reads the harbour.", backendId: backend.id }); + bridge.emit({ type: "session_info", sessionId: "pylos", isNew: true }); + await catalog.settled!(); + expect(writes.safety("voyage", "ithaca").session?.historyOwnerId).toBe("binding-voyage"); + }; + try { + const level = writer.channel(heldWriter, {}); await level.ready; + expect(writer.offloop).toBe(true); expect(await level.call("level")).toBe(2); + await writes.safetyBegin({ turnId: "voyage", bindingId: "binding-voyage", sessionId: null, + principalId: principal.id, backendId: backend.id, at: 0 }); + const bridge = await makeBridge(host, turn, { promptText: "Odysseus repairs the raft.", backendId: backend.id }); + 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 === "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" }); + const scout = openDialogue(db, { conversationId: "scout-voice", principalId: principal.id, epoch: 1, providerId: "voice" }); + await writes.safetyBegin({ turnId: "other", bindingId: "binding-other", sessionId: null, + principalId: principal.id, historyOwnerId: scout.id, backendId: backend.id, at: 0 }); + if (mode === "adoption") await add("other", null); + else bindDialogue(db, "scout-voice", principal.id, "ithaca"); + } + decision = bridge.requestPermission({ toolUseId: "raft-write", toolName: "Write", kind: "command", + input: { file_path: "raft.md", content: "Odysseus repairs the raft." } }); + const timeout = setTimeout(() => raised.reject(new Error("Approval did not appear")), 2000); + try { await raised.promise; } finally { clearTimeout(timeout); } + const before = bridge.admissionSafety!.read(), aggregate = writes.safety("voyage", "ithaca"); + expect(host.coordinator.pendingApprovals.has("raft-write")).toBe(true); + 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 === "adoption") { + bindDialogue(db, "scout-voice", principal.id, "ithaca"); + expect(writes.safety("voyage", "ithaca").evidenceRevision).toBe(aggregate.evidenceRevision); + expect(writes.safety("voyage", "ithaca").unresolvedCount, "ADOPTED_EVIDENCE_JOINS_THE_REQUESTING_SESSION").toBe(1); + expect(BigInt(bridge.admissionSafety!.read().evidenceRevision), "SAME_CURSOR_MEMBERSHIP_ADVANCES_ADMISSION").toBeGreaterThan(BigInt(before.evidenceRevision)); + } else if (mode === "adopted pending") { + const entered = new Int32Array(new SharedArrayBuffer(4)); held = level.call("hold", entered, release); + const waiting = Atomics.waitAsync(entered, 0, 0, 5000); if (waiting.async) await waiting.value; + expect(Atomics.load(entered, 0)).toBe(1); + pending = add("other", null); + expect(writes.safety("voyage", "ithaca").evidenceRevision).toBe(aggregate.evidenceRevision); + expect(host.coordinator.pendingApprovals.has("raft-write"), "ADOPTED_PENDING_INPUT_WITHDRAWS_BEFORE_COMMIT").toBe(false); + expect(writes.recordingAvailable("voyage", "ithaca"), "ADOPTED_PENDING_INPUT_STOPS_PROVIDER_DELIVERY").toBe(false); + expect(writes.taint("voyage", "ithaca"), "ADOPTED_PENDING_INPUT_IS_EFFECTIVE_TAINT").toEqual({ eventId: 0, source: "web_fetch" }); + expect(writes.safety("other", null).pendingCount, "PROVISIONAL_TURN_RESOLVES_CANONICAL_MEMBERSHIP").toBe(1); + Atomics.store(release, 0, 1); Atomics.notify(release, 0); await held; await pending; + } else { + const occurrenceId = (db.query("SELECT id FROM safety_records WHERE kind='occurrence'").get() as { id: string }).id; + const event = { turnId: "voyage", sessionId: "ithaca", actor: "interactive" as const, model: null, profile: "governed" as const, + kind: "taint_exposure" as const, payload: { occurrenceId, state: "finalized" as const } }; + if (mode === "external exposure") { + externalDb = new Database(path); externalWriter = openSqliteWriter(externalDb); + await createGovernanceWrites(externalDb, externalWriter).record(event); + // This process receives no local invalidation hint from the second writer. + expect(host.coordinator.pendingApprovals.has("raft-write")).toBe(true); + const after = writes.safety("voyage", "ithaca"); + expect([after.unresolvedCount, after.earliestUnresolvedId, after.coverage]).toEqual( + [aggregate.unresolvedCount, aggregate.earliestUnresolvedId, aggregate.coverage]); + } else await writes.record(event); + } + await writer.idle(); + const unrelated = mode === "other collection" || mode === "other occurrence"; + if (unrelated) { + expect(writes.safety("voyage", "ithaca").evidenceRevision).not.toBe(aggregate.evidenceRevision); + expect(bridge.admissionSafety!.read(), "UNRELATED_SCOPE_MUST_KEEP_ADMISSION_SNAPSHOT").toEqual(before); + expect(host.coordinator.pendingApprovals.has("raft-write"), "UNRELATED_SESSION_MUST_NOT_WITHDRAW_PENDING_APPROVAL").toBe(true); + } + await handleToolApproval({ host, ws, requireEcho: true, connection: { principal, authorization } } as never, + { type: "tool_approval", toolUseId: "raft-write", turnId: "voyage", channel: "card" }); + const result = await decision; + if (result.behavior === "allow") writeFileSync(join(root, "raft.md"), "Odysseus repairs the raft."); + expect(result.behavior, "ONLY_UNRELATED_EVIDENCE_PRESERVES_APPROVAL").toBe(unrelated ? "allow" : "deny"); + expect(existsSync(join(root, "raft.md")), "SCOPED_APPROVAL_HAS_THE_EXPECTED_FILE_EFFECT").toBe(unrelated); + expect(queryGovernanceEvents(db, { kinds: ["safety_admission_expired"], limit: 10 }), + "RELATED_CHANGE_WITHDRAWS_EXACTLY_ONCE").toHaveLength(unrelated ? 0 : 1); + } finally { + Atomics.store(release, 0, 1); Atomics.notify(release, 0); + controller.abort(); await host.close(); await Promise.allSettled([decision]); authorization.release(); + await Promise.allSettled([held, pending]); + await externalWriter?.close(); externalDb?.close(); await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); + } + }); +} diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 69066db11b..59e65df8a9 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -11,6 +11,7 @@ import { safetyCatalogCreated,safetyProjection,safetyRecords,pruneSafetyDetail } import { governanceEventRow } from "../src/governance/events"; import * as procedures from "../src/governance/event-writes"; import * as decisions from "./fixtures/safety-decision-seed"; +import { openDialogue, bindDialogue } from "../src/ws/dialogue-storage"; function fixture(){const root=mkdtempSync(join(tmpdir(),"odysseus-safety-ledger-")),path=join(root,"ui.db"); const db=createUiDb(path),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); @@ -26,6 +27,20 @@ async function fresh(f:ReturnType,turnId="voyage",sessionId="ith } const triggers=(f:ReturnType,sid="ithaca")=>safetyRecords(f.db,sid).filter(r=>r.kind==="occurrence"); +test("durable pending capacity is shared by a session and its adopted provisional collection",async()=>{ + const f=fixture();try{await fresh(f); + openDialogue(f.db,{conversationId:"target-voice",principalId:"odysseus",epoch:1,providerId:"voice",sessionId:"ithaca"}); + const scout=openDialogue(f.db,{conversationId:"scout-voice",principalId:"odysseus",epoch:1,providerId:"voice"}); + await f.writes.safetyBegin({turnId:"scout",bindingId:"scout-binding",sessionId:null,principalId:"odysseus",historyOwnerId:scout.id,backendId:"claude",at:0}); + bindDialogue(f.db,"scout-voice","odysseus","ithaca"); + const calls=f.writer.channel(procedures,undefined); + const row=(turnId:string)=>governanceEventRow({kind:"taint",turnId,sessionId:turnId==="voyage"?"ithaca":null,actor:"interactive",model:null,profile:null,payload:{source:"web_fetch",tool:"WebFetch",detail:null}}); + for(let n=0;n<256;n++)await calls.call("safetyReserve",row(n%2?"voyage":"scout"),`reserved-${n}`,100); + expect(f.writes.safety("voyage","ithaca").pendingCount).toBe(256); + await expectRejection(calls.call("safetyReserve",row("scout"),"overflow",100),"Safety pending capacity exhausted","ADOPTED_COLLECTION_SHARES_PENDING_LIMIT"); + expect(f.db.query("SELECT COUNT(*) n FROM safety_pending").get()).toEqual({n:256}); + }finally{await f.close();}}); + test("complete durable aggregate retains B/C after a committed decision for A, independently of pruned pages",async()=>{ const f=fixture();try{const {collector}=await fresh(f); expect(f.writes.safety("voyage","ithaca").restriction,"SAFETY_NEW_CONNECTED_COLLECTION_CAN_BE_NORMAL").toBe("normal"); diff --git a/packages/ui-server/tests/safety-reviews.test.ts b/packages/ui-server/tests/safety-reviews.test.ts index 407c8b484a..443d492a53 100644 --- a/packages/ui-server/tests/safety-reviews.test.ts +++ b/packages/ui-server/tests/safety-reviews.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { createUiDb } from "../src/db/client"; import { createPrincipal } from "../src/db/principals"; -import { openSqliteWriter } from "../src/db/write-worker"; +import { openSqliteWriter, type SqliteWriter } from "../src/db/write-worker"; import { createGovernanceWrites } from "../src/governance/event-writes"; import * as procedures from "../src/governance/event-writes"; import * as probe from "./fixtures/write-worker-probe"; @@ -18,6 +18,8 @@ import { retireChat } from "../src/ws/chat-lifecycle"; import { cleanChatStore } from "../src/ws/chat-store-cleanup"; import type { SafetyReviewBody, SafetyReviewReceipt, SafetyReviewer } from "../src/governance/safety-reviews"; import { expectRejection } from "./helpers/expect-rejection"; +import { openDialogue, bindDialogue } from "../src/ws/dialogue-storage"; +import * as heldWriter from "./fixtures/held-publication-writer"; async function fixture() { const root = mkdtempSync(join(tmpdir(), "odysseus-safety-reviews-")), path = join(root, "ui.db"); @@ -75,6 +77,51 @@ test("individual committed A/B/C verdicts preserve same-source restrictions inde } finally { await f.close(); } }); +test("a queued review sees adopted provisional input before its reservation commits", async () => { + const f = await fixture(), release = new Int32Array(new SharedArrayBuffer(4)); + const submitReservation = Promise.withResolvers(); + let held: Promise | undefined, pending: Promise | undefined; + try { + const id = await f.add("A"); + openDialogue(f.db, { conversationId: "target-voice", principalId: f.actor.principalId, epoch: 1, providerId: "voice", sessionId: "ithaca" }); + const scout = openDialogue(f.db, { conversationId: "scout-voice", principalId: f.actor.principalId, epoch: 1, providerId: "voice" }); + await f.writes.safetyBegin({ turnId: "scout", bindingId: "scout-binding", sessionId: null, + historyOwnerId: scout.id, principalId: f.actor.principalId, backendId: "claude", at: 0 }); + await f.writes.safetyReady("scout", "claude", 1); + bindDialogue(f.db, "scout-voice", f.actor.principalId, "ithaca"); + const body = f.body(id), prepared = await f.writes.safetyPrepareReview(body, f.actor); + expect(prepared.stage).toBe("prepared"); + const channel = f.writer.channel(heldWriter, {}); await channel.ready; + const entered = new Int32Array(new SharedArrayBuffer(4)); held = channel.call("hold", entered, release); + const waiting = Atomics.waitAsync(entered, 0, 0, 5000); if (waiting.async) await waiting.value; + expect(Atomics.load(entered, 0)).toBe(1); + // Hold only submission of the reservation, forwarding every call to the + // real FULL writer. The local overlay must restrict before SQL exists. + const delayedWriter: SqliteWriter = { ...f.writer, channel(module, options, revive) { + const channel = f.writer.channel(module, options, revive); + return { ...channel, call(name: string, ...args: unknown[]): Promise { + return name === "safetyReserve" ? submitReservation.promise.then(() => channel.call(name, ...args)) : channel.call(name, ...args); + } }; + } }; + const queuedWrites = createGovernanceWrites(f.db, delayedWriter); + pending = queuedWrites.firstTaint({ kind: "taint", turnId: "scout", sessionId: null, + actor: "interactive", model: null, profile: "governed", payload: { source: "web_fetch", tool: "WebFetch", detail: null, + occurrence: occurrence("scout-binding", "tool_web_input", "scout-input", "open") } }); + const result = f.writes.safetyCommitReview(prepared.requestId!, body, f.actor); + Atomics.store(release, 0, 1); Atomics.notify(release, 0); await held; + expect(await result, "ADOPTED_LOCAL_INPUT_PREVENTS_SAFE_VERDICT").toMatchObject({ stage: "refused", reason: "recording_pending" }); + expect(f.db.query("SELECT COUNT(*) n FROM safety_pending").get()).toEqual({ n: 0 }); + submitReservation.resolve(); + await pending; + expect(f.db.query("SELECT COUNT(*) n FROM safety_decisions").get()).toEqual({ n: 0 }); + expect(f.state().unresolvedCount).toBe(2); + } finally { + submitReservation.resolve(); + Atomics.store(release, 0, 1); Atomics.notify(release, 0); + await Promise.allSettled([held, pending]); await f.close(); + } +}); + for (const mode of ["open", "interrupted_unknown", "finalized"] as const) test(`review eligibility requires explicit finalized delivery: ${mode}`, async () => { const f = await fixture(); try { const a = await f.add("A", false); From 77a948060cec84f8932d7a13b2316f52a4a4076c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 15:36:05 +0000 Subject: [PATCH 8/8] docs: refresh the scoped safety projection citation --- docs/plans/reviewable-session-safety.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index e616f90c3c..2fe9795369 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:230`). Legacy rows prove + `packages/ui-server/src/governance/safety-store.ts:232-237`). 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`,