Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/claude-permission-sdk-assembly-split.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-backend-claude": patch
---

The Claude backend now builds a turn's permission wiring and SDK options in separate steps. Permission wiring is split into its native-file guards, enforcement hook, `canUseTool` callback, mutating hook and rewrite hooks. SDK options are split into the tool roster, the turn environment, the sandbox note and the prompt context. Permission decisions, the tool list and its order, and the system prompt are unchanged.
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ on, links to or describes them.
declared with `defineModule({ name, configSchema, setup })`. Run
`brain module lint` before submitting one.
- Cite code from docs and source comments as an anchor followed by its range:
(`enforcementHook`, `packages/ui-backend-claude/src/permission-hooks.ts:200-229`),
(`enforcementHook`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`),
starting on the anchor's line. **A PR that moves lines under a citation owns
that citation**, wherever it is recorded; find them with
`git grep -n '<file>.ts:' -- docs packages`. `tests/decision-citations.test.ts`
Expand Down
1 change: 1 addition & 0 deletions api-report/ui-sdk.txt
Original file line number Diff line number Diff line change
Expand Up @@ -975,6 +975,7 @@ export "./internal" (./src/internal.ts)
type ClassificationAnswers
type ClassificationPlan
type ClassificationRequest
type CompiledWorkerCommandPolicy
DEFAULT_MAINTENANCE_TEMP_BUDGET_BYTES
DEFAULT_MAINTENANCE_TEMP_BYTES
DEFAULT_OUTPUT_STAGING_BYTES
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ it is told something confidently wrong. So name what you point at, and let the
range follow it:

```md
(`enforcementHook`, `packages/ui-backend-claude/src/permission-hooks.ts:200-229`)
(`enforcementHook`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`)
```

- **The anchor** is the code span immediately before the citation, joined to it
Expand Down
4 changes: 2 additions & 2 deletions docs/decisions/claude-2.1.287-compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,9 @@ call, including when settings or a rewrite could otherwise auto-approve it.
The backend builds the actual turn options and production permission handlers
(`createClaudeSdkTurn`, `packages/ui-backend-claude/src/sdk-options.ts:110-499`).
The explicit ask lives in
(`enforcementHook`, `packages/ui-backend-claude/src/permission-hooks.ts:200-229`)
(`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:575-578`).
(`...(enforced ?`, `packages/ui-backend-claude/src/permission-hooks.ts:646-649`).

`scripts/measure-claude-enforcement.ts` runs `createClaudeBackend().startTurn()`
and forwards to the SDK resolved from that backend. Its query wrapper only
Expand Down
16 changes: 8 additions & 8 deletions docs/decisions/claude-code-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ next to it.
`packages/ui-server/src/agent/backend.ts:505`), read back as a string
(`const claudeCodePath`, `packages/ui-backend-claude/src/module.ts:266-270`)
and handed to the SDK (`backend.claudeCodePath`,
`packages/ui-backend-claude/src/sdk-options.ts:382`). Because of the `||`
`packages/ui-backend-claude/src/sdk-options.ts:429`). Because of the `||`
default the value was never empty, so **the server always overrode the SDK's
own binary**. The variable is withheld from every subprocess
(`CLAUDE_CODE_PATH: NONE`,
Expand Down Expand Up @@ -276,7 +276,7 @@ a permission boundary:
- **A refusal would not buy what it appears to.** The measured version is not
known-safe either: the list of mechanisms that skip `canUseTool` is what has
been measured, not a closed set (`AT LEAST three`,
`permission-hooks.ts:168-171`). A version gate would separate "probed" from "not
`permission-hooks.ts:257-260`). A version gate would separate "probed" from "not
probed", not "safe" from "unsafe", and it would say the second thing to
whoever reads it.
- **It would block the path a CLI fix takes.** The built-in binary moves only
Expand Down Expand Up @@ -356,7 +356,7 @@ so it holds itself to these rules:
about another.
- **Composition, not only parts.** The enforcement hook's `ask` must leave
another hook's `updatedInput` intact (`An explicit "ask" beats all three`,
`permission-hooks.ts:195-197`; `(e) a hook's`,
`permission-hooks.ts:284-286`; `(e) a hook's`,
`allowlist-enforcement.test.ts:18-21`). That is its own case: a rewrite, an
`ask` and a `canUseTool` decision in one call, asserting the input the
callback saw and the input that executed.
Expand All @@ -383,7 +383,7 @@ until re-measured.

