Repository navigation
build(hooks): enforce the shared-tree, brief and dotnet rules - #2778
Merged
Merged
Conversation
guard-shared-tree.sh (PreToolUse, matcher Bash) denies, with exit 2 and a message naming contract §9 and the safe alternative: - git checkout/restore/clean/stash/reset/switch whose worktree is the repository's main worktree (git-dir = common-dir), resolved from git -C, --work-tree, a preceding cd/pushd, or the input cwd; linked worktrees (.claude/worktrees/*, scratchpad worktrees) are allowed; - rm of a path in the main worktree, except .claude/tmp/ and .NET bin/ obj/ beside a *proj (build_tools/bin/ is tracked source); - git add -A/--all/-u/--update/. and git commit -a/--all in any worktree of this repository (-u and commit -a stage a peer's hunks exactly as -A does); - a forced push unless it has --force-with-lease and --force-if-includes and every pushed ref is claude/* (never dev, mainline, --mirror). shell_commands.py splits a command into the simple commands bash runs (lists, pipes, subshells, $(...), backticks, bash -c, eval, VAR=v and env/sudo/timeout/xargs prefixes, heredoc bodies dropped). The header states what it cannot see. 78 new harness cases. Mutation record (bash .claude/hooks/test-hooks.sh, restored with cp+cmp): - break: main_tree() drops the git-dir = common-dir test -> 12 FAIL (every linked-worktree allow case); restore -> 0 FAIL - break: main_tree() returns False -> 29 FAIL (every main-tree deny); restore -> 0 FAIL - break: lease rule requires only --force-with-lease -> 1 FAIL (deny: git push --force-with-lease origin claude/x); restore -> 0 FAIL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
enforce-dotnet-serialized.sh now walks the simple commands (shell_commands.py) and blocks one whose program is dotnet by any path and whose first non-option argument is build, test, vstest, run, format, pack, publish, msbuild, clean or stryker. The "mentions dotnet-serialized anywhere" escape is gone: the wrapper is a different program, so it passes, and a raw call beside it is blocked. Closes the three measured bypasses (/root/.dotnet/dotnet build; echo dotnet-serialized; dotnet test; dotnet vstest) and the documented false positive (grep "dotnet build" docs/ is an argument, now allowed). Exemptions kept: dotnet watch, --version, tool, <app>.dll. Mutation record (bash .claude/hooks/test-hooks.sh, restored with cp+cmp): - break: match argv[0] == dotnet only (no path) -> 2 FAIL; restore -> 0 FAIL - break: drop vstest from the verbs -> 1 FAIL; restore -> 0 FAIL - break: reinstate the mentions-dotnet-serialized escape -> 2 FAIL; restore -> 0 FAIL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
require-agent-brief.sh (PreToolUse, matcher Agent|Task) denies a spawn
whose tool_input.prompt lacks either key sentence of the contract §9
block ('REPORT `git status`; do not "make it clean".' and 'Restore a
mutation-test from the copy you made (`cp`), never from git.'), compared
after dropping leading whitespace and `>` markers and collapsing
whitespace, so a quoted, indented or re-wrapped paste passes and a
paraphrase does not. The denial carries the block, read from the
contract. Exempt: fork (inherits context), web-fetch, claude-code-guide,
statusline-setup (cannot touch the repository); an absent type is
general-purpose. A harness case pastes the contract's own block, so
drift between hook and contract goes red.
plan-flow's brief list now asks for the block verbatim instead of a
paraphrase that this hook would deny (and drops the dotnet-serialized
reminder the block carries); dogfood-analyze and dogfood-analyst's
spawn templates say to append it. Procedure bytes 145556 -> 145434,
baseline lowered.
Mutation record (bash .claude/hooks/test-hooks.sh, restored with cp+cmp):
- break: check only the first key sentence -> 1 FAIL (deny: the block
with its cp/restore line dropped); restore -> 0 FAIL
- break: add Explore to the exemptions -> 1 FAIL; restore -> 0 FAIL
- break: compare without stripping `>` markers -> 1 FAIL (allow: the
block as quoted in the contract); restore -> 0 FAIL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Where CLAUDE.md or a counted skill restated a rule that guard-shared-tree.sh, require-agent-brief.sh or enforce-dotnet-serialized.sh now enforces, the restatement becomes a pointer; obligations no hook enforces stay (staging a file a peer also edited, force-pushing only a branch this session created and only to rewrite its own unmerged commits, the sandbox flag, the probe skills, never tidying a linked worktree a lead shares with its agents: contract §9). Contract §9's block itself is unchanged. Measured (scorecard_metrics.py): procedure bytes 145434 -> 145082 (145556 at the lane's base), CLAUDE.md bytes 9304 -> 9205; baseline lowered with --lower. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
The hooks job comment said 61 cases in about 13 s; the harness now has 186 (183 passed + 1 skipped without ruff, measured with PATH=/usr/bin:/bin) in about 20 s, and needs git for the shared-tree cases. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
guard-shared-tree.sh denied every checkout/switch/stash in the main
worktree, which is a cloud session's only checkout: the skills' own
set-up lines (create-plan, verify-plan, bump-version: git switch -c
claude/x origin/dev, git checkout dev, git stash list) exited 2.
The main-worktree verb rule now splits on the hook input's agent_id,
which the hooks docs say a subagent's PreToolUse input carries:
- a subagent: every checkout/restore/clean/stash/reset/switch is denied
but stash list/show, as before;
- the lead: branch moves and creation are allowed (git refuses them when
they would overwrite local changes); denied are restore, clean without
-n/--dry-run, stash but list/show, reset but --soft, checkout/switch
with -f/--force/--discard-changes/-m/--merge/--ours/--theirs/-p/
--patch, and checkout with a pathspec: --, ., or an argument that is
neither a commit (rev-parse --verify <arg>^{commit}) nor a
refs/remotes/*/<arg> DWIM name.
The rm, add -A/./-u, commit -a and forced-push rules are unchanged.
compiler-audit's italic paraphrase of the §9 block, which
require-agent-brief.sh would deny, becomes a pointer to paste the block.
Harness 186 -> 235 cases; the CI comment says so.
Mutation record (bash .claude/hooks/test-hooks.sh, restored with cp+cmp):
- break: ignore agent_id (agent = False) -> 12 FAIL (every [agent] deny
of a lead-allowed form); restore -> 0 FAIL
- break: is_commit() returns True (every checkout argument a branch)
-> 2 FAIL (deny: git checkout src/a.cs; git checkout dev src/a.txt);
restore -> 0 FAIL
- break: DWIM lookup searches refs/nowhere/ -> 1 FAIL (allow: git
checkout claude/remote-only); restore -> 0 FAIL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Independent review of #2778 (merge after fixes): - rm: a target the text cannot resolve ("$tmp" from mktemp, a loop variable, an unset variable) is skipped, not read as the cwd; rm of the main worktree itself or a directory above it (., ./, .., its path, a glob matching it) is denied for anyone; a directory under .claude/worktrees/ that git worktree list does not register may go. - Here-documents: shell_commands.py strips bodies in a pre-pass at every depth (inside "$(cat <<'EOF' ...)" too), so an odd quote no longer ends parsing and a body line is never a command. On a ParseError the hooks allow only when bash -n refuses the text too; otherwise a whole-string pattern judges it. - Agents: the blanket ban covers the verbs contract §9 names (checkout, restore, clean, stash, reset); git switch is judged by the lead's rules in both modes, so /plan-flow's stage agents can cut and move their branch. - Lead unstaging: restore --staged/-S without --worktree/-W, and reset with paths, are allowed; reset, reset HEAD~1, --hard/--merge/--keep stay denied. - Launchers: time (with options), ionice, taskset, chrt, flock (and -c), strace, watch, parallel, env -S are unwrapped; find -exec/ -execdir/-ok/-okdir are walked and find -delete is read as rm. - GIT_DIR/GIT_WORK_TREE (prefixed or set earlier) and --git-dir decide the worktree; cd -, pushd and popd are tracked; plain and export assignments resolve later $VAR words. Harness 235 -> 317 cases. Mutation record (bash .claude/hooks/test-hooks.sh; each restored with cp, checked with cmp, then 0 FAIL): - M1 break: unknown variable expands to '' -> 3 FAIL; restore -> 0 FAIL - M2 break: no main-toplevel/ancestor rm check -> 15 FAIL; restore -> 0 FAIL - M3 break: heredoc pre-pass removed -> 8 FAIL; restore -> 0 FAIL - M4 break: Hook A parse-failure fallback removed -> 1 FAIL; restore -> 0 FAIL - M5 break: Hook C parse-failure fallback removed -> 1 FAIL; restore -> 0 FAIL - M6 break: agents' git switch banned like the §9 verbs -> 5 FAIL; restore -> 0 FAIL - M7 break: restore --staged not exempt -> 2 FAIL; restore -> 0 FAIL - M8 break: reset with paths not exempt -> 2 FAIL; restore -> 0 FAIL - M9 break: time not a launcher -> 2 FAIL; restore -> 0 FAIL - M10 break: find -exec/-delete not walked -> 5 FAIL; restore -> 0 FAIL - M11 break: stale .claude/worktrees/* not exempt -> 2 FAIL; restore -> 0 FAIL - M12 break: GIT_DIR/GIT_WORK_TREE ignored -> 3 FAIL; restore -> 0 FAIL - M13 break: cd - not tracked -> 2 FAIL; restore -> 0 FAIL - M14 break: ionice/taskset/chrt/flock/strace/watch/parallel not unwrapped -> 9 FAIL; restore -> 0 FAIL - M15 break: agent_id ignored -> 7 FAIL; restore -> 0 FAIL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Second independent review of #2778 (48f7155..9621f22, merge after fixes); each finding reproduced at 9621f22 before the fix: 1. $PWD/$OLDPWD came from the hook process's environment: the walk now seeds PWD from the input cwd (OLDPWD unknown) and sets both on every cd/pushd/popd. 2. (( ... )) and for (( ... )) open an arithmetic frame in the heredoc pre-pass, so `(( y = 1 << 2 ))` no longer swallows the next lines as a here-document (it hid `git reset --hard` and `dotnet test`). 3. Long options are read as git reads them: a unique prefix of a judged subcommand's option (--force-w, --force-with-lea --force-if-incl, --mirr, checkout --forc, switch --discard, restore --work, add --al) is that option; an ambiguous one is left as typed (git refuses it). 4. `rm -f <symlink to the repo>` without a trailing / judges the link (parent realpath + name), not its target. 5. NAME=( ... ) is one array word, not a subshell of commands. 6. Header: find-based bin/obj cleanup through `{}` is a known false deny; the allowed form names the output directory. 7. ${ ... } opens a frame in the pre-pass: a << inside it is not a here-document. Not changed (8): agents may still git switch the shared tree; the lead puts it to the owner. Harness 317 -> 351 cases. Mutation record (bash .claude/hooks/test-hooks.sh; each restored with cp, checked with cmp, then 0 FAIL): - M16 break: no (( frame in the pre-pass -> 5 FAIL; restore -> 0 FAIL - M17 break: no unique-prefix map -> 9 FAIL; restore -> 0 FAIL - M18 break: no PWD/OLDPWD seed -> 2 FAIL; restore -> 0 FAIL - M19 break: top/ancestor check always follows symlinks -> 1 FAIL; restore -> 0 FAIL - M20 break: NAME=( ... ) read as a subshell -> 2 FAIL; restore -> 0 FAIL - M21 break: no ${ frame in the pre-pass -> 1 FAIL; restore -> 0 FAIL (0 FAIL at first: the parse-failure fallback caught the cwd-is-main case, so a case run from outside the main worktree was added) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Third independent review of #2778 (9621f22..2896c9b, merge after fixes); each finding reproduced at 2896c9b before the fix: 1. Regression from 2896c9b: NAME=( ... ) kept its text but dropped the $(...) and backticks inside, so a=($(git reset --hard)) and b=($(dotnet test)) passed. The array's words are now tokenized and their substitutions walked. 2. $(...) and backticks inside an unquoted ${...} or a $((...)) are walked (echo ${x:-$(git reset --hard)}, : ${x:=`git stash`}, echo $(( $(git stash) + 1 ))). 3. A bare { inside ${...} no longer nests, in the pre-pass and in the tokenizer's ${ match (bash prints `{` for ${x:-{}); a nested ${ still does. `echo "${x:-{}"` no longer turns a later heredoc body into code. 4. pushd/popd follow bash's directory stack: +N/-N rotate (pushd) or drop (popd) entry N, a bare pushd swaps the top two; out of range or -n leaves the cwd unknown. 5. destroys() reads options only before `--`: `git restore -S -- --worktree` unstages a file named --worktree. Harness 351 -> 375 cases. Mutation record (bash .claude/hooks/test-hooks.sh; each restored with cp, checked with cmp, then 0 FAIL): - M22 break: array substitutions not collected -> 4 FAIL; restore -> 0 FAIL - M23 break: ${...} substitutions not collected -> 4 FAIL; restore -> 0 FAIL - M24 break: $((...)) substitutions not collected -> 2 FAIL; restore -> 0 FAIL - M25 break: pre-pass ${ frame counts a bare { -> 2 FAIL; restore -> 0 FAIL - M26 break: tokenizer ${ match counts a bare { -> 1 FAIL; restore -> 0 FAIL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Fourth independent review of #2778 (2896c9b..925108f, merge after fixes); each finding reproduced at 925108f before the fix. The class: when the model lost track (an unknown cwd, a parse limit) the verdict was allow. Now it is deny. A. An unknown cwd is judged as the main worktree for git commands not pointed at a known path (-C, --git-dir/GIT_DIR, --work-tree/ GIT_WORK_TREE); rm's unknown-target skip is unchanged. Known false deny, in the header: cd "$X" && git reset --hard from a linked worktree (allowed form: git -C <path> ..., or a literal cd). pushd/popd now model bash exactly: -n edits the stack without a cd, a refused call (empty stack, one entry, N out of range) stays put; `pushd; git stash` (a regression from 925108f) is denied again. B. Parse limits fail closed: past 8 nested substitutions, or at Python's recursion limit, the walk raises ParseError, so bash -n and the whole-string fallback decide; the fallback applies rules 3-4 (add -A/./-u, commit -a, a forced push without both lease flags or to dev/mainline) in every worktree of the repository, rules 1-2 in the main worktree. C. <(...) and >(...) inside ${...} and arrays are walked (both hooks). D. $'...' with \' is skipped whole by _match_close and _match_brace (and by the pre-pass's ${ frame). E. _match_brace's $(...) skip is pinned by a case out of the fallback's reach. Harness 375 -> 407 cases. Mutation record (bash .claude/hooks/test-hooks.sh; each restored with cp, checked with cmp, then 0 FAIL): - M27 break: A, an unknown cwd not judged as main -> 3 FAIL; restore -> 0 FAIL - M28 break: A, pushd/popd -n read as plain pushd/popd -> 3 FAIL; restore -> 0 FAIL - M29 break: B, depth limit returns instead of raising -> 3 FAIL; restore -> 0 FAIL - M30 break: B, fallback rules 3-4 only in the main worktree -> 2 FAIL; restore -> 0 FAIL - M31 break: C, <(...)/>(...) in ${...}/arrays not collected -> 5 FAIL; restore -> 0 FAIL - M32 break: D, $'...' escapes not skipped -> 2 FAIL; restore -> 0 FAIL - M33 break: E, _match_brace does not skip $(...) whole -> 1 FAIL; restore -> 0 FAIL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Review round 6 of the process hooks (class rule: whenever a hook cannot judge, it denies). 1. Input. All three hooks passed the hook input through an environment variable to `exec python3`; at 128 KiB exec failed with exit 126, which does not block. python now reads stdin; unreadable input (not JSON, no string command or prompt) is denied; an internal error pattern-checks the whole text (Hook A: every rule in any worktree; Hook C: the raw dotnet pattern, a superset of dev's grep); a python3 that fails to start or dies is denied by the shell wrapper. bash_accepts feeds `bash -n` on stdin. Each header states the policy. 2. An unresolvable GIT_DIR / --git-dir / GIT_WORK_TREE / --work-tree is judged as the main worktree. `env -C` / `--chdir` and `sudo -D` set the command's cwd (the last -C of one env wins, as GNU env does). 3. A shell's literal here-string or here-document script is walked (here-documents are now inlined as `<<<` words: quoted bodies as data, unquoted bodies with their $(...) walked). A script read from a pipe, a `<` file, `-s`, `<(...)`, and eval / bash -c / `$X args` of a string the text does not show, goes to an `opaque` callback: the whole text is pattern-checked where it runs (unknown: as main). argv[0] is expanded from known assignments (`G=git; $G reset`). Fixed on the way: `<<<` was read as `<<` at its second `<`, so `cat <<< x` swallowed the following lines up to a line `x`. `bash -o pipefail -c '...'` now finds the script. Aliases, `source` and scripts run by path stay out of scope (headers). 4. pushd/popd: OLDPWD moves only when bash changes directory (a refused one, any -n, and popd +N of a non-top entry do not; pushd +0 does, as in bash). After any -n the stack below the top is unknown, so a later rotation or pop gives an unknown cwd (fail closed). Each new case's verdict was checked against real bash. 5. Fallback cases from a linked worktree past the parse limit: lease push to dev (deny) / claude/x (allow), commit -am and commit -a -m (deny). 6. $(mktemp [-d] [-q] [-t] [--suffix=]) is a fresh path in $TMPDIR (-p, --tmpdir=DIR or a template without -t stay unknown); $(git rev-parse --show-toplevel) is the tracked cwd's toplevel; a directory `git init` / `git clone` creates earlier in the text (absent or empty at hook time) is a new repository. The three positive controls pass; the rev-parse command still denies in main. 7. implementer.md points at `.claude/scripts/dotnet-serialized format whitespace` (or /format); implement-plan's task says "Run /format". Procedure bytes 145082 -> 145065 (baseline lowered), CLAUDE.md 9205 unchanged. Two existing cases change direction by these rulings: `pushd -n WT; pushd +1; git reset --hard` (agent, main) is now denied (unknown stack after -n), and `cd "$(mktemp -d)" && git stash` now names a known tmp path, so the unknown-cwd case uses `mktemp -d -p "$X"`. "bad stdin: allow" and "no prompt string: allow" are now denials. Harness: 407 -> 490 cases (487 + 1 skip without ruff on PATH). Mutation record (break -> red; restore with cp, cmp identical; batch green at 490/490): M34 A reads input from an env var (wrapper kept) -> 1 red (200 KB allow) M57 A as round 5: env var + exec, no wrapper -> 3 red (200 KB deny/allow, no python3) M35 C reads input from an env var -> 1 red (200 KB allow) M36 B reads input from an env var -> 1 red (200 KB allow) M37 A wrapper replaced by exec -> 1 red (python3 missing) M38 A internal-error path allows -> 1 red (NUL byte case) M39 A allows unreadable input -> 2 red M40 unresolvable git dir / work tree not main -> 5 red M41 env -C / sudo -D ignored -> 7 red M42 env -C cumulative, not last-wins -> 2 red M43 A ignores opaque scripts -> 8 red M44 A judges an opaque script at the input cwd -> 1 red M45 shell here-string script not walked -> 6 red M58 <<< read as << (round-5 behaviour) -> 2 red M46 argv[0] not expanded from assignments -> 2 red M47 unquoted here-document body read as quoted -> 1 red M48 C ignores opaque scripts -> 3 red M49 OLDPWD moves on refused / -n / non-top pops -> 2 red M50 -n leaves the stack known -> 1 red M51 fallback lease push to dev/mainline allowed -> 1 red M52 fallback commit -a pattern removed -> 2 red M53 $(mktemp ...) unknown -> 2 red M54 $(git rev-parse --show-toplevel) unknown -> 1 red M55 init/clone target still this repository -> 2 red M56 existing non-empty init target made a new repo -> 2 red Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Review round 7 of the process hooks (#2778): the three blocking findings and five cheap residue items. B1. shell_args: in a bundle each o / O takes the next argument, as bash reads it (-euo pipefail -c '...', -co pipefail '...', -Oc extglob '...'). `bash -eo pipefail -c "dotnet build"` was allowed by the PR and blocked by dev's grep hook; now blocked. B2. A shell given a script-file operand (`bash run.sh`, `sh x.sh`), and `source` / `.`, go to the opaque callback: the whole text is pattern-checked where the script runs, so a script written and run in the same text is blocked by Hook C (as dev blocked it) and denied by Hook A; `bash build_tools/x.sh` with no guarded verb in the text stays allowed. B3. A program word is opaque only with a real expansion (`\$[A-Za-z_{(0-9@*#?!$-]` or a backtick); a bare or trailing `$` is literal. Both `[[ ... =~ ...(a|b)$ ]]` commands are allowed controls. `[[ ]]` is not parsed as one unit (not cheap); the docstring says so. R1. Hook A's whole-text patterns split the text at newlines and ; & | first and search each segment in steps from its first `git` (verb after it, flag after the verb): no nested unbounded quantifiers. 2,000 x `git add x` on one line plus an opaque forced push: 158 s before, 82 ms after (harness case, under `timeout 20`, must deny in under 5 s). R2. The fail-closed paragraph names what it covers: unreadable input, internal errors and a dead python3; text it cannot follow is pattern-checked, so `eval "$X"` with nothing visible is allowed. R3. `pushd -n DIR` puts DIR below the top and a bare `popd -n` drops the entry below it, exactly; only -n with +N/-N loses the stack. `pushd -n WT; pushd +1; git reset --hard` (agent, main) is allowed again, its expected value before round 6. R8. `bash -s -- a b <<EOF` walks the here-document as the script. R9. $(git rev-parse --show-toplevel) is cached per directory. Headers' known gaps gain: the init/clone rule trusts a step that can fail at run time (R4); a symlink made in the same text (R5); with no python3 every command is denied (R7). Hook C's header now states its relation to dev's grep hook exactly: it blocks everything that hook blocked except a dotnet verb that is only an argument and the out-of-scope launchers and subprocesses it names. Hook C vs dev over the reviewer's 715-command corpus: 17 dev-only blocks before, 15 after (the two B2 scripts fixed). The 15: argument mentions (echo x2, grep x2, cat|grep, commit message x2) and out-of-scope launchers or subprocesses (docker exec, make, npm run, script -c, ssh, su -c, python3 -c, python3 - <<EOF). Harness: 490 -> 509 cases (506 + 1 skip without ruff on PATH). Mutation record (break -> red; restore with cp, cmp identical; batch green at 509/509): M59 B1 a bundle's o/O takes no argument -> 3 red M60 B2 a shell's script-file operand not opaque -> 3 red M61 B2 source / . not opaque -> 2 red M62 B3 any $ makes argv[0] opaque -> 2 red M63 R1 nested whole-text patterns restored -> 1 red (timing case) M64 R3 every -n loses the stack -> 1 red M65 R8 -s does not make stdin the script -> 1 red Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Review round 8 of the process hooks (#2778), one item. B4: round 7 made every script file opaque, so the whole text was pattern-checked and everyday commands were denied, CLAUDE.md's own cloud prefix first: `. .venv/sharpy-env.sh && git stash list` (lead, main) exit 2, and Hook C blocked `. .venv/sharpy-env.sh && git commit -m "fix: dotnet test flake"`. A script-file operand of a shell, and of `source` / `.`, is now opaque only when the text may have made it: - the same text writes that path: a `>`, `>>`, `>|`, `&>`, `<>` or `>&` target, a `tee` file, or a `cp`/`mv`/`install` destination (including -t DIR and a destination directory), resolved against the tracked cwd; - the path does not exist when the hook runs (or cannot be resolved). An existing script the text does not write (.venv/sharpy-env.sh, build_tools/*.sh, .claude/hooks/test-hooks.sh) is a program like any other, out of scope as before round 7; the headers say so. `source <(...)` / `. <(...)` stay opaque (the first draft of this fix dropped them; the corpus diff caught it). Round 7's script cases stay red (run.sh, .claude/tmp/r.sh, t.sh, x.sh). Positive controls, allowed: the four reported commands, `source .venv/sharpy-env.sh && git switch dev`, `bash build_tools/regenerate_spy_stdlib.sh && git switch -c claude/z`, `bash .claude/hooks/test-hooks.sh && git switch -c claude/h`, `. .venv/sharpy-env.sh && grep -rn "dotnet build" docs/` (Hook C), and `. .venv/sharpy-env.sh && rm -rf .claude/tmp/probe`. New denials pin each clause: an existing script rewritten by >, tee, cp, mv and install -t, and a missing script made by an unseen python3 step. Known gaps added to the headers: a program named by ANSI-C escapes ($'\x67it') (R12), and `[[ $b =~ ($X|y) ]]` read as `$X` naming a program (R13, a pattern-checked false deny). Hook C vs dev over the reviewer's 715-command corpus: 15 dev-only blocks, the same list as round 7 (argument mentions and the out-of-scope launchers and subprocesses the header names). Harness: 509 -> 528 cases (525 + 1 skip without ruff on PATH). Mutation record (break -> red; restore with cp, cmp identical; batch green at 528/528): M66 every script file opaque (condition removed) -> 10 red (controls) M67 no script file opaque (condition always false) -> 12 red (round-7 cases) M68 written-path clause dropped -> 6 red M69 missing-path clause dropped -> 1 red M70 tee / cp / mv / install writes not recorded -> 4 red M71 redirection writes not recorded -> 2 red M72 source / . of <(...) not opaque -> 2 red Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Review round 8b of the process hooks (#2778). Hook C walked with the hook process's own directory (os.getcwd()), while Hook A uses the input's cwd. Round 8 resolves relative script paths against the walk's cwd, so Hook C's verdict depended on where the hook process ran: with the process in a tree without .venv/ and the input cwd in one with it, `. .venv/sharpy-env.sh && echo "dotnet test"` was blocked, and the absolute-path spelling allowed. `cd` tracking had the same mismatch, which a subagent in a linked worktree meets (Claude Code runs hooks from the session's directory). Hook C now walks with the input's cwd, falling back to os.getcwd() only when the input has none; a cwd that does not exist is unknown (relative paths unresolved, so a relative script there is pattern-checked). Harness cases run Hook C from a process cwd different from the input cwd: a relative `. <existing script>` plus an argument mention is allowed; the same script missing in the input cwd (present in the process cwd) is blocked; relative written-in-text scripts are blocked. Harness: 528 -> 532 cases (529 + 1 skip without ruff on PATH). Mutation record (break -> red; restore with cp, cmp identical; green at 532/532): M73 Hook C walks with os.getcwd() again -> 2 red Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Conflict in build_tools/scorecard-baseline.json: took dev's allowlist values (allowlist_rows_outside_seed 2184, allowlist_rows_seed 2368, owner- ruled in #2767); procedure_bytes and claude_md_bytes re-measured on the merged tree with scorecard_metrics.py (145065 and 9205, this lane's prose cuts) and written with --lower. scorecard_metrics --check: OK. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
Owner, 2026-11-20: "i agree with this all. run the inventory", then "let's go with your recs" on its result. The recommendations were to move three process rules from prose into PreToolUse hooks and cut the prose they replace.
What was enforced before this PR:
Contract §9: nothing. §9 says agents must not run destructive git or
rmin the shared tree, and that every agent brief carries its block. Prose failed at this twice before (the contract's own Why).enforce-dotnet-serialized.sh: three bypasses, each measured to exit 0:/root/.dotnet/dotnet build;echo dotnet-serialized; dotnet test;dotnet vstest.It also had false positives on any command that only mentions a verb:
grep "dotnet build" docs/, or a commit message.This PR changes
.claude/hooks,.claude/settings.jsonand.github/workflows/python-build-tools.yml(a comment only), so it goes to the owner before merge.Change
.claude/hooks/shell_commands.pySplits a Bash command into the simple commands bash would run, each with its directory and environment. It handles:
if/while/until/case/for, functions and(( ));$(...), backticks and process substitution, including inside arrays and${...};bash -cwith bundled options (-euo pipefail -c);evalof literal text, andsourceof a script the text has not written;env/sudo/timeout/time/nice-style prefixes,env -Candsudo -D;cd/pushd/popd(the stack is modelled;-n ±Nmakes it unknown),mktemp, andgit init/clonetargets.When the walk loses track, it fails closed. That covers:
GIT_DIR;evalof non-literal text, a script the text writes or that does not exist, orsource <(...).In each case the command is still judged: unknown locations are treated as the main worktree, and unreadable text gets a whole-text pattern check.
guard-shared-tree.sh(matcherBash)Subagents in the main worktree (
agent_idpresent in the hook input) may not runcheckout/restore/clean/stash/reset. Allowed:stash list/show,switch <branch>andswitch -c(§9 forbids only the destructive forms).The lead in the main worktree may move and create branches. It may not run a form that destroys uncommitted work:
restore;cleanwithout-n;stashother than list/show;resetother than--soft;checkout/switchwith a force, merge, ours/theirs or patch flag;checkoutof a pathspec.Git's unique-prefix long options (
--forc) are resolved against git 2.43's option table.rmis denied in the main worktree, except under.claude/tmpand a .NETbin/objnext to a project file.In any worktree, these are denied:
git add -A/./-uandgit commit -a(each stages a peer's hunks);--force-with-leaseand--force-if-includes, or to a ref other thanclaude/*.Other rules: linked worktrees are otherwise not judged. Input it cannot read, an internal error or a missing
python3deny.require-agent-brief.sh(matcherAgent|Task)fork,web-fetch,claude-code-guideandstatusline-setupare exempt.enforce-dotnet-serialized.shJudges each dotnet call bash would run:
/usr/bin/dotnet,"$DOTNET_ROOT/dotnet",\dotnet,dotnet.exe);vstest;bash -c.It no longer blocks a command that only mentions a verb as an argument (
echo,grep, a commit message). The mentions-the-wrapper escape is gone. It walks in the input'scwd.Prose cut where a hook now enforces the rule
Measured, baseline lowered with
--lower:CLAUDE.md9,304 → 9,205.Each deleted sentence and where its rule now lives:
CLAUDE.mdserialized dotnet → Hook C.CLAUDE.md"Tell agents never run git checkout/…" → the §9 block plus Hooks A and B.CLAUDE.mdforce-push flags and refs → Hook A. "A branch this session created" and "never another session's commits" stay as prose.git add -Aban → Hook A. The peer-hunk warning and the--cached --statcheck stay.implementer.mdnow say to paste the §9 block verbatim rather than paraphrase it.implement-plan's "do not stash, restore, or clean" is kept: Hook A does not judge linked worktrees, which a lead's agents may share.What it costs
Workflow commands. Every Bash command block in
dev's.claude/skills,.claude/agents,CLAUDE.mdanddocs/process(149) was run through Hooks A and C at13c7b20e5. Each block ran three ways: as the lead in the main worktree, as an agent there, and as an agent in a linked worktree. Hook A denies none. Hook C blocks one:implementer.md's block, which runs a rawdotnet format whitespace. Dev's hook let it through only by the mentions-the-wrapper escape this PR removes. This PR rewrites that line to the wrapper.Hook C against dev's hook (715 commands, @
70fc8bd5c):echo dotnet test,grep "dotnet build" docs/x.md,git commit -m "run dotnet test", …ssh h "dotnet test",docker exec,make,npm run,script -c,su -c,python3 -c/heredocos.system/usr/bin/dotnet test,D=dotnet; $D test,f() { dotnet test; }; f,x=$(dotnet build),bash -lc 'dotnet test',printf 'dotnet test\n' > t.sh && bash t.sh, …Round 8b changed only which directory Hook C walks in, so the comparison still holds at the head.
Known false denies, each named in its hook's header, with a workaround:
find src -name bin -type d -exec rm -rf {} +cd "$X" && git reset --hardfrom a linked worktreegit -C <path>or a literal pathcat x.sh | bash; git stash list)[[ $x =~ ($X|y) ]](R13)What the hooks cannot see
Each is listed in the hook headers:
eval "$X"with nothing visible to resolve;sourceof an existing file (each is not read);ssh,docker exec,make,npm run,script -c,su -c, and a Python or Node subprocess;find -delete,xargs rm,git rm,mv;SendMessageto a running agent, and whether an agent obeys the block.Residue the reviews named and this PR does not fix:
git init/clonerule trusts a step that can fail at run time.python3, every Bash command is denied (fail closed; the session's environment has it).Mutation record
There are 73 records, M1–M73, one per guard, each in its commit body. Each break turned the harness red; each restore was done with
cp, checked withcmp, and returned to 0 FAIL. The first round's 12 are:main_tree()drops git-dir = common-dirmain_tree()returns False--force-with-leaseagent_idvstestdroppedExploreexempted>strippingGate
13c7b20e5(lane worker, re-run by the lead, measured):test-hooks.sh532 passed / 0 failed / 0 skipped;scorecard_metrics.py --checkOK.dev(afdaa34d6, lane worker, measured):test-hooks.sh532/0/0;pytest build_tools/tests2,283 passed / 0 failed / 1 skipped;scorecard_metrics.py --checkOK. The baseline conflict took dev's two allowlist values (process(plan): plan-777361 (P78) scope decides meaning — draft by the owner's decision (no fifth pass); reviewed, awaiting the owner #2767) and the bytes re-measured on the merged tree (145,065 and 9,205; P78's plan text is not counted)afdaa34d6(measured):hooksjob runs the 532-case harness, plustestanddual-execute-oracle;No C# is touched.
Issues
Closes none, files none.
Independent review
Independent review @ bbc2497: merge after fixes; 1 applied, 2 declined (reasons below); fixes bbc2497..afdaa34 read by the lead
One Opus reviewer, which wrote none of the code, reviewed seven times. It ran the hooks on
git archiveextracts against generated and hand-written commands, and compared them withdev's hooks. Every round returned merge after fixes:48f71558arestore --stageddenied; agentgit switchdenied (the lead's brief was stricter than §9);time -p dotnetallowed9621f22dc9621f22dc(( x << y ))read as a heredoc; git unique-prefix forms (--forc,--force-w) not resolved2896c9b492896c9b49$(...);$(...)in unquoted${}/$(())unwalked925108f7e925108f7epushdmodel's unknown cwd allowedpushd; git stash; depth limit failed open. Every round so far had added an unknown → allow path; the lead's briefs had allowed when unsure. Redesigned to fail closed.78d0b5b9678d0b5b96GIT_DIRwithenv -Callowedc750e38f9c750e38f9-euo pipefail -cunwalked (a regression against dev's Hook C); B2 a written-then-run script weaker than dev; B3[[ =~ (a|b) ]]false deny; R1 a cubic regex (158 s → 0.07 s)bbc2497b2bbc2497b2(narrow). .venv/sharpy-env.sh && git stash listdenied)70fc8bd5cThe lead reproduced each blocking finding on the PR's head before sending it back.
The lead's own re-probe of
70fc8bd5cfound that Hook C walked with the hook process's directory instead of the input'scwd. It was fixed in13c7b20e5(mutation M73).From the last review:
Applied: B4.
Declined:
[[ =~ ]]alternation with a variable): it fails loudly and has a workaround.Both are listed under the gaps above.
The lead read the fixes
bbc2497b2..13c7b20e5against the finding list and re-ran the harness and probes (summarised above). The merge ofdev(afdaa34d6: identical to git's automatic merge except the resolvedscorecard-baseline.json) was read by the lead as well.https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Generated by Claude Code