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
37 changes: 25 additions & 12 deletions host-setup/agent-safety/claude/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,13 @@ host-setup/agent-safety/claude/install.sh
.\host-setup\agent-safety\claude\install.ps1
```

Both are thin wrappers around `install.py`, so every OS runs one tested code path. The installer self-tests the hook before registering it. It merges the settings.json hook entry, the permission rules, and the tagged `autoMode` rules without clobbering other keys. It renders CLAUDE.md whole, backing up a file edited since the last install before replacing it. The settings file is read once and written once, so the hook, the permission rules, and the `autoMode` rules land together or not at all.
Both are thin wrappers around `install.py`, so every OS runs one tested code path. The installer self-tests the hook before registering it. It merges the settings.json hook entry, written in exec form, the permission rules, and the tagged `autoMode` rules without clobbering other keys. It renders CLAUDE.md whole, backing up a file edited since the last install before replacing it. The settings file is read once and written once, so the hook, the permission rules, and the `autoMode` rules land together or not at all.

**Restart Claude Code sessions on the machine afterward** so the new hook and CLAUDE.md load.

## Refreshing After an Upstream Change

The deployed copy on each machine is a snapshot. So when the guard changes upstream (a new rule or a fix), every machine keeps running the old hook until it is refreshed. The installer **is** the refresh: pull the latest template and re-run `install.sh` (or `install.ps1`) on each machine. It re-copies the hook, re-runs the self-test, and re-registers in place, so a re-run is safe and updates the deployed copy. [#365][issue-365] tracks the per-machine rollout and its re-runs.
The deployed copy on each machine is a snapshot. So when the guard changes upstream (a new rule or a fix), every machine keeps running the old hook until it is refreshed. The installer **is** the refresh: pull the latest template and re-run `install.sh` (or `install.ps1`) on each machine. It re-copies the hook, re-runs the self-test, and re-registers in place, so a re-run is safe and updates the deployed copy. A re-run also rewrites each registration an older install wrote in shell form, a `"<launcher>" "<path>"` string, in exec form. [#365][issue-365] tracks the per-machine rollout and its re-runs.

## Verify (POSIX Shell)

Expand Down Expand Up @@ -135,16 +135,29 @@ Withdraw a grant by deleting the `env` entry and restarting. Nothing expires it,
## Manual settings.json Shape (for Reference)

The installer writes this. It is here so you can inspect it, not as a template to hand-place.
The literal `"python3"` shown for `command` is what the installer writes when a `python3` on `PATH`
runs and reports Python 3.11 or newer. Each candidate is run with a probe that prints a token and its
Each hook is registered in exec form. Its `command` is the absolute path of an interpreter, and its
`args` holds the hook's path alone. Claude Code spawns that directly, with no shell, on every
platform. A shell-form string runs under `sh -c` on Linux and macOS. On Windows it runs under Git
Bash, or under PowerShell where Git Bash is absent, so what it ran depended on the host's shell.
Claude Code also runs an exec-form hook without `CLAUDE_CODE_SHELL_PREFIX`. An install over a
host an older install registered in shell form rewrites each such entry in exec form.
The `<python3>` shown for `command` is the absolute path `PATH` resolves `python3` to. The
installer writes it when that interpreter runs and reports Python 3.11 or newer. The path is kept as
`PATH` resolves it, without following its links, so a minor-version upgrade behind
`/usr/bin/python3` keeps it working. A candidate inside a virtual environment yields first to an
interpreter its `pyvenv.cfg` names, since deleting the venv would leave every hook failing to
spawn. The `python3`, or `python.exe` on Windows, in its `home` directory is tried first, then its recorded `executable`, then the venv's own. On Windows a candidate must resolve to a `.exe`. Exec form cannot spawn a `.bat` or `.cmd`
shim, such as pyenv-win's, and `--report` flags an exec-form launcher that is not a `.exe`. Each candidate is run with a probe that prints a token and its
version, and the output is read. That is because presence on `PATH` and a zero exit each pass a stub
that runs no script, such as a Windows app execution alias. A hook naming one fails open. The
installer substitutes `sys.executable`'s own absolute path when `python3` is absent or fails the
probe, most commonly on a Windows host with no `python3` shim. It installs nothing when neither
passes. Each hook's self-test runs under the chosen launcher, so a pass also proves the launcher runs
the hook. `--report` runs the launcher each registration names in the `<launcher> <path>` shape. So
a host registered before the probe existed reports STALE once that launcher stops running. Like the
containment check below, it runs under the reporting shell's `PATH` rather than Claude Code's.
the hook. `--report` runs the launcher each registration names. That is an exec-form entry's
`command`, or the first word of a shell-form entry's `<launcher> <path>` string. So a host
registered before the probe existed reports STALE once that launcher stops running. Like the
containment check below, a bare launcher name resolves under the reporting shell's `PATH` rather
than Claude Code's.
The `Bash(python3 scripts/pr_review.py:*)` rule in
`permissions.allow` always names `python3` literally, since it matches a command line rather than
the hook's own launcher.
Expand All @@ -170,11 +183,11 @@ states the one spelling that matches.
},
"hooks": {
"PreToolUse": [
{ "matcher": "Bash", "hooks": [ { "type": "command", "command": "\"python3\" \"<home>/.claude/hooks/gh-write-guard.py\"" } ] },
{ "matcher": "Agent|Workflow", "hooks": [ { "type": "command", "command": "\"python3\" \"<home>/.claude/hooks/model-tier-guard.py\"" } ] }
{ "matcher": "Bash", "hooks": [ { "type": "command", "command": "<python3>", "args": [ "<home>/.claude/hooks/gh-write-guard.py" ] } ] },
{ "matcher": "Agent|Workflow", "hooks": [ { "type": "command", "command": "<python3>", "args": [ "<home>/.claude/hooks/model-tier-guard.py" ] } ] }
],
"SessionEnd": [
{ "hooks": [ { "type": "command", "command": "\"python3\" \"<home>/.claude/hooks/stray-process-sweep.py\"", "timeout": 35 } ] }
{ "hooks": [ { "type": "command", "command": "<python3>", "args": [ "<home>/.claude/hooks/stray-process-sweep.py" ], "timeout": 35 } ] }
]
},
"permissions": {
Expand Down Expand Up @@ -214,8 +227,8 @@ Every other key in the file is left as it stands, `permissions.allow` and the re
- **Not a credential control.** A fine-grained PAT limited to owned repositories is a separate, stronger structural guard (a hard `403` on any non-owned repo). It is left to per-machine credential setup, out of this kit.
- **Rule 6's ref-checkout and `--ff-only` exemptions are deliberate, not a gap.** The #1073 incident's own literal commands (an unforced `git checkout main`, then `git pull --ff-only`) are exactly this shape. So this rule does not deny the incident's own commands specifically. Denying them would also break the documented base-clone cleanup step in the `repo-worktree` skill, which needs precisely those two. Those commands still carry a concurrent-access hazard: switching HEAD, or fast-forwarding, in a checkout another task might be relying on. That hazard is not decidable from the command text alone, so it stays the prose rule's job. A non-force flag alongside the ref, such as `--detach`, is exempt too, not only a strictly zero-flags invocation. Git's own overwrite-refusal on a dirty tracked file is unaffected by such a flag, verified live.
- **Rule 6's delete-only push exemption is deliberate, not a gap.** A push whose every refspec deletes a remote branch moves no local branch and touches no working tree. So the hazard rule 6 guards is absent. The `cleanup` helper stays the prescribed delete path, since a hand-typed push carries none of its checks. The exemption is narrow. Its remote is a name of letters, digits, `_`, and `-`, never `.` or a path, and it never deletes a protected default. It carries no option beyond delete, dry-run, quiet, and verbose, and no `-c` override. Rule 4 still reads each branch's live rules, so a branch whose rules forbid deletion still denies.
- **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers.** It also requires that the deployed prefix runs as its own executable. The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/<uid>`, since WSLg points the variable at a directory of its own. A cgroup-v1 or hybrid host starts a scope that enforces neither ceiling, so it is treated as unable to contain. Where the installer left the prefix unset because the host cannot contain, `--report` prints a note saying agent commands run uncontained, and why. The prefix runs through its `env python3` shebang for every hook command, the guard included. That is because Claude Code quotes the whole prefix value as one word, and so no interpreter can be named in front of it. A PreToolUse hook that fails is a non-blocking error, so a prefix that cannot run that way would fail the guard open. The installer and `--report` therefore execute the deployed file directly, as Claude Code does, before treating the host as able to contain. What neither can see is a `python3` on Claude Code's own PATH that differs from the installing shell's. An example is a session an IDE launched under another environment. macOS and Windows have no systemd. A `ulimit -u` fallback caps every process the user owns rather than one command's tree. So it would fail unrelated work rather than stop a runaway. The installer leaves the prefix unset on macOS and Windows, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered, containment later fails if `systemd-run` goes missing, or the user manager becomes unreachable or loses those two controllers. Each tool call then runs unbounded and prints one `tool-containment:` line on stderr naming which.
- **Only Bash tool calls are scoped.** Claude Code applies `CLAUDE_CODE_SHELL_PREFIX` to hook commands and to stdio MCP server launches as well as to Bash tool calls, verified on 2.1.283. The prefix runs a hook under its shell directly. That is because a PreToolUse hook exiting 1 is a non-blocking error. So a scope that failed to start would let the command the guard denies go ahead. It runs an MCP server directly too, since a server outlives any one session and starts outside one. A tool call is told apart by the Claude Code shell snapshot it sources first or the cwd bookkeeping appended last, either one enough. Where a later Claude Code drops both, tool calls run bare as well, silently, and the sweep's report of surviving processes is what remains. A `claude` session started from a tool call runs its own tool calls in scopes named for itself, each under its own ceiling. That is because sharing the parent's one ceiling would let a heavy build make the kernel kill the nested `claude` process instead. All of them sit in the root session's tree slice. A chain of agents calling agents therefore meets the tree's total ceiling, however few processes each level adds. The tree's memory ceiling is twice a scope's, so one heavy build alone never reaches it. Where several reach it together, the kernel kills the largest process in the tree, usually a build rather than a nested `claude`. A nested session's scopes are stopped when it ends. Where stopping the parent's scope ended the nested session first, the root's sweep stops them as orphans and names the nested session's id. A session that ended with no sweep at all leaves its scopes running, such as one whose terminal was closed. For that case, `python3 ~/.claude/hooks/stray-process-sweep.py --orphans` lists each scope whose recorded agent is no longer running. It groups them by tree and hands over the line that stops them. It stops nothing itself, and never lists a scope whose agent still runs, so its line is safe to run. A scope started by an older prefix records no agent and is listed apart, as unknown. Such a session also leaves its empty `claude-tree-` slice and the ceiling put on it. Both cost nothing and go at the next reboot, or at once with `systemctl --user stop` and `systemctl --user revert` on the slice. Where a tool call's scope fails to start, that call fails with systemd's own error rather than running uncontained. Each contained tool call costs about 35 ms on the reference host, measured as two Python starts and one scope creation. Anything run directly costs about 10 ms. Finding the agent and the tree's slice adds about 4 ms more.
- **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers.** It also requires that the deployed prefix runs as its own executable. The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/<uid>`, since WSLg points the variable at a directory of its own. A cgroup-v1 or hybrid host starts a scope that enforces neither ceiling, so it is treated as unable to contain. Where the installer left the prefix unset because the host cannot contain, `--report` prints a note saying agent commands run uncontained, and why. The prefix runs through its `env python3` shebang for every Bash tool call and every shell-form hook. That is because Claude Code quotes the whole prefix value as one word, and so no interpreter can be named in front of it. The kit's own hooks are exec form, which Claude Code spawns without the prefix, so a prefix that cannot run never reaches the guard. It does reach a shell-form PreToolUse hook the host keeps of its own. A hook that fails is a non-blocking error, so such a hook would fail open. The installer and `--report` therefore execute the deployed file directly, as Claude Code does, before treating the host as able to contain. What neither can see is a `python3` on Claude Code's own PATH that differs from the installing shell's. An example is a session an IDE launched under another environment. macOS and Windows have no systemd. A `ulimit -u` fallback caps every process the user owns rather than one command's tree. So it would fail unrelated work rather than stop a runaway. The installer leaves the prefix unset on macOS and Windows, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered, containment later fails if `systemd-run` goes missing, or the user manager becomes unreachable or loses those two controllers. Each tool call then runs unbounded and prints one `tool-containment:` line on stderr naming which.
- **Only Bash tool calls are scoped.** Claude Code applies `CLAUDE_CODE_SHELL_PREFIX` to shell-form hook commands and to stdio MCP server launches as well as to Bash tool calls, verified on 2.1.283. Its documentation states that an exec-form hook runs without the prefix, and exec form is how the kit registers its own hooks. The prefix runs a shell-form hook under its shell directly. That is because a PreToolUse hook exiting 1 is a non-blocking error. So a scope that failed to start would let the command such a hook denies go ahead. It runs an MCP server directly too, since a server outlives any one session and starts outside one. A tool call is told apart by the Claude Code shell snapshot it sources first or the cwd bookkeeping appended last, either one enough. Where a later Claude Code drops both, tool calls run bare as well, silently, and the sweep's report of surviving processes is what remains. A `claude` session started from a tool call runs its own tool calls in scopes named for itself, each under its own ceiling. That is because sharing the parent's one ceiling would let a heavy build make the kernel kill the nested `claude` process instead. All of them sit in the root session's tree slice. A chain of agents calling agents therefore meets the tree's total ceiling, however few processes each level adds. The tree's memory ceiling is twice a scope's, so one heavy build alone never reaches it. Where several reach it together, the kernel kills the largest process in the tree, usually a build rather than a nested `claude`. A nested session's scopes are stopped when it ends. Where stopping the parent's scope ended the nested session first, the root's sweep stops them as orphans and names the nested session's id. A session that ended with no sweep at all leaves its scopes running, such as one whose terminal was closed. For that case, `python3 ~/.claude/hooks/stray-process-sweep.py --orphans` lists each scope whose recorded agent is no longer running. It groups them by tree and hands over the line that stops them. It stops nothing itself, and never lists a scope whose agent still runs, so its line is safe to run. A scope started by an older prefix records no agent and is listed apart, as unknown. Such a session also leaves its empty `claude-tree-` slice and the ceiling put on it. Both cost nothing and go at the next reboot, or at once with `systemctl --user stop` and `systemctl --user revert` on the slice. Where a tool call's scope fails to start, that call fails with systemd's own error rather than running uncontained. Each contained tool call costs about 35 ms on the reference host, measured as two Python starts and one scope creation. Anything run directly costs about 10 ms. Finding the agent and the tree's slice adds about 4 ms more.
- **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`. It can also start a scope of its own outside this one, which the session-end stop does not reach. The incident this answers was a mistake rather than an escape, and a ceiling that a deliberate command can lift still stops it.
- **A session's tool-call scopes end with the session.** The sweep stops them whatever they hold, a long build backgrounded on purpose included. That is the one kill in this kit, and it is bounded by the scope name rather than by a judgment about the process. The sweep also stops a scope in the session's tree whose recorded agent is gone, since its own session can no longer stop it. That stop is bounded by the tree's slice and the scope's recorded agent. It never judges what the scope's own processes are. A scope whose agent still runs is left. A scope stop sends SIGTERM and escalates to SIGKILL after two seconds, which keeps it inside the hook's own timeout.
- **The sweep runs on Linux and WSL.** Whether a descendant outlives the agent is decided by comparing session ids, which the sweep reads with `ps -eo sess=,etimes=`. Both are procps format keywords. Windows has no session test at all, and a BSD `ps`, which is what macOS carries, has neither keyword. The script returns immediately on Windows and on macOS rather than printing a failure at every session end there. The installer still deploys and registers it on every platform. That keeps the installer, the payload digest, and the registration checks identical everywhere, which is worth more than a branch nobody has run.
Expand Down
Loading
Loading