| Site | What it asserts | Re-checked by |
| --- | --- | --- |
| `DO NOT WEAKEN THIS INTO A FALLTHROUGH`, `packages/ui-backend-claude/src/permission-hooks.ts:167-198` | Three things admit a tool before `canUseTool` — the safe-command classifier (`echo hi` with an empty allowlist), a built-in tool's own check (`ToolSearch`), a project-settings `PreToolUse` hook returning `allow` — and an explicit `ask` beats all three. `permissions.allow` rules and `defaultMode: "bypassPermissions"` do not bypass. | Probe cases for each of the three, each with and without the `ask`, plus the two negative controls. |
| `DO NOT WEAKEN THIS INTO A FALLTHROUGH`, `packages/ui-backend-claude/src/permission-hooks.ts:256-288` | Three things admit a tool before `canUseTool` — the safe-command classifier (`echo hi` with an empty allowlist), a built-in tool's own check (`ToolSearch`), a project-settings `PreToolUse` hook returning `allow` — and an explicit `ask` beats all three. `permissions.allow` rules and `defaultMode: "bypassPermissions"` do not bypass. | Probe cases for each of the three, each with and without the `ask`, plus the two negative controls. |
| `Both hooks exist to rewrite`, `packages/ui-backend-claude/src/input-rewrite-hooks.ts:7-14` | A hook's `updatedInput` applies with no decision, and the permission path sees the rewritten input. | Probe case: rewrite with no decision; assert the executed input and the `canUseTool` input. |
| `The runtime precedence modelled by`, `packages/ui-backend-claude/tests/allowlist-enforcement.test.ts:11-20` | The precedence `runToolCall` models, (a)–(e). The test cannot re-measure it. | The cases above plus the composition case. A changed result changes the model in the test in the same PR. |
| `the one answer that beats`, `packages/ui-backend-claude/tests/no-grant-surface.test.ts:13-18` | The same three opinions, and that `ask` is what forces the decision. | Same probe cases. |
Expand All @@ -409,7 +409,7 @@ brain-hosting-template.

None of the live sites is accepted as unverifiable. What stays unverifiable is
the absence of a *fourth* mechanism — `AT LEAST three`,
`permission-hooks.ts:168-171` already says three is what has been measured, not a
`permission-hooks.ts:257-260` already says three is what has been measured, not a
closed set — and no probe can close that.

## Where the work goes
Expand Down Expand Up @@ -456,7 +456,7 @@ into them.
A turn's environment is the filtered agent environment plus the profile's
additions (`export function turnEnv`, `packages/ui-backend-claude/src/sdk-options.ts:74-80`,
`envSnapshot`, `packages/ui-backend-claude/src/config/env.ts:201-209`), handed to the SDK
whole (`sdkOptions.env = childEnv`, `sdk-options.ts:456`). A declared bearer-token profile clears both
whole (`sdkOptions.env = childEnv`, `sdk-options.ts:464`). A declared bearer-token profile clears both
ambient credentials (`input.authTokenEnv !== undefined`, `profiles.ts:116-122`); a declared API-key profile sets
the key on purpose (`input.apiKeyEnv !== undefined`, `profiles.ts:123-125`).
- **Billing originally relied on ambient credential classification.** The
Expand Down Expand Up @@ -604,7 +604,7 @@ subscription authenticates.
environment is necessary, whether or not a subscription credential is
present. It is not sufficient: the CLI also takes an API key from an
`apiKeyHelper` in settings — the backend loads the brain repo's project
settings (`settingSources: ["project"]`, `sdk-options.ts:326`) — and from a stored Console login, reported
settings (`settingSources: ["project"]`, `sdk-options.ts:388`) — and from a stored Console login, reported
as `/login managed key` (`sdk.d.ts:5585`). So the turn has to check which
credential the CLI selected **before the prompt is sent**, and end the turn
if it is not a subscription. The check reads the account from the SDK's
Expand Down Expand Up @@ -1409,7 +1409,7 @@ and native flag settings, using the existing subscription credential-clearing
policy. It does not remove other providers' CLI command environment. Only an
ordinary subscription turn can select this input; API and autonomous turns
retain their existing paths (`const inferenceEnv`,
`packages/ui-backend-claude/src/sdk-options.ts:235-253`). The worker note derives
`packages/ui-backend-claude/src/sdk-options.ts:257-274`). The worker note derives
its active-proxy description from that same selection and retains per-use
outward approvals.

Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/design-kit/backend-measurements.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ and each closed before the measured runs:

