diff --git a/.agents/skills/shell-codestyle/SKILL.md b/.agents/skills/shell-codestyle/SKILL.md index 46fbaec05..64bc2ba37 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,15 @@ 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 + `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 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..0f998aef3 100644 --- a/.claude-plugin/fleet-skills/.source-digests/shell-codestyle +++ b/.claude-plugin/fleet-skills/.source-digests/shell-codestyle @@ -1 +1 @@ -40c3f8736d2d6180 +d46e3118a4acca8c diff --git a/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md b/.claude-plugin/fleet-skills/skills/shell-codestyle/SKILL.md index 46fbaec05..64bc2ba37 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,15 @@ 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 + `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 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..64bc2ba37 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,15 @@ 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 + `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 directory at invocation is not a property of the script. diff --git a/AGENTS.md b/AGENTS.md index a2c864674..5ffbb17fe 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 --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/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..5cde88f72 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,33 @@ 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 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. + + 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 + group's limits or start a group outside it, and the incident this answers was a mistake. + ## Decision Flow ```mermaid @@ -321,8 +350,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 +384,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 +394,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..31b4e1678 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 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. - 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 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) @@ -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,12 +126,15 @@ 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\"" } ] } ], "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": { @@ -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 where the installer reports the prefix set. ## Scope and Limits @@ -141,9 +154,13 @@ 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 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. - **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..ada93c614 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 @@ -40,15 +42,18 @@ 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. -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. @@ -173,6 +178,101 @@ def at(data, path): ] +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 + 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. + """ + 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 system.startswith("linux"): + 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. + 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" + # 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})" + return True, "a systemd user manager is running and the prefix runs" + + +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( + [str(prefix), "--selftest"], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=30, + check=False, + ) + 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): + """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 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 not kit_prefix(held) else None + + 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 +383,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 +655,23 @@ 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(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) + # 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})" + ) + # 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 a containment prefix where it cannot contain ({reason}), " + "so re-run the installer to unset it" + ) allow = ( data.get("permissions", {}).get("allow") if isinstance(data.get("permissions"), dict) @@ -642,6 +759,22 @@ 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: + settings_data = json.loads((claude_home / "settings.json").read_text(encoding="utf-8")) + except (ValueError, OSError): + 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) + # 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( + 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")) @@ -692,6 +825,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 +932,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 +994,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(contain_dst) + env = data.setdefault("env", {}) + held = env.get(PREFIX_VAR) + 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" + ) + 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..a7bd8daef 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,183 @@ def report(table, roots): return "\n".join(lines) +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", + errors="replace", + timeout=5, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None, "" + return done.returncode, done.stdout + + +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. + """ + 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 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 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) + + +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] + + +def session_scopes(session_ids, runner=_systemctl): + """The tool-call scopes these sessions left loaded, or None when systemd cannot be asked. + + 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. + """ + tokens = sorted({t for t in map(session_token, session_ids) if t}) + if not tokens: + return [] + code, out = runner( + "list-units", + "--type=scope", + "--all", + "--plain", + "--no-legend", + "--no-pager", + *(f"{_TOOL_UNIT}-{t}-*.scope" for t in tokens), + ) + 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_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 this sweep cannot tell whether any command scope " + "was started or still runs." + ) + 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) + 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_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 = [] + 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 + held = payload.get("session_id") if isinstance(payload, dict) else None + session_ids = [ + held if isinstance(held, str) else "", + os.environ.get("CLAUDE_CODE_SESSION_ID", ""), + ] + reaped = "" + runtime = manager_runtime(os.environ) + if should_reap(runtime, os.environ): + + def runner(*args): + return _systemctl(*args, runtime=runtime) + + 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() if table is None: print( @@ -237,7 +415,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 +515,112 @@ 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.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() + + 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, + "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", + ), + ("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"), + ( + 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", + ), + ( + 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", + ), + ( + "cannot tell whether any command scope" + in reap([sid], table, runner=lambda *a: (1, ""), manager_found=False), + "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, + "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", + ), + ( + 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", + ), + ( + 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 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..dda8faee2 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,16 +24,27 @@ 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): + +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 +63,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 +716,189 @@ 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 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() + 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) + + 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) + # 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() + 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) + # 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.""" + 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() + 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_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("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"]}) + 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 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) + 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) + + @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, controllers=str(self.controllers) + ) + + @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_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) + self.assertIn("no systemd user manager", reason) + + def test_a_non_linux_host_cannot_contain(self): + capable, reason = self._judge(system="darwin") + self.assertFalse(capable) + self.assertIn("darwin", reason) + + 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..71125b9ca --- /dev/null +++ b/host-setup/agent-safety/claude/tool-containment.py @@ -0,0 +1,561 @@ +#!/usr/bin/env python3 +"""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, 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`, `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 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 +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, 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 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, 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. + +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" + +# 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" +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. +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 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 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 lead: + return name + return None + + +def is_tool_call(command): + """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() + 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 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" + + +# 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 +MAX_LIMIT = 2**63 +_UNITS = {"M": 1024**2, "G": 1024**3, "T": 1024**4} + + +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 + return int(text) + + +def valid_tasks(value): + """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 `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, and the size floor is `MIN_MEMORY`. + """ + if value == "infinity": + return True + 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): + """(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_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 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, + 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): + return [shell, "-c", command], {}, [] + if runtime is None: + 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 = [ + which("systemd-run") or "systemd-run", + "--user", + "--scope", + "--collect", + "--quiet", + f"--unit={TOOL_UNIT}-{token}-{suffix}", + "--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, + "-I", + "-S", + os.path.abspath(__file__), + "--inner", + ] + 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 decide(command, env, suffix, runtime, is_delegated, which=which): + """`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) + + +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" + 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 + + +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 + suffix = f"{os.getpid()}-{os.urandom(4).hex()}" + 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}) + 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"' + mcp = "'npx' '-y' 'example-mcp-server'" + + 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) + + 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", 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"} + ) + 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-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", None, fake_which)[2] == [], + "and prints nothing where no manager is reachable", + ), + ( + 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" + 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"), + (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", RUN, fake_which)[1][SHELL_VAR] == "/usr/bin/zsh", + "a zsh one under 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"), + ( + 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"), + ( + 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, which=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, which=fake_which)[0], + "a manager holding them contains it", + ), + ( + decide(hook, hook_env, "55", RUN, lambda: 1 / 0, which=fake_which)[2] == [], + "a hook command never reads the controllers", + ), + ( + "--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, 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"), + "delegation needs both the pids and the memory controller", + ), + ( + 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", "512M", "1T", "25%", "99%", "infinity"))) + and not any( + map( + valid_memory, + ( + "0", + "1024", + "1.5G", + "0.5G", + "08G", + "1K", + "1P", + "100%", + "050%", + "08%", + "0.25%", + "16GB", + "G", + "lots", + "99999999999T", + ), + ) + ), + "only the canonical memory forms are accepted", + ), + ( + all(map(valid_tasks, ("64", "8192", "infinity"))) + and not any( + map( + valid_tasks, + ( + "0", + "1", + "1.5", + "1e3", + "-5", + ".5%", + "\u0663", + "99999999999999999999", + "08192", + "0100", + "50%", + "100%", + ), + ) + ), + "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", 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"), + ( + 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", + ), + ( + manager_runtime(env, "darwin", fake_which, lambda p: True, uid=1000) is None, + "a non-Linux host has no manager", + ), + ( + manager_runtime(env, "linux", fake_which, socket_in(RUN), uid=1000) == RUN, + "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) + 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