From 55d6d11b20107bfb4aa7bd2b7ad722e0bbda46db Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 07:11:49 -0700 Subject: [PATCH 01/22] Contain Every Agent Command in a Task- and Memory-Capped Scope A probe's command shim called itself through PATH, grew past half a million processes, and took the host down. The write guard reads command text, and that recursion lived in a script file the command only named, so the fix bounds every command's process tree instead. tool-containment.py is registered as CLAUDE_CODE_SHELL_PREFIX and runs each Bash tool call and hook command inside a transient systemd user scope with TasksMax and MemoryMax, named for its session. The SessionEnd sweep now stops that session's tool-call scopes before its report-only phase. The installer sets the prefix only where a user manager runs and never over a value it does not own. The spec gains requirement 9. The behavioral layer lands beside it: the self-recursive shim rule in shell-codestyle, and bounded, group-reaped, pgrep-verified probes in AGENTS.md "Commands". Co-Authored-By: Claude Opus 5.5 (1M context) --- .agents/skills/shell-codestyle/SKILL.md | 26 +- .../.source-digests/shell-codestyle | 2 +- .../skills/shell-codestyle/SKILL.md | 26 +- .github/skills/shell-codestyle/SKILL.md | 26 +- AGENTS.md | 1 + CODESTYLE.md | 2 +- host-setup/agent-safety/README.md | 47 ++- host-setup/agent-safety/claude/README.md | 22 +- host-setup/agent-safety/claude/install.py | 74 +++- .../claude/stray-process-sweep.py | 183 +++++++++- .../agent-safety/claude/test_install.py | 88 ++++- .../agent-safety/claude/tool-containment.py | 323 ++++++++++++++++++ host-setup/agent-safety/codex/README.md | 9 +- host-setup/agent-safety/opencode/README.md | 9 +- 14 files changed, 771 insertions(+), 67 deletions(-) create mode 100755 host-setup/agent-safety/claude/tool-containment.py diff --git a/.agents/skills/shell-codestyle/SKILL.md b/.agents/skills/shell-codestyle/SKILL.md index 46fbaec05..085e370ad 100644 --- a/.agents/skills/shell-codestyle/SKILL.md +++ b/.agents/skills/shell-codestyle/SKILL.md @@ -3,16 +3,17 @@ name: shell-codestyle description: >- Governs Bash/shell script style for ptr727/ProjectTemplate fleet repos: when a bootstrap or host-tool script may be shell instead of Python, the mandatory set -Eeuo pipefail header, the - pipefail-versus-early-reader pitfall, self-locating scripts, the shellcheck-plus-shfmt - clean-compile, and the why-not-what comment rule. Use this whenever writing, reviewing, or - editing a shell script (a `.sh` file, or an extensionless bash/sh shebang script), whenever - deciding whether a new script should be Bash or Python, or whenever a pipeline built from - `curl`/`grep`/`jq`-style commands looks like it silently swallowed a failure. Triggers even when - the task looks like a one-line tweak to an existing script, because a missing `-e`/`pipefail`, - or a reader piped straight from a producer that closes the pipe early, are each invisible until - the exact failure mode they guard against actually happens. Fleet-wide: a shell script can - appear in any repo (a bootstrap that installs the interpreter, a host tool that must run before - a toolchain exists), not only a repo whose primary language is shell. + pipefail-versus-early-reader pitfall, self-recursive command shims, self-locating scripts, the + shellcheck-plus-shfmt clean-compile, and the why-not-what comment rule. Use this whenever + writing, reviewing, or editing a shell script (a `.sh` file, or an extensionless bash/sh shebang + script), whenever deciding whether a new script should be Bash or Python, or whenever a pipeline + built from `curl`/`grep`/`jq`-style commands looks like it silently swallowed a failure, or + whenever a script or probe writes a wrapper or shim named after a command it also calls. + Triggers even when the task looks like a one-line tweak to an existing script, because a missing + `-e`/`pipefail`, or a reader piped straight from a producer that closes the pipe early, are each + invisible until the exact failure mode they guard against actually happens. Fleet-wide: a shell + script can appear in any repo (a bootstrap that installs the interpreter, a host tool that must + run before a toolchain exists), not only a repo whose primary language is shell. --- # Shell Codestyle @@ -50,6 +51,11 @@ depend on Python either. Everything else is Python, with a test under its own sc - **A reader that stops early needs its producer read first.** Under `pipefail`, a producer writing to a closed pipe exits non-zero, so `curl ... | grep -q` reports a successful fetch as a failure whenever the match is found early enough. Capture the output, then search it. +- **A shim named for a command resolves that command by absolute path.** A wrapper named `jq`, + placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, + since `command` skips functions and aliases but not the `PATH` search. Every call starts another + copy of the wrapper, so the chain grows until something stops it. Capture the real path with + `command -v` before changing `PATH`, and call that path from inside the shim. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working directory at invocation is not a property of the script. diff --git a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle index e82c01f29..8dc2c6d82 100644 --- a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle +++ b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle @@ -1 +1 @@ -40c3f8736d2d6180 +f8d53a3ed92814a9 diff --git a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md index 46fbaec05..085e370ad 100644 --- a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md @@ -3,16 +3,17 @@ name: shell-codestyle description: >- Governs Bash/shell script style for ptr727/ProjectTemplate fleet repos: when a bootstrap or host-tool script may be shell instead of Python, the mandatory set -Eeuo pipefail header, the - pipefail-versus-early-reader pitfall, self-locating scripts, the shellcheck-plus-shfmt - clean-compile, and the why-not-what comment rule. Use this whenever writing, reviewing, or - editing a shell script (a `.sh` file, or an extensionless bash/sh shebang script), whenever - deciding whether a new script should be Bash or Python, or whenever a pipeline built from - `curl`/`grep`/`jq`-style commands looks like it silently swallowed a failure. Triggers even when - the task looks like a one-line tweak to an existing script, because a missing `-e`/`pipefail`, - or a reader piped straight from a producer that closes the pipe early, are each invisible until - the exact failure mode they guard against actually happens. Fleet-wide: a shell script can - appear in any repo (a bootstrap that installs the interpreter, a host tool that must run before - a toolchain exists), not only a repo whose primary language is shell. + pipefail-versus-early-reader pitfall, self-recursive command shims, self-locating scripts, the + shellcheck-plus-shfmt clean-compile, and the why-not-what comment rule. Use this whenever + writing, reviewing, or editing a shell script (a `.sh` file, or an extensionless bash/sh shebang + script), whenever deciding whether a new script should be Bash or Python, or whenever a pipeline + built from `curl`/`grep`/`jq`-style commands looks like it silently swallowed a failure, or + whenever a script or probe writes a wrapper or shim named after a command it also calls. + Triggers even when the task looks like a one-line tweak to an existing script, because a missing + `-e`/`pipefail`, or a reader piped straight from a producer that closes the pipe early, are each + invisible until the exact failure mode they guard against actually happens. Fleet-wide: a shell + script can appear in any repo (a bootstrap that installs the interpreter, a host tool that must + run before a toolchain exists), not only a repo whose primary language is shell. --- # Shell Codestyle @@ -50,6 +51,11 @@ depend on Python either. Everything else is Python, with a test under its own sc - **A reader that stops early needs its producer read first.** Under `pipefail`, a producer writing to a closed pipe exits non-zero, so `curl ... | grep -q` reports a successful fetch as a failure whenever the match is found early enough. Capture the output, then search it. +- **A shim named for a command resolves that command by absolute path.** A wrapper named `jq`, + placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, + since `command` skips functions and aliases but not the `PATH` search. Every call starts another + copy of the wrapper, so the chain grows until something stops it. Capture the real path with + `command -v` before changing `PATH`, and call that path from inside the shim. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working directory at invocation is not a property of the script. diff --git a/.github/skills/shell-codestyle/SKILL.md b/.github/skills/shell-codestyle/SKILL.md index 46fbaec05..085e370ad 100644 --- a/.github/skills/shell-codestyle/SKILL.md +++ b/.github/skills/shell-codestyle/SKILL.md @@ -3,16 +3,17 @@ name: shell-codestyle description: >- Governs Bash/shell script style for ptr727/ProjectTemplate fleet repos: when a bootstrap or host-tool script may be shell instead of Python, the mandatory set -Eeuo pipefail header, the - pipefail-versus-early-reader pitfall, self-locating scripts, the shellcheck-plus-shfmt - clean-compile, and the why-not-what comment rule. Use this whenever writing, reviewing, or - editing a shell script (a `.sh` file, or an extensionless bash/sh shebang script), whenever - deciding whether a new script should be Bash or Python, or whenever a pipeline built from - `curl`/`grep`/`jq`-style commands looks like it silently swallowed a failure. Triggers even when - the task looks like a one-line tweak to an existing script, because a missing `-e`/`pipefail`, - or a reader piped straight from a producer that closes the pipe early, are each invisible until - the exact failure mode they guard against actually happens. Fleet-wide: a shell script can - appear in any repo (a bootstrap that installs the interpreter, a host tool that must run before - a toolchain exists), not only a repo whose primary language is shell. + pipefail-versus-early-reader pitfall, self-recursive command shims, self-locating scripts, the + shellcheck-plus-shfmt clean-compile, and the why-not-what comment rule. Use this whenever + writing, reviewing, or editing a shell script (a `.sh` file, or an extensionless bash/sh shebang + script), whenever deciding whether a new script should be Bash or Python, or whenever a pipeline + built from `curl`/`grep`/`jq`-style commands looks like it silently swallowed a failure, or + whenever a script or probe writes a wrapper or shim named after a command it also calls. + Triggers even when the task looks like a one-line tweak to an existing script, because a missing + `-e`/`pipefail`, or a reader piped straight from a producer that closes the pipe early, are each + invisible until the exact failure mode they guard against actually happens. Fleet-wide: a shell + script can appear in any repo (a bootstrap that installs the interpreter, a host tool that must + run before a toolchain exists), not only a repo whose primary language is shell. --- # Shell Codestyle @@ -50,6 +51,11 @@ depend on Python either. Everything else is Python, with a test under its own sc - **A reader that stops early needs its producer read first.** Under `pipefail`, a producer writing to a closed pipe exits non-zero, so `curl ... | grep -q` reports a successful fetch as a failure whenever the match is found early enough. Capture the output, then search it. +- **A shim named for a command resolves that command by absolute path.** A wrapper named `jq`, + placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, + since `command` skips functions and aliases but not the `PATH` search. Every call starts another + copy of the wrapper, so the chain grows until something stops it. Capture the real path with + `command -v` before changing `PATH`, and call that path from inside the shim. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working directory at invocation is not a property of the script. diff --git a/AGENTS.md b/AGENTS.md index a2c864674..a63d4cb0e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,7 @@ An agent session is billed on the context it carries, not the work it does. Ever - **Keep a long query in a file, not in the command.** A heredoc re-typed on every call costs its own length in context each time, often more than the answer it retrieves. - **Keep generated caches outside the checkout when the executor restricts writes.** Give each task a cache directory under a writable temporary root. Point tools such as uv and ruff there through their own cache variables. Never repurpose `HOME` or an agent's configuration directory to make a tool run. - **Report an execution boundary separately from a check finding.** A denied path, network request, or Docker socket says the check did not run. Preserve that failure, then use the executor's approval mechanism for the required rerun. Request the narrowest reusable command prefix the executor supports. Report the rerun's result as the verification evidence. +- **Bound every probe, and prove it ended.** A throwaway probe or test harness runs under `timeout`, and one that can recurse or fan out also runs under a task and memory cap. Start it in a process group of its own, as `setsid timeout `, and end it by that group with `kill -- -`. A `pkill -f` pattern that matches nothing exits 1 and kills nothing. Then confirm with `pgrep` that nothing from any earlier run survives, since a later clean run proves nothing about an earlier one. Never suppress a cleanup command's output or exit status. A command the harness moved to the background, where no background job was intended, is stopped and confirmed gone before work continues. ### Delegation diff --git a/CODESTYLE.md b/CODESTYLE.md index a18c45659..208a4eeaf 100644 --- a/CODESTYLE.md +++ b/CODESTYLE.md @@ -51,7 +51,7 @@ This is packaged as the `python-codestyle` Skill at `.agents/skills/python-codes ## Shell -Bash, and only where a program cannot be Python: a bootstrap that installs the interpreter cannot be written in it, and a host tool that must run before a development toolchain exists cannot depend on Python either. Everything else is Python, with a test under its own scripts tree's `tests/` directory. The mandatory `set -Eeuo pipefail` header, the pipefail-versus-early-reader pitfall, self-locating scripts, the `shellcheck`-plus-`shfmt` clean-compile, and the why-not-what comment rule are packaged as the `shell-codestyle` Skill at `.agents/skills/shell-codestyle/SKILL.md` in the hub, not a repo-relative link since that path is hub-local and not carried into every fleet repo. Read the skill for the full rules. Run the clean-compile check itself per `GOVERNANCE.md` "Running the Linters Locally (Known-Working Invocations)", a hub-only section read in a hub checkout rather than carried into every fleet repo, not by probing `command -v shellcheck`. +Bash, and only where a program cannot be Python: a bootstrap that installs the interpreter cannot be written in it, and a host tool that must run before a development toolchain exists cannot depend on Python either. Everything else is Python, with a test under its own scripts tree's `tests/` directory. The mandatory `set -Eeuo pipefail` header, the pipefail-versus-early-reader pitfall, self-recursive command shims, self-locating scripts, the `shellcheck`-plus-`shfmt` clean-compile, and the why-not-what comment rule are packaged as the `shell-codestyle` Skill at `.agents/skills/shell-codestyle/SKILL.md` in the hub, not a repo-relative link since that path is hub-local and not carried into every fleet repo. Read the skill for the full rules. Run the clean-compile check itself per `GOVERNANCE.md` "Running the Linters Locally (Known-Working Invocations)", a hub-only section read in a hub checkout rather than carried into every fleet repo, not by probing `command -v shellcheck`. diff --git a/host-setup/agent-safety/README.md b/host-setup/agent-safety/README.md index ccb791efb..03cc87e12 100644 --- a/host-setup/agent-safety/README.md +++ b/host-setup/agent-safety/README.md @@ -2,7 +2,7 @@ What any coding agent must be stopped from doing when it runs unattended on this host, stated once, independent of which agent implements it. Most of it guards the maintainer's `gh` credentials, which -is where the harm started. Requirements 7 and 8 guard the machine itself, which is the other thing +is where the harm started. Requirements 7 to 9 guard the machine itself, which is the other thing an unattended agent takes down. This file is the source of truth: an implementation is built from the requirements below, and an implementation is audited by checking its decisions against them, not by reading its source as the implicit spec. @@ -21,9 +21,10 @@ prose. The requirements below are that criteria applied to this host. ## Requirements Each requirement is stated as a decision rule, precise enough to implement against any agent's own -hook or approval-gate API, not tied to Claude Code's `PreToolUse` JSON shape. Requirement 8 is the -one stated against the end of a session rather than against a tool call, because what it covers has -already happened by the time any tool call is judged. +hook or approval-gate API, not tied to Claude Code's `PreToolUse` JSON shape. Requirement 8 is +stated against the end of a session rather than against a tool call, because what it covers has +already happened by the time any tool call is judged. Requirement 9 bounds every command whatever its +text says, because the harm it covers was never in the text. 1. **A GitHub write with its output discarded or forced to success is denied.** A state-changing `gh`/API call piped to `>/dev/null`, `2>/dev/null`, `&>/dev/null`, `|| true`, `|| :`, or `|| echo` @@ -256,9 +257,10 @@ already happened by the time any tool call is judged. "Delegation", which states the prohibition for every agent whether or not a hook is installed. 8. **A process outliving the session is reported, never killed.** Requirement 7 stops a leak from - being written. This one finds the leaks already running: the ones a session started before that - deny reached this machine, the four shapes it deliberately does not reach, and anything else - this agent left running whether it leaked or not. At the end of a session, report every descendant + being written, and requirement 9 stops what the session's own bounded commands leave behind. This + one finds the leaks still running: the ones a session started before either reached this machine, + the four shapes requirement 7 deliberately does not reach, and anything else this agent left + running outside requirement 9's groups, whether it leaked or not. At the end of a session, report every descendant of the agent process that runs outside the agent's own session, since a descendant sharing that session ends when the agent does and one in a session of its own does not. Report the root of each such subtree rather than every process under it, name each root's command and age, and hand @@ -278,6 +280,25 @@ already happened by the time any tool call is judged. is the only requirement here that is not a denial, and it is a requirement rather than a nicety because the alternative is that nobody learns the leak happened at all. +9. **Every command is bounded on tasks and memory, and what it leaves running ends with the + session.** Requirement 7 reads the command text, and the harm here was not in it. A probe wrote + a command shim that called itself through `PATH`, the command ran the probe only by name, and the + chain grew past half a million processes before the host had to be reset. Run each command inside + a resource-control group of its own carrying a task ceiling and a memory ceiling, so a runaway + fan-out fails at the ceiling with a visible error. The ceiling belongs to the group rather than to + the foreground wait, so it still holds after the tool moves a timed-out command to the background + and after the command's own shell has exited. + + Name each group for the session that ran it, and at the end of the session stop every group its + commands left running, then report what was stopped. This stop needs none of requirement 8's + judgment about what a process is, since the group's name proves which session started it. Report + a failure to list or to stop a group as loudly as a finding. A hook command is bounded the same + way and is not stopped, since another end-of-session hook may still be running in its own group. + + The maintainer sets the ceilings, in a channel the command being bounded cannot reach. Where the + host offers no such group, the command runs unbounded and says so on every run, because a silent + fallback reads exactly like a bounded command. + ## Decision Flow ```mermaid @@ -321,8 +342,9 @@ flowchart LR ``` The first diagram is this spec's actual decision flow, generalized from `claude/gh-write-guard.py`'s -`classify()`. Requirement 8 appears nowhere in it, deliberately: it judges no tool call, and it runs -once at the end of a session on whatever the denials above did not prevent. The second is why a failure lands in one layer and not another. A rule that never +`classify()`. Requirements 8 and 9 appear nowhere in it, deliberately: neither judges a command's +text. Requirement 9 wraps every command the flow allows, and requirement 8 runs once at the end of a +session on whatever the denials and the ceilings did not prevent. The second is why a failure lands in one layer and not another. A rule that never reached the session at all is a loading bug, fixed the way PR #1081 fixed `local-strict-review`'s missed trigger, by wiring `CLAUDE.md` to import `AGENTS.md`. A rule that reached the session and was still not followed, where the trigger is mechanically decidable and the harm is destructive, @@ -354,7 +376,7 @@ every agent. | Agent | Status | Implementation | | --- | --- | --- | -| Claude Code | All 8 requirements, via a `PreToolUse` hook and a `SessionEnd` sweep | [`claude/README.md`][claude] | +| Claude Code | All 9 requirements, via a `PreToolUse` hook, a shell prefix, and a `SessionEnd` sweep | [`claude/README.md`][claude] | | Codex | No hook yet -- tracked at [issue #781][issue-781] | [`codex/README.md`][codex] | | opencode | No hook yet -- tracked at [issue #781][issue-781] | [`opencode/README.md`][opencode] | @@ -364,8 +386,9 @@ local host-safety hazard for this kit to cover. ## Auditing an Implementation Against This Spec -Run each of the implementation's own self-tests (`claude/gh-write-guard.py --selftest` and -`claude/stray-process-sweep.py --selftest` for Claude Code) and compare every case against the +Run each of the implementation's own self-tests (`claude/gh-write-guard.py --selftest`, +`claude/stray-process-sweep.py --selftest`, and `claude/tool-containment.py --selftest` for Claude +Code) and compare every case against the requirements list above, one by one, rather than reading the implementation's source as though it were the spec. A case the self-test doesn't cover is a gap in the audit, not evidence the requirement is satisfied. This is the concrete shape of "ask Claude to diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index c1df8ea38..24d3d5027 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -13,7 +13,8 @@ installation and operational detail. Codex and opencode have no equivalent hook Into `~/.claude/` (or `%USERPROFILE%\.claude\` on Windows): - **`hooks/gh-write-guard.py`**: a PreToolUse hook that denies four classes of dangerous action. First, the GitHub **write** footguns behind the cross-repo comment incident: a state-changing `gh` call whose output is discarded, a GraphQL mutation passing a **literal** node id instead of a `$variable`, and a `gh` write whose explicit target is under an owner other than the checkout origin's. Sibling repositories under the same owner are allowed, since the harm this guards is reaching a stranger's repository rather than working across one maintainer's own fleet, and a different owner is allowed only when the maintainer names it in `GH_WRITE_GUARD_ALLOW` (an `owner/repo` list, where `owner/*` grants a whole owner). That variable is read from the environment the session was launched with, which is the one channel an agent cannot set for itself: a hook runs as its own process, so an inline `VAR=x cmd` prefix or an `export` inside a Bash call never reaches it. Second, a **git operation that bypasses a repository protection**. The branch-rule cases (a direct push to a branch that requires a pull request, a force-push where history is protected, a branch delete where deletion is blocked) are judged against the branch's **live** rules, so a code-style `develop` is denied while a config-style `develop` is allowed with no per-repo configuration. A push to a protected-default branch fails closed when its rules cannot be determined, either because the API is unreachable or because the checkout's origin cannot be resolved to query them. The explicit-bypass flags are denied **unconditionally**, since the flag is itself the bypass and needs no branch query: `gh pr merge --admin` overrides the server-side merge gate, and `git commit`/`git push --no-verify` skips the local git hooks. Third, a **mutating git operation run directly against a primary checkout** (`checkout`/`switch`/`pull`/`reset`/`rebase`/`merge`/`cherry-pick`/`revert`/`restore`/`add`/`commit`/`rm`/`mv`/`apply`/`am`/`push`/`stash` (anything but `list`/`show`)/`clean -f`/`worktree remove -f`), the harm behind a second incident where an agent reused the maintainer's own primary checkout instead of a worktree despite having read the prose rule against it. "Primary" is decided by comparing `git rev-parse --git-dir` against `--git-common-dir`, not a `.git`-is-a-directory guess. `worktree add`/`list`/`prune`, an unforced `worktree remove`, `merge --ff-only`/`pull --ff-only`, and a `checkout `/`switch ` carrying no force flag (bundled or attached forms like `-qf`/`-Bname` recognized, not only an exact token) stay exempt even in a primary checkout, matching the documented base-clone cleanup step the `repo-worktree` skill already carries. A subcommand this rule does not recognize is resolved through a chain of git aliases, inline and persisted, before falling through, so a custom alias cannot hide a denied builtin behind an unrecognized name. A `!`-prefixed shell alias is denied outright rather than interpreted. The target directory follows real git's own `-C`/`--work-tree`/`--git-dir` priority, not a last-option-wins scan. A different owner-style grant, `GH_WRITE_GUARD_ALLOW_PRIMARY_CHECKOUT`, follows the same channel as `GH_WRITE_GUARD_ALLOW`. Reads and everything else pass through. Fourth, an **unbounded shell wait**, which the root spec's requirement 7 defines in full rather than this bullet redefining it. In outline: a loop that sleeps, carrying no bound the rule recognizes. It is the shape an agent writes when a brief tells it to poll. It is also the harm behind a third incident, where seven such loops outlived the subagents that wrote them and the run that dispatched those subagents. A shell started by a tool call runs in a session of its own, so the agent could not have reaped it even had it tried. A nested loop is judged on its own terms, and a command that forks anything out of a `timeout`'s reach, by backgrounding it or by `setsid`, is bounded by nothing. A heredoc body is data rather than a command line unless a shell is what it is fed to, so a document quoting the forbidden shape is written rather than denied. It fires even in autonomous / bypass-permissions sessions, which is how the first incident happened. See the root spec's requirements 6 and 7 for the exact rules. -- **`hooks/stray-process-sweep.py`**: a SessionEnd hook that reports, and never ends, the process trees that outlive the session. The guard above stops a leak from being written. This finds the ones already running: the ones started before the guard was installed, and the shapes the guard deliberately does not reach. It reads the process table once. It reports every descendant of the agent process running outside the agent's own session. It names each subtree root's command and age, and hands over the `kill` line. It kills nothing itself. A long build backgrounded on purpose reads identically to a leaked wait from there. What is still wanted on the machine is the maintainer's call. A SessionEnd hook cannot block, and its JSON output is discarded, so stderr on exit 2 is the one channel that reaches the maintainer. The sweep uses that for a report rather than for a refusal. It registers under a group carrying no matcher, which fires on every exit reason. It also carries an explicit timeout, since the event's own budget is 1.5 seconds and only a declared per-hook timeout raises it. See the root spec's requirement 8. +- **`hooks/tool-containment.py`**: a shell prefix, registered as `CLAUDE_CODE_SHELL_PREFIX` in the `env` block of `settings.json`, that runs every command Claude Code executes inside a transient systemd user scope carrying `TasksMax` and `MemoryMax`. That covers each Bash tool call and each hook command. A runaway fan-out then fails at the ceiling with `fork: Resource temporarily unavailable` instead of growing until the host has to be reset, the harm behind the probe-shim incident in the root spec's requirement 9. The guard above reads the command text, and that incident's recursion lived in a script file the command only named. The ceilings default to 8192 tasks and 25% of RAM. The maintainer raises them with `AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block, which an agent cannot set for itself, since the prefix reads the environment the session was launched with and runs before anything in the command does. Each scope is named `claude-tool--` for a Bash tool call and `claude-hook--` for a hook command, so the sweep below can stop one session's tool calls and nothing else. The installer sets the prefix only on a host with a running systemd user manager, and never over a `CLAUDE_CODE_SHELL_PREFIX` value that names anything else. +- **`hooks/stray-process-sweep.py`**: a SessionEnd hook in two phases. First, it stops every `claude-tool--*` scope this session left loaded and reports what each held, since the scope's name proves which session started it. Second, it reports, and never ends, the process trees outside those scopes that outlive the session. The guard above stops a leak from being written. This finds the ones already running: the ones started before the guard was installed, and the shapes the guard deliberately does not reach. It reads the process table once. It reports every descendant of the agent process running outside the agent's own session. It names each subtree root's command and age, and hands over the `kill` line. It kills nothing itself. A long build backgrounded on purpose reads identically to a leaked wait from there. What is still wanted on the machine is the maintainer's call. A SessionEnd hook cannot block, and its JSON output is discarded, so stderr on exit 2 is the one channel that reaches the maintainer. The sweep uses that for a report rather than for a refusal. It registers under a group carrying no matcher, which fires on every exit reason. It also carries an explicit timeout, since the event's own budget is 1.5 seconds and only a declared per-hook timeout raises it. See the root spec's requirement 8. - **Two marker-delimited blocks of host-wide content in `CLAUDE.md`**, loaded into every session on the machine (including ad-hoc work outside any project), installed and updated independently so one can change without rewriting the other. - The `agent-safety` block carries restrictions alone, so nothing in it can widen a permission. `Repository Boundaries and Write Safety` mirrors the committed `GOVERNANCE.md` section of the same name, carrying as behavioral guidance its write rules and its rules that a task works in its own checkout and isolates into its own worktree before its first file edit. `Data in Agent-Authored Text` mirrors `GOVERNANCE.md` "Representative Data in Agent-Authored Text", so an agent illustrates with constructed data rather than data observed on the machine. `Authorization Scope and Memory Hygiene` bounds how a granted permission is recorded and read. Each mirrors a rule that otherwise reaches fleet repos only. - The `fleet-bootstrap` block carries `Fleet Governance Entry Point`, which names the template repository and routes by the state a repository is actually in. It is separate precisely because it enables rather than restricts, and the safety block's own text says nothing in it widens a permission, so merging the two would contradict that. It is host-wide rather than per repository because the repositories that most need it are the ones carrying no instruction set to point the way, and it mirrors the byte-locked `AGENTS.md` "Fleet Bootstrap" section that a conformant repository carries. @@ -47,6 +48,8 @@ The deployed copy on each machine is a snapshot, so when the guard changes upstr ```sh python3 ~/.claude/hooks/gh-write-guard.py --selftest # decision matrix: all cases pass python3 ~/.claude/hooks/stray-process-sweep.py --selftest # reporting matrix: all cases pass +python3 ~/.claude/hooks/tool-containment.py --selftest # containment matrix: all cases pass +grep -c CLAUDE_CODE_SHELL_PREFIX ~/.claude/settings.json # expect 1 where a user manager runs, 0 elsewhere grep -c 'agent-safety v' ~/.claude/CLAUDE.md # expect 2 (start + end marker) grep -c 'fleet-bootstrap v' ~/.claude/CLAUDE.md # expect 2 (start + end marker) grep -cF 'Bash(python3 scripts/pr_review.py:*)' ~/.claude/settings.json # expect 1 (never duplicated) @@ -57,6 +60,7 @@ On Windows PowerShell: ```powershell py -3 "$env:USERPROFILE\.claude\hooks\gh-write-guard.py" --selftest # all cases pass py -3 "$env:USERPROFILE\.claude\hooks\stray-process-sweep.py" --selftest # all cases pass +py -3 "$env:USERPROFILE\.claude\hooks\tool-containment.py" --selftest # all cases pass (Select-String 'agent-safety v' "$env:USERPROFILE\.claude\CLAUDE.md").Count # expect 2 (Select-String 'fleet-bootstrap v' "$env:USERPROFILE\.claude\CLAUDE.md").Count # expect 2 (Select-String -SimpleMatch 'Bash(python3 scripts/pr_review.py:*)' "$env:USERPROFILE\.claude\settings.json").Count # expect 1 @@ -68,6 +72,12 @@ Live end-to-end (in any repo): attempt a discarded-output write and confirm the gh api graphql -f query='mutation{noop}' -F t="PRRT_x" >/dev/null 2>&1 || true # blocked by the hook ``` +Where the prefix is registered, confirm a command runs contained. The line names a `claude-tool-` scope: + +```sh +cat /proc/self/cgroup +``` + ## Granting a Write That the Guard Denies The guard denies a `gh` write whose explicit target sits under an owner other than the checkout's `origin` owner, and the denial names `GH_WRITE_GUARD_ALLOW` as the way past it. That grant is the maintainer's to make, and making it is a deliberate act taken outside the session rather than something an agent does for itself once blocked. This is the one denial a maintainer has to act on, because it is the only one with a grant behind it -- the others name a shape to stop using, while this one names a target that may be entirely legitimate. @@ -116,6 +126,9 @@ Run the installer rather than hand-copying this block on a host where the two mi ```json { + "env": { + "CLAUDE_CODE_SHELL_PREFIX": "/.claude/hooks/tool-containment.py" + }, "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "\"python3\" \"/.claude/hooks/gh-write-guard.py\"" } ] } @@ -130,7 +143,7 @@ Run the installer rather than hand-copying this block on a host where the two mi } ``` -Every other key in the file is left as it stands, `permissions.allow` included, apart from the rules whose prefix this kit owns. +Every other key in the file is left as it stands, `permissions.allow` and the rest of `env` included, apart from the rules whose prefix this kit owns. The `env` entry is written only on a host with a running systemd user manager. ## Scope and Limits @@ -141,9 +154,12 @@ Every other key in the file is left as it stands, `permissions.allow` included, - **A write or a wait inside a script file is unseen, so never put either in a script to run it.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string. A `git push` or a `gh` mutation inside the script therefore reaches the server unparsed. An unbounded wait inside that same script is equally unseen, and worse in one way. A denied write fails loudly. A wait the guard never saw runs until something ends it, which is one of the leaks the SessionEnd sweep exists to find afterwards. This is the widest hole in the kit, and an agent opens it by accident. Collecting fifteen repetitive pushes into a loop looks like tidiness, and so does moving a poll into a script to keep a tool call short. Neither looks like disabling a guard. Issue each write and each wait as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and the wait rather than the script. - **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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. +- **Containment runs on Linux and WSL with a systemd user manager.** macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. +- **Containment wraps hook commands too.** Claude Code applies `CLAUDE_CODE_SHELL_PREFIX` to hook commands as well as to Bash tool calls, so the guard and the sweep each run inside a `claude-hook-` scope. A hook scope is bounded and never stopped at session end, since a sibling SessionEnd hook may still be running inside one. Each wrapped command costs about 35 ms on the reference host, measured as two Python starts and one scope creation. +- **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. 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. - **The sweep runs at session end, not at subagent end.** `SubagentStop` is where the incident's own loops were born, and it would catch each one hours earlier. Its exit 2 prevents the subagent from stopping, though, so the one channel that reaches a human on `SessionEnd` is not free there. A sweep that cannot report is a sweep that does nothing. The cost of the later moment is real. A run dispatching workers for hours reaches session end once, having finished many rounds, so every leak it wrote is reported together at the end. -- **The sweep reports and never kills.** It cannot tell a leaked wait from a long build backgrounded on purpose, and nothing about ending a process on the maintainer's machine is reversible. It hands over the `kill` line and stops there. +- **The sweep's second phase reports and never kills.** Outside a containment scope it cannot tell a leaked wait from a long build backgrounded on purpose, and nothing about ending a process on the maintainer's machine is reversible. It hands over the `kill` line and stops there. - **The sweep sees the agent's own descendants, and a leak can leave that tree.** A process whose tool-call shell has since exited is reparented to init, so no descendant walk reaches it. What the sweep does see is the backgrounded tool-call shell itself. That is the shape both incidents left behind, and it stays a child of the agent for the whole session. The residual gap is a process that shell in turn backgrounded and abandoned. It is stated here rather than left for a reader to infer from a clean report. - **Rule 6 needs git 2.31 or newer for `rev-parse --path-format=absolute`.** An older git errors on that flag, `_is_primary_checkout` reads that as an unresolved target, and the rule fails open silently on that host -- no crash, no denial, and no diagnostic pointing at the version. `spec/host-tools.json` carries no floor on `git` today (see its own `why` field for the reasoning that applies fleet-wide). This is a narrower, rule-specific dependency worth knowing about rather than a case for raising that floor on its own. diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 3f352be47..dad144f1a 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 """Install the agent host-safety kit for the current user account. Cross-platform, idempotent. -Deploys the PreToolUse hook and the SessionEnd stray-process sweep, registers both in the user -settings.json, merges the permission rules this kit owns into the same file, adds the safety rules to +Deploys the PreToolUse hook, the SessionEnd stray-process sweep, and the tool-containment shell prefix, +registers the two hooks in the user settings.json and, on a host with a systemd user manager, the prefix +in its `env`, merges the permission rules this kit owns into the same file, adds the safety rules to the user CLAUDE.md (marker-delimited so re-runs update in place), and self-tests each hook before registering it. The bash and PowerShell wrappers both call this, so every OS runs one tested code path. @@ -16,6 +17,7 @@ python3 install.py --report (read-only: is this machine current?) CLAUDE_HOME=/x python3 install.py (override target, for testing) AGENT_SAFETY_DIRTY_OVERRIDE=0/1 python3 install.py (force the dirty-checkout signal, for testing) + AGENT_SAFETY_CONTAINMENT_OVERRIDE=0/1 python3 install.py (force the containment-capable signal, for testing) """ import argparse @@ -26,6 +28,7 @@ import pathlib import platform import re +import shlex import shutil import socket import subprocess @@ -40,11 +43,14 @@ GUARD_STEM = "gh-write-guard" SWEEP_NAME = "stray-process-sweep.py" SWEEP_STEM = "stray-process-sweep" +CONTAIN_NAME = "tool-containment.py" + +PREFIX_VAR = "CLAUDE_CODE_SHELL_PREFIX" # The hook files this kit copies into ~/.claude/hooks, in deploy order. # Named here rather than spelled inside `main`, since a test scraping `main` for a literal path goes silent when the copy is refactored. # That silence reads as a pass. -DEPLOYED_HOOKS = (GUARD_NAME, SWEEP_NAME) +DEPLOYED_HOOKS = (GUARD_NAME, SWEEP_NAME, CONTAIN_NAME) # A SessionEnd hook's own budget is 1.5 seconds, raised to the highest per-hook timeout the settings declare. # The sweep reads one process table, so this is headroom for a loaded machine rather than a duration it uses. @@ -173,6 +179,31 @@ def at(data, path): ] +def containment_capable(): + """(capable, reason): whether this host can start a systemd user scope for an agent command. + + Judged at install and at report time alike, so a host that gains or loses its user manager is + reported against what it can do now. AGENT_SAFETY_CONTAINMENT_OVERRIDE, read as exactly "0" or + "1", replaces the judgment for a test, the way AGENT_SAFETY_DIRTY_OVERRIDE does for the dirty signal. + """ + override = os.environ.get("AGENT_SAFETY_CONTAINMENT_OVERRIDE") + if override in ("0", "1"): + return override == "1", "forced by AGENT_SAFETY_CONTAINMENT_OVERRIDE" + if not sys.platform.startswith("linux"): + return False, f"{platform.system()} has no systemd user manager" + if not shutil.which("systemd-run"): + return False, "systemd-run is not installed" + runtime = os.environ.get("XDG_RUNTIME_DIR") + if not runtime or not os.path.exists(os.path.join(runtime, "systemd", "private")): + return False, "no systemd user manager is running for this account" + return True, "a systemd user manager is running" + + +def prefix_value(path): + """The `CLAUDE_CODE_SHELL_PREFIX` value naming the deployed prefix, spelled once for writer and reader.""" + return shlex.quote(str(path)) + + def hook_launcher(): """A python invocation for the settings.json command. Prefer a bare `python3` (portable and unambiguously Python 3), else this interpreter's absolute path (guaranteed the Python 3 running the @@ -283,7 +314,7 @@ def payload_digest(): Fixed order because a set of files has none, and a digest that depends on directory listing order reports drift on a machine where nothing changed. The order matches the one - `installed_digest` reads, so the two are directly comparable: the guard, the sweep, then each block. + `installed_digest` reads, so the two are directly comparable: each deployed hook, then each block. """ h = hashlib.sha256() for name in PAYLOAD_FILES: @@ -555,6 +586,21 @@ def event_groups(event): ) elif swept > 1: out.append(f"the SessionEnd sweep is registered {swept} times, so it runs more than once") + capable, reason = containment_capable() + env = data.get("env") + held = env.get(PREFIX_VAR) if isinstance(env, dict) else None + want = prefix_value(claude_home / "hooks" / CONTAIN_NAME) + if capable and held != want: + why = f"is held by {held!r}" if held else "is not set" + out.append( + f"{PREFIX_VAR} {why}, so agent commands run with no task or memory ceiling " + f"although this host can contain them ({reason})" + ) + elif not capable and held == want: + out.append( + f"{PREFIX_VAR} names the containment prefix on a host that cannot contain ({reason}), " + "so every command prints a notice and runs uncontained" + ) allow = ( data.get("permissions", {}).get("allow") if isinstance(data.get("permissions"), dict) @@ -692,6 +738,7 @@ def main(): hooks_dir = claude_home / "hooks" hook_dst = hooks_dir / GUARD_NAME sweep_dst = hooks_dir / SWEEP_NAME + contain_dst = hooks_dir / CONTAIN_NAME settings = claude_home / "settings.json" claude_md = claude_home / "CLAUDE.md" @@ -798,6 +845,7 @@ def reject(where, held, want): ("hooks/SessionEnd", list), ("permissions", dict), ("permissions/allow", list), + ("env", dict), ): held = at(data, path) # An explicit null is present rather than absent, and `setdefault` hands back the null it found. @@ -859,6 +907,24 @@ def reject(where, held, want): ) done.append("SessionEnd sweep registered") + # Step 2c sets the containment prefix only where this host can start a scope, and never over a value naming anything else. + capable, reason = containment_capable() + env = data.setdefault("env", {}) + held = env.get(PREFIX_VAR) + ours = held is not None and CONTAIN_NAME in str(held) + if held is not None and not ours: + done.append( + f"{PREFIX_VAR} left as {held!r}, which this kit does not own, so no containment" + ) + elif capable: + env[PREFIX_VAR] = prefix_value(contain_dst) + done.append(f"{PREFIX_VAR} set, so agent commands run contained ({reason})") + else: + env.pop(PREFIX_VAR, None) + done.append(f"{PREFIX_VAR} not set, so agent commands run uncontained ({reason})") + if not env: + del data["env"] + # 3. Permission rules, merged under the prefixes this installer owns. # The strip-then-register shape is the hook registration's above, applied to a flat list. # Written in the same pass as the hook, so the file is read once and written once. diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py index ab1890eab..60343d973 100755 --- a/host-setup/agent-safety/claude/stray-process-sweep.py +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -1,11 +1,18 @@ #!/usr/bin/env python3 -"""SessionEnd sweep: report the shell processes that outlived the session and that nothing will reap. +"""SessionEnd sweep: stop the session's contained commands, then report whatever else outlived it. + +The first phase stops every command scope `tool-containment.py` started for this session's Bash tool +calls. Each is known to be this session's own by its unit name, so stopping it needs no judgment about +what the process is, and a backgrounded runaway ends with the session that started it. What was stopped +is reported. See host-setup/agent-safety/README.md requirement 9. + +The second phase is the report-only sweep below, for everything outside those scopes. Registered as a Claude Code SessionEnd hook. It reads the hook payload on stdin, walks the process table for the agent process this hook is a child of, and reports every descendant running in its own session, since a shell started by a tool call is put in a session of its own and therefore survives -the agent that started it. It never kills anything: the maintainer decides what on the machine is -still wanted, and a long build backgrounded on purpose looks exactly like a leaked wait from here. +the agent that started it. This phase never kills anything: the maintainer decides what on the machine +is still wanted, and a long build backgrounded on purpose looks exactly like a leaked wait from here. Reporting at all is what needs saying. A SessionEnd hook cannot block, and Claude Code discards its JSON output, so stderr on exit 2 is the one channel that reaches the maintainer. Exit 2 is inert on @@ -28,9 +35,12 @@ import json import os import re +import shutil import subprocess import sys +_TOOL_UNIT = "claude-tool" + # The process-table fields this sweep reads, in this order, with no header line. _PS_FORMAT = "pid=,ppid=,sess=,etimes=,args=" @@ -211,15 +221,130 @@ def report(table, roots): return "\n".join(lines) +def _systemctl(*args): + """(exit code, stdout) of `systemctl --user `, or (None, "") when it cannot run at all.""" + try: + done = subprocess.run( + ["systemctl", "--user", *args], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=8, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None, "" + return done.returncode, done.stdout + + +def session_token(session_id): + """The session id as `tool-containment.py` spells it in a unit name, or "" where there is none.""" + return re.sub(r"[^A-Za-z0-9-]", "", session_id or "")[:64] + + +def session_scopes(session_id, runner=_systemctl): + """The tool-call scopes this session left loaded, or None when systemd cannot be asked. + + Only this session's tool-call scopes match. A hook command's scope is named apart, since another + SessionEnd hook may still be running in one while this runs. + """ + token = session_token(session_id) + if not token: + return [] + code, out = runner( + "list-units", + "--type=scope", + "--all", + "--plain", + "--no-legend", + "--no-pager", + f"{_TOOL_UNIT}-{token}-*.scope", + ) + if code != 0: + return None + return [line.split()[0] for line in out.splitlines() if line.split()] + + +def scope_pids(units, runner=_systemctl, read=None): + """{unit: [pid, ...]} read from each scope's cgroup, empty for a scope whose cgroup cannot be read.""" + + def _read(path): + try: + with open(path, encoding="utf-8") as f: + return f.read() + except OSError: + return "" + + read = read or _read + code, out = runner("show", "--property=Id", "--property=ControlGroup", "--", *units) + groups = {} + # One block per unit, blank-line separated, with its properties in systemd's order rather than the order asked. + for block in (out or "").split("\n\n") if code == 0 else []: + props = dict(line.partition("=")[::2] for line in block.splitlines()) + if props.get("Id") and props.get("ControlGroup"): + groups[props["Id"]] = props["ControlGroup"] + return { + u: [int(p) for p in read(f"/sys/fs/cgroup{groups[u]}/cgroup.procs").split() if p.isdigit()] + if u in groups + else [] + for u in units + } + + +def reap(session_id, table, runner=_systemctl, read=None): + """Stop this session's tool-call scopes, returning the report, or "" when there were none.""" + units = session_scopes(session_id, runner) + if units is None: + return ( + "agent-safety: could not list this session's command scopes, so none was stopped. " + f"Check with: systemctl --user list-units '{_TOOL_UNIT}-*'" + ) + if not units: + return "" + pids = scope_pids(units, runner, read) + code, _out = runner("stop", "--", *units) + left = session_scopes(session_id, runner) if code == 0 else units + left = units if left is None else [u for u in left if u in units] + stopped = [u for u in units if u not in left] + lines = [] + if stopped: + noun = "scope" if len(stopped) == 1 else "scopes" + lines.append( + f"agent-safety: stopped {len(stopped)} command {noun} this session left running." + ) + for u in stopped: + members = pids[u] + roots = [p for p in members if table.get(p, (None,))[0] not in members] or members + lines.append(f" {u} {len(members)} process{'' if len(members) == 1 else 'es'}") + for p in roots[:3]: + if p in table: + lines.append(f" pid {p} age {_age(table[p][2])} {table[p][3][:140]}") + if left: + lines.append( + f"agent-safety: {len(left)} command scope(s) did not stop. End them with:\n" + f" systemctl --user kill --signal=SIGKILL {' '.join(left)}" + ) + return "\n".join(lines) + + def main(): try: - json.loads(sys.stdin.read() or "{}") # the payload is read and not otherwise used + payload = json.loads(sys.stdin.read() or "{}") except (ValueError, OSError): - pass + payload = {} # Windows has no session test at all, and a BSD `ps` carries neither `etimes` nor a decimal # `sess`, so on both the hook is inert rather than printing a failure at every session end. if os.name != "posix" or sys.platform == "darwin": return 0 + session_id = ( + payload.get("session_id") if isinstance(payload, dict) else None + ) or os.environ.get("CLAUDE_CODE_SESSION_ID") + reaped = "" + if shutil.which("systemctl"): + reaped = reap(session_id, _read_process_table() or {}) + if reaped: + print(reaped, file=sys.stderr) table = _read_process_table() if table is None: print( @@ -237,7 +362,7 @@ def main(): return 2 text = report(table, survivors(table, agent, os.getpid())) if not text: - return 0 + return 2 if reaped else 0 print(text, file=sys.stderr) return 2 @@ -337,6 +462,52 @@ def _selftest(): "nor is one whose own arguments name a claude path", ), ] + sid = "0a1b-2c3d" + live = {f"{_TOOL_UNIT}-{sid}-400.scope", f"{_TOOL_UNIT}-{sid}-600.scope"} + calls = [] + + def fake(*args, stop_code=0, sticky=()): + calls.append(args) + if args[0] == "list-units": + return 0, "".join( + f"{u} loaded active running Claude Code command\n" for u in sorted(live) + ) + if args[0] == "show": + return 0, "".join( + f"ControlGroup=/app.slice/{u}\nId={u}\n\n" for u in args if u.endswith(".scope") + ) + if args[0] == "stop": + live.difference_update(u for u in args[2:] if u not in sticky) + return stop_code, "" + return 1, "" + + procs = {f"/sys/fs/cgroup/app.slice/{_TOOL_UNIT}-{sid}-400.scope/cgroup.procs": "400\n410\n"} + reaped = reap(sid, table, runner=fake, read=lambda p: procs.get(p, "")) + stopped_all = not live + live.update({f"{_TOOL_UNIT}-{sid}-400.scope"}) + sticky = f"{_TOOL_UNIT}-{sid}-400.scope" + stuck = reap( + sid, table, runner=lambda *a: fake(*a, sticky=(sticky,)), read=lambda p: procs.get(p, "") + ) + live.clear() + checks += [ + (stopped_all, "every tool-call scope of this session is stopped"), + ( + calls[0][-1] == f"{_TOOL_UNIT}-{sid}-*.scope", + "and only this session's tool-call scopes are listed, never a hook's", + ), + ("stopped 2 command scopes" in reaped, "the report counts what was stopped"), + ("2 processes" in reaped and "pid 400" in reaped, "and names each scope's root process"), + ("pid 410" not in reaped, "but not a process under that root"), + ("did not stop" in stuck and f"SIGKILL {sticky}" in stuck, "a scope that stays is named"), + (reap("", table, runner=fake) == "", "a session with no id stops nothing"), + (reap(sid, table, runner=fake) == "", "a session that left nothing reports nothing"), + ( + "could not list" in reap(sid, table, runner=lambda *a: (None, "")), + "a systemctl that cannot run is reported, never read as nothing to stop", + ), + (session_token("a/b c;d") == "abcd", "the unit name is spelled as the prefix spells it"), + ] ok = True for passed, label in checks: if not passed: diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index 76f3d22bd..a035a5206 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -24,15 +24,23 @@ import install -def run(home, *args, dirty=False): +def run(home, *args, dirty=False, contain=True): """Invoke the installer as a subprocess, the way a host actually runs it. dirty forces the dirty-checkout signal install.py's own source_ref() would otherwise read live from this checkout, via AGENT_SAFETY_DIRTY_OVERRIDE, so a verdict this suite asserts depends on the fixture rather than on whether host-setup happens to be mid-edit while the suite runs. The default is clean, since that is what every case but one below needs. + + contain forces the containment-capable signal the same way, so a verdict does not depend on + whether the machine running the suite has a systemd user manager. """ - env = dict(os.environ, CLAUDE_HOME=str(home), AGENT_SAFETY_DIRTY_OVERRIDE="1" if dirty else "0") + env = dict( + os.environ, + CLAUDE_HOME=str(home), + AGENT_SAFETY_DIRTY_OVERRIDE="1" if dirty else "0", + AGENT_SAFETY_CONTAINMENT_OVERRIDE="1" if contain else "0", + ) return subprocess.run( [sys.executable, str(INSTALL), *args], capture_output=True, @@ -51,8 +59,8 @@ def setUp(self): self.stamp = self.home / "agent-safety-stamp.json" self.md = self.home / "CLAUDE.md" - def install(self, dirty=False): - r = run(self.home, dirty=dirty) + def install(self, dirty=False, contain=True): + r = run(self.home, dirty=dirty, contain=contain) self.assertEqual(r.returncode, 0, r.stdout + r.stderr) return r @@ -704,6 +712,78 @@ def test_reinstalling_clears_an_unregistered_hook(self): self.assertEqual(run(self.home, "--report").returncode, 0) +class TestContainmentPrefix(StampCase): + """The shell prefix is set where the host can contain a command, and owned only while it names ours.""" + + def _settings(self): + return json.loads((self.home / "settings.json").read_text(encoding="utf-8")) + + def _write(self, data): + (self.home / "settings.json").write_text( + json.dumps(data, indent=2) + "\n", encoding="utf-8" + ) + + def _want(self): + return install.prefix_value(self.home / "hooks" / install.CONTAIN_NAME) + + def test_a_capable_host_sets_the_prefix_to_the_deployed_file(self): + self.install() + self.assertTrue((self.home / "hooks" / install.CONTAIN_NAME).is_file()) + self.assertEqual(self._settings()["env"][install.PREFIX_VAR], self._want()) + r = run(self.home, "--report") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + def test_an_incapable_host_deploys_the_file_and_sets_no_prefix(self): + """The digest stays identical across hosts, so only the registration differs.""" + self.install(contain=False) + self.assertTrue((self.home / "hooks" / install.CONTAIN_NAME).is_file()) + self.assertNotIn("env", self._settings()) + r = run(self.home, "--report", contain=False) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + def test_a_removed_prefix_reports_stale_on_a_capable_host(self): + self.install() + data = self._settings() + del data["env"] + self._write(data) + r = run(self.home, "--report") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("no task or memory ceiling", r.stdout) + + def test_our_prefix_on_a_host_that_cannot_contain_reports_stale(self): + self.install() + r = run(self.home, "--report", contain=False) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("cannot contain", r.stdout) + + def test_reinstalling_on_a_host_that_lost_its_manager_removes_only_our_prefix(self): + self.install() + data = self._settings() + data["env"]["OTHER"] = "kept" + self._write(data) + self.install(contain=False) + self.assertEqual(self._settings()["env"], {"OTHER": "kept"}) + + def test_a_foreign_prefix_is_kept_and_reported(self): + """Someone else's wrapper is theirs, so the installer neither replaces nor hides it.""" + self.home.mkdir(parents=True) + self._write({"env": {install.PREFIX_VAR: "/usr/local/bin/audit-log"}}) + r = self.install() + self.assertIn("does not own", r.stdout) + self.assertEqual(self._settings()["env"][install.PREFIX_VAR], "/usr/local/bin/audit-log") + r = run(self.home, "--report") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("is held by", r.stdout) + + def test_a_non_object_env_is_refused_rather_than_overwritten(self): + self.home.mkdir(parents=True) + self._write({"env": ["not", "an", "object"]}) + r = run(self.home) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("`env`", r.stderr) + self.assertEqual(self._settings()["env"], ["not", "an", "object"]) + + class TestPreexistingCorruption(StampCase): """A file corrupted before the install, where the stamp records the corruption and agrees.""" diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py new file mode 100755 index 000000000..e1aa6d97a --- /dev/null +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -0,0 +1,323 @@ +#!/usr/bin/env python3 +"""Shell prefix: run every command Claude Code executes inside a scope with a task and memory ceiling. + +Registered as `CLAUDE_CODE_SHELL_PREFIX` in the user settings.json `env`. Claude Code then runs each +Bash tool call and each hook command as ` ''`, one argument holding the +whole string, including the cwd bookkeeping Claude Code appends to it. This file starts a transient +systemd user scope carrying `TasksMax` and `MemoryMax`, and runs the string under a shell inside it. + +A runaway fan-out then meets the ceiling and fails with a visible error, instead of growing until the +host has to be reset. The ceiling belongs to the scope's cgroup rather than to the foreground wait, so +it still holds after the tool moves a timed-out command to the background, and after the command's +own shell has exited and its children were reparented to init. See +host-setup/agent-safety/README.md requirement 9. + +The ceilings default to `DEFAULT_TASKS_MAX` and `DEFAULT_MEMORY_MAX`. The maintainer raises them with +`AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block. An agent +cannot raise them for itself, since this process reads the environment the session was launched with +and runs before anything in the command string does. + +Each scope is named for its session, so the SessionEnd hook stops what a session's commands left +running and nothing else. A Bash tool call sources a Claude Code shell snapshot and a hook command does +not, which is what separates the two names. The sweep stops only the tool-call scopes, since another +SessionEnd hook may still be running in its own scope when it does. + +Where no systemd user manager is reachable, the command runs without a ceiling and one line on stderr +says so, since a silent fallback would read as a contained command. Linux only: the installer does not +register this prefix on a host without a user manager. + +Run `tool-containment.py --selftest` to verify the decision matrix without Claude Code. +""" + +import os +import sys + +DEFAULT_TASKS_MAX = "8192" +DEFAULT_MEMORY_MAX = "25%" + +TOOL_UNIT = "claude-tool" +HOOK_UNIT = "claude-hook" + +# Since version 254, systemd-run expands `${VAR}` in a scope's arguments by default, rewriting a command before its shell sees it. +# The flag turning that off is an error on an older systemd, so the command travels in the environment instead. +COMMAND_VAR = "AGENT_CONTAINMENT_COMMAND" +SHELL_VAR = "AGENT_CONTAINMENT_SHELL" + +# How long a stop waits on SIGTERM before SIGKILL, so the session-end stop fits its hook's budget. +STOP_TIMEOUT = "2s" + +_SNAPSHOT = "/shell-snapshots/snapshot-" + + +def which(name, path=None): + """The executable `name` resolves to on PATH, or None, without importing `shutil`.""" + for d in (path if path is not None else os.environ.get("PATH", "")).split(os.pathsep): + candidate = os.path.join(d or ".", name) + if os.path.isfile(candidate) and os.access(candidate, os.X_OK): + return candidate + return None + + +def _count(text): + """Whether `text` is a positive decimal count with no leading zero.""" + return text.isascii() and text.isdigit() and not text.startswith("0") + + +def session_token(session_id): + """The session id as it appears in a unit name, or "" where there is none to name.""" + return "".join(c for c in session_id or "" if c.isascii() and (c.isalnum() or c == "-"))[:64] + + +def snapshot_shell(command): + """The shell a Bash tool call's snapshot names, or None for a command that sources none.""" + for name in ("bash", "zsh"): + if f"{_SNAPSHOT}{name}-" in command: + return name + return None + + +def unit_kind(command): + """`TOOL_UNIT` for a Bash tool call, `HOOK_UNIT` for anything else Claude Code runs.""" + return TOOL_UNIT if snapshot_shell(command) else HOOK_UNIT + + +def pick_shell(command, which=which): + """The shell the command string was written for. + + A tool call sources a snapshot named for the shell Claude Code chose, so that name decides. Any + other string is a hook command, which is plain enough for bash. + """ + return which(snapshot_shell(command) or "bash") or which("bash") or "/bin/sh" + + +def valid_tasks(value): + """Whether systemd reads `value` as a `TasksMax`.""" + return value == "infinity" or _count(value) + + +def valid_memory(value): + """Whether systemd reads `value` as a `MemoryMax`: bytes, a K/M/G/T size, a percentage, or infinity.""" + if value == "infinity": + return True + if value.endswith("%"): + return _count(value[:-1]) and int(value[:-1]) <= 100 + return _count(value[:-1] if value[-1:] in "KMGT" else value) + + +def ceilings(env): + """(tasks, memory, notices): the ceilings to apply, and a line for each override refused. + + A malformed override falls back to the default rather than to no ceiling, and says so, since + systemd would otherwise reject it and the command would not run at all. + """ + notices = [] + tasks = env.get("AGENT_CONTAINMENT_TASKS_MAX") or DEFAULT_TASKS_MAX + if not valid_tasks(tasks): + notices.append(f"AGENT_CONTAINMENT_TASKS_MAX={tasks!r} is not a task count") + tasks = DEFAULT_TASKS_MAX + memory = env.get("AGENT_CONTAINMENT_MEMORY_MAX") or DEFAULT_MEMORY_MAX + if not valid_memory(memory): + notices.append(f"AGENT_CONTAINMENT_MEMORY_MAX={memory!r} is not a memory size") + memory = DEFAULT_MEMORY_MAX + return tasks, memory, notices + + +def manager_reachable(env, platform=sys.platform, which=which, exists=os.path.exists): + """Whether a systemd user manager can start a scope for this process.""" + runtime = env.get("XDG_RUNTIME_DIR") + return bool( + platform.startswith("linux") + and which("systemd-run") + and runtime + and exists(os.path.join(runtime, "systemd", "private")) + ) + + +def plan(command, env, pid, reachable, which=which): + """(argv, extra_env, notices) for the outer stage, which the caller execs. + + With a manager, argv starts the scope and re-enters this file as the inner stage, the command and + its shell carried in `extra_env`. Without one, argv is the shell itself, run with no ceiling. + """ + shell = pick_shell(command, which) + if not reachable: + note = "no systemd user manager is reachable, so this command runs with no task or memory ceiling" + return [shell, "-c", command], {}, [note] + tasks, memory, notices = ceilings(env) + token = session_token(env.get("CLAUDE_CODE_SESSION_ID")) or "nosession" + argv = [ + which("systemd-run") or "systemd-run", + "--user", + "--scope", + "--collect", + "--quiet", + f"--unit={unit_kind(command)}-{token}-{pid}", + "--description=Claude Code command", + f"--property=TasksMax={tasks}", + f"--property=MemoryMax={memory}", + f"--property=TimeoutStopSec={STOP_TIMEOUT}", + "--", + sys.executable, + "-I", + "-S", + os.path.abspath(__file__), + "--inner", + ] + return argv, {COMMAND_VAR: command, SHELL_VAR: shell}, notices + + +def inner(env): + """(argv, env) for the inner stage: the shell, with the hand-off variables removed.""" + env = dict(env) + command = env.pop(COMMAND_VAR, None) + shell = env.pop(SHELL_VAR, None) or "/bin/sh" + if command is None: + return None, env + return [shell, "-c", command], env + + +def main(argv): + if argv[1:] == ["--inner"]: + run, env = inner(os.environ) + if run is None: + print(f"tool-containment: --inner reached with no {COMMAND_VAR}", file=sys.stderr) + return 2 + os.execve(run[0], run, env) + if len(argv) != 2: + print("usage: tool-containment.py '' | --selftest", file=sys.stderr) + return 2 + run, extra, notices = plan(argv[1], os.environ, os.getpid(), manager_reachable(os.environ)) + for note in notices: + print(f"tool-containment: {note}", file=sys.stderr) + os.execve(run[0], run, {**os.environ, **extra}) + return 2 # unreachable, since execve either replaces this process or raises + + +def _selftest(): + tool = ( + "source /opt/agent/.claude/shell-snapshots/snapshot-bash-1-x.sh 2>/dev/null || true && " + "eval 'echo ${HOME}' < /dev/null && pwd -P >| /tmp/claude-1-cwd" + ) + ztool = tool.replace("snapshot-bash-", "snapshot-zsh-") + hook = '"python3" "/opt/agent/.claude/hooks/gh-write-guard.py"' + + def fake_which(name): + return { + "bash": "/usr/bin/bash", + "zsh": "/usr/bin/zsh", + "systemd-run": "/usr/bin/systemd-run", + }.get(name) + + import shutil + import tempfile + + scratch = tempfile.mkdtemp() + empty, bindir = os.path.join(scratch, "empty"), os.path.join(scratch, "bin") + os.mkdir(empty) + os.mkdir(bindir) + probe = os.path.join(bindir, "probe-tool") + with open(probe, "w", encoding="utf-8") as f: + f.write("#!/bin/sh\n") + os.chmod(probe, 0o755) + + env = {"CLAUDE_CODE_SESSION_ID": "0a1b-2c3d", "XDG_RUNTIME_DIR": "/run/user/1000"} + argv, extra, notes = plan(tool, env, 42, True, fake_which) + hook_argv, _e, _n = plan(hook, env, 43, True, fake_which) + bare, bare_extra, bare_notes = plan(tool, env, 44, False, fake_which) + raised = ceilings( + {"AGENT_CONTAINMENT_TASKS_MAX": "20000", "AGENT_CONTAINMENT_MEMORY_MAX": "64G"} + ) + refused = ceilings({"AGENT_CONTAINMENT_TASKS_MAX": "0", "AGENT_CONTAINMENT_MEMORY_MAX": "lots"}) + inner_argv, inner_env = inner({"PATH": "/bin", COMMAND_VAR: tool, SHELL_VAR: "/usr/bin/bash"}) + checks = [ + ("--unit=claude-tool-0a1b-2c3d-42" in argv, "a tool call's scope is named for its session"), + ("--unit=claude-hook-0a1b-2c3d-43" in hook_argv, "a hook command's scope is named apart"), + (f"--property=TasksMax={DEFAULT_TASKS_MAX}" in argv, "the task ceiling is applied"), + (f"--property=MemoryMax={DEFAULT_MEMORY_MAX}" in argv, "the memory ceiling is applied"), + ( + f"--property=TimeoutStopSec={STOP_TIMEOUT}" in argv, + "a stop escalates to SIGKILL quickly", + ), + (tool not in argv and extra[COMMAND_VAR] == tool, "the command travels in the environment"), + (not any("$" in a for a in argv), "no argument carries a `$` for systemd-run to expand"), + (extra[SHELL_VAR] == "/usr/bin/bash", "a bash snapshot runs under bash"), + ( + plan(ztool, env, 45, True, fake_which)[1][SHELL_VAR] == "/usr/bin/zsh", + "a zsh one under zsh", + ), + ( + plan(hook, env, 46, True, fake_which)[1][SHELL_VAR] == "/usr/bin/bash", + "a hook under bash", + ), + (notes == [], "a contained command prints nothing extra"), + ( + bare == ["/usr/bin/bash", "-c", tool] and bare_extra == {}, + "no manager runs the shell bare", + ), + (len(bare_notes) == 1 and "no task or memory ceiling" in bare_notes[0], "and says so"), + ( + raised[:2] == ("20000", "64G") and raised[2] == [], + "the maintainer can raise both ceilings", + ), + ( + refused[:2] == (DEFAULT_TASKS_MAX, DEFAULT_MEMORY_MAX), + "a malformed override keeps the default", + ), + (len(refused[2]) == 2, "and names each refusal"), + ( + ceilings({"AGENT_CONTAINMENT_MEMORY_MAX": "40%"})[1] == "40%", + "a percentage is a memory size", + ), + (session_token("a/b c;d") == "abcd", "a session id cannot inject into a unit name"), + ( + all(map(valid_memory, ("16G", "1024", "100%", "infinity"))) + and not any(map(valid_memory, ("0", "07G", "101%", "0%", "16GB", "-1", "1.5G"))), + "a memory size is read the way systemd reads one", + ), + ( + all(map(valid_tasks, ("1", "8192", "infinity"))) + and not any(map(valid_tasks, ("0", "08", "1e3", "-5", "\u0663"))), + "and so is a task count", + ), + ( + which("probe-tool", path=os.pathsep.join((empty, bindir))) == probe + and which("no-such-tool-xyz", path=bindir) is None, + "PATH is searched in order, and a miss is None", + ), + ( + "--unit=claude-tool-nosession-47" in plan(tool, {}, 47, True, fake_which)[0], + "a missing session id names no session the sweep would stop", + ), + (inner_argv == ["/usr/bin/bash", "-c", tool], "the inner stage runs the command verbatim"), + ( + COMMAND_VAR not in inner_env and SHELL_VAR not in inner_env, + "and does not leak the hand-off", + ), + ( + inner({"PATH": "/bin"})[0] is None, + "an inner stage with no command refuses rather than runs", + ), + ( + not manager_reachable(env, platform="darwin", which=fake_which, exists=lambda p: True), + "a non-Linux host has no manager", + ), + ( + not manager_reachable({}, platform="linux", which=fake_which, exists=lambda p: True), + "nor does a session with no runtime directory", + ), + ( + manager_reachable(env, platform="linux", which=fake_which, exists=lambda p: True), + "a Linux session with a manager socket has one", + ), + ] + shutil.rmtree(scratch) + ok = True + for passed, label in checks: + ok = ok and passed + print(f" {'ok ' if passed else 'FAIL'} {label}") + print("SELFTEST PASS" if ok else "SELFTEST FAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(_selftest() if sys.argv[1:] == ["--selftest"] else main(sys.argv)) diff --git a/host-setup/agent-safety/codex/README.md b/host-setup/agent-safety/codex/README.md index 4de363036..d9e7f45bf 100644 --- a/host-setup/agent-safety/codex/README.md +++ b/host-setup/agent-safety/codex/README.md @@ -22,18 +22,21 @@ Codex's own approval/sandbox extension points differ from Claude Code's hook sha mechanism Codex offers for intercepting or gating a command before it runs is the place to implement requirements 1 to 7. Requirement 8 is not one of them: it reports the processes a session leaves behind, so it belongs wherever Codex signals that a session has ended, and -[`../claude/stray-process-sweep.py`][claude-sweep] is the worked reference for that one. If Codex -offers neither extension point, that finding belongs on +[`../claude/stray-process-sweep.py`][claude-sweep] is the worked reference for that one. Requirement 9 +wraps every command rather than judging one, so it belongs wherever Codex lets a command be run +through a wrapper, with [`../claude/tool-containment.py`][claude-contain] as its reference. If Codex +offers none of these extension points, that finding belongs on [issue #781][issue-781], not silently worked around. ## Auditing Once a Codex-side implementation exists, audit it the way [`../README.md`][spec] "Auditing an Implementation Against This Spec" describes: run its own self-test and check every case against the -eight requirements, not against `gh-write-guard.py`'s source. +nine requirements, not against `gh-write-guard.py`'s source. [spec]: ../README.md [claude-hook]: ../claude/gh-write-guard.py [claude-sweep]: ../claude/stray-process-sweep.py +[claude-contain]: ../claude/tool-containment.py [issue-781]: https://github.com/ptr727/ProjectTemplate/issues/781 diff --git a/host-setup/agent-safety/opencode/README.md b/host-setup/agent-safety/opencode/README.md index e8725ca6b..ae25f7d29 100644 --- a/host-setup/agent-safety/opencode/README.md +++ b/host-setup/agent-safety/opencode/README.md @@ -22,18 +22,21 @@ opencode's own permission-model extension points differ from Claude Code's hook mechanism opencode offers for intercepting or gating a command before it runs is the place to implement requirements 1 to 7. Requirement 8 is not one of them: it reports the processes a session leaves behind, so it belongs wherever opencode signals that a session has ended, and -[`../claude/stray-process-sweep.py`][claude-sweep] is the worked reference for that one. If opencode -offers neither extension point, that finding belongs +[`../claude/stray-process-sweep.py`][claude-sweep] is the worked reference for that one. Requirement 9 +wraps every command rather than judging one, so it belongs wherever opencode lets a command be run +through a wrapper, with [`../claude/tool-containment.py`][claude-contain] as its reference. If opencode +offers none of these extension points, that finding belongs on [issue #781][issue-781], not silently worked around. ## Auditing Once an opencode-side implementation exists, audit it the way [`../README.md`][spec] "Auditing an Implementation Against This Spec" describes: run its own self-test and check every case against the -eight requirements, not against `gh-write-guard.py`'s source. +nine requirements, not against `gh-write-guard.py`'s source. [spec]: ../README.md [claude-hook]: ../claude/gh-write-guard.py [claude-sweep]: ../claude/stray-process-sweep.py +[claude-contain]: ../claude/tool-containment.py [issue-781]: https://github.com/ptr727/ProjectTemplate/issues/781 From cbf664e4ed9a12244056a710d6dc90d6aeaf93e4 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 07:19:32 -0700 Subject: [PATCH 02/22] Keep Hook Commands Out of the Containment Scope A PreToolUse hook exiting 1 is a non-blocking error, so a scope that failed to start under the write guard would have let the command it denies go ahead. Hook commands now run under their shell directly, told apart by CLAUDE_PROJECT_DIR and the snapshot a tool call sources first, and either sign of a tool call still contains it. Also from the local review: unit names carry a random suffix so a reused pid cannot collide, the shell is picked from the leading source clause only, overrides accept every value systemd accepts, the sweep skips the reap where no user manager runs, and the prose no longer claims an agent cannot lift its own ceiling. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/README.md | 10 +- host-setup/agent-safety/claude/README.md | 7 +- host-setup/agent-safety/claude/install.py | 2 +- .../claude/stray-process-sweep.py | 34 ++++- .../agent-safety/claude/tool-containment.py | 134 ++++++++++++------ 5 files changed, 133 insertions(+), 54 deletions(-) diff --git a/host-setup/agent-safety/README.md b/host-setup/agent-safety/README.md index 03cc87e12..349b7ff26 100644 --- a/host-setup/agent-safety/README.md +++ b/host-setup/agent-safety/README.md @@ -292,13 +292,17 @@ text says, because the harm it covers was never in the text. Name each group for the session that ran it, and at the end of the session stop every group its commands left running, then report what was stopped. This stop needs none of requirement 8's judgment about what a process is, since the group's name proves which session started it. Report - a failure to list or to stop a group as loudly as a finding. A hook command is bounded the same - way and is not stopped, since another end-of-session hook may still be running in its own group. + a failure to list or to stop a group as loudly as a finding. - The maintainer sets the ceilings, in a channel the command being bounded cannot reach. Where the + A hook the agent runs, a guard above included, is not placed in a group. A group that fails to + start fails the command, and a guard that fails that way is a guard that did not run. Where the host offers no such group, the command runs unbounded and says so on every run, because a silent fallback reads exactly like a bounded command. + The maintainer sets the ceilings, where a variable set inline in the bounded command cannot reach + them. They bound an accident rather than an adversary, since a command can still raise its own + group's limits or start a group outside it, and the incident this answers was a mistake. + ## Decision Flow ```mermaid diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 24d3d5027..03dee0b55 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -13,8 +13,8 @@ installation and operational detail. Codex and opencode have no equivalent hook Into `~/.claude/` (or `%USERPROFILE%\.claude\` on Windows): - **`hooks/gh-write-guard.py`**: a PreToolUse hook that denies four classes of dangerous action. First, the GitHub **write** footguns behind the cross-repo comment incident: a state-changing `gh` call whose output is discarded, a GraphQL mutation passing a **literal** node id instead of a `$variable`, and a `gh` write whose explicit target is under an owner other than the checkout origin's. Sibling repositories under the same owner are allowed, since the harm this guards is reaching a stranger's repository rather than working across one maintainer's own fleet, and a different owner is allowed only when the maintainer names it in `GH_WRITE_GUARD_ALLOW` (an `owner/repo` list, where `owner/*` grants a whole owner). That variable is read from the environment the session was launched with, which is the one channel an agent cannot set for itself: a hook runs as its own process, so an inline `VAR=x cmd` prefix or an `export` inside a Bash call never reaches it. Second, a **git operation that bypasses a repository protection**. The branch-rule cases (a direct push to a branch that requires a pull request, a force-push where history is protected, a branch delete where deletion is blocked) are judged against the branch's **live** rules, so a code-style `develop` is denied while a config-style `develop` is allowed with no per-repo configuration. A push to a protected-default branch fails closed when its rules cannot be determined, either because the API is unreachable or because the checkout's origin cannot be resolved to query them. The explicit-bypass flags are denied **unconditionally**, since the flag is itself the bypass and needs no branch query: `gh pr merge --admin` overrides the server-side merge gate, and `git commit`/`git push --no-verify` skips the local git hooks. Third, a **mutating git operation run directly against a primary checkout** (`checkout`/`switch`/`pull`/`reset`/`rebase`/`merge`/`cherry-pick`/`revert`/`restore`/`add`/`commit`/`rm`/`mv`/`apply`/`am`/`push`/`stash` (anything but `list`/`show`)/`clean -f`/`worktree remove -f`), the harm behind a second incident where an agent reused the maintainer's own primary checkout instead of a worktree despite having read the prose rule against it. "Primary" is decided by comparing `git rev-parse --git-dir` against `--git-common-dir`, not a `.git`-is-a-directory guess. `worktree add`/`list`/`prune`, an unforced `worktree remove`, `merge --ff-only`/`pull --ff-only`, and a `checkout `/`switch ` carrying no force flag (bundled or attached forms like `-qf`/`-Bname` recognized, not only an exact token) stay exempt even in a primary checkout, matching the documented base-clone cleanup step the `repo-worktree` skill already carries. A subcommand this rule does not recognize is resolved through a chain of git aliases, inline and persisted, before falling through, so a custom alias cannot hide a denied builtin behind an unrecognized name. A `!`-prefixed shell alias is denied outright rather than interpreted. The target directory follows real git's own `-C`/`--work-tree`/`--git-dir` priority, not a last-option-wins scan. A different owner-style grant, `GH_WRITE_GUARD_ALLOW_PRIMARY_CHECKOUT`, follows the same channel as `GH_WRITE_GUARD_ALLOW`. Reads and everything else pass through. Fourth, an **unbounded shell wait**, which the root spec's requirement 7 defines in full rather than this bullet redefining it. In outline: a loop that sleeps, carrying no bound the rule recognizes. It is the shape an agent writes when a brief tells it to poll. It is also the harm behind a third incident, where seven such loops outlived the subagents that wrote them and the run that dispatched those subagents. A shell started by a tool call runs in a session of its own, so the agent could not have reaped it even had it tried. A nested loop is judged on its own terms, and a command that forks anything out of a `timeout`'s reach, by backgrounding it or by `setsid`, is bounded by nothing. A heredoc body is data rather than a command line unless a shell is what it is fed to, so a document quoting the forbidden shape is written rather than denied. It fires even in autonomous / bypass-permissions sessions, which is how the first incident happened. See the root spec's requirements 6 and 7 for the exact rules. -- **`hooks/tool-containment.py`**: a shell prefix, registered as `CLAUDE_CODE_SHELL_PREFIX` in the `env` block of `settings.json`, that runs every command Claude Code executes inside a transient systemd user scope carrying `TasksMax` and `MemoryMax`. That covers each Bash tool call and each hook command. A runaway fan-out then fails at the ceiling with `fork: Resource temporarily unavailable` instead of growing until the host has to be reset, the harm behind the probe-shim incident in the root spec's requirement 9. The guard above reads the command text, and that incident's recursion lived in a script file the command only named. The ceilings default to 8192 tasks and 25% of RAM. The maintainer raises them with `AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block, which an agent cannot set for itself, since the prefix reads the environment the session was launched with and runs before anything in the command does. Each scope is named `claude-tool--` for a Bash tool call and `claude-hook--` for a hook command, so the sweep below can stop one session's tool calls and nothing else. The installer sets the prefix only on a host with a running systemd user manager, and never over a `CLAUDE_CODE_SHELL_PREFIX` value that names anything else. -- **`hooks/stray-process-sweep.py`**: a SessionEnd hook in two phases. First, it stops every `claude-tool--*` scope this session left loaded and reports what each held, since the scope's name proves which session started it. Second, it reports, and never ends, the process trees outside those scopes that outlive the session. The guard above stops a leak from being written. This finds the ones already running: the ones started before the guard was installed, and the shapes the guard deliberately does not reach. It reads the process table once. It reports every descendant of the agent process running outside the agent's own session. It names each subtree root's command and age, and hands over the `kill` line. It kills nothing itself. A long build backgrounded on purpose reads identically to a leaked wait from there. What is still wanted on the machine is the maintainer's call. A SessionEnd hook cannot block, and its JSON output is discarded, so stderr on exit 2 is the one channel that reaches the maintainer. The sweep uses that for a report rather than for a refusal. It registers under a group carrying no matcher, which fires on every exit reason. It also carries an explicit timeout, since the event's own budget is 1.5 seconds and only a declared per-hook timeout raises it. See the root spec's requirement 8. +- **`hooks/tool-containment.py`**: a shell prefix, registered as `CLAUDE_CODE_SHELL_PREFIX` in the `env` block of `settings.json`, that runs every Bash tool call inside a transient systemd user scope carrying `TasksMax` and `MemoryMax`. A runaway fan-out then fails at the ceiling with `fork: Resource temporarily unavailable` instead of growing until the host has to be reset, the harm behind the probe-shim incident in the root spec's requirement 9. The guard above reads the command text, and that incident's recursion lived in a script file the command only named. The ceilings default to 8192 tasks and 25% of RAM. The maintainer raises them with `AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block, which an inline `VAR=x` in a command cannot change, since the prefix reads them before the command runs. Each scope is named `claude-tool---`, so the sweep below can stop one session's tool calls and nothing else. The installer sets the prefix only on a host with a running systemd user manager, and never over a `CLAUDE_CODE_SHELL_PREFIX` value that names anything else. +- **`hooks/stray-process-sweep.py`**: a SessionEnd hook in two phases. First, it stops every `claude-tool--*` scope this session left loaded and reports what each held, since the scope's name proves which session started it. Second, it reports, and never ends, the process trees outside those scopes that outlive the session. The guard above stops a leak from being written. This finds the ones already running: the ones started before the guard was installed, and the shapes the guard deliberately does not reach. It reports every descendant of the agent process running outside the agent's own session. It names each subtree root's command and age, and hands over the `kill` line. This phase kills nothing itself. A long build backgrounded on purpose reads identically to a leaked wait from there. What is still wanted on the machine is the maintainer's call. A SessionEnd hook cannot block, and its JSON output is discarded, so stderr on exit 2 is the one channel that reaches the maintainer. The sweep uses that for a report rather than for a refusal. It registers under a group carrying no matcher, which fires on every exit reason. It also carries an explicit timeout, since the event's own budget is 1.5 seconds and only a declared per-hook timeout raises it. See the root spec's requirement 8. - **Two marker-delimited blocks of host-wide content in `CLAUDE.md`**, loaded into every session on the machine (including ad-hoc work outside any project), installed and updated independently so one can change without rewriting the other. - The `agent-safety` block carries restrictions alone, so nothing in it can widen a permission. `Repository Boundaries and Write Safety` mirrors the committed `GOVERNANCE.md` section of the same name, carrying as behavioral guidance its write rules and its rules that a task works in its own checkout and isolates into its own worktree before its first file edit. `Data in Agent-Authored Text` mirrors `GOVERNANCE.md` "Representative Data in Agent-Authored Text", so an agent illustrates with constructed data rather than data observed on the machine. `Authorization Scope and Memory Hygiene` bounds how a granted permission is recorded and read. Each mirrors a rule that otherwise reaches fleet repos only. - The `fleet-bootstrap` block carries `Fleet Governance Entry Point`, which names the template repository and routes by the state a repository is actually in. It is separate precisely because it enables rather than restricts, and the safety block's own text says nothing in it widens a permission, so merging the two would contradict that. It is host-wide rather than per repository because the repositories that most need it are the ones carrying no instruction set to point the way, and it mirrors the byte-locked `AGENTS.md` "Fleet Bootstrap" section that a conformant repository carries. @@ -155,7 +155,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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. - **Containment runs on Linux and WSL with a systemd user manager.** macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. -- **Containment wraps hook commands too.** Claude Code applies `CLAUDE_CODE_SHELL_PREFIX` to hook commands as well as to Bash tool calls, so the guard and the sweep each run inside a `claude-hook-` scope. A hook scope is bounded and never stopped at session end, since a sibling SessionEnd hook may still be running inside one. Each wrapped command costs about 35 ms on the reference host, measured as two Python starts and one scope creation. +- **Hook commands pass through the prefix unscoped.** Claude Code applies `CLAUDE_CODE_SHELL_PREFIX` to hook commands as well as to Bash tool calls. The prefix runs a hook under its shell directly, 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. A hook is told apart by the `CLAUDE_PROJECT_DIR` Claude Code sets for hooks and the shell snapshot a tool call sources first, and either sign of a tool call contains it. 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, and a hook command about 10 ms. +- **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. 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. - **The sweep runs at session end, not at subagent end.** `SubagentStop` is where the incident's own loops were born, and it would catch each one hours earlier. Its exit 2 prevents the subagent from stopping, though, so the one channel that reaches a human on `SessionEnd` is not free there. A sweep that cannot report is a sweep that does nothing. The cost of the later moment is real. A run dispatching workers for hours reaches session end once, having finished many rounds, so every leak it wrote is reported together at the end. diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index dad144f1a..44cf09eec 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -53,7 +53,7 @@ DEPLOYED_HOOKS = (GUARD_NAME, SWEEP_NAME, CONTAIN_NAME) # A SessionEnd hook's own budget is 1.5 seconds, raised to the highest per-hook timeout the settings declare. -# The sweep reads one process table, so this is headroom for a loaded machine rather than a duration it uses. +# The sweep stops scopes that escalate to SIGKILL after two seconds and reads two process tables, so this is headroom rather than a duration it uses. SWEEP_TIMEOUT_SECONDS = 10 # The stamp's own format version, separate from the content it describes. diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py index 60343d973..8dc125cf0 100755 --- a/host-setup/agent-safety/claude/stray-process-sweep.py +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -238,6 +238,18 @@ def _systemctl(*args): return done.returncode, done.stdout +def manager_reachable(env, which=shutil.which, exists=os.path.exists): + """Whether a systemd user manager runs for this session, the test `tool-containment.py` applies. + + A host without one never ran a contained command, and asking `systemctl --user` there fails, which + would report a failure to list at every session end on a host the installer never contained. + """ + runtime = env.get("XDG_RUNTIME_DIR") + return bool( + which("systemctl") and runtime and exists(os.path.join(runtime, "systemd", "private")) + ) + + def session_token(session_id): """The session id as `tool-containment.py` spells it in a unit name, or "" where there is none.""" return re.sub(r"[^A-Za-z0-9-]", "", session_id or "")[:64] @@ -341,7 +353,7 @@ def main(): payload.get("session_id") if isinstance(payload, dict) else None ) or os.environ.get("CLAUDE_CODE_SESSION_ID") reaped = "" - if shutil.which("systemctl"): + if manager_reachable(os.environ): reaped = reap(session_id, _read_process_table() or {}) if reaped: print(reaped, file=sys.stderr) @@ -507,6 +519,26 @@ def fake(*args, stop_code=0, sticky=()): "a systemctl that cannot run is reported, never read as nothing to stop", ), (session_token("a/b c;d") == "abcd", "the unit name is spelled as the prefix spells it"), + ( + not manager_reachable({}, which=lambda n: "/usr/bin/systemctl", exists=lambda p: True), + "a session with no runtime directory has no manager to ask", + ), + ( + not manager_reachable( + {"XDG_RUNTIME_DIR": "/run/user/1000"}, + which=lambda n: "/usr/bin/systemctl", + exists=lambda p: False, + ), + "nor does one whose manager socket is absent", + ), + ( + manager_reachable( + {"XDG_RUNTIME_DIR": "/run/user/1000"}, + which=lambda n: "/usr/bin/systemctl", + exists=lambda p: True, + ), + "a session with its manager socket is swept", + ), ] ok = True for passed, label in checks: diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index e1aa6d97a..88d535800 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -1,10 +1,17 @@ #!/usr/bin/env python3 -"""Shell prefix: run every command Claude Code executes inside a scope with a task and memory ceiling. +"""Shell prefix: run every Bash tool call inside a scope with a task and memory ceiling. Registered as `CLAUDE_CODE_SHELL_PREFIX` in the user settings.json `env`. Claude Code then runs each Bash tool call and each hook command as ` ''`, one argument holding the -whole string, including the cwd bookkeeping Claude Code appends to it. This file starts a transient -systemd user scope carrying `TasksMax` and `MemoryMax`, and runs the string under a shell inside it. +whole string, including the cwd bookkeeping Claude Code appends to it. For a tool call this file starts +a transient systemd user scope carrying `TasksMax` and `MemoryMax`, and runs the string under a shell +inside it. + +A hook command runs under its shell directly, with no scope. The write guard is a hook, and a PreToolUse +hook that exits 1 is a non-blocking error, so a scope that failed to start would let the very command +the guard denies go ahead. A hook is told from a tool call by the `CLAUDE_PROJECT_DIR` Claude Code sets +for hooks and by the shell snapshot a tool call sources first. Either sign of a tool call is enough to +contain it, so a change to one of them fails toward containment rather than away from it. A runaway fan-out then meets the ceiling and fails with a visible error, instead of growing until the host has to be reset. The ceiling belongs to the scope's cgroup rather than to the foreground wait, so @@ -13,16 +20,15 @@ host-setup/agent-safety/README.md requirement 9. The ceilings default to `DEFAULT_TASKS_MAX` and `DEFAULT_MEMORY_MAX`. The maintainer raises them with -`AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block. An agent -cannot raise them for itself, since this process reads the environment the session was launched with -and runs before anything in the command string does. +`AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block, which an inline +`VAR=x` in the command cannot change, since this process reads them before the command runs. The +ceilings bound an accident rather than an adversary: a command can still raise its own scope's +properties through `systemctl --user set-property`, or start a scope of its own outside this one. -Each scope is named for its session, so the SessionEnd hook stops what a session's commands left -running and nothing else. A Bash tool call sources a Claude Code shell snapshot and a hook command does -not, which is what separates the two names. The sweep stops only the tool-call scopes, since another -SessionEnd hook may still be running in its own scope when it does. +Each scope is named for its session plus a random suffix, so the SessionEnd hook stops what a session's +tool calls left running and nothing else, and a reused pid never collides with a scope still loaded. -Where no systemd user manager is reachable, the command runs without a ceiling and one line on stderr +Where no systemd user manager is reachable, a tool call runs without a ceiling and one line on stderr says so, since a silent fallback would read as a contained command. Linux only: the installer does not register this prefix on a host without a user manager. @@ -36,7 +42,6 @@ DEFAULT_MEMORY_MAX = "25%" TOOL_UNIT = "claude-tool" -HOOK_UNIT = "claude-hook" # Since version 254, systemd-run expands `${VAR}` in a scope's arguments by default, rewriting a command before its shell sees it. # The flag turning that off is an error on an older systemd, so the command travels in the environment instead. @@ -58,9 +63,11 @@ def which(name, path=None): return None -def _count(text): - """Whether `text` is a positive decimal count with no leading zero.""" - return text.isascii() and text.isdigit() and not text.startswith("0") +def _positive(text, integer=False): + """Whether `text` is a positive plain decimal number, an integer where `integer` is set.""" + if not text.isascii() or not text.replace(".", "", 1).isdigit() or (integer and "." in text): + return False + return float(text) > 0 def session_token(session_id): @@ -69,16 +76,22 @@ def session_token(session_id): def snapshot_shell(command): - """The shell a Bash tool call's snapshot names, or None for a command that sources none.""" + """The shell named by the snapshot a Bash tool call sources first, or None where it sources none. + + Only the leading `source` clause is read, since the command after it may name any snapshot file. + """ + if not command.startswith("source "): + return None + lead = command.split("&&", 1)[0] for name in ("bash", "zsh"): - if f"{_SNAPSHOT}{name}-" in command: + if f"{_SNAPSHOT}{name}-" in lead: return name return None -def unit_kind(command): - """`TOOL_UNIT` for a Bash tool call, `HOOK_UNIT` for anything else Claude Code runs.""" - return TOOL_UNIT if snapshot_shell(command) else HOOK_UNIT +def is_tool_call(command, env): + """Whether Claude Code runs `command` as a Bash tool call rather than as a hook command.""" + return snapshot_shell(command) is not None or "CLAUDE_PROJECT_DIR" not in env def pick_shell(command, which=which): @@ -90,18 +103,21 @@ def pick_shell(command, which=which): return which(snapshot_shell(command) or "bash") or which("bash") or "/bin/sh" +def _percent(value): + """Whether `value` is a percentage above 0 and at most 100, fractional or whole.""" + return value.endswith("%") and _positive(value[:-1]) and float(value[:-1]) <= 100 + + def valid_tasks(value): - """Whether systemd reads `value` as a `TasksMax`.""" - return value == "infinity" or _count(value) + """Whether `value` is a `TasksMax`: a count, a percentage of the system's limit, or infinity.""" + return value == "infinity" or _positive(value, integer=True) or _percent(value) def valid_memory(value): - """Whether systemd reads `value` as a `MemoryMax`: bytes, a K/M/G/T size, a percentage, or infinity.""" - if value == "infinity": + """Whether `value` is a `MemoryMax`: bytes, a size in K to E, a percentage of RAM, or infinity.""" + if value == "infinity" or _percent(value): return True - if value.endswith("%"): - return _count(value[:-1]) and int(value[:-1]) <= 100 - return _count(value[:-1] if value[-1:] in "KMGT" else value) + return _positive(value[:-1] if value[-1:] in ("K", "M", "G", "T", "P", "E") else value) def ceilings(env): @@ -133,13 +149,16 @@ def manager_reachable(env, platform=sys.platform, which=which, exists=os.path.ex ) -def plan(command, env, pid, reachable, which=which): +def plan(command, env, suffix, reachable, which=which): """(argv, extra_env, notices) for the outer stage, which the caller execs. - With a manager, argv starts the scope and re-enters this file as the inner stage, the command and - its shell carried in `extra_env`. Without one, argv is the shell itself, run with no ceiling. + For a tool call with a manager, argv starts the scope and re-enters this file as the inner stage, + the command and its shell carried in `extra_env`. A hook command, or a tool call with no manager, + gets the shell itself, and only the tool call is told it runs with no ceiling. """ shell = pick_shell(command, which) + if not is_tool_call(command, env): + return [shell, "-c", command], {}, [] if not reachable: note = "no systemd user manager is reachable, so this command runs with no task or memory ceiling" return [shell, "-c", command], {}, [note] @@ -151,7 +170,7 @@ def plan(command, env, pid, reachable, which=which): "--scope", "--collect", "--quiet", - f"--unit={unit_kind(command)}-{token}-{pid}", + f"--unit={TOOL_UNIT}-{token}-{suffix}", "--description=Claude Code command", f"--property=TasksMax={tasks}", f"--property=MemoryMax={memory}", @@ -186,7 +205,8 @@ def main(argv): if len(argv) != 2: print("usage: tool-containment.py '' | --selftest", file=sys.stderr) return 2 - run, extra, notices = plan(argv[1], os.environ, os.getpid(), manager_reachable(os.environ)) + suffix = f"{os.getpid()}-{os.urandom(4).hex()}" + run, extra, notices = plan(argv[1], os.environ, suffix, manager_reachable(os.environ)) for note in notices: print(f"tool-containment: {note}", file=sys.stderr) os.execve(run[0], run, {**os.environ, **extra}) @@ -221,17 +241,39 @@ def fake_which(name): os.chmod(probe, 0o755) env = {"CLAUDE_CODE_SESSION_ID": "0a1b-2c3d", "XDG_RUNTIME_DIR": "/run/user/1000"} - argv, extra, notes = plan(tool, env, 42, True, fake_which) - hook_argv, _e, _n = plan(hook, env, 43, True, fake_which) - bare, bare_extra, bare_notes = plan(tool, env, 44, False, fake_which) + hook_env = dict(env, CLAUDE_PROJECT_DIR="/opt/agent/project") + # A zsh tool call whose own command names a bash snapshot file after the leading clause. + mixed = ztool.replace("eval 'echo", "eval 'ls /x/shell-snapshots/snapshot-bash-1.sh; echo") + argv, extra, notes = plan(tool, env, "42-ab", True, fake_which) + hook_plan = plan(hook, hook_env, "43-cd", True, fake_which) + bare, bare_extra, bare_notes = plan(tool, env, "44-ef", False, fake_which) raised = ceilings( {"AGENT_CONTAINMENT_TASKS_MAX": "20000", "AGENT_CONTAINMENT_MEMORY_MAX": "64G"} ) refused = ceilings({"AGENT_CONTAINMENT_TASKS_MAX": "0", "AGENT_CONTAINMENT_MEMORY_MAX": "lots"}) inner_argv, inner_env = inner({"PATH": "/bin", COMMAND_VAR: tool, SHELL_VAR: "/usr/bin/bash"}) checks = [ - ("--unit=claude-tool-0a1b-2c3d-42" in argv, "a tool call's scope is named for its session"), - ("--unit=claude-hook-0a1b-2c3d-43" in hook_argv, "a hook command's scope is named apart"), + ( + "--unit=claude-tool-0a1b-2c3d-42-ab" in argv, + "a tool call's scope is named for its session", + ), + ( + hook_plan == (["/usr/bin/bash", "-c", hook], {}, []), + "a hook command runs under its shell with no scope, so no systemd failure reaches it", + ), + ( + plan(hook, hook_env, "43-cd", False, fake_which)[2] == [], + "and prints nothing where no manager is reachable", + ), + ( + "--unit=claude-tool-0a1b-2c3d-48-ab" in plan(hook, env, "48-ab", True, fake_which)[0], + "a command with no snapshot and no hook's project dir is still contained", + ), + ( + "--unit=claude-tool-0a1b-2c3d-49-ab" + in plan(tool, hook_env, "49-ab", True, fake_which)[0], + "and so is one sourcing a snapshot whatever its environment", + ), (f"--property=TasksMax={DEFAULT_TASKS_MAX}" in argv, "the task ceiling is applied"), (f"--property=MemoryMax={DEFAULT_MEMORY_MAX}" in argv, "the memory ceiling is applied"), ( @@ -242,12 +284,12 @@ def fake_which(name): (not any("$" in a for a in argv), "no argument carries a `$` for systemd-run to expand"), (extra[SHELL_VAR] == "/usr/bin/bash", "a bash snapshot runs under bash"), ( - plan(ztool, env, 45, True, fake_which)[1][SHELL_VAR] == "/usr/bin/zsh", + plan(ztool, env, "45", True, fake_which)[1][SHELL_VAR] == "/usr/bin/zsh", "a zsh one under zsh", ), ( - plan(hook, env, 46, True, fake_which)[1][SHELL_VAR] == "/usr/bin/bash", - "a hook under bash", + plan(mixed, env, "46", True, fake_which)[1][SHELL_VAR] == "/usr/bin/zsh", + "only the leading source clause picks the shell", ), (notes == [], "a contained command prints nothing extra"), ( @@ -270,13 +312,13 @@ def fake_which(name): ), (session_token("a/b c;d") == "abcd", "a session id cannot inject into a unit name"), ( - all(map(valid_memory, ("16G", "1024", "100%", "infinity"))) - and not any(map(valid_memory, ("0", "07G", "101%", "0%", "16GB", "-1", "1.5G"))), - "a memory size is read the way systemd reads one", + all(map(valid_memory, ("16G", "1024", "1.5G", "12.5%", "1P", "100%", "infinity"))) + and not any(map(valid_memory, ("0", "101%", "0%", "16GB", "-1", "G", "lots"))), + "a memory size systemd accepts is accepted, and a malformed one is not", ), ( - all(map(valid_tasks, ("1", "8192", "infinity"))) - and not any(map(valid_tasks, ("0", "08", "1e3", "-5", "\u0663"))), + all(map(valid_tasks, ("1", "8192", "50%", "infinity"))) + and not any(map(valid_tasks, ("0", "1.5", "1e3", "-5", "\u0663"))), "and so is a task count", ), ( @@ -285,7 +327,7 @@ def fake_which(name): "PATH is searched in order, and a miss is None", ), ( - "--unit=claude-tool-nosession-47" in plan(tool, {}, 47, True, fake_which)[0], + "--unit=claude-tool-nosession-47" in plan(tool, {}, "47", True, fake_which)[0], "a missing session id names no session the sweep would stop", ), (inner_argv == ["/usr/bin/bash", "-c", tool], "the inner stage runs the command verbatim"), From 450d93a7ab1036bc14febb2ba24a6e35a8be2479 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 07:28:44 -0700 Subject: [PATCH 03/22] Register the Prefix Only Where python3 Can Run It The prefix runs through its env python3 shebang for every hook command, the write guard included, and Claude Code quotes the whole prefix value as one word, so no interpreter can be named in front of it. A python3 that cannot run it would fail the guard open, so the installer now checks for a 3.11 or newer python3 on PATH before registering, and falls back to the account's own runtime directory when the installing shell carries no XDG_RUNTIME_DIR. Also from the second local review: overrides need a unit and a floor so a mistyped value cannot kill every command, the sweep re-lists after a stop whatever it returned, a non-string session id no longer crashes it, and a foreign prefix is a report note rather than drift a re-run can never clear. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/README.md | 2 +- host-setup/agent-safety/claude/install.py | 67 ++++++++++++++++--- .../claude/stray-process-sweep.py | 25 ++++--- .../agent-safety/claude/test_install.py | 24 ++++--- .../agent-safety/claude/tool-containment.py | 59 +++++++++++----- 5 files changed, 135 insertions(+), 42 deletions(-) diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 03dee0b55..2c5f490ce 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -154,7 +154,7 @@ Every other key in the file is left as it stands, `permissions.allow` and the re - **A write or a wait inside a script file is unseen, so never put either in a script to run it.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string. A `git push` or a `gh` mutation inside the script therefore reaches the server unparsed. An unbounded wait inside that same script is equally unseen, and worse in one way. A denied write fails loudly. A wait the guard never saw runs until something ends it, which is one of the leaks the SessionEnd sweep exists to find afterwards. This is the widest hole in the kit, and an agent opens it by accident. Collecting fifteen repetitive pushes into a loop looks like tidiness, and so does moving a poll into a script to keep a tool call short. Neither looks like disabling a guard. Issue each write and each wait as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and the wait rather than the script. - **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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. -- **Containment runs on Linux and WSL with a systemd user manager.** macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. +- **Containment runs on Linux and WSL with a systemd user manager and a `python3` 3.11 or newer on PATH.** The prefix runs through its `env python3` shebang for every hook command, the guard included, 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 `python3` unable to run the prefix would fail the guard open, and the installer checks that interpreter before registering anything. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. - **Hook commands pass through the prefix unscoped.** Claude Code applies `CLAUDE_CODE_SHELL_PREFIX` to hook commands as well as to Bash tool calls. The prefix runs a hook under its shell directly, 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. A hook is told apart by the `CLAUDE_PROJECT_DIR` Claude Code sets for hooks and the shell snapshot a tool call sources first, and either sign of a tool call contains it. 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, and a hook command about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. A scope stop sends SIGTERM and escalates to SIGKILL after two seconds, which keeps it inside the hook's own timeout. diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 44cf09eec..90d7dc74d 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -28,7 +28,6 @@ import pathlib import platform import re -import shlex import shutil import socket import subprocess @@ -193,15 +192,53 @@ def containment_capable(): return False, f"{platform.system()} has no systemd user manager" if not shutil.which("systemd-run"): return False, "systemd-run is not installed" - runtime = os.environ.get("XDG_RUNTIME_DIR") - if not runtime or not os.path.exists(os.path.join(runtime, "systemd", "private")): + # The prefix runs through its `env python3` shebang for every hook command, the write guard included. + # A PreToolUse hook that fails is a non-blocking error, so a `python3` that cannot run it fails the guard open. + if not python3_runs_the_prefix(): + return False, "no python3 3.11 or newer is on PATH to run the prefix" + # A `su -`, cron, or `docker exec` shell carries no XDG_RUNTIME_DIR, while the account's sessions do. + runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" + if not os.path.exists(os.path.join(runtime, "systemd", "private")): return False, "no systemd user manager is running for this account" return True, "a systemd user manager is running" +def python3_runs_the_prefix(): + """Whether the `python3` the prefix's shebang resolves to is one this kit supports.""" + found = shutil.which("python3") + if not found: + return False + try: + done = subprocess.run( + [found, "-c", "import sys; sys.exit(sys.version_info < (3, 11))"], + capture_output=True, + timeout=10, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return False + return done.returncode == 0 + + def prefix_value(path): - """The `CLAUDE_CODE_SHELL_PREFIX` value naming the deployed prefix, spelled once for writer and reader.""" - return shlex.quote(str(path)) + """The `CLAUDE_CODE_SHELL_PREFIX` value naming the deployed prefix, spelled once for writer and reader. + + A bare path, since Claude Code quotes the whole value as one word, so an interpreter named in front + of it is read as part of the file name. + """ + return str(path) + + +def names_prefix(held, path): + """Whether a `CLAUDE_CODE_SHELL_PREFIX` value names the deployed prefix.""" + return held == prefix_value(path) + + +def foreign_prefix(data): + """The `CLAUDE_CODE_SHELL_PREFIX` value when it names something other than this kit's prefix, else None.""" + env = data.get("env") if isinstance(data, dict) else None + held = env.get(PREFIX_VAR) if isinstance(env, dict) else None + return held if held is not None and CONTAIN_NAME not in str(held) else None def hook_launcher(): @@ -589,14 +626,15 @@ def event_groups(event): capable, reason = containment_capable() env = data.get("env") held = env.get(PREFIX_VAR) if isinstance(env, dict) else None - want = prefix_value(claude_home / "hooks" / CONTAIN_NAME) - if capable and held != want: - why = f"is held by {held!r}" if held else "is not set" + ours = names_prefix(held, claude_home / "hooks" / CONTAIN_NAME) + # A foreign value is the maintainer's own choice, which a re-run leaves alone, so it is a note rather than drift. + if capable and not ours and foreign_prefix(data) is None: + why = f"is {held!r}, which does not run the deployed prefix" if held else "is not set" out.append( f"{PREFIX_VAR} {why}, so agent commands run with no task or memory ceiling " f"although this host can contain them ({reason})" ) - elif not capable and held == want: + elif not capable and ours: out.append( f"{PREFIX_VAR} names the containment prefix on a host that cannot contain ({reason}), " "so every command prints a notice and runs uncontained" @@ -688,6 +726,17 @@ def report(claude_home): problems.append("the installed content differs from what this checkout would write") # Correct bytes on disk are not a running guard, so the wiring is checked as well. problems.extend(registration_problems(claude_home)) + try: + foreign = foreign_prefix( + json.loads((claude_home / "settings.json").read_text(encoding="utf-8")) + ) + except (ValueError, OSError): + foreign = None + if foreign is not None: + print( + f"Note: {PREFIX_VAR} is {foreign!r}, which this kit does not own, so agent commands run " + "uncontained. Remove it and re-run the installer to contain them." + ) # Read from the file rather than compared against the stamp. # An install onto a corrupted file writes the corruption into the stamp, and the two then agree. problems.extend(marker_corruption(claude_home / "CLAUDE.md")) diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py index 8dc125cf0..0c0a36749 100755 --- a/host-setup/agent-safety/claude/stray-process-sweep.py +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -258,8 +258,7 @@ def session_token(session_id): def session_scopes(session_id, runner=_systemctl): """The tool-call scopes this session left loaded, or None when systemd cannot be asked. - Only this session's tool-call scopes match. A hook command's scope is named apart, since another - SessionEnd hook may still be running in one while this runs. + Only this session's tool-call scopes match, since the prefix places nothing else in a scope. """ token = session_token(session_id) if not token: @@ -315,8 +314,9 @@ def reap(session_id, table, runner=_systemctl, read=None): if not units: return "" pids = scope_pids(units, runner, read) - code, _out = runner("stop", "--", *units) - left = session_scopes(session_id, runner) if code == 0 else units + runner("stop", "--", *units) + # Re-listed whatever the stop returned, since a scope collected between the list and the stop fails it. + left = session_scopes(session_id, runner) left = units if left is None else [u for u in left if u in units] stopped = [u for u in units if u not in left] lines = [] @@ -349,9 +349,10 @@ def main(): # `sess`, so on both the hook is inert rather than printing a failure at every session end. if os.name != "posix" or sys.platform == "darwin": return 0 - session_id = ( - payload.get("session_id") if isinstance(payload, dict) else None - ) or os.environ.get("CLAUDE_CODE_SESSION_ID") + held = payload.get("session_id") if isinstance(payload, dict) else None + session_id = (held if isinstance(held, str) else None) or os.environ.get( + "CLAUDE_CODE_SESSION_ID" + ) reaped = "" if manager_reachable(os.environ): reaped = reap(session_id, _read_process_table() or {}) @@ -501,12 +502,20 @@ def fake(*args, stop_code=0, sticky=()): stuck = reap( sid, table, runner=lambda *a: fake(*a, sticky=(sticky,)), read=lambda p: procs.get(p, "") ) + live.update({f"{_TOOL_UNIT}-{sid}-400.scope", f"{_TOOL_UNIT}-{sid}-600.scope"}) + raced = reap( + sid, table, runner=lambda *a: fake(*a, stop_code=5), read=lambda p: procs.get(p, "") + ) live.clear() checks += [ + ( + "stopped 2 command scopes" in raced and "did not stop" not in raced, + "a stop that fails on a scope already collected still reports what the re-list shows", + ), (stopped_all, "every tool-call scope of this session is stopped"), ( calls[0][-1] == f"{_TOOL_UNIT}-{sid}-*.scope", - "and only this session's tool-call scopes are listed, never a hook's", + "and only this session's tool-call scopes are listed", ), ("stopped 2 command scopes" in reaped, "the report counts what was stopped"), ("2 processes" in reaped and "pid 400" in reaped, "and names each scope's root process"), diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index a035a5206..ce0abc413 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -723,13 +723,12 @@ def _write(self, data): json.dumps(data, indent=2) + "\n", encoding="utf-8" ) - def _want(self): - return install.prefix_value(self.home / "hooks" / install.CONTAIN_NAME) - def test_a_capable_host_sets_the_prefix_to_the_deployed_file(self): + """A bare path, since Claude Code quotes the whole value as one word.""" self.install() - self.assertTrue((self.home / "hooks" / install.CONTAIN_NAME).is_file()) - self.assertEqual(self._settings()["env"][install.PREFIX_VAR], self._want()) + deployed = self.home / "hooks" / install.CONTAIN_NAME + self.assertTrue(deployed.is_file()) + self.assertEqual(self._settings()["env"][install.PREFIX_VAR], str(deployed)) r = run(self.home, "--report") self.assertEqual(r.returncode, 0, r.stdout + r.stderr) @@ -764,16 +763,25 @@ def test_reinstalling_on_a_host_that_lost_its_manager_removes_only_our_prefix(se self.install(contain=False) self.assertEqual(self._settings()["env"], {"OTHER": "kept"}) - def test_a_foreign_prefix_is_kept_and_reported(self): - """Someone else's wrapper is theirs, so the installer neither replaces nor hides it.""" + def test_a_foreign_prefix_is_kept_and_noted_without_a_stale_verdict(self): + """Someone else's wrapper is theirs, and a re-run leaves it, so it cannot be drift a re-run clears.""" self.home.mkdir(parents=True) self._write({"env": {install.PREFIX_VAR: "/usr/local/bin/audit-log"}}) r = self.install() self.assertIn("does not own", r.stdout) self.assertEqual(self._settings()["env"][install.PREFIX_VAR], "/usr/local/bin/audit-log") r = run(self.home, "--report") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("Note:", r.stdout) + + def test_a_prefix_naming_another_copy_reports_stale(self): + self.install() + data = self._settings() + data["env"][install.PREFIX_VAR] = "/elsewhere/hooks/" + install.CONTAIN_NAME + self._write(data) + r = run(self.home, "--report") self.assertEqual(r.returncode, 1, r.stdout + r.stderr) - self.assertIn("is held by", r.stdout) + self.assertIn("does not run the deployed prefix", r.stdout) def test_a_non_object_env_is_refused_rather_than_overwritten(self): self.home.mkdir(parents=True) diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index 88d535800..61f462b16 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -63,13 +63,6 @@ def which(name, path=None): return None -def _positive(text, integer=False): - """Whether `text` is a positive plain decimal number, an integer where `integer` is set.""" - if not text.isascii() or not text.replace(".", "", 1).isdigit() or (integer and "." in text): - return False - return float(text) > 0 - - def session_token(session_id): """The session id as it appears in a unit name, or "" where there is none to name.""" return "".join(c for c in session_id or "" if c.isascii() and (c.isalnum() or c == "-"))[:64] @@ -103,21 +96,46 @@ def pick_shell(command, which=which): return which(snapshot_shell(command) or "bash") or which("bash") or "/bin/sh" +# The smallest override accepted, so a unitless or mistyped value cannot kill every command at its start. +MIN_TASKS = 64 +MIN_MEMORY = 256 * 1024**2 +_UNITS = {"K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4, "P": 1024**5, "E": 1024**6} + + +def _number(text): + """`text` as a positive number when it is plain decimal digits with at most one inner point, else None.""" + whole, _dot, frac = text.partition(".") + if not (whole.isascii() and whole.isdigit()) or ( + _dot and not (frac.isascii() and frac.isdigit()) + ): + return None + value = float(text) + return value if value > 0 else None + + def _percent(value): """Whether `value` is a percentage above 0 and at most 100, fractional or whole.""" - return value.endswith("%") and _positive(value[:-1]) and float(value[:-1]) <= 100 + number = _number(value[:-1]) if value.endswith("%") else None + return number is not None and number <= 100 def valid_tasks(value): - """Whether `value` is a `TasksMax`: a count, a percentage of the system's limit, or infinity.""" - return value == "infinity" or _positive(value, integer=True) or _percent(value) + """Whether `value` is a `TasksMax` of at least `MIN_TASKS`, a percentage of the system limit, or infinity.""" + if value == "infinity" or _percent(value): + return True + return value.isascii() and value.isdigit() and int(value) >= MIN_TASKS def valid_memory(value): - """Whether `value` is a `MemoryMax`: bytes, a size in K to E, a percentage of RAM, or infinity.""" + """Whether `value` is a `MemoryMax` of at least `MIN_MEMORY` in K to E units, a percentage of RAM, or infinity. + + A unitless count is bytes to systemd, and one written meaning megabytes kills every command at its + start, so a unit is required. + """ if value == "infinity" or _percent(value): return True - return _positive(value[:-1] if value[-1:] in ("K", "M", "G", "T", "P", "E") else value) + number = _number(value[:-1]) if value[-1:] in _UNITS else None + return number is not None and number * _UNITS[value[-1]] >= MIN_MEMORY def ceilings(env): @@ -312,13 +330,22 @@ def fake_which(name): ), (session_token("a/b c;d") == "abcd", "a session id cannot inject into a unit name"), ( - all(map(valid_memory, ("16G", "1024", "1.5G", "12.5%", "1P", "100%", "infinity"))) - and not any(map(valid_memory, ("0", "101%", "0%", "16GB", "-1", "G", "lots"))), + all( + map( + valid_memory, ("16G", "1.5G", "0.5G", "512M", "12.5%", "1P", "100%", "infinity") + ) + ) + and not any( + map( + valid_memory, + ("0", "1024", "0.5", ".5G", "1K", "101%", "0%", "16GB", "G", "lots"), + ) + ), "a memory size systemd accepts is accepted, and a malformed one is not", ), ( - all(map(valid_tasks, ("1", "8192", "50%", "infinity"))) - and not any(map(valid_tasks, ("0", "1.5", "1e3", "-5", "\u0663"))), + all(map(valid_tasks, ("64", "8192", "50%", "infinity"))) + and not any(map(valid_tasks, ("0", "1", "1.5", "1e3", "-5", ".5%", "\u0663"))), "and so is a task count", ), ( From fa57deca95996d7e1b9da9d25ba2eae6b70cdeff Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 07:46:35 -0700 Subject: [PATCH 04/22] Execute the Deployed Prefix Before Treating a Host as Contained Claude Code runs the prefix as its own executable for every hook command, so a missing python3, a lost execute bit, or a noexec mount would fail the write guard open while the installer's interpreter-run self-test still passed. The installer and --report now execute the deployed file directly, as Claude Code does, and tests cover the real capability judgment rather than only its override. Also from the third local review, authorized by the maintainer: the user manager is found under /run/user/ when XDG_RUNTIME_DIR lacks its socket, as on WSLg, with the command's own value restored; the sweep lists scopes under both the payload's and the environment's session id; a percentage override has a 1% floor; and the README states when the prefix is set the way the code decides it. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/README.md | 8 +- host-setup/agent-safety/claude/install.py | 64 ++++++---- .../claude/stray-process-sweep.py | 114 +++++++++++------- .../agent-safety/claude/test_install.py | 65 ++++++++++ .../agent-safety/claude/tool-containment.py | 106 +++++++++++----- 5 files changed, 254 insertions(+), 103 deletions(-) diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 2c5f490ce..8d981cabd 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -13,7 +13,7 @@ installation and operational detail. Codex and opencode have no equivalent hook Into `~/.claude/` (or `%USERPROFILE%\.claude\` on Windows): - **`hooks/gh-write-guard.py`**: a PreToolUse hook that denies four classes of dangerous action. First, the GitHub **write** footguns behind the cross-repo comment incident: a state-changing `gh` call whose output is discarded, a GraphQL mutation passing a **literal** node id instead of a `$variable`, and a `gh` write whose explicit target is under an owner other than the checkout origin's. Sibling repositories under the same owner are allowed, since the harm this guards is reaching a stranger's repository rather than working across one maintainer's own fleet, and a different owner is allowed only when the maintainer names it in `GH_WRITE_GUARD_ALLOW` (an `owner/repo` list, where `owner/*` grants a whole owner). That variable is read from the environment the session was launched with, which is the one channel an agent cannot set for itself: a hook runs as its own process, so an inline `VAR=x cmd` prefix or an `export` inside a Bash call never reaches it. Second, a **git operation that bypasses a repository protection**. The branch-rule cases (a direct push to a branch that requires a pull request, a force-push where history is protected, a branch delete where deletion is blocked) are judged against the branch's **live** rules, so a code-style `develop` is denied while a config-style `develop` is allowed with no per-repo configuration. A push to a protected-default branch fails closed when its rules cannot be determined, either because the API is unreachable or because the checkout's origin cannot be resolved to query them. The explicit-bypass flags are denied **unconditionally**, since the flag is itself the bypass and needs no branch query: `gh pr merge --admin` overrides the server-side merge gate, and `git commit`/`git push --no-verify` skips the local git hooks. Third, a **mutating git operation run directly against a primary checkout** (`checkout`/`switch`/`pull`/`reset`/`rebase`/`merge`/`cherry-pick`/`revert`/`restore`/`add`/`commit`/`rm`/`mv`/`apply`/`am`/`push`/`stash` (anything but `list`/`show`)/`clean -f`/`worktree remove -f`), the harm behind a second incident where an agent reused the maintainer's own primary checkout instead of a worktree despite having read the prose rule against it. "Primary" is decided by comparing `git rev-parse --git-dir` against `--git-common-dir`, not a `.git`-is-a-directory guess. `worktree add`/`list`/`prune`, an unforced `worktree remove`, `merge --ff-only`/`pull --ff-only`, and a `checkout `/`switch ` carrying no force flag (bundled or attached forms like `-qf`/`-Bname` recognized, not only an exact token) stay exempt even in a primary checkout, matching the documented base-clone cleanup step the `repo-worktree` skill already carries. A subcommand this rule does not recognize is resolved through a chain of git aliases, inline and persisted, before falling through, so a custom alias cannot hide a denied builtin behind an unrecognized name. A `!`-prefixed shell alias is denied outright rather than interpreted. The target directory follows real git's own `-C`/`--work-tree`/`--git-dir` priority, not a last-option-wins scan. A different owner-style grant, `GH_WRITE_GUARD_ALLOW_PRIMARY_CHECKOUT`, follows the same channel as `GH_WRITE_GUARD_ALLOW`. Reads and everything else pass through. Fourth, an **unbounded shell wait**, which the root spec's requirement 7 defines in full rather than this bullet redefining it. In outline: a loop that sleeps, carrying no bound the rule recognizes. It is the shape an agent writes when a brief tells it to poll. It is also the harm behind a third incident, where seven such loops outlived the subagents that wrote them and the run that dispatched those subagents. A shell started by a tool call runs in a session of its own, so the agent could not have reaped it even had it tried. A nested loop is judged on its own terms, and a command that forks anything out of a `timeout`'s reach, by backgrounding it or by `setsid`, is bounded by nothing. A heredoc body is data rather than a command line unless a shell is what it is fed to, so a document quoting the forbidden shape is written rather than denied. It fires even in autonomous / bypass-permissions sessions, which is how the first incident happened. See the root spec's requirements 6 and 7 for the exact rules. -- **`hooks/tool-containment.py`**: a shell prefix, registered as `CLAUDE_CODE_SHELL_PREFIX` in the `env` block of `settings.json`, that runs every Bash tool call inside a transient systemd user scope carrying `TasksMax` and `MemoryMax`. A runaway fan-out then fails at the ceiling with `fork: Resource temporarily unavailable` instead of growing until the host has to be reset, the harm behind the probe-shim incident in the root spec's requirement 9. The guard above reads the command text, and that incident's recursion lived in a script file the command only named. The ceilings default to 8192 tasks and 25% of RAM. The maintainer raises them with `AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block, which an inline `VAR=x` in a command cannot change, since the prefix reads them before the command runs. Each scope is named `claude-tool---`, so the sweep below can stop one session's tool calls and nothing else. The installer sets the prefix only on a host with a running systemd user manager, and never over a `CLAUDE_CODE_SHELL_PREFIX` value that names anything else. +- **`hooks/tool-containment.py`**: a shell prefix, registered as `CLAUDE_CODE_SHELL_PREFIX` in the `env` block of `settings.json`, that runs every Bash tool call inside a transient systemd user scope carrying `TasksMax` and `MemoryMax`. A runaway fan-out then fails at the ceiling with `fork: Resource temporarily unavailable` instead of growing until the host has to be reset, the harm behind the probe-shim incident in the root spec's requirement 9. The guard above reads the command text, and that incident's recursion lived in a script file the command only named. The ceilings default to 8192 tasks and 25% of RAM. The maintainer raises them with `AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block, which an inline `VAR=x` in a command cannot change, since the prefix reads them before the command runs. Each scope is named `claude-tool---`, so the sweep below can stop one session's tool calls and nothing else. The installer sets the prefix only where it can contain, per the Linux bullet under "Scope and Limits", and never over a `CLAUDE_CODE_SHELL_PREFIX` value that names anything else. - **`hooks/stray-process-sweep.py`**: a SessionEnd hook in two phases. First, it stops every `claude-tool--*` scope this session left loaded and reports what each held, since the scope's name proves which session started it. Second, it reports, and never ends, the process trees outside those scopes that outlive the session. The guard above stops a leak from being written. This finds the ones already running: the ones started before the guard was installed, and the shapes the guard deliberately does not reach. It reports every descendant of the agent process running outside the agent's own session. It names each subtree root's command and age, and hands over the `kill` line. This phase kills nothing itself. A long build backgrounded on purpose reads identically to a leaked wait from there. What is still wanted on the machine is the maintainer's call. A SessionEnd hook cannot block, and its JSON output is discarded, so stderr on exit 2 is the one channel that reaches the maintainer. The sweep uses that for a report rather than for a refusal. It registers under a group carrying no matcher, which fires on every exit reason. It also carries an explicit timeout, since the event's own budget is 1.5 seconds and only a declared per-hook timeout raises it. See the root spec's requirement 8. - **Two marker-delimited blocks of host-wide content in `CLAUDE.md`**, loaded into every session on the machine (including ad-hoc work outside any project), installed and updated independently so one can change without rewriting the other. - The `agent-safety` block carries restrictions alone, so nothing in it can widen a permission. `Repository Boundaries and Write Safety` mirrors the committed `GOVERNANCE.md` section of the same name, carrying as behavioral guidance its write rules and its rules that a task works in its own checkout and isolates into its own worktree before its first file edit. `Data in Agent-Authored Text` mirrors `GOVERNANCE.md` "Representative Data in Agent-Authored Text", so an agent illustrates with constructed data rather than data observed on the machine. `Authorization Scope and Memory Hygiene` bounds how a granted permission is recorded and read. Each mirrors a rule that otherwise reaches fleet repos only. @@ -49,7 +49,7 @@ The deployed copy on each machine is a snapshot, so when the guard changes upstr python3 ~/.claude/hooks/gh-write-guard.py --selftest # decision matrix: all cases pass python3 ~/.claude/hooks/stray-process-sweep.py --selftest # reporting matrix: all cases pass python3 ~/.claude/hooks/tool-containment.py --selftest # containment matrix: all cases pass -grep -c CLAUDE_CODE_SHELL_PREFIX ~/.claude/settings.json # expect 1 where a user manager runs, 0 elsewhere +grep -c CLAUDE_CODE_SHELL_PREFIX ~/.claude/settings.json # expect 1 where the installer reported the prefix set grep -c 'agent-safety v' ~/.claude/CLAUDE.md # expect 2 (start + end marker) grep -c 'fleet-bootstrap v' ~/.claude/CLAUDE.md # expect 2 (start + end marker) grep -cF 'Bash(python3 scripts/pr_review.py:*)' ~/.claude/settings.json # expect 1 (never duplicated) @@ -143,7 +143,7 @@ Run the installer rather than hand-copying this block on a host where the two mi } ``` -Every other key in the file is left as it stands, `permissions.allow` and the rest of `env` included, apart from the rules whose prefix this kit owns. The `env` entry is written only on a host with a running systemd user manager. +Every other key in the file is left as it stands, `permissions.allow` and the rest of `env` included, apart from the rules whose prefix this kit owns. The `env` entry is written only where the installer reports the prefix set. ## Scope and Limits @@ -154,7 +154,7 @@ Every other key in the file is left as it stands, `permissions.allow` and the re - **A write or a wait inside a script file is unseen, so never put either in a script to run it.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string. A `git push` or a `gh` mutation inside the script therefore reaches the server unparsed. An unbounded wait inside that same script is equally unseen, and worse in one way. A denied write fails loudly. A wait the guard never saw runs until something ends it, which is one of the leaks the SessionEnd sweep exists to find afterwards. This is the widest hole in the kit, and an agent opens it by accident. Collecting fifteen repetitive pushes into a loop looks like tidiness, and so does moving a poll into a script to keep a tool call short. Neither looks like disabling a guard. Issue each write and each wait as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and the wait rather than the script. - **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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. -- **Containment runs on Linux and WSL with a systemd user manager and a `python3` 3.11 or newer on PATH.** The prefix runs through its `env python3` shebang for every hook command, the guard included, 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 `python3` unable to run the prefix would fail the guard open, and the installer checks that interpreter before registering anything. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. +- **Containment runs on Linux and WSL with a systemd user manager, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, since WSLg points the variable at a directory of its own. The prefix runs through its `env python3` shebang for every hook command, the guard included, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. - **Hook commands pass through the prefix unscoped.** Claude Code applies `CLAUDE_CODE_SHELL_PREFIX` to hook commands as well as to Bash tool calls. The prefix runs a hook under its shell directly, 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. A hook is told apart by the `CLAUDE_PROJECT_DIR` Claude Code sets for hooks and the shell snapshot a tool call sources first, and either sign of a tool call contains it. 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, and a hook command about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. A scope stop sends SIGTERM and escalates to SIGKILL after two seconds, which keeps it inside the hook's own timeout. diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 90d7dc74d..4e011302e 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -178,46 +178,58 @@ def at(data, path): ] -def containment_capable(): - """(capable, reason): whether this host can start a systemd user scope for an agent command. +def containment_capable(prefix, env=None, system=None, uid=None): + """(capable, reason): whether this host can run the deployed `prefix` and start a scope for a command. Judged at install and at report time alike, so a host that gains or loses its user manager is reported against what it can do now. AGENT_SAFETY_CONTAINMENT_OVERRIDE, read as exactly "0" or "1", replaces the judgment for a test, the way AGENT_SAFETY_DIRTY_OVERRIDE does for the dirty signal. """ - override = os.environ.get("AGENT_SAFETY_CONTAINMENT_OVERRIDE") + env = os.environ if env is None else env + system = sys.platform if system is None else system + override = env.get("AGENT_SAFETY_CONTAINMENT_OVERRIDE") if override in ("0", "1"): return override == "1", "forced by AGENT_SAFETY_CONTAINMENT_OVERRIDE" - if not sys.platform.startswith("linux"): + if not system.startswith("linux"): return False, f"{platform.system()} has no systemd user manager" if not shutil.which("systemd-run"): return False, "systemd-run is not installed" - # The prefix runs through its `env python3` shebang for every hook command, the write guard included. - # A PreToolUse hook that fails is a non-blocking error, so a `python3` that cannot run it fails the guard open. - if not python3_runs_the_prefix(): - return False, "no python3 3.11 or newer is on PATH to run the prefix" - # A `su -`, cron, or `docker exec` shell carries no XDG_RUNTIME_DIR, while the account's sessions do. - runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" - if not os.path.exists(os.path.join(runtime, "systemd", "private")): + # WSLg, `su -`, cron, and `docker exec` shells point elsewhere or nowhere, while the manager listens here. + uid = os.getuid() if uid is None else uid + if not any( + runtime and os.path.exists(os.path.join(runtime, "systemd", "private")) + for runtime in (env.get("XDG_RUNTIME_DIR"), f"/run/user/{uid}") + ): return False, "no systemd user manager is running for this account" - return True, "a systemd user manager is running" + ran = prefix_runs_directly(prefix) + if ran: + return False, f"the deployed prefix does not run as its own executable ({ran})" + return True, "a systemd user manager is running and the prefix runs" -def python3_runs_the_prefix(): - """Whether the `python3` the prefix's shebang resolves to is one this kit supports.""" - found = shutil.which("python3") - if not found: - return False +def prefix_runs_directly(prefix): + """Why `prefix --selftest` fails when executed the way Claude Code executes it, or "" where it passes. + + Claude Code runs the file itself, through its `env python3` shebang, for every hook command, the + write guard included. A PreToolUse hook that fails is a non-blocking error, so a prefix that cannot + run that way, from a missing `python3`, a lost execute bit, or a `noexec` mount, fails the guard open. + """ try: done = subprocess.run( - [found, "-c", "import sys; sys.exit(sys.version_info < (3, 11))"], + [str(prefix), "--selftest"], capture_output=True, - timeout=10, + text=True, + encoding="utf-8", + errors="replace", + timeout=30, check=False, ) - except (OSError, subprocess.SubprocessError): - return False - return done.returncode == 0 + except (OSError, subprocess.SubprocessError) as e: + return str(e) + if done.returncode != 0: + last = (done.stdout + done.stderr).strip().splitlines()[-1:] or ["no output"] + return f"exit {done.returncode}: {last[0]}" + return "" def prefix_value(path): @@ -623,7 +635,7 @@ def event_groups(event): ) elif swept > 1: out.append(f"the SessionEnd sweep is registered {swept} times, so it runs more than once") - capable, reason = containment_capable() + capable, reason = containment_capable(claude_home / "hooks" / CONTAIN_NAME) env = data.get("env") held = env.get(PREFIX_VAR) if isinstance(env, dict) else None ours = names_prefix(held, claude_home / "hooks" / CONTAIN_NAME) @@ -636,8 +648,8 @@ def event_groups(event): ) elif not capable and ours: out.append( - f"{PREFIX_VAR} names the containment prefix on a host that cannot contain ({reason}), " - "so every command prints a notice and runs uncontained" + f"{PREFIX_VAR} names the containment prefix where it cannot contain ({reason}), " + "so re-run the installer to unset it" ) allow = ( data.get("permissions", {}).get("allow") @@ -957,7 +969,7 @@ def reject(where, held, want): done.append("SessionEnd sweep registered") # Step 2c sets the containment prefix only where this host can start a scope, and never over a value naming anything else. - capable, reason = containment_capable() + capable, reason = containment_capable(contain_dst) env = data.setdefault("env", {}) held = env.get(PREFIX_VAR) ours = held is not None and CONTAIN_NAME in str(held) diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py index 0c0a36749..80b16cb49 100755 --- a/host-setup/agent-safety/claude/stray-process-sweep.py +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -221,11 +221,17 @@ def report(table, roots): return "\n".join(lines) -def _systemctl(*args): - """(exit code, stdout) of `systemctl --user `, or (None, "") when it cannot run at all.""" +def _systemctl(*args, runtime=None): + """(exit code, stdout) of `systemctl --user `, or (None, "") when it cannot run at all. + + `runtime` points it at the manager found by `manager_runtime`, which may not be the session's own + `XDG_RUNTIME_DIR`. + """ + env = dict(os.environ, XDG_RUNTIME_DIR=runtime) if runtime else None try: done = subprocess.run( ["systemctl", "--user", *args], + env=env, capture_output=True, text=True, encoding="utf-8", @@ -238,16 +244,19 @@ def _systemctl(*args): return done.returncode, done.stdout -def manager_reachable(env, which=shutil.which, exists=os.path.exists): - """Whether a systemd user manager runs for this session, the test `tool-containment.py` applies. +def manager_runtime(env, which=shutil.which, exists=os.path.exists, uid=None): + """The runtime directory holding the user manager socket, found as `tool-containment.py` finds it. A host without one never ran a contained command, and asking `systemctl --user` there fails, which would report a failure to list at every session end on a host the installer never contained. """ - runtime = env.get("XDG_RUNTIME_DIR") - return bool( - which("systemctl") and runtime and exists(os.path.join(runtime, "systemd", "private")) - ) + if not which("systemctl"): + return None + uid = os.getuid() if uid is None else uid + for runtime in (env.get("XDG_RUNTIME_DIR"), f"/run/user/{uid}"): + if runtime and exists(os.path.join(runtime, "systemd", "private")): + return runtime + return None def session_token(session_id): @@ -255,13 +264,15 @@ def session_token(session_id): return re.sub(r"[^A-Za-z0-9-]", "", session_id or "")[:64] -def session_scopes(session_id, runner=_systemctl): - """The tool-call scopes this session left loaded, or None when systemd cannot be asked. +def session_scopes(session_ids, runner=_systemctl): + """The tool-call scopes these sessions left loaded, or None when systemd cannot be asked. - Only this session's tool-call scopes match, since the prefix places nothing else in a scope. + Only tool-call scopes match, since the prefix places nothing else in a scope. Several ids are + accepted because the hook payload and the environment can name different ones, and the prefix + names a scope from the environment. """ - token = session_token(session_id) - if not token: + tokens = sorted({t for t in map(session_token, session_ids) if t}) + if not tokens: return [] code, out = runner( "list-units", @@ -270,7 +281,7 @@ def session_scopes(session_id, runner=_systemctl): "--plain", "--no-legend", "--no-pager", - f"{_TOOL_UNIT}-{token}-*.scope", + *(f"{_TOOL_UNIT}-{t}-*.scope" for t in tokens), ) if code != 0: return None @@ -303,9 +314,9 @@ def _read(path): } -def reap(session_id, table, runner=_systemctl, read=None): +def reap(session_ids, table, runner=_systemctl, read=None): """Stop this session's tool-call scopes, returning the report, or "" when there were none.""" - units = session_scopes(session_id, runner) + units = session_scopes(session_ids, runner) if units is None: return ( "agent-safety: could not list this session's command scopes, so none was stopped. " @@ -316,7 +327,7 @@ def reap(session_id, table, runner=_systemctl, read=None): pids = scope_pids(units, runner, read) runner("stop", "--", *units) # Re-listed whatever the stop returned, since a scope collected between the list and the stop fails it. - left = session_scopes(session_id, runner) + left = session_scopes(session_ids, runner) left = units if left is None else [u for u in left if u in units] stopped = [u for u in units if u not in left] lines = [] @@ -350,12 +361,18 @@ def main(): if os.name != "posix" or sys.platform == "darwin": return 0 held = payload.get("session_id") if isinstance(payload, dict) else None - session_id = (held if isinstance(held, str) else None) or os.environ.get( - "CLAUDE_CODE_SESSION_ID" - ) + session_ids = [ + held if isinstance(held, str) else "", + os.environ.get("CLAUDE_CODE_SESSION_ID", ""), + ] reaped = "" - if manager_reachable(os.environ): - reaped = reap(session_id, _read_process_table() or {}) + runtime = manager_runtime(os.environ) + if runtime: + + def runner(*args): + return _systemctl(*args, runtime=runtime) + + reaped = reap(session_ids, _read_process_table() or {}, runner=runner) if reaped: print(reaped, file=sys.stderr) table = _read_process_table() @@ -495,18 +512,27 @@ def fake(*args, stop_code=0, sticky=()): return 1, "" procs = {f"/sys/fs/cgroup/app.slice/{_TOOL_UNIT}-{sid}-400.scope/cgroup.procs": "400\n410\n"} - reaped = reap(sid, table, runner=fake, read=lambda p: procs.get(p, "")) + reaped = reap([sid], table, runner=fake, read=lambda p: procs.get(p, "")) stopped_all = not live live.update({f"{_TOOL_UNIT}-{sid}-400.scope"}) sticky = f"{_TOOL_UNIT}-{sid}-400.scope" stuck = reap( - sid, table, runner=lambda *a: fake(*a, sticky=(sticky,)), read=lambda p: procs.get(p, "") + [sid], table, runner=lambda *a: fake(*a, sticky=(sticky,)), read=lambda p: procs.get(p, "") ) live.update({f"{_TOOL_UNIT}-{sid}-400.scope", f"{_TOOL_UNIT}-{sid}-600.scope"}) raced = reap( - sid, table, runner=lambda *a: fake(*a, stop_code=5), read=lambda p: procs.get(p, "") + [sid], table, runner=lambda *a: fake(*a, stop_code=5), read=lambda p: procs.get(p, "") ) live.clear() + + def has(name): + return "/usr/bin/" + name + + def socket_in(*dirs): + return lambda path: any(path == os.path.join(d, "systemd", "private") for d in dirs) + + two_calls = [] + session_scopes(["b", "a", "a", ""], runner=lambda *a: two_calls.append(a) or (0, "")) checks += [ ( "stopped 2 command scopes" in raced and "did not stop" not in raced, @@ -521,32 +547,36 @@ def fake(*args, stop_code=0, sticky=()): ("2 processes" in reaped and "pid 400" in reaped, "and names each scope's root process"), ("pid 410" not in reaped, "but not a process under that root"), ("did not stop" in stuck and f"SIGKILL {sticky}" in stuck, "a scope that stays is named"), - (reap("", table, runner=fake) == "", "a session with no id stops nothing"), - (reap(sid, table, runner=fake) == "", "a session that left nothing reports nothing"), + (reap(["", ""], table, runner=fake) == "", "a session with no id stops nothing"), + (reap([sid], table, runner=fake) == "", "a session that left nothing reports nothing"), ( - "could not list" in reap(sid, table, runner=lambda *a: (None, "")), + "could not list" in reap([sid], table, runner=lambda *a: (None, "")), "a systemctl that cannot run is reported, never read as nothing to stop", ), (session_token("a/b c;d") == "abcd", "the unit name is spelled as the prefix spells it"), ( - not manager_reachable({}, which=lambda n: "/usr/bin/systemctl", exists=lambda p: True), - "a session with no runtime directory has no manager to ask", + manager_runtime({}, which=has, exists=socket_in(), uid=1000) is None, + "a host with no manager socket anywhere has no manager to ask", + ), + ( + manager_runtime( + {"XDG_RUNTIME_DIR": "/mnt/wslg/runtime-dir"}, + which=has, + exists=socket_in("/run/user/1000"), + uid=1000, + ) + == "/run/user/1000", + "a runtime directory lacking the socket falls back to the account's standard one", ), ( - not manager_reachable( - {"XDG_RUNTIME_DIR": "/run/user/1000"}, - which=lambda n: "/usr/bin/systemctl", - exists=lambda p: False, - ), - "nor does one whose manager socket is absent", + manager_runtime({"XDG_RUNTIME_DIR": "/run/user/1000"}, which=lambda n: None, uid=1000) + is None, + "and a host with no systemctl is never asked", ), ( - manager_reachable( - {"XDG_RUNTIME_DIR": "/run/user/1000"}, - which=lambda n: "/usr/bin/systemctl", - exists=lambda p: True, - ), - "a session with its manager socket is swept", + len(two_calls) == 1 + and two_calls[0][-2:] == (f"{_TOOL_UNIT}-a-*.scope", f"{_TOOL_UNIT}-b-*.scope"), + "a payload id and an environment id that differ are both listed, in one call", ), ] ok = True diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index ce0abc413..31649f4de 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -16,6 +16,7 @@ import sys import tempfile import unittest +from unittest import mock HERE = pathlib.Path(__file__).resolve().parent INSTALL = HERE / "install.py" @@ -23,6 +24,9 @@ sys.path.insert(0, str(HERE)) import install +# Held before any case patches `shutil.which`, which is the same object `install` reads. +REAL_WHICH = shutil.which + def run(home, *args, dirty=False, contain=True): """Invoke the installer as a subprocess, the way a host actually runs it. @@ -792,6 +796,67 @@ def test_a_non_object_env_is_refused_rather_than_overwritten(self): self.assertEqual(self._settings()["env"], ["not", "an", "object"]) +class TestContainmentCapable(unittest.TestCase): + """The judgment every other case forces through AGENT_SAFETY_CONTAINMENT_OVERRIDE, run for real.""" + + def setUp(self): + self.tmp = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.runtime = self.tmp / "runtime" + (self.runtime / "systemd").mkdir(parents=True) + (self.runtime / "systemd" / "private").write_text("", encoding="utf-8") + self.prefix = self.tmp / install.CONTAIN_NAME + shutil.copyfile(HERE / install.CONTAIN_NAME, self.prefix) + os.chmod(self.prefix, 0o755) + which = mock.patch.object(install.shutil, "which", side_effect=self._which) + which.start() + self.addCleanup(which.stop) + + @staticmethod + def _which(name): + # The fake claims systemd-run is present, and every other name resolves as it really does. + return "/usr/bin/systemd-run" if name == "systemd-run" else REAL_WHICH(name) + + def _judge(self, env=None, system="linux", uid=987654): + env = {"XDG_RUNTIME_DIR": str(self.runtime)} if env is None else env + return install.containment_capable(self.prefix, env=env, system=system, uid=uid) + + @unittest.skipUnless( + sys.platform.startswith("linux"), "the prefix runs through a POSIX shebang" + ) + def test_a_manager_and_a_runnable_prefix_can_contain(self): + capable, reason = self._judge() + self.assertTrue(capable, reason) + + @unittest.skipUnless(sys.platform.startswith("linux"), "the execute bit is a POSIX property") + def test_a_prefix_that_cannot_run_directly_cannot_contain(self): + """Run through its interpreter it passes, and run the way Claude Code runs it, it fails.""" + os.chmod(self.prefix, 0o644) + capable, reason = self._judge() + self.assertFalse(capable) + self.assertIn("does not run as its own executable", reason) + + def test_a_runtime_directory_lacking_the_socket_falls_back_to_the_standard_one(self): + standard = os.path.join("/run/user/987654", "systemd", "private") + real = os.path.exists + with ( + mock.patch.object( + install.os.path, "exists", side_effect=lambda p: p == standard or real(p) + ), + mock.patch.object(install, "prefix_runs_directly", return_value=""), + ): + capable, reason = self._judge(env={"XDG_RUNTIME_DIR": str(self.tmp / "wslg")}) + self.assertTrue(capable, reason) + + def test_no_socket_anywhere_cannot_contain(self): + capable, reason = self._judge(env={"XDG_RUNTIME_DIR": str(self.tmp / "wslg")}) + self.assertFalse(capable) + self.assertIn("no systemd user manager", reason) + + def test_a_non_linux_host_cannot_contain(self): + self.assertFalse(self._judge(system="darwin")[0]) + + class TestPreexistingCorruption(StampCase): """A file corrupted before the install, where the stamp records the corruption and agrees.""" diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index 61f462b16..68ccaae17 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -47,6 +47,7 @@ # The flag turning that off is an error on an older systemd, so the command travels in the environment instead. COMMAND_VAR = "AGENT_CONTAINMENT_COMMAND" SHELL_VAR = "AGENT_CONTAINMENT_SHELL" +RESTORE_VAR = "AGENT_CONTAINMENT_RUNTIME_RESTORE" # How long a stop waits on SIGTERM before SIGKILL, so the session-end stop fits its hook's budget. STOP_TIMEOUT = "2s" @@ -114,9 +115,9 @@ def _number(text): def _percent(value): - """Whether `value` is a percentage above 0 and at most 100, fractional or whole.""" + """Whether `value` is a percentage from 1 to 100, fractional or whole, so `0.25%` typed for `25%` is refused.""" number = _number(value[:-1]) if value.endswith("%") else None - return number is not None and number <= 100 + return number is not None and 1 <= number <= 100 def valid_tasks(value): @@ -156,18 +157,22 @@ def ceilings(env): return tasks, memory, notices -def manager_reachable(env, platform=sys.platform, which=which, exists=os.path.exists): - """Whether a systemd user manager can start a scope for this process.""" - runtime = env.get("XDG_RUNTIME_DIR") - return bool( - platform.startswith("linux") - and which("systemd-run") - and runtime - and exists(os.path.join(runtime, "systemd", "private")) - ) +def manager_runtime(env, platform=sys.platform, which=which, exists=os.path.exists, uid=None): + """The runtime directory holding this account's systemd user manager socket, or None where there is none. + + `XDG_RUNTIME_DIR` is read first and `/run/user/` second, since WSLg points the variable at a + directory of its own while the user manager listens in the standard one. + """ + if not platform.startswith("linux") or not which("systemd-run"): + return None + uid = os.getuid() if uid is None else uid + for runtime in (env.get("XDG_RUNTIME_DIR"), f"/run/user/{uid}"): + if runtime and exists(os.path.join(runtime, "systemd", "private")): + return runtime + return None -def plan(command, env, suffix, reachable, which=which): +def plan(command, env, suffix, runtime, which=which): """(argv, extra_env, notices) for the outer stage, which the caller execs. For a tool call with a manager, argv starts the scope and re-enters this file as the inner stage, @@ -177,7 +182,7 @@ def plan(command, env, suffix, reachable, which=which): shell = pick_shell(command, which) if not is_tool_call(command, env): return [shell, "-c", command], {}, [] - if not reachable: + if runtime is None: note = "no systemd user manager is reachable, so this command runs with no task or memory ceiling" return [shell, "-c", command], {}, [note] tasks, memory, notices = ceilings(env) @@ -200,7 +205,14 @@ def plan(command, env, suffix, reachable, which=which): os.path.abspath(__file__), "--inner", ] - return argv, {COMMAND_VAR: command, SHELL_VAR: shell}, notices + extra = {COMMAND_VAR: command, SHELL_VAR: shell} + # The scope finds the manager through this variable, and the command gets its original value back. + if env.get("XDG_RUNTIME_DIR") != runtime: + extra["XDG_RUNTIME_DIR"] = runtime + extra[RESTORE_VAR] = ( + "set:" + env["XDG_RUNTIME_DIR"] if "XDG_RUNTIME_DIR" in env else "unset:" + ) + return argv, extra, notices def inner(env): @@ -208,6 +220,11 @@ def inner(env): env = dict(env) command = env.pop(COMMAND_VAR, None) shell = env.pop(SHELL_VAR, None) or "/bin/sh" + state, _sep, original = env.pop(RESTORE_VAR, "").partition(":") + if state == "set": + env["XDG_RUNTIME_DIR"] = original + elif state == "unset": + env.pop("XDG_RUNTIME_DIR", None) if command is None: return None, env return [shell, "-c", command], env @@ -224,7 +241,7 @@ def main(argv): print("usage: tool-containment.py '' | --selftest", file=sys.stderr) return 2 suffix = f"{os.getpid()}-{os.urandom(4).hex()}" - run, extra, notices = plan(argv[1], os.environ, suffix, manager_reachable(os.environ)) + run, extra, notices = plan(argv[1], os.environ, suffix, manager_runtime(os.environ)) for note in notices: print(f"tool-containment: {note}", file=sys.stderr) os.execve(run[0], run, {**os.environ, **extra}) @@ -258,13 +275,22 @@ def fake_which(name): f.write("#!/bin/sh\n") os.chmod(probe, 0o755) - env = {"CLAUDE_CODE_SESSION_ID": "0a1b-2c3d", "XDG_RUNTIME_DIR": "/run/user/1000"} + RUN = "/run/user/1000" + env = {"CLAUDE_CODE_SESSION_ID": "0a1b-2c3d", "XDG_RUNTIME_DIR": RUN} + wslg = dict(env, XDG_RUNTIME_DIR="/mnt/wslg/runtime-dir") + wslg_extra = plan(tool, wslg, "50", RUN, fake_which)[1] + restored = inner({**wslg, **wslg_extra})[1] + unset_extra = plan(tool, {"CLAUDE_CODE_SESSION_ID": "x"}, "51", RUN, fake_which)[1] + + def socket_in(*dirs): + return lambda path: any(path == os.path.join(d, "systemd", "private") for d in dirs) + hook_env = dict(env, CLAUDE_PROJECT_DIR="/opt/agent/project") # A zsh tool call whose own command names a bash snapshot file after the leading clause. mixed = ztool.replace("eval 'echo", "eval 'ls /x/shell-snapshots/snapshot-bash-1.sh; echo") - argv, extra, notes = plan(tool, env, "42-ab", True, fake_which) - hook_plan = plan(hook, hook_env, "43-cd", True, fake_which) - bare, bare_extra, bare_notes = plan(tool, env, "44-ef", False, fake_which) + argv, extra, notes = plan(tool, env, "42-ab", RUN, fake_which) + hook_plan = plan(hook, hook_env, "43-cd", RUN, fake_which) + bare, bare_extra, bare_notes = plan(tool, env, "44-ef", None, fake_which) raised = ceilings( {"AGENT_CONTAINMENT_TASKS_MAX": "20000", "AGENT_CONTAINMENT_MEMORY_MAX": "64G"} ) @@ -280,16 +306,16 @@ def fake_which(name): "a hook command runs under its shell with no scope, so no systemd failure reaches it", ), ( - plan(hook, hook_env, "43-cd", False, fake_which)[2] == [], + plan(hook, hook_env, "43-cd", None, fake_which)[2] == [], "and prints nothing where no manager is reachable", ), ( - "--unit=claude-tool-0a1b-2c3d-48-ab" in plan(hook, env, "48-ab", True, fake_which)[0], + "--unit=claude-tool-0a1b-2c3d-48-ab" in plan(hook, env, "48-ab", RUN, fake_which)[0], "a command with no snapshot and no hook's project dir is still contained", ), ( "--unit=claude-tool-0a1b-2c3d-49-ab" - in plan(tool, hook_env, "49-ab", True, fake_which)[0], + in plan(tool, hook_env, "49-ab", RUN, fake_which)[0], "and so is one sourcing a snapshot whatever its environment", ), (f"--property=TasksMax={DEFAULT_TASKS_MAX}" in argv, "the task ceiling is applied"), @@ -302,11 +328,11 @@ def fake_which(name): (not any("$" in a for a in argv), "no argument carries a `$` for systemd-run to expand"), (extra[SHELL_VAR] == "/usr/bin/bash", "a bash snapshot runs under bash"), ( - plan(ztool, env, "45", True, fake_which)[1][SHELL_VAR] == "/usr/bin/zsh", + plan(ztool, env, "45", RUN, fake_which)[1][SHELL_VAR] == "/usr/bin/zsh", "a zsh one under zsh", ), ( - plan(mixed, env, "46", True, fake_which)[1][SHELL_VAR] == "/usr/bin/zsh", + plan(mixed, env, "46", RUN, fake_which)[1][SHELL_VAR] == "/usr/bin/zsh", "only the leading source clause picks the shell", ), (notes == [], "a contained command prints nothing extra"), @@ -338,7 +364,7 @@ def fake_which(name): and not any( map( valid_memory, - ("0", "1024", "0.5", ".5G", "1K", "101%", "0%", "16GB", "G", "lots"), + ("0", "1024", "0.5", ".5G", "1K", "101%", "0%", "0.25%", "16GB", "G", "lots"), ) ), "a memory size systemd accepts is accepted, and a malformed one is not", @@ -354,7 +380,7 @@ def fake_which(name): "PATH is searched in order, and a miss is None", ), ( - "--unit=claude-tool-nosession-47" in plan(tool, {}, "47", True, fake_which)[0], + "--unit=claude-tool-nosession-47" in plan(tool, {}, "47", RUN, fake_which)[0], "a missing session id names no session the sweep would stop", ), (inner_argv == ["/usr/bin/bash", "-c", tool], "the inner stage runs the command verbatim"), @@ -367,16 +393,34 @@ def fake_which(name): "an inner stage with no command refuses rather than runs", ), ( - not manager_reachable(env, platform="darwin", which=fake_which, exists=lambda p: True), + manager_runtime(env, "darwin", fake_which, lambda p: True, uid=1000) is None, "a non-Linux host has no manager", ), ( - not manager_reachable({}, platform="linux", which=fake_which, exists=lambda p: True), - "nor does a session with no runtime directory", + manager_runtime(env, "linux", fake_which, socket_in(RUN), uid=1000) == RUN, + "a Linux session with a manager socket has one", ), ( - manager_reachable(env, platform="linux", which=fake_which, exists=lambda p: True), - "a Linux session with a manager socket has one", + manager_runtime(wslg, "linux", fake_which, socket_in(RUN), uid=1000) == RUN, + "a runtime directory lacking the socket falls back to the account's standard one", + ), + ( + manager_runtime({}, "linux", fake_which, socket_in(), uid=1000) is None, + "and no socket anywhere is no manager", + ), + ( + wslg_extra.get("XDG_RUNTIME_DIR") == RUN + and restored.get("XDG_RUNTIME_DIR") == "/mnt/wslg/runtime-dir" + and RESTORE_VAR not in restored, + "systemd-run is pointed at the manager, and the command gets the original directory back", + ), + ( + "XDG_RUNTIME_DIR" not in inner({"PATH": "/bin", **unset_extra})[1], + "and an unset directory stays unset for the command", + ), + ( + RESTORE_VAR not in extra and "XDG_RUNTIME_DIR" not in extra, + "a session already pointing at the manager carries no restore", ), ] shutil.rmtree(scratch) From 903c4ce1fd57f8932b55774433a1db590dae7b0f Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 08:00:40 -0700 Subject: [PATCH 05/22] Scope Only Bash Tool Calls, and Report a Foreign-Path Prefix Claude Code also launches every stdio MCP server through the shell prefix, and those launches carry no CLAUDE_PROJECT_DIR, so each server landed in a long-lived tool-call scope named for no session. A command is now scoped only when it sources a Claude Code shell snapshot, and hooks and MCP servers run directly. --report now flags any copy of the prefix registered where this host cannot contain, such as a path synced from another machine, since that path exits 127 on every hook. Percentage overrides are whole numbers, since systemd before 248 rejects a fractional one. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/README.md | 3 +- host-setup/agent-safety/claude/README.md | 2 +- host-setup/agent-safety/claude/install.py | 5 +- .../agent-safety/claude/test_install.py | 10 +++ .../agent-safety/claude/tool-containment.py | 61 +++++++++++-------- 5 files changed, 53 insertions(+), 28 deletions(-) diff --git a/host-setup/agent-safety/README.md b/host-setup/agent-safety/README.md index 349b7ff26..6932dccb0 100644 --- a/host-setup/agent-safety/README.md +++ b/host-setup/agent-safety/README.md @@ -295,7 +295,8 @@ text says, because the harm it covers was never in the text. a failure to list or to stop a group as loudly as a finding. A hook the agent runs, a guard above included, is not placed in a group. A group that fails to - start fails the command, and a guard that fails that way is a guard that did not run. Where the + start fails the command, and a guard that fails that way is a guard that did not run. Nor is a + long-lived server the agent starts, which outlives any one session. Where the host offers no such group, the command runs unbounded and says so on every run, because a silent fallback reads exactly like a bounded command. diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 8d981cabd..7c5caf739 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -155,7 +155,7 @@ 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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. - **Containment runs on Linux and WSL with a systemd user manager, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, since WSLg points the variable at a directory of its own. The prefix runs through its `env python3` shebang for every hook command, the guard included, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. -- **Hook commands pass through the prefix unscoped.** Claude Code applies `CLAUDE_CODE_SHELL_PREFIX` to hook commands as well as to Bash tool calls. The prefix runs a hook under its shell directly, 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. A hook is told apart by the `CLAUDE_PROJECT_DIR` Claude Code sets for hooks and the shell snapshot a tool call sources first, and either sign of a tool call contains it. 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, and a hook command about 10 ms. +- **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, 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. Where a later Claude Code stops sourcing one, tool calls run bare as well, silently, and the sweep's report of surviving processes is what remains. 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, and anything run directly about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. 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. diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 4e011302e..4dbf4c172 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -646,9 +646,10 @@ def event_groups(event): f"{PREFIX_VAR} {why}, so agent commands run with no task or memory ceiling " f"although this host can contain them ({reason})" ) - elif not capable and ours: + # Any copy of the prefix counts here, since a value synced from another host names a path this one lacks. + elif not capable and held is not None and foreign_prefix(data) is None: out.append( - f"{PREFIX_VAR} names the containment prefix where it cannot contain ({reason}), " + f"{PREFIX_VAR} names a containment prefix where it cannot contain ({reason}), " "so re-run the installer to unset it" ) allow = ( diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index 31649f4de..c3511f35f 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -759,6 +759,16 @@ def test_our_prefix_on_a_host_that_cannot_contain_reports_stale(self): self.assertEqual(r.returncode, 1, r.stdout + r.stderr) self.assertIn("cannot contain", r.stdout) + def test_a_prefix_synced_from_another_host_reports_stale_where_it_cannot_contain(self): + """A path this host lacks exits 127 on every hook, which fails the guard open.""" + self.install(contain=False) + data = self._settings() + data["env"] = {install.PREFIX_VAR: "/elsewhere/.claude/hooks/" + install.CONTAIN_NAME} + self._write(data) + r = run(self.home, "--report", contain=False) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("cannot contain", r.stdout) + def test_reinstalling_on_a_host_that_lost_its_manager_removes_only_our_prefix(self): self.install() data = self._settings() diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index 68ccaae17..47c985784 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -2,16 +2,16 @@ """Shell prefix: run every Bash tool call inside a scope with a task and memory ceiling. Registered as `CLAUDE_CODE_SHELL_PREFIX` in the user settings.json `env`. Claude Code then runs each -Bash tool call and each hook command as ` ''`, one argument holding the -whole string, including the cwd bookkeeping Claude Code appends to it. For a tool call this file starts -a transient systemd user scope carrying `TasksMax` and `MemoryMax`, and runs the string under a shell -inside it. +Bash tool call, each hook command, and each stdio MCP server launch as ` ''`, +one argument holding the whole string. For a tool call this file starts a transient systemd user scope +carrying `TasksMax` and `MemoryMax`, and runs the string under a shell inside it. -A hook command runs under its shell directly, with no scope. The write guard is a hook, and a PreToolUse -hook that exits 1 is a non-blocking error, so a scope that failed to start would let the very command -the guard denies go ahead. A hook is told from a tool call by the `CLAUDE_PROJECT_DIR` Claude Code sets -for hooks and by the shell snapshot a tool call sources first. Either sign of a tool call is enough to -contain it, so a change to one of them fails toward containment rather than away from it. +Everything else runs under its shell directly, with no scope. The write guard is a hook, and a +PreToolUse hook that exits 1 is a non-blocking error, so a scope that failed to start would let the very +command the guard denies go ahead. An MCP server is long-lived and started outside any session, so a +scope would bound it for its whole life and outlive the session that named it. A tool call is told +apart by the Claude Code shell snapshot it sources first. Where a later Claude Code stops sourcing one, +tool calls run bare too, and the SessionEnd sweep's report of surviving processes is what remains. A runaway fan-out then meets the ceiling and fails with a visible error, instead of growing until the host has to be reset. The ceiling belongs to the scope's cgroup rather than to the foreground wait, so @@ -83,9 +83,9 @@ def snapshot_shell(command): return None -def is_tool_call(command, env): - """Whether Claude Code runs `command` as a Bash tool call rather than as a hook command.""" - return snapshot_shell(command) is not None or "CLAUDE_PROJECT_DIR" not in env +def is_tool_call(command): + """Whether Claude Code runs `command` as a Bash tool call rather than as a hook or an MCP server.""" + return snapshot_shell(command) is not None def pick_shell(command, which=which): @@ -115,9 +115,12 @@ def _number(text): def _percent(value): - """Whether `value` is a percentage from 1 to 100, fractional or whole, so `0.25%` typed for `25%` is refused.""" - number = _number(value[:-1]) if value.endswith("%") else None - return number is not None and 1 <= number <= 100 + """Whether `value` is a whole percentage from 1 to 100, the form every systemd reads. + + A fractional one is an error before systemd 248, and the floor refuses `0.25%` typed for `25%`. + """ + digits = value[:-1] if value.endswith("%") else "" + return digits.isascii() and digits.isdigit() and 1 <= int(digits) <= 100 def valid_tasks(value): @@ -180,7 +183,7 @@ def plan(command, env, suffix, runtime, which=which): gets the shell itself, and only the tool call is told it runs with no ceiling. """ shell = pick_shell(command, which) - if not is_tool_call(command, env): + if not is_tool_call(command): return [shell, "-c", command], {}, [] if runtime is None: note = "no systemd user manager is reachable, so this command runs with no task or memory ceiling" @@ -255,6 +258,7 @@ def _selftest(): ) ztool = tool.replace("snapshot-bash-", "snapshot-zsh-") hook = '"python3" "/opt/agent/.claude/hooks/gh-write-guard.py"' + mcp = "'npx' '-y' 'example-mcp-server'" def fake_which(name): return { @@ -310,8 +314,8 @@ def socket_in(*dirs): "and prints nothing where no manager is reachable", ), ( - "--unit=claude-tool-0a1b-2c3d-48-ab" in plan(hook, env, "48-ab", RUN, fake_which)[0], - "a command with no snapshot and no hook's project dir is still contained", + plan(mcp, env, "48-ab", RUN, fake_which) == (["/usr/bin/bash", "-c", mcp], {}, []), + "an MCP server launch, sourcing no snapshot, runs under its shell with no scope", ), ( "--unit=claude-tool-0a1b-2c3d-49-ab" @@ -356,15 +360,24 @@ def socket_in(*dirs): ), (session_token("a/b c;d") == "abcd", "a session id cannot inject into a unit name"), ( - all( - map( - valid_memory, ("16G", "1.5G", "0.5G", "512M", "12.5%", "1P", "100%", "infinity") - ) - ) + all(map(valid_memory, ("16G", "1.5G", "0.5G", "512M", "25%", "1P", "100%", "infinity"))) and not any( map( valid_memory, - ("0", "1024", "0.5", ".5G", "1K", "101%", "0%", "0.25%", "16GB", "G", "lots"), + ( + "0", + "1024", + "0.5", + ".5G", + "1K", + "101%", + "0%", + "0.25%", + "12.5%", + "16GB", + "G", + "lots", + ), ) ), "a memory size systemd accepts is accepted, and a malformed one is not", From c3d7ab8cfa2a106c0a7a72573d2f4de56765dec6 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 08:27:04 -0700 Subject: [PATCH 06/22] Refuse Unenforceable Ceilings, and Report an Uncontained Host An override past systemd's 64-bit limits passed validation and then failed every tool call, so both ceilings now carry an upper bound. A host whose user manager is not delegated the pids and memory controllers, as on cgroup v1, starts scopes that enforce neither ceiling, so the installer now treats it as unable to contain. Requirement 9 said an unbounded host announces it on every run, which the implementation cannot do where no prefix is registered. The spec now puts that statement in the installation report, and --report prints a note wherever agent commands run uncontained. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/README.md | 8 +++++--- host-setup/agent-safety/claude/README.md | 2 +- host-setup/agent-safety/claude/install.py | 16 +++++++++++++++- .../agent-safety/claude/test_install.py | 19 ++++++++++++++++++- .../agent-safety/claude/tool-containment.py | 15 ++++++++++++--- 5 files changed, 51 insertions(+), 9 deletions(-) diff --git a/host-setup/agent-safety/README.md b/host-setup/agent-safety/README.md index 6932dccb0..a85fb1428 100644 --- a/host-setup/agent-safety/README.md +++ b/host-setup/agent-safety/README.md @@ -296,9 +296,11 @@ text says, because the harm it covers was never in the text. A hook the agent runs, a guard above included, is not placed in a group. A group that fails to start fails the command, and a guard that fails that way is a guard that did not run. Nor is a - long-lived server the agent starts, which outlives any one session. Where the - host offers no such group, the command runs unbounded and says so on every run, because a silent - fallback reads exactly like a bounded command. + long-lived server the agent starts, which outlives any one session. + + Where the host offers no such group, commands run unbounded and the host's installation report + says so, because a silent fallback reads exactly like a bounded host. A host that registered the + bounding and later lost its group says so on every command instead. The maintainer sets the ceilings, where a variable set inline in the bounded command cannot reach them. They bound an accident rather than an adversary, since a command can still raise its own diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 7c5caf739..34f4e2d36 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -154,7 +154,7 @@ Every other key in the file is left as it stands, `permissions.allow` and the re - **A write or a wait inside a script file is unseen, so never put either in a script to run it.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string. A `git push` or a `gh` mutation inside the script therefore reaches the server unparsed. An unbounded wait inside that same script is equally unseen, and worse in one way. A denied write fails loudly. A wait the guard never saw runs until something ends it, which is one of the leaks the SessionEnd sweep exists to find afterwards. This is the widest hole in the kit, and an agent opens it by accident. Collecting fifteen repetitive pushes into a loop looks like tidiness, and so does moving a poll into a script to keep a tool call short. Neither looks like disabling a guard. Issue each write and each wait as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and the wait rather than the script. - **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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. -- **Containment runs on Linux and WSL with a systemd user manager, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, since WSLg points the variable at a directory of its own. The prefix runs through its `env python3` shebang for every hook command, the guard included, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. +- **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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. Wherever the prefix is left unset, `--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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. - **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, 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. Where a later Claude Code stops sourcing one, tool calls run bare as well, silently, and the sweep's report of surviving processes is what remains. 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, and anything run directly about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. A scope stop sends SIGTERM and escalates to SIGKILL after two seconds, which keeps it inside the hook's own timeout. diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 4dbf4c172..e13d56bdc 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -178,7 +178,7 @@ def at(data, path): ] -def containment_capable(prefix, env=None, system=None, uid=None): +def containment_capable(prefix, env=None, system=None, uid=None, controllers=None): """(capable, reason): whether this host can run the deployed `prefix` and start a scope for a command. Judged at install and at report time alike, so a host that gains or loses its user manager is @@ -201,6 +201,17 @@ def containment_capable(prefix, env=None, system=None, uid=None): for runtime in (env.get("XDG_RUNTIME_DIR"), f"/run/user/{uid}") ): return False, "no systemd user manager is running for this account" + # A scope on a cgroup-v1 or hybrid host, or under a manager not delegated these two, enforces neither ceiling. + controllers = controllers or ( + f"/sys/fs/cgroup/user.slice/user-{uid}.slice/user@{uid}.service/cgroup.controllers" + ) + try: + with open(controllers, encoding="utf-8") as f: + delegated = set(f.read().split()) + except OSError: + delegated = set() + if not {"pids", "memory"} <= delegated: + return False, "the user manager is not delegated the pids and memory controllers" ran = prefix_runs_directly(prefix) if ran: return False, f"the deployed prefix does not run as its own executable ({ran})" @@ -745,6 +756,9 @@ def report(claude_home): ) except (ValueError, OSError): foreign = None + capable, reason = containment_capable(claude_home / "hooks" / CONTAIN_NAME) + if not capable and foreign is None: + print(f"Note: agent commands on this host run uncontained ({reason}).") if foreign is not None: print( f"Note: {PREFIX_VAR} is {foreign!r}, which this kit does not own, so agent commands run " diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index c3511f35f..fa11a1586 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -743,6 +743,8 @@ def test_an_incapable_host_deploys_the_file_and_sets_no_prefix(self): self.assertNotIn("env", self._settings()) r = run(self.home, "--report", contain=False) self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + # The report says so, since a silent fallback reads exactly like a contained host. + self.assertIn("run uncontained", r.stdout) def test_a_removed_prefix_reports_stale_on_a_capable_host(self): self.install() @@ -818,6 +820,8 @@ def setUp(self): self.prefix = self.tmp / install.CONTAIN_NAME shutil.copyfile(HERE / install.CONTAIN_NAME, self.prefix) os.chmod(self.prefix, 0o755) + self.controllers = self.tmp / "cgroup.controllers" + self.controllers.write_text("cpu memory pids\n", encoding="utf-8") which = mock.patch.object(install.shutil, "which", side_effect=self._which) which.start() self.addCleanup(which.stop) @@ -829,7 +833,9 @@ def _which(name): def _judge(self, env=None, system="linux", uid=987654): env = {"XDG_RUNTIME_DIR": str(self.runtime)} if env is None else env - return install.containment_capable(self.prefix, env=env, system=system, uid=uid) + return install.containment_capable( + self.prefix, env=env, system=system, uid=uid, controllers=str(self.controllers) + ) @unittest.skipUnless( sys.platform.startswith("linux"), "the prefix runs through a POSIX shebang" @@ -858,6 +864,17 @@ def test_a_runtime_directory_lacking_the_socket_falls_back_to_the_standard_one(s capable, reason = self._judge(env={"XDG_RUNTIME_DIR": str(self.tmp / "wslg")}) self.assertTrue(capable, reason) + def test_a_manager_without_the_pids_and_memory_controllers_cannot_contain(self): + """A scope under it starts and enforces neither ceiling, as on a cgroup-v1 or hybrid host.""" + self.controllers.write_text("cpu\n", encoding="utf-8") + capable, reason = self._judge() + self.assertFalse(capable) + self.assertIn("pids and memory", reason) + + def test_an_unreadable_controllers_file_cannot_contain(self): + self.controllers.unlink() + self.assertFalse(self._judge()[0]) + def test_no_socket_anywhere_cannot_contain(self): capable, reason = self._judge(env={"XDG_RUNTIME_DIR": str(self.tmp / "wslg")}) self.assertFalse(capable) diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index 47c985784..9a3c379ec 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -100,6 +100,8 @@ def pick_shell(command, which=which): # The smallest override accepted, so a unitless or mistyped value cannot kill every command at its start. MIN_TASKS = 64 MIN_MEMORY = 256 * 1024**2 +# The largest override accepted, below what systemd parses into its 64-bit limits and rejects past. +MAX_LIMIT = 2**63 _UNITS = {"K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4, "P": 1024**5, "E": 1024**6} @@ -127,7 +129,7 @@ def valid_tasks(value): """Whether `value` is a `TasksMax` of at least `MIN_TASKS`, a percentage of the system limit, or infinity.""" if value == "infinity" or _percent(value): return True - return value.isascii() and value.isdigit() and int(value) >= MIN_TASKS + return value.isascii() and value.isdigit() and MIN_TASKS <= int(value) < MAX_LIMIT def valid_memory(value): @@ -139,7 +141,7 @@ def valid_memory(value): if value == "infinity" or _percent(value): return True number = _number(value[:-1]) if value[-1:] in _UNITS else None - return number is not None and number * _UNITS[value[-1]] >= MIN_MEMORY + return number is not None and MIN_MEMORY <= number * _UNITS[value[-1]] < MAX_LIMIT def ceilings(env): @@ -377,6 +379,8 @@ def socket_in(*dirs): "16GB", "G", "lots", + "99999999999E", + "9" * 400 + "G", ), ) ), @@ -384,7 +388,12 @@ def socket_in(*dirs): ), ( all(map(valid_tasks, ("64", "8192", "50%", "infinity"))) - and not any(map(valid_tasks, ("0", "1", "1.5", "1e3", "-5", ".5%", "\u0663"))), + and not any( + map( + valid_tasks, + ("0", "1", "1.5", "1e3", "-5", ".5%", "\u0663", "99999999999999999999"), + ) + ), "and so is a task count", ), ( From f266de1322814d1059f6dc41ea1c2781f01a2814 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 08:31:24 -0700 Subject: [PATCH 07/22] Refuse an Octal Task Count, and Check Delegation Per Command systemd reads a TasksMax with a leading zero as octal, so 0100 became a ceiling of 64 and 0099 failed every tool call. A leading zero is now refused and the default kept. The prefix now also checks per command that the user manager still holds the pids and memory controllers, and says so on stderr where it does not, as requirement 9 states, rather than starting a scope that enforces neither ceiling. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/README.md | 2 +- .../agent-safety/claude/tool-containment.py | 58 +++++++++++++++++-- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 34f4e2d36..4844565ac 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -154,7 +154,7 @@ Every other key in the file is left as it stands, `permissions.allow` and the re - **A write or a wait inside a script file is unseen, so never put either in a script to run it.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string. A `git push` or a `gh` mutation inside the script therefore reaches the server unparsed. An unbounded wait inside that same script is equally unseen, and worse in one way. A denied write fails loudly. A wait the guard never saw runs until something ends it, which is one of the leaks the SessionEnd sweep exists to find afterwards. This is the widest hole in the kit, and an agent opens it by accident. Collecting fifteen repetitive pushes into a loop looks like tidiness, and so does moving a poll into a script to keep a tool call short. Neither looks like disabling a guard. Issue each write and each wait as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and the wait rather than the script. - **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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. -- **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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. Wherever the prefix is left unset, `--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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable, each command runs unbounded and prints one `tool-containment:` line on stderr saying so. +- **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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. Wherever the prefix is left unset, `--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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable or loses those two controllers, each tool call runs unbounded and prints one `tool-containment:` line on stderr saying so. - **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, 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. Where a later Claude Code stops sourcing one, tool calls run bare as well, silently, and the sweep's report of surviving processes is what remains. 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, and anything run directly about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. A scope stop sends SIGTERM and escalates to SIGKILL after two seconds, which keeps it inside the hook's own timeout. diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index 9a3c379ec..2fff360f5 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -49,6 +49,9 @@ SHELL_VAR = "AGENT_CONTAINMENT_SHELL" RESTORE_VAR = "AGENT_CONTAINMENT_RUNTIME_RESTORE" +UNREACHABLE = "no systemd user manager is reachable" +UNDELEGATED = "the user manager is not delegated the pids and memory controllers" + # How long a stop waits on SIGTERM before SIGKILL, so the session-end stop fits its hook's budget. STOP_TIMEOUT = "2s" @@ -129,7 +132,9 @@ def valid_tasks(value): """Whether `value` is a `TasksMax` of at least `MIN_TASKS`, a percentage of the system limit, or infinity.""" if value == "infinity" or _percent(value): return True - return value.isascii() and value.isdigit() and MIN_TASKS <= int(value) < MAX_LIMIT + # A leading zero makes systemd read the count as octal, a different ceiling or none at all. + plain = value.isascii() and value.isdigit() and not value.startswith("0") + return plain and MIN_TASKS <= int(value) < MAX_LIMIT def valid_memory(value): @@ -177,7 +182,22 @@ def manager_runtime(env, platform=sys.platform, which=which, exists=os.path.exis return None -def plan(command, env, suffix, runtime, which=which): +def delegated(uid=None, read=None): + """Whether the user manager holds the pids and memory controllers, without which a scope enforces neither ceiling.""" + uid = os.getuid() if uid is None else uid + path = f"/sys/fs/cgroup/user.slice/user-{uid}.slice/user@{uid}.service/cgroup.controllers" + try: + if read: + text = read(path) + else: + with open(path, encoding="utf-8") as f: + text = f.read() + except OSError: + return False + return {"pids", "memory"} <= set(text.split()) + + +def plan(command, env, suffix, runtime, which=which, why=UNREACHABLE): """(argv, extra_env, notices) for the outer stage, which the caller execs. For a tool call with a manager, argv starts the scope and re-enters this file as the inner stage, @@ -188,8 +208,11 @@ def plan(command, env, suffix, runtime, which=which): if not is_tool_call(command): return [shell, "-c", command], {}, [] if runtime is None: - note = "no systemd user manager is reachable, so this command runs with no task or memory ceiling" - return [shell, "-c", command], {}, [note] + return ( + [shell, "-c", command], + {}, + [f"{why}, so this command runs with no task or memory ceiling"], + ) tasks, memory, notices = ceilings(env) token = session_token(env.get("CLAUDE_CODE_SESSION_ID")) or "nosession" argv = [ @@ -246,7 +269,10 @@ def main(argv): print("usage: tool-containment.py '' | --selftest", file=sys.stderr) return 2 suffix = f"{os.getpid()}-{os.urandom(4).hex()}" - run, extra, notices = plan(argv[1], os.environ, suffix, manager_runtime(os.environ)) + runtime, why = manager_runtime(os.environ), UNREACHABLE + if runtime and is_tool_call(argv[1]) and not delegated(): + runtime, why = None, UNDELEGATED + run, extra, notices = plan(argv[1], os.environ, suffix, runtime, why=why) for note in notices: print(f"tool-containment: {note}", file=sys.stderr) os.execve(run[0], run, {**os.environ, **extra}) @@ -347,6 +373,15 @@ def socket_in(*dirs): "no manager runs the shell bare", ), (len(bare_notes) == 1 and "no task or memory ceiling" in bare_notes[0], "and says so"), + ( + UNDELEGATED in plan(tool, env, "52", None, fake_which, why=UNDELEGATED)[2][0], + "a manager lacking the controllers is named as the reason, per command", + ), + ( + delegated(1000, read=lambda p: "cpu memory pids\n") + and not delegated(1000, read=lambda p: "cpu\n"), + "delegation needs both the pids and the memory controller", + ), ( raised[:2] == ("20000", "64G") and raised[2] == [], "the maintainer can raise both ceilings", @@ -391,7 +426,18 @@ def socket_in(*dirs): and not any( map( valid_tasks, - ("0", "1", "1.5", "1e3", "-5", ".5%", "\u0663", "99999999999999999999"), + ( + "0", + "1", + "1.5", + "1e3", + "-5", + ".5%", + "\u0663", + "99999999999999999999", + "08192", + "0100", + ), ) ), "and so is a task count", From d04a74851fe87bd86e0fb8592980ab0ba2144a28 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 08:36:53 -0700 Subject: [PATCH 08/22] Accept One Canonical Override Form, and Test the Delegation Check Mirroring systemd's parser kept finding new edges: a leading zero is octal in a percentage too, TasksMax rejects 100%, and fractional forms vary by version. Overrides now accept one form, a plain count with no leading zero, whole 1-99% for memory only, or infinity, and anything else keeps the default with a notice. The per-command delegation check moves into decide(), which the self-test now covers. The --report note appears only where the prefix is unset because the host cannot contain, since a registered but broken prefix is already a STALE problem. The sweep's hook budget rises to 35s with each systemctl call bounded at 5s, so a loaded manager cannot cut its report off. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/README.md | 4 +- host-setup/agent-safety/claude/install.py | 16 +-- .../claude/stray-process-sweep.py | 2 +- .../agent-safety/claude/test_install.py | 2 + .../agent-safety/claude/tool-containment.py | 107 ++++++++++-------- 5 files changed, 76 insertions(+), 55 deletions(-) diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 4844565ac..508412ee1 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -134,7 +134,7 @@ Run the installer rather than hand-copying this block on a host where the two mi { "matcher": "Bash", "hooks": [ { "type": "command", "command": "\"python3\" \"/.claude/hooks/gh-write-guard.py\"" } ] } ], "SessionEnd": [ - { "hooks": [ { "type": "command", "command": "\"python3\" \"/.claude/hooks/stray-process-sweep.py\"", "timeout": 10 } ] } + { "hooks": [ { "type": "command", "command": "\"python3\" \"/.claude/hooks/stray-process-sweep.py\"", "timeout": 35 } ] } ] }, "permissions": { @@ -154,7 +154,7 @@ Every other key in the file is left as it stands, `permissions.allow` and the re - **A write or a wait inside a script file is unseen, so never put either in a script to run it.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string. A `git push` or a `gh` mutation inside the script therefore reaches the server unparsed. An unbounded wait inside that same script is equally unseen, and worse in one way. A denied write fails loudly. A wait the guard never saw runs until something ends it, which is one of the leaks the SessionEnd sweep exists to find afterwards. This is the widest hole in the kit, and an agent opens it by accident. Collecting fifteen repetitive pushes into a loop looks like tidiness, and so does moving a poll into a script to keep a tool call short. Neither looks like disabling a guard. Issue each write and each wait as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and the wait rather than the script. - **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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. -- **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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. Wherever the prefix is left unset, `--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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable or loses those two controllers, each tool call runs unbounded and prints one `tool-containment:` line on stderr saying so. +- **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable or loses those two controllers, each tool call runs unbounded and prints one `tool-containment:` line on stderr saying so. - **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, 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. Where a later Claude Code stops sourcing one, tool calls run bare as well, silently, and the sweep's report of surviving processes is what remains. 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, and anything run directly about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. A scope stop sends SIGTERM and escalates to SIGKILL after two seconds, which keeps it inside the hook's own timeout. diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index e13d56bdc..11a7c5e59 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -52,8 +52,8 @@ DEPLOYED_HOOKS = (GUARD_NAME, SWEEP_NAME, CONTAIN_NAME) # A SessionEnd hook's own budget is 1.5 seconds, raised to the highest per-hook timeout the settings declare. -# The sweep stops scopes that escalate to SIGKILL after two seconds and reads two process tables, so this is headroom rather than a duration it uses. -SWEEP_TIMEOUT_SECONDS = 10 +# The sweep's own calls are each bounded, two `ps` reads at 5s and four `systemctl` calls at 5s, all inside this. +SWEEP_TIMEOUT_SECONDS = 35 # The stamp's own format version, separate from the content it describes. # A reader that predates a field needs to know the shape changed rather than infer it from a missing key. @@ -751,13 +751,15 @@ def report(claude_home): # Correct bytes on disk are not a running guard, so the wiring is checked as well. problems.extend(registration_problems(claude_home)) try: - foreign = foreign_prefix( - json.loads((claude_home / "settings.json").read_text(encoding="utf-8")) - ) + settings_data = json.loads((claude_home / "settings.json").read_text(encoding="utf-8")) except (ValueError, OSError): - foreign = None + settings_data = None + foreign = foreign_prefix(settings_data) + env_block = settings_data.get("env") if isinstance(settings_data, dict) else None + unset = not isinstance(env_block, dict) or env_block.get(PREFIX_VAR) is None capable, reason = containment_capable(claude_home / "hooks" / CONTAIN_NAME) - if not capable and foreign is None: + # A registered prefix on a host that cannot run it is a STALE problem above, not an uncontained host. + if unset and not capable: print(f"Note: agent commands on this host run uncontained ({reason}).") if foreign is not None: print( diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py index 80b16cb49..2e48b1263 100755 --- a/host-setup/agent-safety/claude/stray-process-sweep.py +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -236,7 +236,7 @@ def _systemctl(*args, runtime=None): text=True, encoding="utf-8", errors="replace", - timeout=8, + timeout=5, check=False, ) except (OSError, subprocess.SubprocessError): diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index fa11a1586..0e9db18b6 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -760,6 +760,8 @@ def test_our_prefix_on_a_host_that_cannot_contain_reports_stale(self): r = run(self.home, "--report", contain=False) self.assertEqual(r.returncode, 1, r.stdout + r.stderr) self.assertIn("cannot contain", r.stdout) + # Every hook fails to exec there, so the note that commands run uncontained would contradict it. + self.assertNotIn("run uncontained", r.stdout) def test_a_prefix_synced_from_another_host_reports_stale_where_it_cannot_contain(self): """A path this host lacks exits 127 on every hook, which fails the guard open.""" diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index 2fff360f5..b15b514c4 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -100,53 +100,42 @@ def pick_shell(command, which=which): return which(snapshot_shell(command) or "bash") or which("bash") or "/bin/sh" -# The smallest override accepted, so a unitless or mistyped value cannot kill every command at its start. +# The override grammar is one canonical form rather than everything systemd parses. +# Systemd reads a leading zero as octal, rejects some percentages per property, and varies by version. MIN_TASKS = 64 MIN_MEMORY = 256 * 1024**2 -# The largest override accepted, below what systemd parses into its 64-bit limits and rejects past. MAX_LIMIT = 2**63 -_UNITS = {"K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4, "P": 1024**5, "E": 1024**6} +_UNITS = {"M": 1024**2, "G": 1024**3, "T": 1024**4} -def _number(text): - """`text` as a positive number when it is plain decimal digits with at most one inner point, else None.""" - whole, _dot, frac = text.partition(".") - if not (whole.isascii() and whole.isdigit()) or ( - _dot and not (frac.isascii() and frac.isdigit()) - ): +def _count(text): + """`text` as an int when it is decimal digits with no leading zero, else None.""" + if not (text.isascii() and text.isdigit()) or text.startswith("0"): return None - value = float(text) - return value if value > 0 else None - - -def _percent(value): - """Whether `value` is a whole percentage from 1 to 100, the form every systemd reads. - - A fractional one is an error before systemd 248, and the floor refuses `0.25%` typed for `25%`. - """ - digits = value[:-1] if value.endswith("%") else "" - return digits.isascii() and digits.isdigit() and 1 <= int(digits) <= 100 + return int(text) def valid_tasks(value): - """Whether `value` is a `TasksMax` of at least `MIN_TASKS`, a percentage of the system limit, or infinity.""" - if value == "infinity" or _percent(value): - return True - # A leading zero makes systemd read the count as octal, a different ceiling or none at all. - plain = value.isascii() and value.isdigit() and not value.startswith("0") - return plain and MIN_TASKS <= int(value) < MAX_LIMIT + """Whether `value` is `infinity` or a count from `MIN_TASKS` up, the only `TasksMax` forms accepted.""" + count = _count(value) + return value == "infinity" or (count is not None and MIN_TASKS <= count < MAX_LIMIT) def valid_memory(value): - """Whether `value` is a `MemoryMax` of at least `MIN_MEMORY` in K to E units, a percentage of RAM, or infinity. + """Whether `value` is `infinity`, a whole `1%` to `99%` of RAM, or a whole count of M, G, or T. A unitless count is bytes to systemd, and one written meaning megabytes kills every command at its - start, so a unit is required. + start, so a unit is required, and the size floor is `MIN_MEMORY`. """ - if value == "infinity" or _percent(value): + if value == "infinity": return True - number = _number(value[:-1]) if value[-1:] in _UNITS else None - return number is not None and MIN_MEMORY <= number * _UNITS[value[-1]] < MAX_LIMIT + count = _count(value[:-1]) + if count is None: + return False + if value.endswith("%"): + return 1 <= count <= 99 + unit = _UNITS.get(value[-1]) + return unit is not None and MIN_MEMORY <= count * unit < MAX_LIMIT def ceilings(env): @@ -243,6 +232,14 @@ def plan(command, env, suffix, runtime, which=which, why=UNREACHABLE): return argv, extra, notices +def decide(command, env, suffix, runtime, is_delegated, which=which): + """`plan` for this host: a tool call under a manager lacking the controllers runs bare, and says why.""" + why = UNREACHABLE + if runtime and is_tool_call(command) and not is_delegated(): + runtime, why = None, UNDELEGATED + return plan(command, env, suffix, runtime, which, why=why) + + def inner(env): """(argv, env) for the inner stage: the shell, with the hand-off variables removed.""" env = dict(env) @@ -269,10 +266,9 @@ def main(argv): print("usage: tool-containment.py '' | --selftest", file=sys.stderr) return 2 suffix = f"{os.getpid()}-{os.urandom(4).hex()}" - runtime, why = manager_runtime(os.environ), UNREACHABLE - if runtime and is_tool_call(argv[1]) and not delegated(): - runtime, why = None, UNDELEGATED - run, extra, notices = plan(argv[1], os.environ, suffix, runtime, why=why) + run, extra, notices = decide( + argv[1], os.environ, suffix, manager_runtime(os.environ), delegated + ) for note in notices: print(f"tool-containment: {note}", file=sys.stderr) os.execve(run[0], run, {**os.environ, **extra}) @@ -377,6 +373,24 @@ def socket_in(*dirs): UNDELEGATED in plan(tool, env, "52", None, fake_which, why=UNDELEGATED)[2][0], "a manager lacking the controllers is named as the reason, per command", ), + ( + decide(tool, env, "53", RUN, lambda: False, fake_which) + == ( + ["/usr/bin/bash", "-c", tool], + {}, + [f"{UNDELEGATED}, so this command runs with no task or memory ceiling"], + ), + "a manager that lost the controllers runs a tool call bare and says why", + ), + ( + "--unit=claude-tool-0a1b-2c3d-54" + in decide(tool, env, "54", RUN, lambda: True, fake_which)[0], + "a manager holding them contains it", + ), + ( + decide(hook, hook_env, "55", RUN, lambda: 1 / 0, fake_which)[2] == [], + "a hook command never reads the controllers", + ), ( delegated(1000, read=lambda p: "cpu memory pids\n") and not delegated(1000, read=lambda p: "cpu\n"), @@ -397,32 +411,33 @@ def socket_in(*dirs): ), (session_token("a/b c;d") == "abcd", "a session id cannot inject into a unit name"), ( - all(map(valid_memory, ("16G", "1.5G", "0.5G", "512M", "25%", "1P", "100%", "infinity"))) + all(map(valid_memory, ("16G", "512M", "1T", "25%", "99%", "infinity"))) and not any( map( valid_memory, ( "0", "1024", - "0.5", - ".5G", + "1.5G", + "0.5G", + "08G", "1K", - "101%", - "0%", + "1P", + "100%", + "050%", + "08%", "0.25%", - "12.5%", "16GB", "G", "lots", - "99999999999E", - "9" * 400 + "G", + "99999999999T", ), ) ), - "a memory size systemd accepts is accepted, and a malformed one is not", + "only the canonical memory forms are accepted", ), ( - all(map(valid_tasks, ("64", "8192", "50%", "infinity"))) + all(map(valid_tasks, ("64", "8192", "infinity"))) and not any( map( valid_tasks, @@ -437,6 +452,8 @@ def socket_in(*dirs): "99999999999999999999", "08192", "0100", + "50%", + "100%", ), ) ), From 30644fbed5e15cdfd8c8da981ef6ab5e2d19beef Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 09:26:32 -0700 Subject: [PATCH 09/22] Cap Swap, Keep Nested Sessions Inside Their Parent's Scope A scope with MemoryMax but no swap cap lets a runaway at the ceiling spill into the host's swap and thrash it, so scopes now set MemorySwapMax=0. A claude session started from a tool call ran each of its own tool calls in a fresh scope outside its parent's ceiling, so a tool call already inside a tool-call scope now runs directly within it. A tool call is also recognised by its cwd bookkeeping, so one whose snapshot failed is still contained. AGENTS.md now spells the probe launch setsid --wait, since plain setsid returns at once when its caller leads a process group, and the installer's reason string names the platform it judged. Co-Authored-By: Claude Opus 5.5 (1M context) --- AGENTS.md | 2 +- host-setup/agent-safety/claude/README.md | 4 +- host-setup/agent-safety/claude/install.py | 2 +- .../agent-safety/claude/test_install.py | 4 +- .../agent-safety/claude/tool-containment.py | 63 ++++++++++++++++--- 5 files changed, 62 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a63d4cb0e..5ffbb17fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,7 +52,7 @@ An agent session is billed on the context it carries, not the work it does. Ever - **Keep a long query in a file, not in the command.** A heredoc re-typed on every call costs its own length in context each time, often more than the answer it retrieves. - **Keep generated caches outside the checkout when the executor restricts writes.** Give each task a cache directory under a writable temporary root. Point tools such as uv and ruff there through their own cache variables. Never repurpose `HOME` or an agent's configuration directory to make a tool run. - **Report an execution boundary separately from a check finding.** A denied path, network request, or Docker socket says the check did not run. Preserve that failure, then use the executor's approval mechanism for the required rerun. Request the narrowest reusable command prefix the executor supports. Report the rerun's result as the verification evidence. -- **Bound every probe, and prove it ended.** A throwaway probe or test harness runs under `timeout`, and one that can recurse or fan out also runs under a task and memory cap. Start it in a process group of its own, as `setsid timeout `, and end it by that group with `kill -- -`. A `pkill -f` pattern that matches nothing exits 1 and kills nothing. Then confirm with `pgrep` that nothing from any earlier run survives, since a later clean run proves nothing about an earlier one. Never suppress a cleanup command's output or exit status. A command the harness moved to the background, where no background job was intended, is stopped and confirmed gone before work continues. +- **Bound every probe, and prove it ended.** A throwaway probe or test harness runs under `timeout`, and one that can recurse or fan out also runs under a task and memory cap. Start it in a process group of its own, as `setsid --wait timeout ` on Linux, and end it by that group with `kill -- -`. Without `--wait`, `setsid` returns at once when its caller leads a process group, and the probe runs on detached. A `pkill -f` pattern that matches nothing exits 1 and kills nothing. Then confirm with `pgrep` that nothing from any earlier run survives, since a later clean run proves nothing about an earlier one. Never suppress a cleanup command's output or exit status. A command the harness moved to the background, where no background job was intended, is stopped and confirmed gone before work continues. ### Delegation diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 508412ee1..cb55f9727 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -13,7 +13,7 @@ installation and operational detail. Codex and opencode have no equivalent hook Into `~/.claude/` (or `%USERPROFILE%\.claude\` on Windows): - **`hooks/gh-write-guard.py`**: a PreToolUse hook that denies four classes of dangerous action. First, the GitHub **write** footguns behind the cross-repo comment incident: a state-changing `gh` call whose output is discarded, a GraphQL mutation passing a **literal** node id instead of a `$variable`, and a `gh` write whose explicit target is under an owner other than the checkout origin's. Sibling repositories under the same owner are allowed, since the harm this guards is reaching a stranger's repository rather than working across one maintainer's own fleet, and a different owner is allowed only when the maintainer names it in `GH_WRITE_GUARD_ALLOW` (an `owner/repo` list, where `owner/*` grants a whole owner). That variable is read from the environment the session was launched with, which is the one channel an agent cannot set for itself: a hook runs as its own process, so an inline `VAR=x cmd` prefix or an `export` inside a Bash call never reaches it. Second, a **git operation that bypasses a repository protection**. The branch-rule cases (a direct push to a branch that requires a pull request, a force-push where history is protected, a branch delete where deletion is blocked) are judged against the branch's **live** rules, so a code-style `develop` is denied while a config-style `develop` is allowed with no per-repo configuration. A push to a protected-default branch fails closed when its rules cannot be determined, either because the API is unreachable or because the checkout's origin cannot be resolved to query them. The explicit-bypass flags are denied **unconditionally**, since the flag is itself the bypass and needs no branch query: `gh pr merge --admin` overrides the server-side merge gate, and `git commit`/`git push --no-verify` skips the local git hooks. Third, a **mutating git operation run directly against a primary checkout** (`checkout`/`switch`/`pull`/`reset`/`rebase`/`merge`/`cherry-pick`/`revert`/`restore`/`add`/`commit`/`rm`/`mv`/`apply`/`am`/`push`/`stash` (anything but `list`/`show`)/`clean -f`/`worktree remove -f`), the harm behind a second incident where an agent reused the maintainer's own primary checkout instead of a worktree despite having read the prose rule against it. "Primary" is decided by comparing `git rev-parse --git-dir` against `--git-common-dir`, not a `.git`-is-a-directory guess. `worktree add`/`list`/`prune`, an unforced `worktree remove`, `merge --ff-only`/`pull --ff-only`, and a `checkout `/`switch ` carrying no force flag (bundled or attached forms like `-qf`/`-Bname` recognized, not only an exact token) stay exempt even in a primary checkout, matching the documented base-clone cleanup step the `repo-worktree` skill already carries. A subcommand this rule does not recognize is resolved through a chain of git aliases, inline and persisted, before falling through, so a custom alias cannot hide a denied builtin behind an unrecognized name. A `!`-prefixed shell alias is denied outright rather than interpreted. The target directory follows real git's own `-C`/`--work-tree`/`--git-dir` priority, not a last-option-wins scan. A different owner-style grant, `GH_WRITE_GUARD_ALLOW_PRIMARY_CHECKOUT`, follows the same channel as `GH_WRITE_GUARD_ALLOW`. Reads and everything else pass through. Fourth, an **unbounded shell wait**, which the root spec's requirement 7 defines in full rather than this bullet redefining it. In outline: a loop that sleeps, carrying no bound the rule recognizes. It is the shape an agent writes when a brief tells it to poll. It is also the harm behind a third incident, where seven such loops outlived the subagents that wrote them and the run that dispatched those subagents. A shell started by a tool call runs in a session of its own, so the agent could not have reaped it even had it tried. A nested loop is judged on its own terms, and a command that forks anything out of a `timeout`'s reach, by backgrounding it or by `setsid`, is bounded by nothing. A heredoc body is data rather than a command line unless a shell is what it is fed to, so a document quoting the forbidden shape is written rather than denied. It fires even in autonomous / bypass-permissions sessions, which is how the first incident happened. See the root spec's requirements 6 and 7 for the exact rules. -- **`hooks/tool-containment.py`**: a shell prefix, registered as `CLAUDE_CODE_SHELL_PREFIX` in the `env` block of `settings.json`, that runs every Bash tool call inside a transient systemd user scope carrying `TasksMax` and `MemoryMax`. A runaway fan-out then fails at the ceiling with `fork: Resource temporarily unavailable` instead of growing until the host has to be reset, the harm behind the probe-shim incident in the root spec's requirement 9. The guard above reads the command text, and that incident's recursion lived in a script file the command only named. The ceilings default to 8192 tasks and 25% of RAM. The maintainer raises them with `AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block, which an inline `VAR=x` in a command cannot change, since the prefix reads them before the command runs. Each scope is named `claude-tool---`, so the sweep below can stop one session's tool calls and nothing else. The installer sets the prefix only where it can contain, per the Linux bullet under "Scope and Limits", and never over a `CLAUDE_CODE_SHELL_PREFIX` value that names anything else. +- **`hooks/tool-containment.py`**: a shell prefix, registered as `CLAUDE_CODE_SHELL_PREFIX` in the `env` block of `settings.json`, that runs every Bash tool call inside a transient systemd user scope carrying `TasksMax`, `MemoryMax`, and `MemorySwapMax=0`, the last so a runaway at the memory ceiling is killed rather than spilled into the host's swap. A runaway fan-out then fails at the ceiling with `fork: Resource temporarily unavailable` instead of growing until the host has to be reset, the harm behind the probe-shim incident in the root spec's requirement 9. The guard above reads the command text, and that incident's recursion lived in a script file the command only named. The ceilings default to 8192 tasks and 25% of RAM. The maintainer raises them with `AGENT_CONTAINMENT_TASKS_MAX` and `AGENT_CONTAINMENT_MEMORY_MAX` in the same `env` block, which an inline `VAR=x` in a command cannot change, since the prefix reads them before the command runs. Each scope is named `claude-tool---`, so the sweep below can stop one session's tool calls and nothing else. The installer sets the prefix only where it can contain, per the Linux bullet under "Scope and Limits", and never over a `CLAUDE_CODE_SHELL_PREFIX` value that names anything else. - **`hooks/stray-process-sweep.py`**: a SessionEnd hook in two phases. First, it stops every `claude-tool--*` scope this session left loaded and reports what each held, since the scope's name proves which session started it. Second, it reports, and never ends, the process trees outside those scopes that outlive the session. The guard above stops a leak from being written. This finds the ones already running: the ones started before the guard was installed, and the shapes the guard deliberately does not reach. It reports every descendant of the agent process running outside the agent's own session. It names each subtree root's command and age, and hands over the `kill` line. This phase kills nothing itself. A long build backgrounded on purpose reads identically to a leaked wait from there. What is still wanted on the machine is the maintainer's call. A SessionEnd hook cannot block, and its JSON output is discarded, so stderr on exit 2 is the one channel that reaches the maintainer. The sweep uses that for a report rather than for a refusal. It registers under a group carrying no matcher, which fires on every exit reason. It also carries an explicit timeout, since the event's own budget is 1.5 seconds and only a declared per-hook timeout raises it. See the root spec's requirement 8. - **Two marker-delimited blocks of host-wide content in `CLAUDE.md`**, loaded into every session on the machine (including ad-hoc work outside any project), installed and updated independently so one can change without rewriting the other. - The `agent-safety` block carries restrictions alone, so nothing in it can widen a permission. `Repository Boundaries and Write Safety` mirrors the committed `GOVERNANCE.md` section of the same name, carrying as behavioral guidance its write rules and its rules that a task works in its own checkout and isolates into its own worktree before its first file edit. `Data in Agent-Authored Text` mirrors `GOVERNANCE.md` "Representative Data in Agent-Authored Text", so an agent illustrates with constructed data rather than data observed on the machine. `Authorization Scope and Memory Hygiene` bounds how a granted permission is recorded and read. Each mirrors a rule that otherwise reaches fleet repos only. @@ -155,7 +155,7 @@ 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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. - **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable or loses those two controllers, each tool call runs unbounded and prints one `tool-containment:` line on stderr saying so. -- **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, 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. Where a later Claude Code stops sourcing one, tool calls run bare as well, silently, and the sweep's report of surviving processes is what remains. 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, and anything run directly about 10 ms. +- **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, 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 tool call already inside a tool-call scope, which is every tool call of a `claude` session started from one, runs directly inside it, so a nested session shares its parent's ceiling rather than escaping it, and ends with the parent's scope. 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, and anything run directly about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. 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. diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 11a7c5e59..6d87e1fa2 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -191,7 +191,7 @@ def containment_capable(prefix, env=None, system=None, uid=None, controllers=Non if override in ("0", "1"): return override == "1", "forced by AGENT_SAFETY_CONTAINMENT_OVERRIDE" if not system.startswith("linux"): - return False, f"{platform.system()} has no systemd user manager" + return False, f"{system} has no systemd user manager" if not shutil.which("systemd-run"): return False, "systemd-run is not installed" # WSLg, `su -`, cron, and `docker exec` shells point elsewhere or nowhere, while the manager listens here. diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index 0e9db18b6..aabe41107 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -883,7 +883,9 @@ def test_no_socket_anywhere_cannot_contain(self): self.assertIn("no systemd user manager", reason) def test_a_non_linux_host_cannot_contain(self): - self.assertFalse(self._judge(system="darwin")[0]) + capable, reason = self._judge(system="darwin") + self.assertFalse(capable) + self.assertIn("darwin", reason) class TestPreexistingCorruption(StampCase): diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index b15b514c4..5500b112b 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -87,8 +87,27 @@ def snapshot_shell(command): def is_tool_call(command): - """Whether Claude Code runs `command` as a Bash tool call rather than as a hook or an MCP server.""" - return snapshot_shell(command) is not None + """Whether Claude Code runs `command` as a Bash tool call rather than as a hook or an MCP server. + + Either sign is enough: the shell snapshot sourced first, or the cwd bookkeeping appended last, so a + session whose snapshot failed is still contained. + """ + tail = command.rstrip().rsplit("&&", 1)[-1].strip() + cwd_tail = tail.startswith("pwd -P >| ") and "claude-" in tail and tail.endswith("-cwd") + return snapshot_shell(command) is not None or cwd_tail + + +def in_tool_scope(read=None): + """Whether this process already runs inside a tool-call scope, as a nested Claude Code session does.""" + try: + if read: + text = read("/proc/self/cgroup") + else: + with open("/proc/self/cgroup", encoding="utf-8") as f: + text = f.read() + except OSError: + return False + return any(line.rsplit("/", 1)[-1].startswith(f"{TOOL_UNIT}-") for line in text.splitlines()) def pick_shell(command, which=which): @@ -214,6 +233,8 @@ def plan(command, env, suffix, runtime, which=which, why=UNREACHABLE): "--description=Claude Code command", f"--property=TasksMax={tasks}", f"--property=MemoryMax={memory}", + # Without it a runaway at the memory ceiling spills into the host's swap rather than being killed. + "--property=MemorySwapMax=0", f"--property=TimeoutStopSec={STOP_TIMEOUT}", "--", sys.executable, @@ -232,8 +253,15 @@ def plan(command, env, suffix, runtime, which=which, why=UNREACHABLE): return argv, extra, notices -def decide(command, env, suffix, runtime, is_delegated, which=which): - """`plan` for this host: a tool call under a manager lacking the controllers runs bare, and says why.""" +def decide(command, env, suffix, runtime, is_delegated, nested=lambda: False, which=which): + """`plan` for this host. + + A tool call already inside a tool-call scope runs directly, since the outer scope's ceiling bounds + it, and a fresh scope would escape that ceiling and outlive the session that stops the outer one. A + tool call under a manager lacking the controllers runs bare, and says why. + """ + if is_tool_call(command) and nested(): + return [pick_shell(command, which), "-c", command], {}, [] why = UNREACHABLE if runtime and is_tool_call(command) and not is_delegated(): runtime, why = None, UNDELEGATED @@ -267,7 +295,7 @@ def main(argv): return 2 suffix = f"{os.getpid()}-{os.urandom(4).hex()}" run, extra, notices = decide( - argv[1], os.environ, suffix, manager_runtime(os.environ), delegated + argv[1], os.environ, suffix, manager_runtime(os.environ), delegated, in_tool_scope ) for note in notices: print(f"tool-containment: {note}", file=sys.stderr) @@ -374,7 +402,7 @@ def socket_in(*dirs): "a manager lacking the controllers is named as the reason, per command", ), ( - decide(tool, env, "53", RUN, lambda: False, fake_which) + decide(tool, env, "53", RUN, lambda: False, which=fake_which) == ( ["/usr/bin/bash", "-c", tool], {}, @@ -384,13 +412,32 @@ def socket_in(*dirs): ), ( "--unit=claude-tool-0a1b-2c3d-54" - in decide(tool, env, "54", RUN, lambda: True, fake_which)[0], + in decide(tool, env, "54", RUN, lambda: True, which=fake_which)[0], "a manager holding them contains it", ), ( - decide(hook, hook_env, "55", RUN, lambda: 1 / 0, fake_which)[2] == [], + decide(hook, hook_env, "55", RUN, lambda: 1 / 0, which=fake_which)[2] == [], "a hook command never reads the controllers", ), + ( + decide(tool, env, "56", RUN, lambda: True, lambda: True, fake_which) + == (["/usr/bin/bash", "-c", tool], {}, []), + "a tool call already inside a tool-call scope runs within it rather than escaping it", + ), + ( + in_tool_scope(read=lambda p: "0::/user.slice/app.slice/claude-tool-a-1-ff.scope\n") + and not in_tool_scope(read=lambda p: "0::/user.slice/app.slice/session-3.scope\n"), + "a nested session is recognised by the scope it runs in", + ), + ( + "--property=MemorySwapMax=0" in argv, + "a runaway at the memory ceiling is killed rather than spilled into swap", + ), + ( + is_tool_call("eval 'ls' < /dev/null && pwd -P >| /tmp/claude-9d32-cwd") + and not is_tool_call(mcp), + "a tool call without its snapshot is still recognised by its cwd bookkeeping", + ), ( delegated(1000, read=lambda p: "cpu memory pids\n") and not delegated(1000, read=lambda p: "cpu\n"), From f3a8ca0eb9abfa8722c5476ad022e6a1dff4c472 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 09:36:02 -0700 Subject: [PATCH 10/22] Give a Nested Session Its Own Scopes Again Sharing the parent's one ceiling let a memory-heavy build in a nested claude session make the kernel kill the nested claude process rather than the build, so each tool call gets its own scope again, named for the session that ran it, as requirement 9 states. The cwd-bookkeeping fallback now also matches a sandboxed session's cwd- file and a shell-quoted path, and the prefix's docstring describes the swap cap and both tool-call signs. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/README.md | 2 +- .../agent-safety/claude/tool-containment.py | 55 ++++++------------- 2 files changed, 18 insertions(+), 39 deletions(-) diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index cb55f9727..ec24cf44f 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -155,7 +155,7 @@ 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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. - **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable or loses those two controllers, each tool call runs unbounded and prints one `tool-containment:` line on stderr saying so. -- **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, 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 tool call already inside a tool-call scope, which is every tool call of a `claude` session started from one, runs directly inside it, so a nested session shares its parent's ceiling rather than escaping it, and ends with the parent's scope. 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, and anything run directly about 10 ms. +- **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, 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, since sharing the parent's one ceiling would let a heavy build make the kernel kill the nested `claude` process instead. Those scopes are stopped when the nested session ends, and where stopping the parent's scope ended the nested session first, they are left for `systemctl --user stop 'claude-tool-*'` by hand. 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, and anything run directly about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. 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. diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index 5500b112b..2205f6d91 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -4,14 +4,17 @@ Registered as `CLAUDE_CODE_SHELL_PREFIX` in the user settings.json `env`. Claude Code then runs each Bash tool call, each hook command, and each stdio MCP server launch as ` ''`, one argument holding the whole string. For a tool call this file starts a transient systemd user scope -carrying `TasksMax` and `MemoryMax`, and runs the string under a shell inside it. +carrying `TasksMax`, `MemoryMax`, and `MemorySwapMax=0`, the last so a runaway at the memory ceiling is +killed rather than spilled into the host's swap, and runs the string under a shell inside it. Everything else runs under its shell directly, with no scope. The write guard is a hook, and a PreToolUse hook that exits 1 is a non-blocking error, so a scope that failed to start would let the very command the guard denies go ahead. An MCP server is long-lived and started outside any session, so a scope would bound it for its whole life and outlive the session that named it. A tool call is told -apart by the Claude Code shell snapshot it sources first. Where a later Claude Code stops sourcing one, -tool calls run bare too, and the SessionEnd sweep's report of surviving processes is what remains. +apart by the Claude Code shell snapshot it sources first or by the cwd bookkeeping appended last, +either one enough. Where a later Claude Code drops both, tool calls run bare too, and the SessionEnd +sweep's report of surviving processes is what remains. A `claude` session started from a tool call +runs its own tool calls in scopes of its own, named for it, each under its own ceiling. A runaway fan-out then meets the ceiling and fails with a visible error, instead of growing until the host has to be reset. The ceiling belongs to the scope's cgroup rather than to the foreground wait, so @@ -93,23 +96,14 @@ def is_tool_call(command): session whose snapshot failed is still contained. """ tail = command.rstrip().rsplit("&&", 1)[-1].strip() - cwd_tail = tail.startswith("pwd -P >| ") and "claude-" in tail and tail.endswith("-cwd") + if not tail.startswith("pwd -P >| "): + return snapshot_shell(command) is not None + # A sandboxed session writes `/cwd-`, and the path may arrive shell-quoted. + name = tail[len("pwd -P >| ") :].strip().strip("'\"").rsplit("/", 1)[-1] + cwd_tail = name.startswith("cwd-") or (name.startswith("claude-") and name.endswith("-cwd")) return snapshot_shell(command) is not None or cwd_tail -def in_tool_scope(read=None): - """Whether this process already runs inside a tool-call scope, as a nested Claude Code session does.""" - try: - if read: - text = read("/proc/self/cgroup") - else: - with open("/proc/self/cgroup", encoding="utf-8") as f: - text = f.read() - except OSError: - return False - return any(line.rsplit("/", 1)[-1].startswith(f"{TOOL_UNIT}-") for line in text.splitlines()) - - def pick_shell(command, which=which): """The shell the command string was written for. @@ -253,15 +247,8 @@ def plan(command, env, suffix, runtime, which=which, why=UNREACHABLE): return argv, extra, notices -def decide(command, env, suffix, runtime, is_delegated, nested=lambda: False, which=which): - """`plan` for this host. - - A tool call already inside a tool-call scope runs directly, since the outer scope's ceiling bounds - it, and a fresh scope would escape that ceiling and outlive the session that stops the outer one. A - tool call under a manager lacking the controllers runs bare, and says why. - """ - if is_tool_call(command) and nested(): - return [pick_shell(command, which), "-c", command], {}, [] +def decide(command, env, suffix, runtime, is_delegated, which=which): + """`plan` for this host: a tool call under a manager lacking the controllers runs bare, and says why.""" why = UNREACHABLE if runtime and is_tool_call(command) and not is_delegated(): runtime, why = None, UNDELEGATED @@ -295,7 +282,7 @@ def main(argv): return 2 suffix = f"{os.getpid()}-{os.urandom(4).hex()}" run, extra, notices = decide( - argv[1], os.environ, suffix, manager_runtime(os.environ), delegated, in_tool_scope + argv[1], os.environ, suffix, manager_runtime(os.environ), delegated ) for note in notices: print(f"tool-containment: {note}", file=sys.stderr) @@ -419,24 +406,16 @@ def socket_in(*dirs): decide(hook, hook_env, "55", RUN, lambda: 1 / 0, which=fake_which)[2] == [], "a hook command never reads the controllers", ), - ( - decide(tool, env, "56", RUN, lambda: True, lambda: True, fake_which) - == (["/usr/bin/bash", "-c", tool], {}, []), - "a tool call already inside a tool-call scope runs within it rather than escaping it", - ), - ( - in_tool_scope(read=lambda p: "0::/user.slice/app.slice/claude-tool-a-1-ff.scope\n") - and not in_tool_scope(read=lambda p: "0::/user.slice/app.slice/session-3.scope\n"), - "a nested session is recognised by the scope it runs in", - ), ( "--property=MemorySwapMax=0" in argv, "a runaway at the memory ceiling is killed rather than spilled into swap", ), ( is_tool_call("eval 'ls' < /dev/null && pwd -P >| /tmp/claude-9d32-cwd") + and is_tool_call("eval 'ls' < /dev/null && pwd -P >| '/tmp/sandbox dir/cwd-9d32'") + and not is_tool_call("eval 'ls' && pwd -P >| /tmp/elsewhere.txt") and not is_tool_call(mcp), - "a tool call without its snapshot is still recognised by its cwd bookkeeping", + "a tool call without its snapshot is still recognised by its cwd bookkeeping, sandboxed or quoted", ), ( delegated(1000, read=lambda p: "cpu memory pids\n") From f2cc3dfea8e8dc29064020768e45984a7d984837 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 09:41:00 -0700 Subject: [PATCH 11/22] Stop Recommending a Cleanup That Ends Every Session's Tool Calls The README told the maintainer to clean up a nested session's orphaned scopes with systemctl --user stop 'claude-tool-*', which also stops every other live session's running tool calls. It now says how to find the orphaned ones by session id and to stop only those. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index ec24cf44f..3baf8f85b 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -155,7 +155,7 @@ 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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. - **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable or loses those two controllers, each tool call runs unbounded and prints one `tool-containment:` line on stderr saying so. -- **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, 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, since sharing the parent's one ceiling would let a heavy build make the kernel kill the nested `claude` process instead. Those scopes are stopped when the nested session ends, and where stopping the parent's scope ended the nested session first, they are left for `systemctl --user stop 'claude-tool-*'` by hand. 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, and anything run directly about 10 ms. +- **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, 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, since sharing the parent's one ceiling would let a heavy build make the kernel kill the nested `claude` process instead. Those scopes are stopped when the nested session ends. Where stopping the parent's scope ended the nested session first, they keep running unreported, and `systemctl --user list-units 'claude-tool-*'` shows each by the session id in its name. Stop only the ones whose session has ended, since the same pattern matches every live session's tool calls. 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, and anything run directly about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. 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. From 21e19573f0bb98fcbb39962b390d246358acd53f Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 09:49:03 -0700 Subject: [PATCH 12/22] Sweep Under the Prefix Even With No Manager, and Own the Prefix by Name A session running under the containment prefix whose user manager was unreachable at its end skipped the reap, and with it the failure report requirement 9 asks for. The sweep now runs the reap whenever the session's CLAUDE_CODE_SHELL_PREFIX names the prefix, so a failed list says so. The installer judged a prefix value its own by substring, which claimed another wrapper whose name contained this one's. It now compares the file name exactly. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/install.py | 13 +++++++++++-- .../agent-safety/claude/stray-process-sweep.py | 18 ++++++++++++++++-- host-setup/agent-safety/claude/test_install.py | 11 +++++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 6d87e1fa2..ada93c614 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -257,11 +257,20 @@ def names_prefix(held, path): return held == prefix_value(path) +def kit_prefix(held): + """Whether a `CLAUDE_CODE_SHELL_PREFIX` value names this kit's prefix, deployed here or at another path. + + Judged on the file name exactly, since a substring match claims someone else's wrapper whose name + merely contains this one's. + """ + return os.path.basename(str(held).replace("\\", "/")) == CONTAIN_NAME + + def foreign_prefix(data): """The `CLAUDE_CODE_SHELL_PREFIX` value when it names something other than this kit's prefix, else None.""" env = data.get("env") if isinstance(data, dict) else None held = env.get(PREFIX_VAR) if isinstance(env, dict) else None - return held if held is not None and CONTAIN_NAME not in str(held) else None + return held if held is not None and not kit_prefix(held) else None def hook_launcher(): @@ -989,7 +998,7 @@ def reject(where, held, want): capable, reason = containment_capable(contain_dst) env = data.setdefault("env", {}) held = env.get(PREFIX_VAR) - ours = held is not None and CONTAIN_NAME in str(held) + ours = held is not None and kit_prefix(held) if held is not None and not ours: done.append( f"{PREFIX_VAR} left as {held!r}, which this kit does not own, so no containment" diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py index 2e48b1263..c82ef706e 100755 --- a/host-setup/agent-safety/claude/stray-process-sweep.py +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -259,6 +259,12 @@ def manager_runtime(env, which=shutil.which, exists=os.path.exists, uid=None): return None +def prefix_registered(env): + """Whether this session runs under the containment prefix, whose file name the installer registers.""" + held = env.get("CLAUDE_CODE_SHELL_PREFIX", "") + return os.path.basename(held.replace("\\", "/")) == "tool-containment.py" + + def session_token(session_id): """The session id as `tool-containment.py` spells it in a unit name, or "" where there is none.""" return re.sub(r"[^A-Za-z0-9-]", "", session_id or "")[:64] @@ -367,8 +373,8 @@ def main(): ] reaped = "" runtime = manager_runtime(os.environ) - if runtime: - + if runtime or prefix_registered(os.environ): + # With the prefix registered and no manager found, the list fails and says so, as requirement 9 asks. def runner(*args): return _systemctl(*args, runtime=runtime) @@ -554,6 +560,14 @@ def socket_in(*dirs): "a systemctl that cannot run is reported, never read as nothing to stop", ), (session_token("a/b c;d") == "abcd", "the unit name is spelled as the prefix spells it"), + ( + prefix_registered({"CLAUDE_CODE_SHELL_PREFIX": "/h/.claude/hooks/tool-containment.py"}) + and not prefix_registered( + {"CLAUDE_CODE_SHELL_PREFIX": "/bin/audit-tool-containment.py-x"} + ) + and not prefix_registered({}), + "a session under the prefix is swept even with no manager found, so a failed list is reported", + ), ( manager_runtime({}, which=has, exists=socket_in(), uid=1000) is None, "a host with no manager socket anywhere has no manager to ask", diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index aabe41107..dda8faee2 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -801,6 +801,17 @@ def test_a_prefix_naming_another_copy_reports_stale(self): self.assertEqual(r.returncode, 1, r.stdout + r.stderr) self.assertIn("does not run the deployed prefix", r.stdout) + def test_a_wrapper_merely_containing_the_prefix_name_is_foreign(self): + """Someone else's wrapper is neither overwritten nor reported as a stale copy of ours.""" + self.home.mkdir(parents=True) + other = "/usr/local/bin/audit-" + install.CONTAIN_NAME + "-wrapper" + self._write({"env": {install.PREFIX_VAR: other}}) + self.install() + self.assertEqual(self._settings()["env"][install.PREFIX_VAR], other) + r = run(self.home, "--report") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("Note:", r.stdout) + def test_a_non_object_env_is_refused_rather_than_overwritten(self): self.home.mkdir(parents=True) self._write({"env": ["not", "an", "object"]}) From 94c86d42e6f10ca2a0820e87a5dc42a051d38c61 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 09:51:36 -0700 Subject: [PATCH 13/22] Test the Sweep's Reap Gate, and Name a Lost Manager The gate deciding whether the stop phase runs lived inline in main(), so reverting it left every test green. It is now should_reap(), which the self-test pins. Where the session ran under the prefix but no user manager was found at its end, the report now says that is why its scopes could not be listed, rather than a generic failure whose suggested command fails the same way. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../claude/stray-process-sweep.py | 37 +++++++++++++++++-- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py index c82ef706e..131fdcc2c 100755 --- a/host-setup/agent-safety/claude/stray-process-sweep.py +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -259,6 +259,15 @@ def manager_runtime(env, which=shutil.which, exists=os.path.exists, uid=None): return None +def should_reap(runtime, env): + """Whether the stop phase runs: where a manager was found, or where the session ran under the prefix. + + The second covers a manager that was lost by the session's end, whose failed list is reported as + requirement 9 asks rather than skipped in silence. + """ + return bool(runtime) or prefix_registered(env) + + def prefix_registered(env): """Whether this session runs under the containment prefix, whose file name the installer registers.""" held = env.get("CLAUDE_CODE_SHELL_PREFIX", "") @@ -320,9 +329,16 @@ def _read(path): } -def reap(session_ids, table, runner=_systemctl, read=None): +def reap(session_ids, table, runner=_systemctl, read=None, manager_found=True): """Stop this session's tool-call scopes, returning the report, or "" when there were none.""" units = session_scopes(session_ids, runner) + if units is None and not manager_found: + return ( + "agent-safety: this session ran under the containment prefix, but no systemd user " + "manager was found at its end, so its command scopes could not be listed or stopped. " + "Start the user manager, then check with: " + f"systemctl --user list-units '{_TOOL_UNIT}-*'" + ) if units is None: return ( "agent-safety: could not list this session's command scopes, so none was stopped. " @@ -373,12 +389,14 @@ def main(): ] reaped = "" runtime = manager_runtime(os.environ) - if runtime or prefix_registered(os.environ): - # With the prefix registered and no manager found, the list fails and says so, as requirement 9 asks. + if should_reap(runtime, os.environ): + def runner(*args): return _systemctl(*args, runtime=runtime) - reaped = reap(session_ids, _read_process_table() or {}, runner=runner) + reaped = reap( + session_ids, _read_process_table() or {}, runner=runner, manager_found=bool(runtime) + ) if reaped: print(reaped, file=sys.stderr) table = _read_process_table() @@ -568,6 +586,17 @@ def socket_in(*dirs): and not prefix_registered({}), "a session under the prefix is swept even with no manager found, so a failed list is reported", ), + ( + should_reap(None, {"CLAUDE_CODE_SHELL_PREFIX": "/h/.claude/hooks/tool-containment.py"}) + and should_reap("/run/user/1000", {}) + and not should_reap(None, {}), + "the stop phase runs under the prefix or a manager, and a host with neither is skipped", + ), + ( + "no systemd user manager was found" + in reap([sid], table, runner=lambda *a: (1, ""), manager_found=False), + "a lost manager is named as the reason the scopes were not stopped", + ), ( manager_runtime({}, which=has, exists=socket_in(), uid=1000) is None, "a host with no manager socket anywhere has no manager to ask", From 55d13c13069ee6fc1e306290025877de03e41782 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 09:55:22 -0700 Subject: [PATCH 14/22] Report an Unknown Rather Than a Lost Manager at Session End With the prefix registered and no user manager found at session end, the sweep claimed the manager was lost and advised a check that cannot work. The manager may never have existed, in which case the prefix ran every call bare and no scope was started, and a stopped manager has already ended its scopes. The report now says only that the sweep cannot tell whether any scope was started or still runs. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/stray-process-sweep.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py index 131fdcc2c..2d8d005fd 100755 --- a/host-setup/agent-safety/claude/stray-process-sweep.py +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -335,9 +335,8 @@ def reap(session_ids, table, runner=_systemctl, read=None, manager_found=True): if units is None and not manager_found: return ( "agent-safety: this session ran under the containment prefix, but no systemd user " - "manager was found at its end, so its command scopes could not be listed or stopped. " - "Start the user manager, then check with: " - f"systemctl --user list-units '{_TOOL_UNIT}-*'" + "manager was found at its end, so this sweep cannot tell whether any command scope " + "was started or still runs. The report below covers the processes it can see." ) if units is None: return ( @@ -593,9 +592,9 @@ def socket_in(*dirs): "the stop phase runs under the prefix or a manager, and a host with neither is skipped", ), ( - "no systemd user manager was found" + "cannot tell whether any command scope" in reap([sid], table, runner=lambda *a: (1, ""), manager_found=False), - "a lost manager is named as the reason the scopes were not stopped", + "no manager at session end is reported as unknown, never as a lost manager", ), ( manager_runtime({}, which=has, exists=socket_in(), uid=1000) is None, From a7db99c2daa626d84bcab8ef43a2144d855f2917 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 09:56:21 -0700 Subject: [PATCH 15/22] Drop the Sweep's Promise of a Report That May Not Follow The unknown-scopes line promised a report below it, which does not follow when the sweep finds no survivors or cannot read the process table. The line now ends at the unknown, and should_reap's docstring no longer describes that case as a lost manager. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/stray-process-sweep.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py index 2d8d005fd..a7bd8daef 100755 --- a/host-setup/agent-safety/claude/stray-process-sweep.py +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -262,8 +262,8 @@ def manager_runtime(env, which=shutil.which, exists=os.path.exists, uid=None): def should_reap(runtime, env): """Whether the stop phase runs: where a manager was found, or where the session ran under the prefix. - The second covers a manager that was lost by the session's end, whose failed list is reported as - requirement 9 asks rather than skipped in silence. + The second covers a session under the prefix with no manager found at its end, which is reported as + an unknown, since the manager may never have run, rather than skipped in silence. """ return bool(runtime) or prefix_registered(env) @@ -336,7 +336,7 @@ def reap(session_ids, table, runner=_systemctl, read=None, manager_found=True): return ( "agent-safety: this session ran under the containment prefix, but no systemd user " "manager was found at its end, so this sweep cannot tell whether any command scope " - "was started or still runs. The report below covers the processes it can see." + "was started or still runs." ) if units is None: return ( From 5bcfb1898a5af59a12bd2152494e873d1fbfedb8 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 10:07:22 -0700 Subject: [PATCH 16/22] State Which Servers Requirement 9 Leaves Unbounded Requirement 9 exempted a long-lived server the agent starts, which read as though a server started from a command outlived the session, while nothing tells such a command from any other. The exemption now names tool servers the agent's harness launches for itself, such as MCP servers, and says a server started by a command ends with its session. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/host-setup/agent-safety/README.md b/host-setup/agent-safety/README.md index a85fb1428..57b754a33 100644 --- a/host-setup/agent-safety/README.md +++ b/host-setup/agent-safety/README.md @@ -296,7 +296,9 @@ text says, because the harm it covers was never in the text. A hook the agent runs, a guard above included, is not placed in a group. A group that fails to start fails the command, and a guard that fails that way is a guard that did not run. Nor is a - long-lived server the agent starts, which outlives any one session. + tool server the agent's harness launches for itself, such as an MCP server, which serves the + harness rather than any one session. A server started by a command is a command like any other, + and it ends with the session that started it. Where the host offers no such group, commands run unbounded and the host's installation report says so, because a silent fallback reads exactly like a bounded host. A host that registered the From f9b36050adba5a39de598667d6e1659137b366eb Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 10:08:30 -0700 Subject: [PATCH 17/22] Limit Requirement 9's Server Rule to Tool Calls The rewording said any server a command starts ends with its session, which a hook's server does not, since hooks run unbounded and the stop covers tool-call groups only. It now names tool calls, and says a server a hook starts shares the hook's exemption and falls to requirement 8's report. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/host-setup/agent-safety/README.md b/host-setup/agent-safety/README.md index 57b754a33..2a26ed7aa 100644 --- a/host-setup/agent-safety/README.md +++ b/host-setup/agent-safety/README.md @@ -297,8 +297,9 @@ text says, because the harm it covers was never in the text. A hook the agent runs, a guard above included, is not placed in a group. A group that fails to start fails the command, and a guard that fails that way is a guard that did not run. Nor is a tool server the agent's harness launches for itself, such as an MCP server, which serves the - harness rather than any one session. A server started by a command is a command like any other, - and it ends with the session that started it. + harness rather than any one session. A server started by a tool call is part of that tool call, + and it ends with the session that started it. One a hook starts shares the hook's exemption, and + requirement 8 reports it if it outlives the session. Where the host offers no such group, commands run unbounded and the host's installation report says so, because a silent fallback reads exactly like a bounded host. A host that registered the From af797da3bd22d3ed2f57078be44b6054344c2b61 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 10:11:18 -0700 Subject: [PATCH 18/22] Drop Requirement 9's Claims About Which Servers End With the Session Each wording of what a started server does at session end drew a counterexample: a server handed to a daemon leaves the tool call's group, and one a hook starts is reparented out of the agent's tree. Requirement 9 keeps only the exemption for servers the harness launches for itself, and claims nothing beyond the group stop it already states. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/host-setup/agent-safety/README.md b/host-setup/agent-safety/README.md index 2a26ed7aa..5cde88f72 100644 --- a/host-setup/agent-safety/README.md +++ b/host-setup/agent-safety/README.md @@ -297,9 +297,7 @@ text says, because the harm it covers was never in the text. A hook the agent runs, a guard above included, is not placed in a group. A group that fails to start fails the command, and a guard that fails that way is a guard that did not run. Nor is a tool server the agent's harness launches for itself, such as an MCP server, which serves the - harness rather than any one session. A server started by a tool call is part of that tool call, - and it ends with the session that started it. One a hook starts shares the hook's exemption, and - requirement 8 reports it if it outlives the session. + harness rather than any one session. Where the host offers no such group, commands run unbounded and the host's installation report says so, because a silent fallback reads exactly like a bounded host. A host that registered the From 138c49822032f3b1462ab8a51b1c474a24e34394 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 10:28:54 -0700 Subject: [PATCH 19/22] Resolve a Shim's Real Command With type -P command -v prints the bare name when a shell function or alias of that name is defined, so a shim that captured it could still call itself. The shell-codestyle rule now captures the path with type -P, which resolves an executable only, and stops where it prints nothing. Co-Authored-By: Claude Opus 5.5 (1M context) --- .agents/skills/shell-codestyle/SKILL.md | 4 +++- .claude-plugin/fleet-skills/.source-digests/shell-codestyle | 2 +- .claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md | 4 +++- .github/skills/shell-codestyle/SKILL.md | 4 +++- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/.agents/skills/shell-codestyle/SKILL.md b/.agents/skills/shell-codestyle/SKILL.md index 085e370ad..98d00bf1f 100644 --- a/.agents/skills/shell-codestyle/SKILL.md +++ b/.agents/skills/shell-codestyle/SKILL.md @@ -55,7 +55,9 @@ depend on Python either. Everything else is Python, with a test under its own sc placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, since `command` skips functions and aliases but not the `PATH` search. Every call starts another copy of the wrapper, so the chain grows until something stops it. Capture the real path with - `command -v` before changing `PATH`, and call that path from inside the shim. + `type -P` before changing `PATH`, stop where it prints nothing, and call that path from inside + the shim. `command -v` is not a substitute, since it prints the bare name when a shell function + or alias of that name is defined. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working directory at invocation is not a property of the script. diff --git a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle index 8dc2c6d82..8ebdc7bfd 100644 --- a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle +++ b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle @@ -1 +1 @@ -f8d53a3ed92814a9 +43fc3c70018bb6ed diff --git a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md index 085e370ad..98d00bf1f 100644 --- a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md @@ -55,7 +55,9 @@ depend on Python either. Everything else is Python, with a test under its own sc placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, since `command` skips functions and aliases but not the `PATH` search. Every call starts another copy of the wrapper, so the chain grows until something stops it. Capture the real path with - `command -v` before changing `PATH`, and call that path from inside the shim. + `type -P` before changing `PATH`, stop where it prints nothing, and call that path from inside + the shim. `command -v` is not a substitute, since it prints the bare name when a shell function + or alias of that name is defined. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working directory at invocation is not a property of the script. diff --git a/.github/skills/shell-codestyle/SKILL.md b/.github/skills/shell-codestyle/SKILL.md index 085e370ad..98d00bf1f 100644 --- a/.github/skills/shell-codestyle/SKILL.md +++ b/.github/skills/shell-codestyle/SKILL.md @@ -55,7 +55,9 @@ depend on Python either. Everything else is Python, with a test under its own sc placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, since `command` skips functions and aliases but not the `PATH` search. Every call starts another copy of the wrapper, so the chain grows until something stops it. Capture the real path with - `command -v` before changing `PATH`, and call that path from inside the shim. + `type -P` before changing `PATH`, stop where it prints nothing, and call that path from inside + the shim. `command -v` is not a substitute, since it prints the bare name when a shell function + or alias of that name is defined. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working directory at invocation is not a property of the script. From 57bedfbfba1c164dfc81c5bca8b135ad3caa6e56 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 10:30:15 -0700 Subject: [PATCH 20/22] Require the Shim's Captured Path Be Absolute and Outside the Shim type -P returns the shim itself where an inherited PATH already holds it, and a relative path where PATH carries a dot entry, so the rule now stops unless the captured path is absolute and outside the shim's own directory. The reason command -v falls short is stated for functions only, since an active alias prints its definition instead. Co-Authored-By: Claude Opus 5.5 (1M context) --- .agents/skills/shell-codestyle/SKILL.md | 7 ++++--- .../fleet-skills/.source-digests/shell-codestyle | 2 +- .../fleet-skills/skills/shell-codestyle/SKILL.md | 7 ++++--- .github/skills/shell-codestyle/SKILL.md | 7 ++++--- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/.agents/skills/shell-codestyle/SKILL.md b/.agents/skills/shell-codestyle/SKILL.md index 98d00bf1f..e36ba2148 100644 --- a/.agents/skills/shell-codestyle/SKILL.md +++ b/.agents/skills/shell-codestyle/SKILL.md @@ -55,9 +55,10 @@ depend on Python either. Everything else is Python, with a test under its own sc placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, since `command` skips functions and aliases but not the `PATH` search. Every call starts another copy of the wrapper, so the chain grows until something stops it. Capture the real path with - `type -P` before changing `PATH`, stop where it prints nothing, and call that path from inside - the shim. `command -v` is not a substitute, since it prints the bare name when a shell function - or alias of that name is defined. + `type -P` before changing `PATH`, stop unless it is an absolute path outside the shim's own + directory, and call that path from inside the shim. An inherited `PATH` can already hold the + shim, and a `.` entry yields a relative path. `command -v` is not a substitute, since it prints + the bare name for a shell function of that name. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working directory at invocation is not a property of the script. diff --git a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle index 8ebdc7bfd..ce115d57d 100644 --- a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle +++ b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle @@ -1 +1 @@ -43fc3c70018bb6ed +2c61897bfbd918e9 diff --git a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md index 98d00bf1f..e36ba2148 100644 --- a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md @@ -55,9 +55,10 @@ depend on Python either. Everything else is Python, with a test under its own sc placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, since `command` skips functions and aliases but not the `PATH` search. Every call starts another copy of the wrapper, so the chain grows until something stops it. Capture the real path with - `type -P` before changing `PATH`, stop where it prints nothing, and call that path from inside - the shim. `command -v` is not a substitute, since it prints the bare name when a shell function - or alias of that name is defined. + `type -P` before changing `PATH`, stop unless it is an absolute path outside the shim's own + directory, and call that path from inside the shim. An inherited `PATH` can already hold the + shim, and a `.` entry yields a relative path. `command -v` is not a substitute, since it prints + the bare name for a shell function of that name. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working directory at invocation is not a property of the script. diff --git a/.github/skills/shell-codestyle/SKILL.md b/.github/skills/shell-codestyle/SKILL.md index 98d00bf1f..e36ba2148 100644 --- a/.github/skills/shell-codestyle/SKILL.md +++ b/.github/skills/shell-codestyle/SKILL.md @@ -55,9 +55,10 @@ depend on Python either. Everything else is Python, with a test under its own sc placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, since `command` skips functions and aliases but not the `PATH` search. Every call starts another copy of the wrapper, so the chain grows until something stops it. Capture the real path with - `type -P` before changing `PATH`, stop where it prints nothing, and call that path from inside - the shim. `command -v` is not a substitute, since it prints the bare name when a shell function - or alias of that name is defined. + `type -P` before changing `PATH`, stop unless it is an absolute path outside the shim's own + directory, and call that path from inside the shim. An inherited `PATH` can already hold the + shim, and a `.` entry yields a relative path. `command -v` is not a substitute, since it prints + the bare name for a shell function of that name. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working directory at invocation is not a property of the script. From 4e40cd4ca4145bac6c03f8329b4280450bd87ec4 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 13:59:06 -0700 Subject: [PATCH 21/22] Test the Shim's Captured Path by File Identity A directory comparison passes when an inherited PATH holds the shim under a symlinked or dot-dot spelling, as macOS's /var does, so the shim could still call itself. The rule now stops unless the captured path is absolute and is not the shim itself, tested as files with -ef. Co-Authored-By: Claude Opus 5.5 (1M context) --- .agents/skills/shell-codestyle/SKILL.md | 7 ++++--- .../fleet-skills/.source-digests/shell-codestyle | 2 +- .../fleet-skills/skills/shell-codestyle/SKILL.md | 7 ++++--- .github/skills/shell-codestyle/SKILL.md | 7 ++++--- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/.agents/skills/shell-codestyle/SKILL.md b/.agents/skills/shell-codestyle/SKILL.md index e36ba2148..64bc2ba37 100644 --- a/.agents/skills/shell-codestyle/SKILL.md +++ b/.agents/skills/shell-codestyle/SKILL.md @@ -55,9 +55,10 @@ depend on Python either. Everything else is Python, with a test under its own sc placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, since `command` skips functions and aliases but not the `PATH` search. Every call starts another copy of the wrapper, so the chain grows until something stops it. Capture the real path with - `type -P` before changing `PATH`, stop unless it is an absolute path outside the shim's own - directory, and call that path from inside the shim. An inherited `PATH` can already hold the - shim, and a `.` entry yields a relative path. `command -v` is not a substitute, since it prints + `type -P` before changing `PATH`, stop unless it is an absolute path that is not the shim itself, + tested as files with `[ "$real" -ef "$shim" ]` rather than as spellings, and call that path from + inside the shim. An inherited `PATH` can already hold the shim, under a symlinked spelling too, + and a `.` entry yields a relative path. `command -v` is not a substitute, since it prints the bare name for a shell function of that name. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working diff --git a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle index ce115d57d..0f998aef3 100644 --- a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle +++ b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle @@ -1 +1 @@ -2c61897bfbd918e9 +d46e3118a4acca8c diff --git a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md index e36ba2148..64bc2ba37 100644 --- a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md @@ -55,9 +55,10 @@ depend on Python either. Everything else is Python, with a test under its own sc placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, since `command` skips functions and aliases but not the `PATH` search. Every call starts another copy of the wrapper, so the chain grows until something stops it. Capture the real path with - `type -P` before changing `PATH`, stop unless it is an absolute path outside the shim's own - directory, and call that path from inside the shim. An inherited `PATH` can already hold the - shim, and a `.` entry yields a relative path. `command -v` is not a substitute, since it prints + `type -P` before changing `PATH`, stop unless it is an absolute path that is not the shim itself, + tested as files with `[ "$real" -ef "$shim" ]` rather than as spellings, and call that path from + inside the shim. An inherited `PATH` can already hold the shim, under a symlinked spelling too, + and a `.` entry yields a relative path. `command -v` is not a substitute, since it prints the bare name for a shell function of that name. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working diff --git a/.github/skills/shell-codestyle/SKILL.md b/.github/skills/shell-codestyle/SKILL.md index e36ba2148..64bc2ba37 100644 --- a/.github/skills/shell-codestyle/SKILL.md +++ b/.github/skills/shell-codestyle/SKILL.md @@ -55,9 +55,10 @@ depend on Python either. Everything else is Python, with a test under its own sc placed ahead of the real one on `PATH`, that calls `command jq` or a bare `jq` calls itself, since `command` skips functions and aliases but not the `PATH` search. Every call starts another copy of the wrapper, so the chain grows until something stops it. Capture the real path with - `type -P` before changing `PATH`, stop unless it is an absolute path outside the shim's own - directory, and call that path from inside the shim. An inherited `PATH` can already hold the - shim, and a `.` entry yields a relative path. `command -v` is not a substitute, since it prints + `type -P` before changing `PATH`, stop unless it is an absolute path that is not the shim itself, + tested as files with `[ "$real" -ef "$shim" ]` rather than as spellings, and call that path from + inside the shim. An inherited `PATH` can already hold the shim, under a symlinked spelling too, + and a `.` entry yields a relative path. `command -v` is not a substitute, since it prints the bare name for a shell function of that name. - **Self-locating, never dependent on the caller's directory.** A script resolves its own directory from `BASH_SOURCE` and references its payloads through it, since the working From 7eca7ac130f24c9d410ee41f287414a992b6210a Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 26 Sep 2026 15:11:37 -0700 Subject: [PATCH 22/22] Name a Missing systemd-run Apart From an Unreachable Manager A registered prefix on a host that lost systemd-run reported that no user manager was reachable, sending the maintainer to the wrong cause. The per-call notice now names a missing systemd-run as such. Co-Authored-By: Claude Opus 5.5 (1M context) --- host-setup/agent-safety/claude/README.md | 2 +- .../agent-safety/claude/tool-containment.py | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 3baf8f85b..31b4e1678 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -154,7 +154,7 @@ Every other key in the file is left as it stands, `permissions.allow` and the re - **A write or a wait inside a script file is unseen, so never put either in a script to run it.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string. A `git push` or a `gh` mutation inside the script therefore reaches the server unparsed. An unbounded wait inside that same script is equally unseen, and worse in one way. A denied write fails loudly. A wait the guard never saw runs until something ends it, which is one of the leaks the SessionEnd sweep exists to find afterwards. This is the widest hole in the kit, and an agent opens it by accident. Collecting fifteen repetitive pushes into a loop looks like tidiness, and so does moving a poll into a script to keep a tool call short. Neither looks like disabling a guard. Issue each write and each wait as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and the wait rather than the script. - **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) and 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. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) 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 it, verified live. -- **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and the user manager later becomes unreachable or loses those two controllers, each tool call runs unbounded and prints one `tool-containment:` line on stderr saying so. +- **Containment runs on Linux and WSL with a systemd user manager delegated the `pids` and `memory` controllers, where the deployed prefix runs as its own executable.** The manager socket is looked for under `XDG_RUNTIME_DIR` and then under `/run/user/`, 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, 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, such as a session an IDE launched under another environment. macOS and Windows have no systemd, and 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 there, and `--report` flags a prefix registered on a host that can no longer contain. Where the prefix is registered and `systemd-run` later goes missing, or the user manager becomes unreachable or loses those two controllers, each tool call 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, 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, since sharing the parent's one ceiling would let a heavy build make the kernel kill the nested `claude` process instead. Those scopes are stopped when the nested session ends. Where stopping the parent's scope ended the nested session first, they keep running unreported, and `systemctl --user list-units 'claude-tool-*'` shows each by the session id in its name. Stop only the ones whose session has ended, since the same pattern matches every live session's tool calls. 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, and anything run directly about 10 ms. - **The ceilings bound an accident, not an adversary.** A command can raise its own scope's properties with `systemctl --user set-property`, or 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. A scope stop sends SIGTERM and escalates to SIGKILL after two seconds, which keeps it inside the hook's own timeout. diff --git a/host-setup/agent-safety/claude/tool-containment.py b/host-setup/agent-safety/claude/tool-containment.py index 2205f6d91..71125b9ca 100755 --- a/host-setup/agent-safety/claude/tool-containment.py +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -53,6 +53,7 @@ RESTORE_VAR = "AGENT_CONTAINMENT_RUNTIME_RESTORE" UNREACHABLE = "no systemd user manager is reachable" +NO_SYSTEMD_RUN = "systemd-run is not installed" UNDELEGATED = "the user manager is not delegated the pids and memory controllers" # How long a stop waits on SIGTERM before SIGKILL, so the session-end stop fits its hook's budget. @@ -248,8 +249,8 @@ def plan(command, env, suffix, runtime, which=which, why=UNREACHABLE): def decide(command, env, suffix, runtime, is_delegated, which=which): - """`plan` for this host: a tool call under a manager lacking the controllers runs bare, and says why.""" - why = UNREACHABLE + """`plan` for this host: a tool call that cannot be contained runs bare, and says which reason applies.""" + why = UNREACHABLE if which("systemd-run") else NO_SYSTEMD_RUN if runtime and is_tool_call(command) and not is_delegated(): runtime, why = None, UNDELEGATED return plan(command, env, suffix, runtime, which, why=why) @@ -417,6 +418,19 @@ def socket_in(*dirs): and not is_tool_call(mcp), "a tool call without its snapshot is still recognised by its cwd bookkeeping, sandboxed or quoted", ), + ( + NO_SYSTEMD_RUN + in decide( + tool, + env, + "57", + None, + lambda: True, + which=lambda n: None if n == "systemd-run" else fake_which(n), + )[2][0] + and UNREACHABLE in decide(tool, env, "58", None, lambda: True, which=fake_which)[2][0], + "a missing systemd-run is named as such, apart from an unreachable manager", + ), ( delegated(1000, read=lambda p: "cpu memory pids\n") and not delegated(1000, read=lambda p: "cpu\n"),