- **The brain has to live outside the operator's home directory, not only
outside a checkout.** `settingSources: ["project"]`,
`packages/ui-backend-claude/src/sdk-options.ts:326`, makes the CLI walk up
`packages/ui-backend-claude/src/sdk-options.ts:388`, makes the CLI walk up
from the cwd, and at every ancestor it reads `.claude/CLAUDE.md`,
`.claude/skills/` and `.claude/agents/`. A brain anywhere under a home
directory therefore loads `~/.claude/CLAUDE.md` as *project* instructions,
Expand Down
6 changes: 3 additions & 3 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1335,7 +1335,7 @@ classification:
`strict`.
- **Native tools return under `governed`.** In Claude the
`Write`/`Edit`/`NotebookEdit` disallow is lifted
(`disallowedTools`, `packages/ui-backend-claude/src/sdk-options.ts:343`). In
(`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 (`const bash`, `packages/ui-backend-pi/src/tools.ts:549`).
- **Approvals do not change.** Confirmation patterns and destructive-operation
Expand All @@ -1356,7 +1356,7 @@ canonical bytes for a frozen view (`createWorkerFileObserver`,
read cannot establish a new version. Claude's native `file_unchanged` response
also preserves the previous observation: it supplied no new bytes
(`const finishNativeFile`,
`packages/ui-backend-claude/src/permission-hooks.ts:107`).
`packages/ui-backend-claude/src/permission-hooks.ts:155`).

Claude keeps these observations in its backend-owned session map
(`fileVersionsBySession: new Map()`,
Expand Down Expand Up @@ -3877,7 +3877,7 @@ files, `.claude/`, `.agents/`, `.pi/`, `.mcp.json`, and
[module resolution](https://bun.sh/docs/runtime/module-resolution) and
[startup configuration](https://bun.sh/docs/runtime/bunfig) rules.
- Claude's project MCP location is root `.mcp.json`; its cwd is the selected
brain (`const sdkOptions`, `packages/ui-backend-claude/src/sdk-options.ts:310-327`).
brain (`const sdkOptions`, `packages/ui-backend-claude/src/sdk-options.ts:372-389`).
Existing instruction, skills, `.claude/`, `.agents/`, `.pi/` and scheduled-task
surfaces remain unchanged. Their retained module references can likewise
identify package metadata within that same scope.
Expand Down
20 changes: 10 additions & 10 deletions docs/decisions/voice-permission.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ functions**: `decideToolPermission` with `DEFAULT_ALLOWED_TOOLS`
(`DEFAULT_ALLOWED_TOOLS`, `packages/ui-backend-claude/src/tool-policy.ts:27`), the
six bridge tools the backend appends per turn (the `allowed.push` block in
`createClaudeSdkTurn`, from `const allowed`,
`packages/ui-backend-claude/src/sdk-options.ts:194-219`)
`packages/ui-backend-claude/src/sdk-options.ts:208-233`)
and `DEFAULT_CONFIRM_BASH_PATTERNS`
(`DEFAULT_CONFIRM_BASH_PATTERNS`, `packages/ui-sdk/src/server/confirm-patterns.ts:55`).
Tools that exist only in the recording harness and have no counterpart in this
Expand Down Expand Up @@ -258,7 +258,7 @@ as its allowlist and declares both `enforceAllowedTools` and `noGrantSurface`.
| `mcp__brain-ui__brain_update` | Edits an existing document. "Add this to my note about X" is the second most valuable eyes-free action, and the handler's shape is why it is safe enough to allow: it **never rewrites the body**, it only appends to it (`const appendTo`, `packages/core/src/lib/frontmatter-edit.ts:303-308`), so no prose can be lost. The exact bound on what it *can* destroy: the six frontmatter params are independent optionals on one call (`summary: z.string()`, `packages/core/src/mcp-server.ts:428-433`), applied independently (`input.summary !== undefined`, `packages/core/src/lib/ops/write.ts:88-100`), so **a single call can overwrite all six** — and `tags` replaces the whole tag list rather than merging into it (the terminal MCP accepts a comma-separated string, while the hosted route accepts a string array; `input.tags !== undefined`, `packages/core/src/lib/ops/write.ts:91`), while `deadline` and `next_review` take `""` as *delete the field* (`input.deadline !== undefined`, `packages/core/src/lib/ops/write.ts:92-99`). `updated` is bumped unconditionally (`updates.updated = updated`, `packages/core/src/lib/ops/write.ts:115`). None of it is checkpointed, so git recovers a prior value only if the document was committed. The claim this row rests on is therefore "loses no prose, and at most the six declared frontmatter fields, recoverable only if committed" — not "recoverable". `status` is the field that matters and it is handled separately below. |
| `Read`, `Glob`, `Grep` | Read-only over the brain repo, for the questions the brain tools do not cover. No mutation, no egress. |
| `WebSearch`, `WebFetch` | Read-only egress. Kept, with the exposure stated below. |
| the bridge tools, minus the mask editor | `ask_user`, `get_current_location`, `query_activity`, `show_block`, `turn_temp` are auto-allowed today and none of them is a permission decision (the same `allowed.push` block, from `const allowed`, `sdk-options.ts:194-219`). `request_image_mask` needs the user to paint a region, so it needs eyes; it is out. |
| the bridge tools, minus the mask editor | `ask_user`, `get_current_location`, `query_activity`, `show_block`, `turn_temp` are auto-allowed today and none of them is a permission decision (the same `allowed.push` block, from `const allowed`, `sdk-options.ts:208-233`). `request_image_mask` needs the user to paint a region, so it needs eyes; it is out. |

Module tools are admitted only by exact name, never by their own annotations,
as [module-mcp-tools.md §6](module-mcp-tools.md#6-annotations-and-permissions)
Expand Down Expand Up @@ -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:309-319`) and is not
`permission-hooks.ts:383-393`) 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
Expand Down Expand Up @@ -517,8 +517,8 @@ to a turn — `InferenceProfile.allowedTools`
(`allowedTools?: string[]`, `packages/ui-backend-claude/src/profiles.ts:27`) and
`ClaudeBackendOptions.allowedTools` (`Backend-wide tool allowlist`,
`options.ts:52-53`), resolved into the SDK's `allowedTools` per turn (the
`allowed` array, from `const allowed`, `sdk-options.ts:194`, and what it
becomes, `allowedTools: allowed`, `:340`). The voice posture is one
`allowed` array, from `const allowed`, `sdk-options.ts:208`, and what it
becomes, `allowedTools: allowed`, `:402`). The voice posture is one
named entry in that mechanism.

