Repository navigation
fork-kit/agent-guards: the machine's agent guard hooks as a kit (#834 G4) - #847
Conversation
…G4) Five Claude Code hooks that guard every agent on a shared machine, as one kit with one installer, facts from the machine file and the same messages and exit codes as before: - actions-disable-guard (PreToolUse Bash): no disabling of workflows, Actions or branch protection; fails closed (a missing or failing hook refuses, and says so) - capacity-pipe-guard (PreToolUse Bash|Monitor): no pipe out of a capacity check - memory-index-guard (Pre/PostToolUse): the auto-memory index stays inside its budget - bg-guard (Stop): no stop while a background Bash command still runs - agent-slots (UserPromptSubmit, Stop): slot and ready-queue context for orchestrators The others fail open with a visible line. `agent-guards check` runs each wired command with a case it must refuse and one it must pass; `--settings` writes a managed settings drop-in. Shared bootstrap and kit_install contract tests cover the new kit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
lens: B · reviewer: lens agent (security boundary and fail-safe) · read at: f64f2c7 |
|
lens: code · reviewer: lens agent (A: correctness and parity) · read at: f64f2c7 |
- actions-disable-guard and capacity-pipe-guard match Bash|Monitor; the memory-index after-call check matches Monitor too; check reports a guard wired for Bash only as missing. - The owner's approval is a root-owned file with the hash of a one-time code (agent-guards approve); the session variable is no longer read, since nested sessions inherited it. - Refuse starting a nested session without this machine's hooks (claude --bare/--safe-mode, CLAUDE_CODE_SIMPLE, codex). - The closed hook sets onFailure block; an empty guard file refuses. - A ruleset set to evaluate is refused like disabled. - Each hook reads only its own part of the machine file section; bad keys and refuseScripts rows are dropped one by one and named to the agent; self-check does the strict check. - Uninstall refuses while a foreign settings file names a hook or an older session runs; rollback is --no-settings. - check --settings as root reads only a root-owned file; check runs hooks under a temporary HOME; self-check checks links, an open approval and passwordless ways to root. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
lens: code r2 · reviewer: lens agent (A: correctness and parity) · read at: 6d5047d |
|
lens: B r2 · reviewer: lens agent (security boundary and fail-safe) · read at: 6d5047d |
…able is refused (lens B r2 minor 1) The off word of updateRepositoryRuleset was looked for in canon() text, which blanks text with no cue word, so `-F e=EVALUATE` (or a JSON variables block) was '' before OFF_WORD saw it. It is now read without the cue words, as the REST ruleset body already was. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…older, once (lens B r2 major 2) `sudo agent-guards approve --command '<cmd>' [--cwd DIR]` now stores the hash of the normalised command and the folder next to the code's hash (approval file version 2). The guard passes only that command, ending in the marker, run in that folder, and records the use in its state folder (O_EXCL link; the same tool_use_id passes again), so the approval is used up. A code seen in a transcript, the app database or ps opens no other command. A version 1 file counts as no approval. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e and wrapper, and say what the guards are not (lens B r2 major 1)
A list of strings cannot be complete, so this does both things the review asked for:
(a) Wider detection where it is cheap and reliable. claude and codex now count by name, by their real
program path (.../claude/versions/<v>, the @anthropic-ai/claude-code and @openai/codex packages), as a
link to or a copy of the installed program, through npx, bunx, pnpm dlx, npm exec, bun x and
`node <their cli>`, behind `$(which claude)`, and inside python -c, node -e, perl -e, at, systemd-run
and the other wrappers already read for gh. CLAUDE_CODE_SIMPLE counts in the command, through env -S,
in a sourced file, in BASH_ENV/--rcfile and in the user's shell start files.
(b) The threat model, written plainly in the README ("What the guards are and are not") and the guard's
docstring: the guards stop mistakes and casual misuse; they are not a boundary against a hostile agent;
the boundary is the GitHub permissions of the agent's token (a fine-grained token without Actions and
Administration write is the recommended setup).
Codex arguments are now read option by option (an option's value is not taken for the subcommand),
because the new path and package forms need it; the separate codex nits follow in their own commit.
Tests: LensSecurityR2Test.test_r2_major1_* (each fails on 6d5047d).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ex mcp passes (lens A r2 nit) `codex -m o3 exec x` is now refused as `codex exec` (the option's value is no longer taken for the subcommand), `codex mcp list` (MCP setup, no session) passes, and `npx -y @openai/codex exec x` is refused (the package form came with the major-1 commit). `codex mcp-server` stays refused. Test: LensSecurityR2Test.test_r2_nit_codex_arguments_name_the_right_subcommand_mcp_passes_npx_refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ses inside a hooked session, remembers hand-wired entries (lens B r2 minor 2, lens A r2 minors 1 and 2) - Sessions are found by the real path of their program (/proc/<pid>/exe: the native build in .../claude/versions/<v> under any name, the @anthropic-ai/claude-code script node runs through any link, an installed `claude`), not by the process name alone. - The uninstall's own ancestors are no longer skipped: run from inside a Claude Code session that has the hooks, it refuses and says to run it from a terminal. - A refusal for a hand-wired entry is remembered (/etc/agent-guards/hand-wired-seen.json, removed with /etc/agent-guards); the next run then counts every session older than itself, as does a run where the drop-in was never on. A broken record counts as seen now. - The project .claude/settings*.json of each running session's working folder (and the folders above it) is searched too. Tests: Install.test_r2_minorB2_*, test_r2_minorA1_*, test_r2_minorA2_* and test_r2_state_* (each fails on 6d5047d). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s onFailure, and how often a machine-file note shows (r2 nits) - onFailure: "block" is honoured from Claude Code 2.1.295 on; older versions ignore it and let a failed or timed-out hook's call run (lens B r2 nit 1). - A broken part of the machine file is named on every call the hook handles, once per hook with a problem, so a Bash call can carry it up to three times: kept loud on purpose, now said in the README (lens A r2 nit). - The --safe-mode refusal is kept, with its reason in the README since the major-1 commit: safe mode runs managed hooks but not hooks wired by hand in user settings (lens B r2 nit 2). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…de Code session runs (follow-up to the session-check commit) The session check now runs on every uninstall, so it must not refuse for a /proc/stat it does not need: the boot time is read only once a Claude Code process is found, and an unreadable process list still refuses with "cannot be read". Found by the shared fork-kit/common/tests/kit_install.test.py run (its fake /proc has no stat file). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
override for head a90b854: the round 2 fix diff (6d5047d..a90b854) checked against lens B r2 and lens A r2. The lens rounds are used up (2 of 2), so the orchestrator checked the fixes itself.
🤖 Generated with Claude Code |
Part of #834 (item G4, first half). The Claude Code hooks that guard every agent on a shared machine move into the
fork as one kit,
fork-kit/agent-guards, laid out likefork-kit/model-guard. A project keeps only its factsin the machine file. Agents see the same messages and the same exit codes as before, except where the lens fixes
below say otherwise.
Hooks
actions-disable-guardBash|Monitor), 10 s,onFailure: blockenforcementdisabledorevaluate) on any repo;refuseScriptsfrom the machine file; a nested agent session without this machine's hookscapacity-pipe-guardBash|Monitor), 10 smemory-index-guardWrite|Edit|MultiEdit), PostToolUse (Write|Edit|MultiEdit|Bash|Monitor), 5 sbg-guardmaxBlocksper session)agent-slotsbin/agent-guardsadds four commands:hooksprints the settings entries;self-checkchecks the whole machine file section strictly, the hook files and their/usr/local/binlinks, thedrop-in, an open approval, and warns when the agents' user can become root without a password;
check [--settings F]runs every wired command the way Claude Code does (Bash and Monitor cases), with one caseit must refuse and one it must pass, under a temporary
HOME, and changes nothing on the machine. As root itreads
Fonly when it is root-owned and not writable by others;approve [--hours N] [--cwd DIR] --command '<cmd>' | --revoke(root only): the owner's approval of one command,below.
sbin/agent-guards-installis on the sharedkit_install.py. The shared bootstrap accepts it with--kit agent-guards [--settings | --no-settings].--settingswrites a managed settings drop-in,/etc/claude-code/managed-settings.d/agent-guards.json. It is written after the hook links and never written overa drop-in of that name the installer did not write. The rollback is
--no-settings(keeps the hook files).Config keys (machine file,
"agent-guards"section; all optional, defaults = the old values)actionsDisable.stateDir~/.local/state/actions-disable-guardactionsDisable.refuseScripts[]({"name", "flag", "why"})capacityPipe.commands["t3-capacity"]memoryIndex.maxChars/maxLine/stateDir6000/160/~/.cache/memory-index-guardbgGuard.skipSessionsFiles/maxBlocks/stateDir[]/3/~/.local/state/bg-guardagentSlots.sessionsFile/queue/readyHeading/maxAlive/processName/note""(off) /""/"## Ready"/10/"claude"/""The machine file must be owned by root and not writable by others; otherwise it is not used. Each hook reads only
its own part: a bad key keeps its default, an unknown key is ignored, a bad
refuseScriptsrow is dropped and thegood rows kept. The hook tells the agent (a
systemMessage, plus context for PreToolUse) and stderr. Another hook'spart, or an unknown top-level key (a later G4b section), changes nothing for it.
self-checknames every problem.Lens round 1 fixes
Approval: a root-owned file, not an environment variable (lens B major). Options were (a) refuse any command
that names or sets the variable, or (b) a root-owned approval file. (a) cannot work: the variable is set when the
owner starts a session, so every nested
claude -porcodex execinherits it without any command naming it. (b)is the root fix:
sudo agent-guards approve --hours Nwrites/etc/fork-kit/agent-guards-approval.json(root-owned,0644, atomic) with only the SHA-256 of a random code and an end time (at most 24 h), and prints the code. (Round 2
binds it to one command, one folder and one use: see below.)
The command carries
#owner-approved:actions-disable:<code>. An agent cannot write the file and cannot guess the code;a nested session gets nothing it did not already have. The file is read under the machine file's rules (owner,
mode, no links); anything wrong is no approval. The old variable is not read any more. Who can become root without
a password (sudo
NOPASSWD, thedockergroup) can still write it:self-checkwarns about both and the README says so.Nested sessions (lens B minor). Managed hooks run in a nested
claude -peven withdisableAllHooksin a user or--settingsfile, so those pass.claude --bare/--safe-mode/CLAUDE_CODE_SIMPLEandcodex(except login,logout, help, completion, version) run no managed hooks, so starting one is refused (the owner's approval opens it). Round 2 widens this and says what
it is not: see below.
Bash|Monitor; the guard reads Monitor events;checkhas a Monitor case and reports a Bash-only wiring as MISSINGWrite|Edit|MultiEdit|Bash|MonitoronFailure: blockon the closed hook; a missing or empty hook file refuses too--bare,CLAUDE_CODE_SIMPLE,codex execcheck --settingsas rootenforcement=evaluatedisabled(fields, JSON body, GraphQL)self-checkwarning + README--no-settingsself-checkrefuseScriptsrow drops allsystemMessage(and PreToolUse context) on stdout as well as stderrvp checkensure_dirchmods an existing/etc/claude-codewiring.oursis loosecheckwrites the real log and cacheHOME[ -s ])Not fixed (nits):
t3-capacityis one machine's name. It is the old value the hooks had; amachine sets its own in
capacityPipe.commands. Changing the default would silently turn the guard off where itruns today.
bg-guardhas no lock in the short window while both copies are wired during the switch; theREADME says to remove the old entries soon after. Worst case is one extra block.
Lens round 2 fixes
One commit per finding; each new test is named after its finding (
test_r2_<finding>_...) and fails on theround-2 head 6d5047d (19 of 19: run there with the new test files copied in).
sudo agent-guards approve --command '<cmd>' [--cwd DIR]keeps the SHA-256 of the normalised command (marker off, runs of blanks as one) and the real folder next to the code's hash (approval file version 2). The guard passes only that command, in that folder, once: the first run records the use (approval-used-<hash>in the guard's state folder, written as a temp file then linked, so two runs at once cannot both win); a second run, or any other command with the code, is refused. A code seen in a transcript, the app's database orpsopens nothing else. README, docstring and this body no longer say "one-time code" for the old behaviourtest_r2_major2_*(6 in actions-disable, 1 in wiring).../claude/versions/<v>, the@anthropic-ai/claude-codeand@openai/codexpackages), a link to or a copy of the installed program,npx/bunx/pnpm dlx/npm exec/bun x/node <cli>,$(which claude), a name the same command gives one (ln -s), and insidepython -c,node -e,perl -e,at,systemd-run(the same token layer as for gh).CLAUDE_CODE_SIMPLEin the command, throughenv -S, in a sourced file, inBASH_ENV/--rcfile, and in the user's shell start files. (b) The threat model below, in the README ("What the guards are and are not") and the guard's docstringtest_r2_major1_*(4)-F,-f,--raw-field,--field=,i[enforcement], a JSON--inputfile) are read like the REST fields, so EVALUATE is refused like DISABLEDtest_r2_minor1_*/proc/<pid>/exe, the script node runs, an installedclaude), not the name. The uninstall's own parent session is no longer skipped: run from inside a session that has the hooks, it refuses ("run uninstall from a terminal"). A refusal for a hand-wired entry is remembered (/etc/agent-guards/hand-wired-seen.json, removed with/etc/agent-guards), so the next run still counts every session older than itself; so does a run where the drop-in was never on. The project.claude/settings*.jsonof each running session's folder (and the folders above) is searched tootest_r2_minorB2_*,test_r2_minorA1_*,test_r2_minorA2_*(3),test_r2_state_*codex -m o3 exec xis refused ascodex exec;codex mcp listpasses (MCP setup, no session);npx -y @openai/codex exec xis refused;codex mcp-serverstays refusedtest_r2_nit_codex_*onFailure--safe-moderefusalagent-guards hooksroute). The reason is in the README and docstringtest_r2_major1_*Also: origin/main merged twice (seam check
fork-seam-check.cjs --config-ref origin/main origin/main HEAD= 0).What the guards are and are not (threat model)
The guards stop mistakes and casual misuse by an agent: a command typed from habit, a step copied from an old
note, a short cut it was told not to take. Each refusal says why. They are not a security boundary against a
hostile agent: they read shell text before it runs, and text can be built so that no reader sees what it does
until it runs (words made at run time, a program the guard does not know, an MCP tool that starts a session, a file
read by a file the command sources).
The real boundary is the GitHub permissions of the token the agent holds. Recommended setup: agents get a
fine-grained token for their repos without Actions (write) and Administration (write), so turning off a workflow,
Actions or a ruleset fails at GitHub whatever command asks for it; the token that can do that stays with the owner.
The guards then catch the mistake earlier, with a reason, and the token holds when they miss one.
Not covered (known, by design of a text check): other agent programs; an MCP tool or app that starts a session
(another provider's child, for example); command words built at run time with no
claude/codexin the text;files read in turn by a sourced or start file; a copy of the Claude Code program under another name in a folder
uninstall does not know (uninstall matches the program's real path, the package path and installed
claudelinks, not file contents). The approval's use record is in the agents' user's state folder: an agent that sets out
to can delete it, and can then only repeat the one approved command, in the approved folder, until the end time.
Unfixed nits: the machine-file note is not merged across hooks within one call (each hook is its own process;
merging needs shared per-call state, not worth it for a note meant to be fixed quickly).
Round 2 state question
approvetwice: the second replaces the first (the first code stops working). The approvedcommand run twice: the second run is refused ("used already"); a second hook run for the same tool call passes.
Uninstall again after any refusal: the drop-in stays gone, the hand-wired record stays, the session check runs again.
approvekilled: a stray temp file at worst, never a half approval file (temp, fsync, rename).The guard killed while recording a use: no use record and no half file (temp then link), so the approval is still
unused, never half used. Uninstall killed after writing the hand-wired record: the next run counts more sessions
as older, never fewer.
or empty hand-wired record counts as seen now; no machine file gives the defaults.
Round 2 test run (this head, each file through
heavyaftert3-capacity 1536said OK)actions-disable 115, agent-slots 6, bg-guard 9, capacity-pipe 22, config 15, install 20, memory-index 14, wiring
21, common/free_contract 17, common/kit_install 127, common/machine_file 27: all OK.
Tests (state question included)
New and changed tests are failing-first against the head before this round. They cover:
over, a group-writable file, a link, broken JSON, more than 24 h;
claude -p,claude --bare,disableAllHooks,CLAUDE_CODE_SIMPLE,codex exec, andmentions that only name them;
a G4b section, a broken key of another hook, a bad
refuseScriptsrow;onFailure), an empty or missing guard file;session running, stopped after the drop-in is gone; the rollback; a managed folder others can write;
check --settingsas root with a group-writable file and a link;checkleaves the realHOMEuntouched.General vs project
General (this PR): all hook code, the settings entries, the installer, the approval, the checks and the tests.
Nothing in it names a project, a person or a machine path.
Project or machine (not in this PR): the facts in the machine file section. These are the capacity command's
name, the memory budget, the orchestrator's sessions file and queue, and a project script that must not run with a
given flag. A project's own copies of these hooks are deleted in a follow-up on that project's side, after the
machine switches to the kit. This kit's
agent-slotsis unrelated to the T3 app's ownagentSlotssetting.Not in this PR (G4b): new hooks for further rules (no CI-skip marker in commit messages, no
git stashinworktrees, no bare CLI against a live database).
🤖 Generated with Claude Code