**#51's U15 originally chose availability control for the same bypass reason.**
Expand Down Expand Up @@ -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:542-562`).
`const agentHook`, `permission-hooks.ts:601-622`).
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
Expand All @@ -645,7 +645,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one.
before the lookup, which is what this record asked for.

**Closed, by #110.** The enforcement hook still answers `ask`, not `deny`
(`enforcementHook`, `permission-hooks.ts:200-229`) — that is what beats the
(`enforcementHookFor`, `permission-hooks.ts:289-330`) — that is what beats the
runtime's own shortcuts
below, and replacing it would reopen all three. What changed is the decision the
`ask` forces. A turn declares `StartTurnRequest.noGrantSurface`, and both
Expand All @@ -665,7 +665,7 @@ with a `BackendRequestError` (`assertTurnPosture`,
codebase's own shortcuts was never sufficient: the runtime has permission
opinions of its own that also land before `canUseTool`
(the block above `enforcementHook`, `DO NOT WEAKEN THIS INTO A FALLTHROUGH`,
`permission-hooks.ts:167-198`, with the measurements in #154) — a safe-command
`permission-hooks.ts:256-288`, with the measurements in #154) — a safe-command
classifier (`echo hi` runs with an **empty** `allowedTools` and the callback is
never consulted), a built-in tool's own check (`ToolSearch` executed twice under
the same conditions), and a `PreToolUse` hook in the project settings this
Expand Down Expand Up @@ -718,8 +718,8 @@ Bash call through `canUseTool` first: the PreToolUse `mutatingHook` fires
before permission
evaluation and evaluates the confirm patterns against `commandAllowed`, which
adds `Bash` back unconditionally (`commandAllowed`,
`permission-hooks.ts:250-252`, and the call in `mutatingHook` that reads it,
`decideToolPermission`, `:318-325`). So a
`permission-hooks.ts:90-92`, and the call in `mutatingHook` that reads it,
`decideToolPermission`, `:480-487`). 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
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/async-collaboration-requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ Stated before the requirements because five of them derive from it.
`DEFAULT_ALLOWED_TOOLS` auto-allows `Bash`, `Write`, `Edit`, `WebFetch`, `WebSearch`, and
`Agent` (`export const DEFAULT_ALLOWED_TOOLS = [`, `packages/ui-backend-claude/src/tool-policy.ts:27-80`), and auto-allowed tools bypass
`canUseTool` entirely — the backend says so where it explains why the write lock had to
move into a `PreToolUse` hook (`const enforcementHook: HookCallback`, `packages/ui-backend-claude/src/permission-hooks.ts:200-229`). Existing mandatory tool/no-grant posture closes measured permission bypasses,
move into a `PreToolUse` hook (`export function enforcementHookFor`, `packages/ui-backend-claude/src/permission-hooks.ts:289-330`). Existing mandatory tool/no-grant posture closes measured permission bypasses,
but it does not express the full filesystem/network envelope. Building it requires: the SDK's tool **availability** control
(`tools`, not merely `allowedTools`), a scrubbed environment carrying only inference
credentials and minimum runtime variables (the current environment is filtered but retains operator/profile extras — (`export function envSnapshot(`, `packages/ui-backend-claude/src/config/env.ts:201-209`)),
Expand Down
Loading
Loading