diff --git a/.claude/agents/dogfood-analyst.md b/.claude/agents/dogfood-analyst.md index 800f0240df..22ed803681 100644 --- a/.claude/agents/dogfood-analyst.md +++ b/.claude/agents/dogfood-analyst.md @@ -139,7 +139,7 @@ Example: ``` Task tool: subagent_type: test-expert - prompt: Create a file-based integration test for [feature]. The .spy source is: ... The expected error is: ... + prompt: Create a file-based integration test for [feature]. The .spy source is: ... The expected error is: ... + the contract §9 block verbatim (hook-enforced) ``` ## Writing Temporary Files diff --git a/.claude/agents/implementer.md b/.claude/agents/implementer.md index 93c43b8e95..0f2c086e99 100644 --- a/.claude/agents/implementer.md +++ b/.claude/agents/implementer.md @@ -47,7 +47,7 @@ All `dotnet` commands go through `.claude/scripts/dotnet-serialized` (requires ` .claude/scripts/dotnet-serialized build sharpy.sln # Build all .claude/scripts/dotnet-serialized test --filter "Category!=Benchmark" --logger "console;verbosity=normal" # LOCAL whole-solution gate, the fallback to /ci-gate (the logger keeps the stall watchdog fed, #2257) .claude/scripts/dotnet-serialized test --filter "FullyQualifiedName~Parser" --no-build # Edit loop -dotnet format whitespace # Format code (auto-formatted on save by Claude hook) +.claude/scripts/dotnet-serialized format whitespace # Format code, or /format (the save hook is best-effort) python3 -c "..." # Verify Python behavior .claude/scripts/dotnet-serialized run --project src/Sharpy.Cli -- emit csharp file.spy # Debug codegen .claude/scripts/dotnet-serialized run --project src/Sharpy.Cli -- emit ast file.spy # Debug parser diff --git a/.claude/hooks/enforce-dotnet-serialized.sh b/.claude/hooks/enforce-dotnet-serialized.sh index 8cfda0e6e8..09326b5327 100755 --- a/.claude/hooks/enforce-dotnet-serialized.sh +++ b/.claude/hooks/enforce-dotnet-serialized.sh @@ -4,21 +4,108 @@ # CLAUDE.md "Serialized dotnet"). Every such invocation must go through # .claude/scripts/dotnet-serialized (exclusive flock lock). # -# Verbs covered: build, test, run (builds the project first — /spy-run, /spy-emit, /quick-check, -# /lsp-hover, /benchmark), format (loads the whole solution workspace), pack, publish, msbuild, -# clean (deletes bin/obj under a concurrent build), stryker (builds + tests repeatedly). -# Not covered: `dotnet watch` (/playground, long-lived by design), `dotnet --version`, `dotnet tool`. -# A script that calls dotnet internally (`bash build_tools/regenerate_spy_stdlib.sh`) is not seen -# by this hook — those scripts take SHARPYC= to stay off the lock. +# Verbs covered: build, test, vstest, run (builds the project first — /spy-run, /spy-emit, +# /quick-check, /lsp-hover, /benchmark), format (loads the whole solution workspace), pack, +# publish, msbuild, clean (deletes bin/obj under a concurrent build), stryker (builds + tests +# repeatedly). Not covered: `dotnet watch` (/playground, long-lived by design), `dotnet --version`, +# `dotnet tool`, `dotnet .dll`. # -# Hook input is JSON on stdin; the command is tool_input.command. +# Each simple command is judged on its own (.claude/hooks/shell_commands.py splits lists, pipes, +# subshells, `$(...)`, `bash -c '...'`, a shell's here-string or here-document script, `eval`, +# VAR=v, `$X` naming the program (`D=dotnet; $D test`), the launchers in its PREFIXES — env, +# sudo, time, timeout, nice, ionice, taskset, chrt, flock, strace, watch, parallel, xargs, setsid, +# nohup, stdbuf — and `find -exec`): it is +# blocked when the program it runs is `dotnet` by any path (`/root/.dotnet/dotnet build`) and its +# first non-option argument is a covered verb. The wrapper is a different program, so it passes, +# and a raw call beside it in the same command (`echo dotnet-serialized; dotnet test`) is blocked. +# `dotnet build` as an argument (`grep "dotnet build" docs/`, `echo dotnet test`) or in a +# here-document fed to a non-shell (`cat > notes.md <`/`>>`/`tee` target, a `cp`/`mv`/`install` destination) or that does not +# exist when the hook runs, so a script written and run in the same text is blocked. Out of +# scope: an existing script the text does not write (`. .venv/sharpy-env.sh`, `bash +# build_tools/regenerate_spy_stdlib.sh`; those scripts take SHARPYC= to stay off +# the lock), a script run by its own path (`./x.sh`), an alias or function, a python/node +# subprocess, a launcher outside PREFIXES (ssh, su -c, script -c, docker exec, make, npm run), a +# program named by ANSI-C escapes (`$'\x64otnet' test`). +# +# FAILS CLOSED when it cannot read the input or run: unreadable input (not JSON, no string +# command) is blocked; an internal error applies the whole-string pattern (a superset of the old +# grep's); a python3 that fails to start or dies is blocked by the shell wrapper (so with no +# python3 every Bash command is blocked). The input is read from stdin by python (no size +# limit). It blocks everything the grep hook it replaced blocked, except a dotnet verb that is +# only an argument (`echo dotnet test`, `grep "dotnet build"`, a commit message) and the +# out-of-scope launchers and subprocesses above. +# +# Hook input is JSON on stdin; the command is tool_input.command, run in the input's cwd (the +# hook process's own directory only when the input has none; a cwd that does not exist is +# unknown). # Falsified by .claude/hooks/test-hooks.sh. -input=$(cat) -cmd=$(printf '%s' "$input" | python3 -c "import json,sys; print(json.load(sys.stdin).get('tool_input',{}).get('command',''))" 2>/dev/null) +read -r -d '' PROG <<'PY' +import json, os, re, sys +sys.dont_write_bytecode = True + +VERBS = {"build", "test", "vstest", "run", "format", "pack", "publish", "msbuild", "clean", "stryker"} +RAW = re.compile(r"(^|[\s;&|(\"'`])(\S*/)?dotnet(\.exe)?[\"')`]*\s+(-\S+\s+)*(" + "|".join(VERBS) + + r")\b") + +def block(verb, why=""): + sys.stderr.write( + "BLOCKED by .claude/hooks/enforce-dotnet-serialized.sh: " + why + "raw `dotnet " + verb + + "` (any of build|test|vstest|run|format|pack|publish|msbuild|clean|stryker) is " + "forbidden: parallel runs OOM the machine. Use the drop-in wrapper instead, same args, " + "same output, same exit code: .claude/scripts/dotnet-serialized test --filter " + "\"FullyQualifiedName~Lexer\" --no-build (lock-free alternative for probes: " + "src/Sharpy.Cli/bin/Debug/net10.0/sharpyc run file.spy)\n") + sys.exit(2) + +def by_pattern(why): + m = RAW.search(cmd) + if m: + block(m.group(5), why) + +try: + data = json.loads(sys.stdin.buffer.read()) + cmd = data["tool_input"]["command"] + # The command runs in the input's cwd, not the hook process's: relative script paths and + # `cd` are read against it. A cwd that does not exist is unknown (relative paths unresolved). + cwd = data.get("cwd") or os.getcwd() + assert isinstance(cmd, str) and isinstance(cwd, str) + cwd = cwd if os.path.isdir(cwd) else None +except Exception as e: + sys.stderr.write("BLOCKED by .claude/hooks/enforce-dotnet-serialized.sh: cannot read the hook " + "input (%s: %s); the hook fails closed.\n" % (type(e).__name__, e)) + sys.exit(2) + +def visit(argv, *_): + if os.path.basename(argv[0]) not in ("dotnet", "dotnet.exe"): + return + verb = next((a for a in argv[1:] if not a.startswith("-")), "") + if verb in VERBS: + block(verb) -if printf '%s' "$cmd" | grep -qE '(^|[;&|[:space:]("])dotnet[[:space:]]+(build|test|run|format|pack|publish|msbuild|clean|stryker)([[:space:]]|$|")' \ - && ! printf '%s' "$cmd" | grep -q 'dotnet-serialized'; then - echo 'BLOCKED: raw `dotnet build|test|run|format|pack|publish|msbuild|clean|stryker` is forbidden (parallel runs OOM the machine). Use the drop-in wrapper instead — same args, same output, same exit code: .claude/scripts/dotnet-serialized test --filter "FullyQualifiedName~Lexer" --no-build (lock-free alternative for probes: src/Sharpy.Cli/bin/Debug/net10.0/sharpyc run file.spy)' >&2 - exit 2 -fi -exit 0 +try: + sys.path.insert(0, os.environ["HOOKS_DIR"]) + import shell_commands as sc + try: + sc.walk(cmd, cwd, visit, + opaque=lambda cwd, what: by_pattern("a script the hook cannot read (%s): " % what)) + except sc.ParseError: + if sc.bash_accepts(cmd): + by_pattern("an unparseable command: ") +except Exception as e: + by_pattern("the hook failed (%s: %s): " % (type(e).__name__, e)) +sys.exit(0) +PY +HOOKS_DIR="$(cd "$(dirname "$0")" && pwd)" python3 -c "$PROG" +rc=$? +case $rc in + 0 | 2) exit "$rc" ;; +esac +echo "BLOCKED by .claude/hooks/enforce-dotnet-serialized.sh: the hook could not judge this" \ + "command (python3 exit $rc); it fails closed." >&2 +exit 2 diff --git a/.claude/hooks/guard-shared-tree.sh b/.claude/hooks/guard-shared-tree.sh new file mode 100755 index 0000000000..6d26881827 --- /dev/null +++ b/.claude/hooks/guard-shared-tree.sh @@ -0,0 +1,573 @@ +#!/bin/bash +# PreToolUse(Bash) hook: the shared-tree contract (docs/design/verification-contract.md §9) and the +# force-push rule (CLAUDE.md › Git & Release), enforced instead of asked for. Denies (exit 2): +# +# 1. In the repository's MAIN worktree (`git rev-parse --git-dir` = `--git-common-dir`), the one +# a session's agents share (a linked worktree — .claude/worktrees/*, a scratchpad `git +# worktree add` — is its owner's own and is never judged here): +# a. a SUBAGENT (hook input has `agent_id`) may not run the verbs §9 names — `git checkout| +# restore|clean|stash|reset` — in any form but `stash list|show`; +# b. the LEAD, and a subagent's `git switch`, may move and create branches (`switch `, +# `switch -c [start]`, `switch --detach`, `checkout `, `checkout -b +# [start]`; git refuses them when they would overwrite local changes) and unstage +# (`restore --staged|-S` without `--worktree|-W`; `reset [-q] [] [--] `), +# but not the forms that destroy uncommitted work: other `restore`; `clean` without +# -n/--dry-run; `stash` but list/show; `reset` without paths, but --soft; checkout/switch +# with -f/--force/--discard-changes/-m/--merge/--ours/--theirs/-p/--patch; `checkout` of a +# pathspec (`--`, `.`, or an argument neither a commit by `rev-parse --verify ^{commit}` +# nor a refs/remotes/*/). +# The docs (code.claude.com/docs/en/hooks, "Hooks in subagents"): "When a subagent calls a +# tool, tool events such as `PreToolUse` and `PostToolUse` fire the same configured hooks as +# in the main conversation, and the input carries the `agent_id` and `agent_type` common +# input fields that identify the subagent." +# 2. `rm` (and `find -delete`, `find -exec rm`) of the main worktree itself or any directory +# above it, for anyone; and of a path inside the main worktree, except under .claude/tmp/, a +# .NET build output (`bin/` or `obj/` beside a *.*proj; build_tools/bin/ is source), and a +# directory under .claude/worktrees/ that `git worktree list` does not register. The path's +# parent decides, so removing a registered linked worktree's root is denied: `git worktree +# remove`. A target the text cannot resolve (a loop variable, an unset variable, a `$(cmd)` +# other than mktemp) is skipped. `$PWD`/`$OLDPWD` are the command's own (input cwd, then +# each cd), never the hook process's. The top/ancestor check reads a target without a +# trailing `/` through its parent's realpath, so `rm -f ` is allowed. +# Known false deny: `find src -name bin -type d -exec rm -rf {} +` (find's `{}` is read as +# `src/{}`); name the output directory instead: `find src/X/bin -name '*.dll' -delete`. +# An UNKNOWN directory fails closed: when the text loses the cwd (`cd "$X"`, a `cd` into a +# substitution, a rotation or pop after `pushd -n +N`), or names a -C, GIT_DIR/--git-dir or +# GIT_WORK_TREE/--work-tree it cannot resolve, the git command is judged as in the main worktree. +# Known false deny: `cd "$X" && git reset --hard` from a linked worktree; name the directory +# instead: `git -C reset --hard`, or `cd `. `$(mktemp [-d])` is a fresh +# path in $TMPDIR, `$(git rev-parse --show-toplevel)` the cwd's toplevel, and a directory that +# `git init ` / `git clone ` creates earlier in the text (one that does not +# exist yet, or is empty) is a new repository, not this one, even if that step fails at run +# time. A symlink the same text makes (`ln -s
x && git -C x reset --hard`) does not +# exist yet when the hook runs, so the command is judged in the directory holding the link. +# 3. Staging without per-file pathspecs, in any worktree of this repository: `git add -A|--all| +# -u|--update|.|./|:/` and `git commit -a|--all`. -u and commit -a are the same hazard as -A: +# they stage every tracked file's changes, a peer's uncommitted hunks included. +# Long options are read as git reads them: a unique prefix (`--force-w`, `--mirr`, `--forc`, +# `--discard`, `--work`, `--al`) is the option it abbreviates, per subcommand (LONG_OPTS). +# 4. A forced `git push` (`--force`, `-f`, `--force-with-lease`, `+refspec`, `--mirror`) unless it +# carries both `--force-with-lease` and `--force-if-includes` and every pushed ref is +# `claude/*` (so never dev or mainline). `--mirror`, `--all`, `--branches`, `--tags` never. +# +# The worktree is resolved from the command itself: `git -C ` (cumulative), `--work-tree`, +# `--git-dir`, `GIT_DIR=`/`GIT_WORK_TREE=` (prefixed or set earlier in the text), `env -C`/`sudo +# -D`, a preceding `cd`/`cd -`/`pushd`/`popd`, else the hook input's `cwd`. "This repository" is +# the one whose common dir matches that of $CLAUDE_PROJECT_DIR (else `cwd`), so a scratch repo is +# not guarded. Commands are found by .claude/hooks/shell_commands.py (its docstring lists what it +# follows). +# +# Out of scope (not followed, and not pattern-checked): an existing script the text does not +# write (`. .venv/sharpy-env.sh`, `bash build_tools/setup_env.sh`), a script run by its own path +# (`./x.sh`), a function or alias, a python/node subprocess, `xargs rm` input, `git rm`, +# `unlink`/`mv`, an rm target the text cannot resolve, a `git` alias, launchers outside +# shell_commands.PREFIXES (ssh, su -c, script -c, docker exec, make, npm run), a program named +# by ANSI-C escapes (`$'\x67it' reset --hard`). +# PATTERN-CHECKED instead of walked: unparseable text (or substitutions nested more than 8 +# deep), allowed when `bash -n` refuses it too (bash will not run it); and a script the text +# runs but does not show: `eval "$X"`, `bash -c "$X"`, `$X args`, `... | bash`, `sh -s`, `bash +# < file`, `bash <(...)`, and a script file (`bash x.sh`, `source x.sh`) the text writes (a +# `>`/`>>`/`tee` target, a `cp`/`mv`/`install` destination) or that does not exist when the +# hook runs. A literal `bash -c '...'`, here-string or here-document body is +# walked. The whole text is then searched for rules 1-2's verbs (where the opaque script runs in +# the main worktree, or anywhere unknown) and rules 3-4's (add -A/./-u, commit -a, a forced push +# without both lease flags or to dev/mainline; in every worktree of this repository). +# Known false deny: a guarded verb anywhere in such a text, e.g. `cat x.sh | bash; git stash +# list` in the main worktree; run the two commands separately. And `[[ $b =~ ($X|y) ]]`: the +# `(`, `|`, `)` split it, so `$X` reads as a program named by a variable (pattern-checked). +# +# FAILS CLOSED when it cannot read the input or run: unreadable input (not JSON, no string +# command) is denied; an internal error pattern-checks the whole text for every rule, in any +# worktree; a python3 that fails to start or dies is denied by the shell wrapper (so with no +# python3 every Bash command is denied). Text it cannot follow is pattern-checked as above, not +# denied: `eval "$X"` with nothing guarded visible in the text is allowed. The input is read +# from stdin by python (no size limit). A hook timeout (settings.json, 5 s) is Claude Code's to +# handle; a 200 KB command, or 2,000 `git add x` on one line, takes well under one second. +# +# Hook input is JSON on stdin (tool_input.command, cwd, agent_id). Falsified by +# .claude/hooks/test-hooks.sh. +read -r -d '' PROG <<'PY' +import glob, json, os, re, subprocess, sys +sys.dont_write_bytecode = True + +def deny(msg): + sys.stderr.write("BLOCKED by .claude/hooks/guard-shared-tree.sh: " + msg + "\n") + sys.exit(2) + +try: + data = json.loads(sys.stdin.buffer.read()) + cmd = data["tool_input"]["command"] + cwd = data.get("cwd") or os.getcwd() + agent = bool(data.get("agent_id")) + assert isinstance(cmd, str) and isinstance(cwd, str) +except Exception as e: + deny("cannot read the hook input (%s: %s); the hook fails closed." % (type(e).__name__, e)) +if not cmd: + sys.exit(0) + +# Whole-text patterns for text the walk cannot follow: rules 1 and 2 in the main worktree, +# rules 3 and 4 in every worktree of this repository. The text is split at newlines and ; & | +# first, and each segment is searched in steps from its first `git` (a verb after it, then a +# flag after the verb): no nested unbounded quantifiers, so a long line stays linear. +SEGMENT = re.compile(r"[\n;&|]") +GIT = re.compile(r"\bgit\b") +RM = re.compile(r"(^|[\s(`])rm\s") +MAIN_VERB = re.compile(r"\b(checkout|restore|clean|stash|reset|switch)\b") +STAGE_ALL = ((re.compile(r"\badd\b"), re.compile(r"\s(-A|--all|-u|--update|\.)(?=[\s)]|$)")), + (re.compile(r"\bcommit\b"), + re.compile(r"\s(-[A-Za-z]*a[A-Za-z]*|--all)(?=[\s)]|$)"))) +PUSH = re.compile(r"\bpush\b") +FORCE = re.compile(r"\s(--force(?![-\w])|-[A-Za-z]*f[A-Za-z]*|--mirror|\+\S)") +DEV = re.compile(r"\b(dev|mainline)\b") + +def forced_push_text(push): + """`push`: a segment from its `git`, holding `push` after it.""" + if FORCE.search(push): + return True + return "--force-with-lease" in push and ("--force-if-includes" not in push + or bool(DEV.search(push))) + +def matches(text, main, any_tree): + for seg in SEGMENT.split(text): + if main and RM.search(seg): + return True + g = GIT.search(seg) if "git" in seg else None + if not g: + continue + if main and MAIN_VERB.search(seg, g.end()): + return True + if any_tree: + for verb, flag in STAGE_ALL: + v = verb.search(seg, g.end()) + if v and flag.search(seg, v.end()): + return True + if PUSH.search(seg, g.end()) and forced_push_text(seg[g.start():]): + return True + return False + +def failed(e): + """An internal error: every pattern, in any worktree.""" + if matches(cmd, True, True): + deny("the hook failed (%s: %s) and the command names a guarded git verb, rm, a " + "stage-everything add/commit or a forced push; the hook fails closed." % ( + type(e).__name__, e)) + sys.exit(0) + +try: + sys.path.insert(0, os.environ["HOOKS_DIR"]) + import shell_commands as sc +except Exception as e: + failed(e) + +def git(*args): + return subprocess.run(["git"] + list(args), capture_output=True, text=True) + +_cache = {} +NEW_REPOS = [] # directories `git init`/`git clone` creates earlier in the text +def repo_of(path): + """(toplevel, git_dir, common_dir) of the worktree holding path, or None.""" + real = os.path.realpath(path) + if any(real == d or real.startswith(d + "/") for d in NEW_REPOS): + return None + p = path + while p and not os.path.isdir(p): + p = os.path.dirname(p) + if not p: + return None + if p not in _cache: + r = git("-C", p, "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-dir", + "--git-common-dir") + lines = r.stdout.split("\n") + _cache[p] = (tuple(os.path.realpath(x) for x in lines[:3]) + if r.returncode == 0 and len(lines) >= 3 and all(lines[:3]) else None) + return _cache[p] + +def repo_of_gitdir(gitdir): + r = git("--git-dir=" + gitdir, "rev-parse", "--path-format=absolute", "--git-dir", + "--git-common-dir") + lines = r.stdout.split("\n") + if r.returncode or len(lines) < 2 or not all(lines[:2]): + return None + gd, common = (os.path.realpath(x) for x in lines[:2]) + return (os.path.dirname(common), gd, common) + +project = None # set by run() +def ours(info): + return bool(info and project and info[2] == project[2]) +def main_tree(info): + return ours(info) and info[1] == info[2] + +_wt = [] +def worktrees(): + """Registered worktree roots of this repository, the main one first.""" + if not _wt and project: + out = git("-C", project[0], "worktree", "list", "--porcelain").stdout + _wt.extend(os.path.realpath(l[9:]) for l in out.split("\n") if l.startswith("worktree ")) + return _wt + +def main_info(): + """The main worktree, for a command whose directory or repository the text lost.""" + return (worktrees()[0], project[2], project[2]) if project and worktrees() else None + +SHARED = ("The main worktree is shared with this session's agents (contract §9): REPORT `git status`, " + "do not make it clean; restore a mutation from your `cp` copy. To reset, stash or discard, " + "work in your own worktree (`git worktree add /wt `), where it is allowed.") +AGENT = ("Agents never run contract §9's checkout/restore/clean/stash/reset in the shared tree " + "(`git switch` to move branches is allowed); work in your own worktree " + "(`git worktree add /wt `) if you need one.") +S9 = {"checkout", "restore", "clean", "stash", "reset"} +GIT_OPTS_WITH_ARG = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env", + "--exec-path", "--super-prefix"} +FORCE_LONG = {"--force", "--discard-changes", "--merge", "--ours", "--theirs", "--patch"} +CO_NAME_OPTS = {"-b", "-B", "--orphan", "-c", "-C", "--create", "--force-create"} +# Each judged subcommand's long options (git 2.43 docs), for git's unique-prefix abbreviation; +# every option's --no- form counts too. An ambiguous prefix is left as typed: git refuses it. +LONG_OPTS = {k: set(v.split()) for k, v in { + "push": "verbose quiet repo all branches mirror delete tags dry-run porcelain force " + "force-with-lease force-if-includes recurse-submodules receive-pack exec set-upstream " + "progress prune verify follow-tags signed atomic push-option ipv4 ipv6 thin", + "checkout": "quiet progress force merge conflict detach track guess orphan " + "ignore-skip-worktree-bits ignore-other-worktrees ours theirs patch overlay " + "recurse-submodules pathspec-from-file pathspec-file-nul", + "switch": "create force-create detach guess discard-changes force merge conflict quiet " + "progress track orphan ignore-other-worktrees recurse-submodules", + "restore": "source patch worktree staged quiet progress ours theirs merge conflict " + "ignore-unmerged ignore-skip-worktree-bits recurse-submodules overlay " + "pathspec-from-file pathspec-file-nul", + "reset": "quiet refresh soft mixed hard merge keep recurse-submodules patch intent-to-add " + "pathspec-from-file pathspec-file-nul", + "clean": "quiet dry-run force interactive exclude", + "add": "dry-run verbose force interactive patch edit all ignore-removal update sparse " + "intent-to-add refresh ignore-errors ignore-missing chmod pathspec-from-file " + "pathspec-file-nul renormalize", + "commit": "all patch reuse-message reedit-message fixup squash reset-author short branch " + "porcelain long null file author date message template signoff trailer verify " + "allow-empty allow-empty-message cleanup edit amend post-rewrite include only " + "pathspec-from-file pathspec-file-nul untracked-files verbose quiet dry-run status " + "gpg-sign", +}.items()} +for _v in LONG_OPTS.values(): + _v |= {"no-" + o for o in list(_v)} + +def canon(verb, rest): + """rest with each `--prefix[=v]` (before `--`) spelled as the long option it abbreviates.""" + names, out = LONG_OPTS.get(verb), [] + for k, a in enumerate(rest): + if a == "--": + return out + rest[k:] + if names and a.startswith("--") and len(a) > 2: + name, eq, val = a[2:].partition("=") + if name not in names: + hits = [o for o in names if o.startswith(name)] + if len(hits) == 1: + a = "--" + hits[0] + eq + val + out.append(a) + return out + +def is_commit(arg, where): + if git("-C", where, "rev-parse", "--verify", "--quiet", arg + "^{commit}").returncode == 0: + return True + r = git("-C", where, "for-each-ref", "--count=1", "--format=%(refname)", "refs/remotes/*/" + arg) + return bool(r.stdout.strip()) + +def positionals(rest, name_opts=()): + pos, j = [], 0 + while j < len(rest): + a = rest[j] + if a == "--": + break + if a in name_opts: + j += 2 + continue + if not a.startswith("-"): # `-` alone is the previous branch: an option here + pos.append(a) + j += 1 + return pos + +def destroys(verb, rest, where): + """Why this verb can destroy uncommitted work in the main worktree, or None.""" + opts = rest[:rest.index("--")] if "--" in rest else rest # after `--` come paths only + shorts = "".join(a[1:] for a in opts if a.startswith("-") and not a.startswith("--")) + if verb == "restore": + staged = "--staged" in opts or "S" in shorts + worktree = "--worktree" in opts or "W" in shorts + return None if staged and not worktree else "`git restore` discards uncommitted changes" + if verb == "clean": + return None if "--dry-run" in opts or "n" in shorts else "`git clean` deletes untracked files" + if verb == "stash": + if rest and rest[0] in ("list", "show"): + return None + return "`git stash` moves uncommitted changes (a peer's included) off the tree" + if verb == "reset": + if {"--hard", "--merge", "--keep"} & set(opts): + return "`git reset --hard|--merge|--keep` discards uncommitted changes" + if "--soft" in opts: + return None + if "--" in rest and rest.index("--") < len(rest) - 1: + return None # a path reset: only the index moves + if any(a.startswith("--pathspec-from-file") for a in opts): + return None + if any(not is_commit(a, where) for a in positionals(rest)): + return None + return "`git reset` without paths moves the branch and unstages every file" + # checkout / switch + for a in rest: + if a == "--": + break + if a.split("=", 1)[0] in FORCE_LONG or a.startswith("--pathspec-from-file"): + return "`git %s %s` overwrites uncommitted changes" % (verb, a) + if a.startswith("-") and not a.startswith("--"): + for ch in a[1:]: + if ch in "bBcC": + break + if ch in "fmp": + return "`git %s %s` overwrites uncommitted changes" % (verb, a) + if verb != "checkout": + return None + if "--" in rest: + return "`git checkout -- ` overwrites the path's uncommitted changes" + for a in positionals(rest, CO_NAME_OPTS): + if a == "." or not is_commit(a, where): + return "`git checkout %s` names a path: it overwrites that path's uncommitted changes" % a + return None + +def from_env(name, cwd, env, assigns): + """(given, path) for GIT_DIR / GIT_WORK_TREE: a prefix assignment, else one the text set + earlier (env holds None for a value it lost).""" + if name in assigns: + return True, sc.resolve(assigns[name], cwd, env) + if name in env and env[name] != "": + return True, None if env[name] is None else sc.resolve(env[name], cwd, env) + return False, None + +INIT_OPTS = ("-b", "--initial-branch", "--separate-git-dir", "--template", "--object-format", + "--ref-format") +CLONE_OPTS = ("-o", "--origin", "-b", "--branch", "-u", "--upload-pack", "--reference", + "--reference-if-able", "--separate-git-dir", "--depth", "--shallow-since", + "--shallow-exclude", "-c", "--config", "-j", "--jobs", "--template", + "--server-option", "--filter", "--bundle-uri", "--ref-format") + +def new_repo(verb, rest, where, env): + """Record the directory `git init [dir]` / `git clone [dir]` makes a new repository: + only one that does not exist yet, or is empty (an existing tree stays this repository's).""" + pos = positionals(rest, INIT_OPTS if verb == "init" else CLONE_OPTS) + if verb == "init": + target = sc.resolve(pos[0], where, env) if pos else where + elif len(pos) >= 2: + target = sc.resolve(pos[1], where, env) + elif pos: + name = re.sub(r"(/\.git|\.git)?/*$", "", pos[0]).rstrip("/") + name = re.split(r"[/:]", name)[-1] if name else "" + target = sc.resolve(name, where, env) if name else None + else: + target = None + if target and (not os.path.lexists(target) or ( + os.path.isdir(target) and not os.path.islink(target) and not os.listdir(target))): + NEW_REPOS.append(os.path.realpath(target)) + +def check_git(argv, cwd, env, assigns): + args, i, where = argv[1:], 0, cwd + gd_given, gitdir = from_env("GIT_DIR", cwd, env, assigns) + wt_given, worktree = from_env("GIT_WORK_TREE", cwd, env, assigns) + while i < len(args) and args[i].startswith("-"): + a = args[i] + if a in GIT_OPTS_WITH_ARG and i + 1 < len(args): + v = args[i + 1] + if a == "-C": + where = sc.resolve(v, where, env) + elif a == "--work-tree": + wt_given, worktree = True, sc.resolve(v, where, env) + elif a == "--git-dir": + gd_given, gitdir = True, sc.resolve(v, where, env) + i += 2 + continue + if a.startswith("--work-tree="): + wt_given, worktree = True, sc.resolve(a.split("=", 1)[1], where, env) + elif a.startswith("--git-dir="): + gd_given, gitdir = True, sc.resolve(a.split("=", 1)[1], where, env) + i += 1 + if i >= len(args): + return + verb, rest = args[i], canon(args[i], args[i + 1:]) + if verb in ("init", "clone"): + new_repo(verb, rest, worktree or where, env) + return + if (gd_given and gitdir is None) or (wt_given and worktree is None) or where is None: + # The text lost the directory or the repository (cd "$X", GIT_DIR="$X", a pop after + # pushd -n): fail closed, judge it as the main worktree. + info = main_info() + elif gitdir: + info = repo_of_gitdir(gitdir) + else: + info = repo_of(worktree or where) + if verb in S9 or verb == "switch": + if main_tree(info): + if agent and verb in S9: + if not (verb == "stash" and rest and rest[0] in ("list", "show")): + deny("`git %s` by a subagent in the main worktree %s. %s" % (verb, info[0], AGENT)) + else: + why = destroys(verb, rest, info[0]) + if why: + deny("%s in the main worktree %s. %s" % (why, info[0], SHARED)) + elif verb == "add" and ours(info): + for a in rest: + if a == "--": + break + if a in ("-A", "--all", "-u", "--update", "--no-ignore-removal") or ( + a.startswith("-") and not a.startswith("--") and set(a[1:]) & set("Au")): + deny("`git add %s` stages every change, a peer's hunks included (contract §9). " + "Stage explicit per-file pathspecs (`git add path/to/file`) and check " + "`git diff --cached --stat`." % a) + if any(p in (".", "./", ":/", ":", "*") for p in rest): + deny("`git add .` stages every change, a peer's hunks included (contract §9). " + "Stage explicit per-file pathspecs and check `git diff --cached --stat`.") + elif verb == "commit" and ours(info): + j = 0 + while j < len(rest): + a = rest[j] + if a == "--": + break + if a == "--all": + deny("`git commit --all` stages every tracked change (contract §9). Stage per-file, then commit.") + if a in ("--message", "--file", "--author", "--date", "--template", "--reuse-message", + "--reedit-message", "--fixup", "--squash", "--trailer", "--cleanup"): + j += 2 + continue + if a.startswith("-") and not a.startswith("--"): + for k, ch in enumerate(a[1:]): + if ch == "a": + deny("`git commit -a` stages every tracked change (contract §9). Stage per-file, then commit.") + if ch in "mFcCt": + if k == len(a) - 2: + j += 1 + break + j += 1 + elif verb == "push" and ours(info): + check_push(rest, where) + +def check_push(rest, where): + flags, pos, j = set(), [], 0 + while j < len(rest): + a = rest[j] + if a == "--": + pos += rest[j + 1:] + break + if a.startswith("--"): + flags.add(a.split("=", 1)[0]) + if a in ("--repo", "--receive-pack", "--exec", "--push-option"): + j += 1 + elif a.startswith("-") and len(a) > 1: + for ch in a[1:]: + flags.add("-" + ch) + if a[-1] == "o": + j += 1 + else: + pos.append(a) + j += 1 + refspecs = pos[1:] + forced = bool(flags & {"--force", "-f", "--force-with-lease", "--mirror"}) or any( + r.startswith("+") for r in refspecs) + if not forced: + return + rule = ("Force-push only with both `--force-with-lease` and `--force-if-includes`, only to " + "`claude/*` branches, never dev or mainline (CLAUDE.md › Git & Release).") + if flags & {"--mirror", "--all", "--branches", "--tags"}: + deny("a forced `git push` of every ref. " + rule) + if "--force" in flags or "-f" in flags or not {"--force-with-lease", "--force-if-includes"} <= flags: + deny("a forced `git push` without both lease flags. " + rule) + dsts = [] + for r in refspecs or ["HEAD"]: + r = r.lstrip("+") + dst = r.split(":", 1)[1] if ":" in r else r + if dst == "HEAD": + dst = (git("-C", where, "symbolic-ref", "--short", "-q", "HEAD").stdout.strip() + if where else "") or "HEAD" # an unknown directory: HEAD is not claude/* + dsts.append(dst[len("refs/heads/"):] if dst.startswith("refs/heads/") else dst) + for d in dsts: + if not d.startswith("claude/"): + deny("a forced `git push` to `%s`. %s" % (d, rule)) + +def check_rm(argv, cwd, env): + targets, opts = [], True + for a in argv[1:]: + if opts and a == "--": + opts = False + continue + if opts and a.startswith("-") and a != "-": + continue + targets.append(a) + wts = worktrees() + top = wts[0] if wts else None + for t in targets: + path = sc.resolve(t, cwd, env) + if path is None: + continue # cannot resolve: "$tmp", a loop variable, an unknown cwd + if top: + for c in [path] + (glob.glob(path) if glob.has_magic(path) else []): + # without a trailing `/`, rm removes the name itself (a symlink, not its target) + rp = os.path.realpath(c) if t.endswith("/") else os.path.join( + os.path.realpath(os.path.dirname(c)), os.path.basename(c)) + if rp == top or top.startswith(rp.rstrip("/") + "/"): + deny("`rm %s` removes the main worktree %s%s. Contract §9." % ( + t, top, "" if rp == top else " (it is below " + rp + ")")) + parent = os.path.dirname(path) + info = repo_of(parent) + if not main_tree(info): + continue + rel = os.path.relpath(os.path.join(os.path.realpath(parent), os.path.basename(path)), info[0]) + parts = rel.split(os.sep) + if parts[:2] == [".claude", "tmp"] and len(parts) > 2: + continue + if parts[:2] == [".claude", "worktrees"] and len(parts) > 2 and os.path.realpath( + os.path.join(info[0], ".claude", "worktrees", parts[2])) not in wts: + continue # a stale directory, no longer a registered worktree + if any(p in ("bin", "obj") and glob.glob(os.path.join(info[0], *parts[:k], "*.*proj")) + for k, p in enumerate(parts)): + continue + deny("`rm %s` inside the shared main worktree %s. Restore a mutation from the copy you made " + "(`cp`); put scratch files in your scratchpad or .claude/tmp/ (bin/ and obj/ build " + "outputs may be removed; a registered worktree goes with `git worktree remove`). " + "Contract §9." % (t, info[0])) + +def visit(argv, cwd, env, assigns): + name = os.path.basename(argv[0]) + if name == "git": + check_git(argv, cwd, env, assigns) + elif name == "rm": + check_rm(argv, cwd, env) + +def run(): + global project + project = repo_of(os.environ.get("CLAUDE_PROJECT_DIR") or cwd) + opaque = [] + try: + sc.walk(cmd, cwd, visit, opaque=lambda where, what: opaque.append((where, what))) + except sc.ParseError: + if not sc.bash_accepts(cmd): + sys.exit(0) # bash refuses it too: nothing runs + here = repo_of(cwd) + if matches(cmd, main_tree(here), ours(here)): + deny("this command could not be parsed (bash can parse it) and names a guarded git " + "verb, rm, a stage-everything add/commit or a forced push. Split it into simpler " + "commands.") + for where, what in opaque: + info = repo_of(where) if where else main_info() + if matches(cmd, main_tree(info), ours(info)): + deny("this command runs a script the hook cannot read (%s) in %s, and its text names " + "a guarded git verb, rm, a stage-everything add/commit or a forced push. Run the " + "commands directly." % (what, where or "an unknown directory")) + +try: + run() +except Exception as e: + failed(e) +sys.exit(0) +PY +HOOKS_DIR="$(cd "$(dirname "$0")" && pwd)" python3 -c "$PROG" +rc=$? +case $rc in + 0 | 2) exit "$rc" ;; +esac +echo "BLOCKED by .claude/hooks/guard-shared-tree.sh: the hook could not judge this command" \ + "(python3 exit $rc); it fails closed." >&2 +exit 2 diff --git a/.claude/hooks/require-agent-brief.sh b/.claude/hooks/require-agent-brief.sh new file mode 100755 index 0000000000..42e0e7507e --- /dev/null +++ b/.claude/hooks/require-agent-brief.sh @@ -0,0 +1,72 @@ +#!/bin/bash +# PreToolUse(Agent|Task) hook: every agent brief carries the shared-tree block of +# docs/design/verification-contract.md §9, which says to paste it verbatim into every agent +# prompt that touches the repository. Denies (exit 2) a spawn whose tool_input.prompt lacks +# either KEY sentence below, compared after dropping each line's leading whitespace and `>` +# quote markers and collapsing whitespace (so a quoted, indented or re-wrapped copy passes; a +# paraphrase does not). The denial message carries the block, read from the contract. +# +# Exempt subagent_type values (pinned by .claude/hooks/test-hooks.sh): +# fork inherits the parent conversation, the block included +# web-fetch, claude-code-guide, statusline-setup cannot touch the repository +# An absent subagent_type is general-purpose and is not exempt. +# +# Cannot see: a message sent to a running agent (SendMessage), a resumed agent, an agent started +# outside Claude Code's agent tool (create_session, a scheduled task), and whether the agent +# obeys the block. +# +# FAILS CLOSED: unreadable input (not JSON, a prompt that is not a string), an internal error, +# and a python3 that fails to start or dies are denied. The input is read from stdin by python +# (no size limit). +# +# Hook input is JSON on stdin (tool_input.prompt, tool_input.subagent_type). +read -r -d '' PROG <<'PY' +import json, os, re, sys + +KEYS = ( + 'REPORT `git status`; do not "make it clean".', + "Restore a mutation-test from the copy you made (`cp`), never from git.", +) +EXEMPT = {"fork", "web-fetch", "claude-code-guide", "statusline-setup"} + +def norm(text): + lines = (re.sub(r"^[\s>]*", "", line) for line in text.split("\n")) + return re.sub(r"\s+", " ", " ".join(lines)).strip() + +def deny(msg): + sys.stderr.write("BLOCKED by .claude/hooks/require-agent-brief.sh: " + msg) + sys.exit(2) + +try: + tool_input = json.loads(sys.stdin.buffer.read())["tool_input"] + kind = tool_input.get("subagent_type") or "general-purpose" + if kind in EXEMPT: + sys.exit(0) + prompt = tool_input["prompt"] + assert isinstance(prompt, str) + missing = [k for k in KEYS if norm(k) not in norm(prompt)] +except Exception as e: + deny("cannot read the hook input (%s: %s); the hook fails closed.\n" % (type(e).__name__, e)) +if not missing: + sys.exit(0) + +block = "" +try: + contract = open(os.path.join(os.environ["HOOKS_DIR"], "..", "..", "docs", "design", + "verification-contract.md"), encoding="utf-8").read() + m = re.search(r"^## 9\.[^\n]*\n(?:(?!> )[^\n]*\n)*?((?:> [^\n]*\n)+)", contract, re.M) + block = m.group(1) if m else "" +except (OSError, KeyError): + pass +deny("this " + kind + " agent's prompt lacks the shared-tree block " + "(docs/design/verification-contract.md §9), missing: " + " / ".join(missing) + + "\nPaste the block verbatim into the prompt and spawn again:\n\n" + block) +PY +HOOKS_DIR="$(cd "$(dirname "$0")" && pwd)" python3 -c "$PROG" +rc=$? +case $rc in + 0 | 2) exit "$rc" ;; +esac +echo "BLOCKED by .claude/hooks/require-agent-brief.sh: the hook could not judge this spawn" \ + "(python3 exit $rc); it fails closed." >&2 +exit 2 diff --git a/.claude/hooks/shell_commands.py b/.claude/hooks/shell_commands.py new file mode 100644 index 0000000000..5ede8d6695 --- /dev/null +++ b/.claude/hooks/shell_commands.py @@ -0,0 +1,1151 @@ +"""Split a Bash tool command into the simple commands bash would run, for the PreToolUse hooks. + +Used by guard-shared-tree.sh and enforce-dotnet-serialized.sh (imported from this directory). +``walk(src, cwd, visit, opaque=...)`` calls ``visit(argv, cwd, env, assigns)`` for every simple +command, in order, with: + +- here-documents turned into ``<<<`` here-strings first, at any depth (inside ``"$(cat <<'EOF' + ... EOF)"`` too): a body is data to ``cat``, a script to ``bash <'``, a shell's + here-string script, ``eval``, ``env -S``, ``flock -c``, ``watch`` and ``parallel`` walked as + scripts; +- quotes removed, ``\\`` escapes and line continuations applied, redirections removed from argv; +- leading ``VAR=value`` assignments (passed to visit as ``assigns``) and the launchers in + PREFIXES stripped with their options, so argv[0] is the program run; ``env -C``/``sudo -D`` + set its cwd; a program named by a known variable (``G=git; $G reset``) expanded; ``find -exec/ + -execdir/-ok/-okdir ... ;|+`` visited as commands (``{}`` read as ``/{}``) and + ``find -delete`` as ``rm /{}``; +- ``cd`` / ``cd -`` / ``pushd`` / ``popd`` and plain assignments (``X=v``, ``export X=v``) + tracked: ``cwd`` is the directory the command runs in and ``env`` the variables the command text + set, as far as the text says. ``None`` means unknown (``cd "$X"``, a loop variable, a pop + after ``pushd -n +N``). ``$(mktemp [-d])`` is a fresh path in $TMPDIR and ``$(git rev-parse + --show-toplevel)`` the cwd's toplevel. + +A script it cannot see (``eval "$X"``, ``bash -c "$X"``, ``$X args``, ``... | bash``, ``sh -s``, +``bash < file``, ``bash <(...)``, and ``bash x.sh`` / ``source x.sh`` of a script the text writes +or that does not exist yet) goes to ``opaque(cwd, what)``, else raises ParseError. An existing +script the text does not write is a program like any other. +It does not evaluate the shell: a variable not set in the text resolves from the hook's own +environment, else it is unknown; globs stay unexpanded; functions, aliases and scripts run by +their own path (``./x.sh``) are not followed; ``[[ ... ]]`` is split like any other words; control keywords (``if``/``then``/``do``/``{``...) +are skipped as argv[0], not parsed. Launchers not in PREFIXES (ssh, su -c, script -c, docker +exec, chroot, make, npm run ...) hide their command. An unterminated quote or substitution +raises ParseError; ``bash_accepts`` tells whether bash itself would refuse the text. +""" + +import os +import re +import subprocess + +# launcher -> (options that take a separate argument, positional args before the command, mode) +# mode: "cmd" (the rest is argv), "script" (the rest, joined, is a shell script) +PREFIXES = { + "env": ({"-u", "--unset", "-C", "--chdir"}, 0, "cmd"), + "sudo": ({"-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U", "-T"}, 0, "cmd"), + "nice": ({"-n", "--adjustment"}, 0, "cmd"), + "timeout": ({"-s", "--signal", "-k", "--kill-after"}, 1, "cmd"), + "stdbuf": ({"-i", "-o", "-e", "--input", "--output", "--error"}, 0, "cmd"), + "xargs": ({"-I", "-n", "-L", "-P", "-s", "-d", "-E", "-a", "--arg-file", "--delimiter", + "--max-args", "--max-lines", "--max-procs", "--max-chars", "--eof", "--replace"}, + 0, "cmd"), + "exec": ({"-a"}, 0, "cmd"), + "command": (set(), 0, "cmd"), + "nohup": (set(), 0, "cmd"), + "setsid": (set(), 0, "cmd"), + "time": ({"-f", "--format", "-o", "--output"}, 0, "cmd"), + "ionice": ({"-c", "--class", "-n", "--classdata", "-p", "--pid", "-P", "--pgid", "-u", + "--uid"}, 0, "cmd"), + "taskset": (set(), 1, "cmd"), + "chrt": (set(), 1, "cmd"), + "flock": ({"-w", "--wait", "--timeout", "-E", "--conflict-exit-code"}, 1, "cmd"), + "strace": ({"-e", "-o", "-p", "-s", "-u", "-E", "-P", "-a", "-b", "-I", "-O", "-S", "-X", + "-U"}, 0, "cmd"), + "watch": ({"-n", "--interval", "-q", "--equexit"}, 0, "script"), + "parallel": ({"-j", "--jobs", "-S", "--sshlogin", "-a", "--arg-file", "--delay", "--timeout", + "-n", "--max-args", "-N", "--colsep", "-C", "-d", "--delimiter", "-I", "-E", + "--env", "--joblog", "--results", "--tmpdir", "--workdir", "--wd", "-P", + "--max-procs", "--halt", "--retries"}, 0, "script"), +} +SHELLS = {"bash", "sh", "zsh", "dash", "ksh"} +KEYWORDS = {"if", "then", "else", "elif", "fi", "do", "done", "while", "until", "{", "}", "!", + "coproc"} +DECLARERS = {"export", "declare", "local", "readonly", "typeset"} +ASSIGN = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)(\[[^]]*\])?\+?=(.*)$", re.S) +FIND_EXEC = {"-exec", "-execdir", "-ok", "-okdir"} + + +class ParseError(Exception): + pass + + +def bash_accepts(src): + """True when `bash -n` parses src (it runs nothing); also True if bash cannot be run. + The text goes on stdin: an argv string is capped at 128 KiB.""" + try: + r = subprocess.run(["bash", "-n"], input=src.encode("utf-8", "surrogateescape"), + capture_output=True, timeout=3) + except Exception: + return True + return r.returncode == 0 + + +# --------------------------------------------------------------------------------------------- +# Pre-pass: here-document bodies out, at every nesting depth. + +_DELIM_END = set(" \t\n;&|<>()") + + +def _herestring(body, quoted, kind): + """The ``<<<`` word bash would read for a here-document body: single-quoted when the + delimiter was quoted (no expansion), else double-quoted with its substitutions intact.""" + if kind == "bt" and "`" in body: + raise ParseError("a here-document holding a backtick inside backticks") + if quoted: + return "<<< '" + body.replace("'", "'\\''") + "' " + out, k, n = [], 0, len(body) + while k < n: + ch = body[k] + if ch == "\\": + pair = body[k:k + 2] + out.append(pair if pair[1:] in ("$", "`", "\\", "\n") else "\\\\") + k += 2 if pair[1:] in ("$", "`", "\\", "\n") else 1 + elif body.startswith("$(", k) or body.startswith("${", k) or ch == "`": + # copied whole: a substitution's own quotes are code, not the body's text + e = (_skip_backtick(body, k + 1) if ch == "`" else _match_brace(body, k + 2) + if body[k + 1] == "{" else _match_close(body, k + 2, "(", ")")) + out.append(body[k:e]) + k = e + else: + out.append('\\"' if ch == '"' else ch) + k += 1 + return '<<< "' + "".join(out) + '" ' + + +def inline_heredocs(src): + """``src`` with each ``<<[-]WORD`` and its body turned into a ``<<<`` here-string at the + operator, so a body is data (``cat``), a script (``bash < 0: + stack[-1][1] -= 1 + elif src.startswith("))", i): + stack.pop() + out.append("))") + i += 2 + prev = ")" + continue + out.append(c) + i += 1 + prev = c + continue + if kind == "br": # ${...}: no here-documents or comments inside; True = opened in "..." + if c == "\\": + out.append(src[i:i + 2]) + i += 2 + continue + if src.startswith("$'", i) and not stack[-1][2]: + j = i + 2 + while j < n and src[j] != "'": + j += 2 if src[j] == "\\" else 1 + out.append(src[i:j + 1]) + i = j + 1 + continue + if c == "'" and not stack[-1][2]: + j = src.find("'", i + 1) + j = n - 1 if j < 0 else j + out.append(src[i:j + 1]) + i = j + 1 + continue + if src.startswith("${", i) or src.startswith("$(", i): + stack.append(["br", 0, stack[-1][2]] if src[i + 1] == "{" else ["sh", 0, True]) + out.append(src[i:i + 2]) + i += 2 + continue + if c == '"': + stack.append(["dq", 0, False]) + elif c == "}": # a bare { does not nest: `${x:-{}` is complete (bash prints `{`) + stack.pop() + out.append(c) + i += 1 + prev = c + continue + # shell code: "sh" (top level or a $( frame) or "bt" (inside backticks) + if c == "\\": + out.append(src[i:i + 2]) + i += 2 + prev = "a" + continue + if c == "'": + j = src.find("'", i + 1) + j = n - 1 if j < 0 else j + out.append(src[i:j + 1]) + i = j + 1 + prev = "'" + continue + if src.startswith("$'", i): + j = i + 2 + while j < n and src[j] != "'": + j += 2 if src[j] == "\\" else 1 + out.append(src[i:j + 1]) + i = j + 1 + prev = "'" + continue + if c == "#" and prev in " \t\n;&|(": + j = src.find("\n", i) + j = n if j < 0 else j + out.append(src[i:j]) + i = j + continue + if c == '"': + stack.append(["dq", 0, False]) + elif c == "`": + if kind == "bt": + stack.pop() + else: + stack.append(["bt", 0, False]) + elif src.startswith("${", i): + stack.append(["br", 0, False]) + out.append("${") + i += 2 + prev = "{" + continue + elif src.startswith("$((", i) or (src.startswith("((", i) and prev in " \t\n;&|("): + k = 3 if c == "$" else 2 # $(( )) expansion, or the (( )) / for (( )) command + stack.append(["ar", 0, False]) + out.append(src[i:i + k]) + i += k + prev = "(" + continue + elif src.startswith("$(", i): + stack.append(["sh", 0, True]) + out.append("$(") + i += 2 + prev = "(" + continue + elif c == "(": + stack[-1][1] += 1 + elif c == ")": + if stack[-1][1] > 0: + stack[-1][1] -= 1 + elif stack[-1][2]: + stack.pop() + elif src.startswith("<<<", i): # a here-string: its second `<` opens no here-document + out.append("<<<") + i += 3 + prev = "<" + continue + elif src.startswith("<<", i): + j = i + 2 + strip_tabs = j < n and src[j] == "-" + j += 1 if strip_tabs else 0 + while j < n and src[j] in " \t": + j += 1 + word, quoted = [], False + while j < n and src[j] not in _DELIM_END: + d = src[j] + if d in "'\"": + k = src.find(d, j + 1) + k = n if k < 0 else k + word.append(src[j + 1:k]) + j = k + 1 + quoted = True + elif d == "\\": + word.append(src[j + 1:j + 2]) + j += 2 + quoted = True + else: + word.append(d) + j += 1 + if word: + pending.append((len(out), "".join(word), strip_tabs, quoted)) + out.append("<<< '' ") # filled when the body is read; empty if it never is + i = j + prev = " " + continue + out.append(c) + i += 1 + prev = c + return "".join(out) + + +# --------------------------------------------------------------------------------------------- +# Tokenizer. + +def _match_close(src, i, open_ch, close_ch): + """Index just past the ``close_ch`` matching the ``open_ch`` already consumed before ``i``.""" + depth, n = 1, len(src) + while i < n: + c = src[i] + if c == "\\": + i += 2 + continue + if src.startswith("$'", i): + i = _skip_ansi(src, i + 2) + continue + if c == "'": + j = src.find("'", i + 1) + if j < 0: + raise ParseError("unterminated '") + i = j + 1 + continue + if c == '"': + i = _skip_dquote(src, i + 1) + continue + if c == "`": + i = _skip_backtick(src, i + 1) + continue + if c == "#" and i > 0 and src[i - 1] in " \t\n;&|(": + j = src.find("\n", i) + i = n if j < 0 else j + continue + if c == open_ch: + depth += 1 + elif c == close_ch: + depth -= 1 + if depth == 0: + return i + 1 + i += 1 + raise ParseError("unterminated " + open_ch) + + +def _match_brace(src, i): + """Index just past the ``}`` closing a ``${`` consumed before ``i``. A nested ``${`` nests; + a bare ``{`` does not (bash: ``echo ${x:-{a}b}`` prints ``{ab}``).""" + depth, n = 1, len(src) + while i < n: + c = src[i] + if c == "\\": + i += 2 + continue + if src.startswith("$'", i): + i = _skip_ansi(src, i + 2) + continue + if c == "'": + j = src.find("'", i + 1) + if j < 0: + raise ParseError("unterminated '") + i = j + 1 + continue + if c == '"': + i = _skip_dquote(src, i + 1) + continue + if c == "`": + i = _skip_backtick(src, i + 1) + continue + if src.startswith("$(", i): + i = _match_close(src, i + 2, "(", ")") + continue + if src.startswith("${", i): + depth += 1 + i += 2 + continue + if c == "}": + depth -= 1 + if depth == 0: + return i + 1 + i += 1 + raise ParseError("unterminated ${") + + +def _subs_in(text): + """The command substitutions ($(...), backticks) and process substitutions (<(...), + >(...)) inside a span of shell words.""" + found = [sub for t in tokenize(text) if t[0] == "w" for sub in t[2]] + i, n = 0, len(text) + while i < n: + c = text[i] + if c == "\\": + i += 2 + elif text.startswith("$'", i): + i = _skip_ansi(text, i + 2) + elif c == "'": + j = text.find("'", i + 1) + i = n if j < 0 else j + 1 + elif c == '"': + i = _skip_dquote(text, i + 1) + elif text.startswith("<(", i) or text.startswith(">(", i): + k = _match_close(text, i + 2, "(", ")") + found.append(text[i + 2:k - 1]) + i = k + else: + i += 1 + return found + + +def _skip_ansi(src, i): + """Index just past the ``'`` closing a ``$'`` consumed before ``i`` (``\\'`` is escaped).""" + n = len(src) + while i < n: + if src[i] == "\\": + i += 2 + continue + if src[i] == "'": + return i + 1 + i += 1 + raise ParseError("unterminated $'") + + +def _skip_dquote(src, i): + n = len(src) + while i < n: + c = src[i] + if c == "\\": + i += 2 + continue + if c == '"': + return i + 1 + if src.startswith("$(", i): + i = _match_close(src, i + 2, "(", ")") + continue + if c == "`": + i = _skip_backtick(src, i + 1) + continue + i += 1 + raise ParseError('unterminated "') + + +def _skip_backtick(src, i): + n = len(src) + while i < n: + if src[i] == "\\": + i += 2 + continue + if src[i] == "`": + return i + 1 + i += 1 + raise ParseError("unterminated `") + + +_ARRAY_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\[[^]]*\])?\+?=$") +_REDIR = re.compile(r"&>>|&>|<<<|<<-|<<|<>|>>|>&|<&|>\||<|>") + + +def tokenize(src): + """Tokens: ('w', text, [substitution sources]), ('op', text) or ('redir', text). + + Expects here-documents already inlined (inline_heredocs).""" + toks = [] + word, subs = None, [] + i, n = 0, len(src) + + def flush(): + nonlocal word, subs + if word is not None: + toks.append(("w", "".join(word), subs)) + word, subs = None, [] + + def add(text): + nonlocal word + if word is None: + word = [] + word.append(text) + + while i < n: + c = src[i] + if c == "\n": + flush() + toks.append(("op", ";")) + i += 1 + continue + if c in " \t\r": + flush() + i += 1 + continue + if c == "#" and word is None: + j = src.find("\n", i) + i = n if j < 0 else j + continue + if c == "\\": + if i + 1 < n and src[i + 1] == "\n": + i += 2 + continue + add(src[i + 1] if i + 1 < n else "") + i += 2 + continue + if c == "'": + j = src.find("'", i + 1) + if j < 0: + raise ParseError("unterminated '") + add(src[i + 1:j]) + i = j + 1 + continue + if src.startswith("$'", i): + j = i + 2 + while j < n and src[j] != "'": + j += 2 if src[j] == "\\" else 1 + if j >= n: + raise ParseError("unterminated $'") + add(src[i + 2:j]) + i = j + 1 + continue + if c == '"': + j, buf = i + 1, [] + while True: + if j >= n: + raise ParseError('unterminated "') + d = src[j] + if d == '"': + break + if d == "\\" and j + 1 < n and src[j + 1] in '$`"\\\n': + if src[j + 1] != "\n": + buf.append(src[j + 1]) + j += 2 + continue + if src.startswith("$(", j) and not src.startswith("$((", j): + k = _match_close(src, j + 2, "(", ")") + subs.append(src[j + 2:k - 1]) + buf.append(src[j:k]) + j = k + continue + if d == "`": + k = _skip_backtick(src, j + 1) + subs.append(src[j + 1:k - 1]) + buf.append(src[j:k]) + j = k + continue + buf.append(d) + j += 1 + add("".join(buf)) + i = j + 1 + continue + if src.startswith("$((", i): + k = _match_close(src, i + 3, "(", ")") # arithmetic, which may hold $(...) + if k < n and src[k] == ")": + k += 1 + subs.extend(_subs_in(src[i + 3:k - 2])) + add(src[i:k]) + i = k + continue + if src.startswith("$(", i): + k = _match_close(src, i + 2, "(", ")") + subs.append(src[i + 2:k - 1]) + add(src[i:k]) + i = k + continue + if src.startswith("${", i): + k = _match_brace(src, i + 2) + subs.extend(_subs_in(src[i + 2:k - 1])) # ${x:-$(cmd)} runs cmd + add(src[i:k]) + i = k + continue + if c == "`": + k = _skip_backtick(src, i + 1) + subs.append(src[i + 1:k - 1]) + add(src[i:k]) + i = k + continue + if c in "<>" or (c == "&" and i + 1 < n and src[i + 1] == ">"): + if word is not None and "".join(word).isdigit(): + word, subs = None, [] # an fd number: 2>&1 + flush() + m = _REDIR.match(src, i) + i = m.end() + toks.append(("redir", m.group(0))) + continue + if c == "(" and word is not None and _ARRAY_ASSIGN.match("".join(word)): + k = _match_close(src, i + 1, "(", ")") # NAME=( ... ): words, not a subshell, + subs.extend(_subs_in(src[i + 1:k - 1])) # but their $(...) still run + add(src[i:k]) + i = k + continue + if c in ";&|()": + flush() + two = src[i:i + 2] + if two in ("&&", "||", ";;", "|&"): + toks.append(("op", two)) + i += 2 + else: + toks.append(("op", c)) + i += 1 + continue + add(c) + i += 1 + flush() + return toks + + +# --------------------------------------------------------------------------------------------- +# Words. + +_VAR = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))") + + +_SUB_HEAD = re.compile(r"^\$\(([^()`$'\"]*)\)") +_mktemps = [0] +_toplevels = {} + + +def _known_sub(inner, env, cwd): + """The value of two substitutions whose output the text fixes: ``mktemp [-d] [-q] [-t] + [--suffix=S] [TEMPLATE]`` (a fresh name in $TMPDIR, else /tmp; with -p/--tmpdir=DIR or a + template outside it, unknown) and ``git rev-parse --show-toplevel`` (run in ``cwd``).""" + words = inner.split() + if words == ["git", "rev-parse", "--show-toplevel"]: + if cwd is None: + return None + if cwd not in _toplevels: # once per directory: a long text may repeat it + try: + r = subprocess.run(["git", "-C", cwd, "rev-parse", "--show-toplevel"], + capture_output=True, text=True, timeout=3) + _toplevels[cwd] = r.stdout.strip() or None if r.returncode == 0 else None + except Exception: + _toplevels[cwd] = None + return _toplevels[cwd] + if not words or words[0] != "mktemp": + return None + in_tmp, template = False, None + for w in words[1:]: + if w in ("-t", "--tmpdir"): + in_tmp = True + elif w in ("-d", "--directory", "-q", "--quiet", "-u", "--dry-run") or w.startswith( + "--suffix="): + continue + elif w.startswith("-") or template is not None: + return None # -p DIR, --tmpdir=DIR, an option this does not know + else: + template = w + if template is not None and ("/" in template or not in_tmp): + return None # mktemp TEMPLATE creates it in the current directory + tmp = env["TMPDIR"] if "TMPDIR" in env else (os.environ.get("TMPDIR") or "/tmp") + if tmp is None: + return None + _mktemps[0] += 1 + return os.path.join(tmp, "tmp.hook%d" % _mktemps[0]) + + +def expand(word, env=None, cwd=None): + """``word`` with ~ and $VAR / ${VAR} expanded, or None when it cannot be resolved: it holds a + substitution (but a leading ``$(mktemp ...)`` or ``$(git rev-parse --show-toplevel)``), a + special or unset variable, or one the command text made unknown.""" + env = {} if env is None else env + m = _SUB_HEAD.match(word) + if m: + head = _known_sub(m.group(1), env, cwd) + tail = expand(word[m.end():], env, cwd) if head is not None else None + return None if tail is None else head + tail + if "`" in word or "$(" in word: + return None + if word == "~" or word.startswith("~/"): + home = env.get("HOME", os.environ.get("HOME")) + if home is None: + return None + word = home + word[1:] + out, pos = [], 0 + for m in _VAR.finditer(word): + name = m.group(1) or m.group(2) + val = env[name] if name in env else os.environ.get(name) + if val is None: + return None + out.append(word[pos:m.start()]) + out.append(val) + pos = m.end() + rest = word[pos:] + if "$" in rest: + return None # $1, $@, $$, ${x:-y} ... + return "".join(out) + rest + + +def resolve(path, cwd, env=None): + """Absolute normalized path for ``path`` run in ``cwd``, or None when unknown.""" + p = expand(path, env, cwd) + if p is None or p == "": + return None + if not os.path.isabs(p): + if cwd is None: + return None + p = os.path.join(cwd, p) + return os.path.normpath(p) + + +def _skip_opts(argv, takes): + while argv and argv[0].startswith("-") and argv[0] != "-": + opt = argv.pop(0) + if opt == "--": + break + if opt in takes and argv: + argv.pop(0) + + +def _find(argv): + """The commands ``find`` runs: its -exec family, and -delete as an rm.""" + args = argv[1:] + while args and args[0] in ("-H", "-L", "-P") or (args and args[0].startswith("-O")): + args.pop(0) + if args and args[0] == "-D" and len(args) > 1: + args = args[2:] + starts = [] + while args and not args[0].startswith("-") and args[0] not in ("(", "!", "\\("): + starts.append(args.pop(0)) + base = (starts or ["."])[0] + placeholder = base.rstrip("/") + "/{}" + extras, k = [], 0 + while k < len(args): + if args[k] in FIND_EXEC: + cmd, k = [], k + 1 + while k < len(args) and args[k] not in (";", "+"): + cmd.append(placeholder if args[k] == "{}" else args[k]) + k += 1 + if cmd: + extras.append(cmd) + elif args[k] == "-delete": + extras.extend(["rm", s.rstrip("/") + "/{}"] for s in (starts or ["."])) + k += 1 + return extras + + +def shell_args(argv): + """(single-letter flags, index of the first operand) of a ``bash|sh|... [options]`` argv: + with ``c`` the operand is the script; else with ``s``, none, or ``-``, stdin is the script; + else the operand names a script file.""" + flags, k = set(), 1 + while k < len(argv): + a = argv[k] + if a in ("--", "-"): + k += a == "--" + break + if a[:1] not in ("-", "+") or a == "+": + break + if a.startswith("--"): + k += 2 if a in ("--rcfile", "--init-file") else 1 + continue + # a bundle, as bash reads it: each o / O takes the next argument (-euo pipefail, + # -co pipefail 'cmd', -Oc extglob 'cmd') + flags.update(a[1:]) + k += 1 + sum(ch in "oO" for ch in a[1:]) + return flags, k + + +_CHDIR = {"env": ("-C", "--chdir"), "sudo": ("-D", "--chdir")} + + +def _take_opts(name, argv, chdirs, scripts): + """Pop env's or sudo's options off ``argv``, recording the last ``-C DIR`` / + ``--chdir[=]DIR`` (env) or ``-D DIR`` / ``--chdir[=]DIR`` (sudo) in ``chdirs`` (a later one + replaces an earlier one). True when ``env -S`` took a script.""" + short, long_ = _CHDIR[name] + takes = PREFIXES[name][0] + mine, took = [], False + while argv and argv[0].startswith("-") and argv[0] != "-": + opt = argv.pop(0) + if opt == "--": + break + if name == "env" and opt in ("-S", "--split-string") and argv: + scripts.append(argv.pop(0)) + took = True + break + if name == "env" and opt.startswith("--split-string="): + scripts.append(opt.split("=", 1)[1]) + took = True + break + if opt in (short, long_): + if argv: + mine.append(argv.pop(0)) + elif opt.startswith(long_ + "="): + mine.append(opt.split("=", 1)[1]) + elif opt.startswith(short) and not opt.startswith("--"): + mine.append(opt[len(short):]) + elif opt in takes and argv: + argv.pop(0) + chdirs.extend(mine[-1:]) + return took + + +def unwrap(argv): + """Strip assignments, keywords and launchers. Returns (argv, scripts, extras, assigns, + chdirs): the program's argv, shell scripts it runs, further argvs it runs (find -exec), the + VAR=value assignments that prefixed it, and the directories ``env -C`` / ``sudo -D`` run it + in (each relative to the one before).""" + argv, scripts, extras, assigns, chdirs = list(argv), [], [], {}, [] + + def take_assigns(): + while argv and ASSIGN.match(argv[0]): + m = ASSIGN.match(argv.pop(0)) + assigns[m.group(1)] = m.group(3) + + while argv: + take_assigns() + if not argv: + break + if argv[0] in KEYWORDS: + argv.pop(0) + continue + name = os.path.basename(argv[0]) + if name in _CHDIR: + argv.pop(0) + if _take_opts(name, argv, chdirs, scripts): + return [], scripts, extras, assigns, chdirs + continue + if name in PREFIXES: + takes, npos, mode = PREFIXES[name] + argv.pop(0) + _skip_opts(argv, takes) + if name == "flock": + if argv: + argv.pop(0) # the lock file or fd + if argv and argv[0] in ("-c", "--command"): + return [], argv[1:2], extras, assigns, chdirs + _skip_opts(argv, takes) + else: + for _ in range(npos): + if argv: + argv.pop(0) + if mode == "script": + if name == "parallel": + for k, a in enumerate(argv): + if a.startswith(":::"): + argv = argv[:k] + break + if argv: + scripts.append(" ".join(argv)) + return [], scripts, extras, assigns, chdirs + continue + if name == "find": + extras.extend(_find(argv)) + return argv, scripts, extras, assigns, chdirs + if name in SHELLS: + flags, k = shell_args(argv) + if "c" in flags: + return [], argv[k:k + 1], extras, assigns, chdirs + return argv, scripts, extras, assigns, chdirs + if name == "eval": + return [], [" ".join(argv[1:])], extras, assigns, chdirs + break + return argv, scripts, extras, assigns, chdirs + + +# --------------------------------------------------------------------------------------------- +# The walk. + +_WRITES = {">", ">>", ">|", "&>", "&>>", "<>", ">&"} + + +def _split(toks): + """Group tokens into ('cmd', [words], io), ('open',), ('close',), ('subs', [sources]), + ('write', word) for a redirection that writes a file. + ``io`` says where the command's stdin comes from: ``piped`` (after ``|``), ``file`` (a ``<`` + redirect), ``procsub`` (a ``<(...)`` operand), ``herestring`` (the ``<<<`` word's text).""" + out, cur, io, redir, piped = [], [], {}, None, False + for t in toks: + if t[0] == "redir": + redir = t[1] + continue + if t[0] == "w": + if redir is not None: + if redir == "<<<": + io["herestring"] = t[1] + elif redir in ("<", "<>"): + io["file"] = True + if redir in _WRITES and not (redir == ">&" and (t[1].isdigit() or t[1] == "-")): + out.append(("write", t[1])) + redir = None + out.append(("subs", t[2])) + continue + if not cur and piped: + io["piped"] = True + cur.append(t) + continue + if redir == "<" and t[1] == "(": + io["procsub"] = True # <(...): its commands are walked as a subshell below + redir = None + if cur: + out.append(("cmd", cur, io)) + cur, io = [], {} + piped = t[1] in ("|", "|&") or (piped and t[1] == "(") + if t[1] == "(": + out.append(("open",)) + elif t[1] == ")": + out.append(("close",)) + if cur: + out.append(("cmd", cur, io)) + return out + + +class _State: + def __init__(self, cwd, env, old=None, dirs=()): + self.cwd, self.env, self.old = cwd, dict(env), old + self.dirs = None if dirs is None else list(dirs) # None: the stack is not followed + + def copy(self): + return _State(self.cwd, self.env, self.old, self.dirs) + + +def walk(src, cwd, visit, env=None, opaque=None, _depth=0): + """Call visit(argv, cwd, env, assigns) for each simple command in ``src``, and + opaque(cwd, what) for each script the text runs but does not show: ``eval "$X"``, + ``bash -c "$X"``, ``$X args``, ``... | bash``, ``bash < file``, ``sh -s``. Without + ``opaque``, such a script raises ParseError.""" + env = dict(env or {}) + env["PWD"], env["OLDPWD"] = cwd, None # the command's, never the hook process's + + def no_opaque(cwd, what): + raise ParseError("runs a script the text does not show: " + what) + + try: + _walk(src, _State(cwd, env), (visit, opaque or no_opaque, set()), _depth) + except RecursionError: + raise ParseError("nested too deeply") + + +def _walk(src, st, cb, depth): + if depth > 8: + raise ParseError("substitutions nested more than 8 deep") + stack = [] + for item in _split(tokenize(inline_heredocs(src))): + if item[0] == "open": + stack.append(st) + st = st.copy() + continue + if item[0] == "close": + st = stack.pop() if stack else st + continue + if item[0] == "subs": + for s in item[1]: + _walk(s, st.copy(), cb, depth + 1) + continue + if item[0] == "write": + cb[2].add(resolve(item[1], st.cwd, st.env)) + continue + words = item[1] + for w in words: + for s in w[2]: + _walk(s, st.copy(), cb, depth + 1) + _command([w[1] for w in words], st, cb, depth, item[2]) + + +_EXPANSION = re.compile(r"\$[A-Za-z_{(0-9@*#?!$-]|`") + + +def _opaque_name(word): + """A word naming its program by an expansion; a bare or trailing ``$`` is literal (the + ``$`` of ``[[ $b =~ ^(dev|mainline)$ ]]``, which the tokenizer splits at ``(`` ``|`` ``)``).""" + return bool(_EXPANSION.search(word)) + + +def _command(raw, st, cb, depth, io=None): + visit, opaque, written = cb[:3] + io = io or {} + if raw and raw[0] in ("for", "select") and len(raw) > 1: + st.env[raw[1]] = None + return + if raw and raw[0] == "read": + for a in raw[1:]: + if not a.startswith("-"): + st.env[a] = None + return + if raw and all(ASSIGN.match(a) for a in raw): + for a in raw: + m = ASSIGN.match(a) + st.env[m.group(1)] = expand(m.group(3), st.env, st.cwd) + return + argv, scripts, extras, assigns, chdirs = unwrap(raw) + for _ in range(4): # a program named by a variable: G=git; $G reset + if not argv or not _opaque_name(argv[0]): + break + val = expand(argv[0], st.env, st.cwd) + if val is None: + break + more = unwrap(val.split() + argv[1:]) + argv = more[0] + scripts += more[1] + extras += more[2] + assigns.update(more[3]) + chdirs += more[4] + cst = st + if chdirs: + cst = st.copy() + for d in chdirs: + cst.cwd = resolve(d, cst.cwd, cst.env) + for s in scripts: + _walk(s, cst.copy(), cb, depth + 1) + if argv and _opaque_name(argv[0]): + opaque(cst.cwd, argv[0]) + return + if argv and argv[0] in DECLARERS: + for a in argv[1:]: + m = ASSIGN.match(a) + if m: + st.env[m.group(1)] = expand(m.group(3), st.env, st.cwd) + return + if argv: + name = argv[0] + if name in ("cd", "pushd", "popd"): + _chdir(name, argv, st) + return + if os.path.basename(name) in SHELLS: + flags, k = shell_args(argv) + if "s" in flags or k >= len(argv) or argv[k] == "-": # stdin is the script + if "herestring" in io: + _walk(io["herestring"], cst.copy(), cb, depth + 1) + elif io.get("piped") or io.get("file") or io.get("procsub"): + opaque(cst.cwd, name + " reading its script from stdin") + elif _unseen_script(argv[k], cst, written): + opaque(cst.cwd, name + " running a script file the text writes") + elif name in ("source", "."): + ops = [a for a in argv[1:] if a != "--"] + if io.get("procsub") or (ops and _unseen_script(ops[0], cst, written)): + opaque(cst.cwd, name + " of a script file the text writes") + _note_writes(argv, cst, written) + visit(argv, cst.cwd, cst.env, assigns) + for e in extras: + _command(e, cst.copy(), cb, depth + 1) + + +def _unseen_script(word, st, written): + """A script file whose text this command line may have made: one it writes (a redirection, + tee, a cp/mv/install destination), one that does not exist when the hook runs, or a path it + cannot resolve. An existing script the text does not write (.venv/sharpy-env.sh, + build_tools/*.sh) is out of scope, like any program.""" + path = resolve(word, st.cwd, st.env) + return path is None or path in written or not os.path.exists(path) + + +def _note_writes(argv, st, written): + """Record the files ``tee`` and ``cp``/``mv``/``install`` write.""" + base = os.path.basename(argv[0]) + if base == "tee": + written.update(resolve(a, st.cwd, st.env) for a in argv[1:] if not a.startswith("-")) + elif base in ("cp", "mv", "install"): + ops, target, k = [], None, 1 + while k < len(argv): + a = argv[k] + if a == "--": + ops += argv[k + 1:] + break + if a in ("-t", "--target-directory") and k + 1 < len(argv): + target, k = argv[k + 1], k + 2 + continue + if a.startswith("--target-directory="): + target = a.split("=", 1)[1] + elif not a.startswith("-"): + ops.append(a) + k += 1 + if target is None and len(ops) >= 2: + target, ops = ops[-1], ops[:-1] + dest = resolve(target, st.cwd, st.env) + if dest is not None and not os.path.isdir(dest): + written.add(dest) + return + dest = resolve(target, st.cwd, st.env) if target is not None else None + if dest is not None: + written.update(os.path.join(dest, os.path.basename(o.rstrip("/"))) for o in ops) + + +def _chdir(name, argv, st): + """cd / pushd / popd. OLDPWD moves only when bash changes directory (`pushd +0` does; a + refused pushd/popd, or any -n, does not).""" + prev, moved = st.cwd, True + if name == "cd": + args = [a for a in argv[1:] if not a.startswith("-") or a == "-"] + if not args: + st.cwd = resolve("~", None, st.env) + elif args[0] == "-": + st.cwd = st.old + else: + st.cwd = resolve(args[0], st.cwd, st.env) + elif "-n" in argv[1:]: + # -n edits the stack without a cd: `pushd -n DIR` puts DIR below the top, a bare + # `popd -n` drops the entry below the top (refused on a one-entry stack). With +N/-N + # (or a bare pushd -n) bash indexes the stack in ways this does not model: from there + # the stack below the top is unknown. + args = [a for a in argv[1:] if a != "-n"] + moved = False + if st.dirs is None: + pass + elif name == "pushd" and args and not re.match(r"^[+-][0-9]+$", args[0]): + st.dirs.append(resolve(args[0], st.cwd, st.env)) # dirs[-1] is index 1 + elif name == "popd" and not args: + if st.dirs: + st.dirs.pop() + else: + st.dirs = None + else: + # bash's directory stack: index 0 is the cwd, then the most recently pushed. A refused + # pushd/popd (empty stack, N out of range) changes nothing, as in bash. + args = argv[1:] + rot = args[0] if args and re.match(r"^[+-][0-9]+$", args[0]) else None + if name == "pushd" and args and rot is None: + st.cwd = resolve(args[0], st.cwd, st.env) + if st.dirs is not None: + st.dirs.append(prev) + elif st.dirs is None: # pops or rotates into the unknown part: unknown, maybe refused + st.cwd = st.old = None + st.env["PWD"] = st.env["OLDPWD"] = None + return + else: + full = [st.cwd] + st.dirs[::-1] + if rot is not None: # +N|-N: rotate (pushd) or drop (popd) entry N + k = int(rot[1:]) if rot[0] == "+" else len(full) - 1 - int(rot[1:]) + if not 0 <= k < len(full) or (name == "popd" and len(full) < 2): + moved = False + elif name == "pushd": + full = full[k:] + full[:k] + else: + moved = k == 0 + del full[k] + elif len(full) >= 2: # bare pushd swaps the top two; popd drops the top + full = [full[1], full[0]] + full[2:] if name == "pushd" else full[1:] + else: + moved = False + st.cwd, st.dirs = full[0], full[1:][::-1] + if moved: + st.old = prev + st.env["PWD"], st.env["OLDPWD"] = st.cwd, prev diff --git a/.claude/hooks/test-hooks.sh b/.claude/hooks/test-hooks.sh index 6f6c022c17..8b8e9fa470 100755 --- a/.claude/hooks/test-hooks.sh +++ b/.claude/hooks/test-hooks.sh @@ -11,6 +11,7 @@ # fails here instead of passing vacuously — which is exactly how three of these hooks were # no-ops for months (they read $TOOL_INPUT_FILE_PATH, which Claude Code never sets). # Mutation record (break hook → red, restore → green) lives in the commit body of each change. +# shellcheck disable=SC2016 # single-quoted $... are the commands under test, not this shell's set -uo pipefail HOOKS="$(cd "$(dirname "$0")" && pwd)" @@ -25,7 +26,7 @@ skp() { skip=$((skip+1)); printf 'SKIP %s (%s)\n' "$1" "$2"; } # json TOOL KEY VALUE → the stdin Claude Code would send for that tool call. json() { - python3 -c 'import json,sys; print(json.dumps({"session_id":"t","hook_event_name":"PreToolUse","tool_name":sys.argv[1],"tool_input":{sys.argv[2]:sys.argv[3]}}))' "$1" "$2" "$3" + printf '%s' "$3" | python3 -c 'import json,sys; print(json.dumps({"session_id":"t","hook_event_name":"PreToolUse","tool_name":sys.argv[1],"tool_input":{sys.argv[2]:sys.stdin.read()}}))' "$1" "$2" } # run HOOK STDIN → sets OUT, ERR, RC @@ -79,6 +80,7 @@ mkdir -p "$WORK/bin" "$WORK/repo/build_tools/sub" "$WORK/repo/other" "$WORK/repo "$WORK/repo/src/Proj/Sub" "$WORK/repo/src/NoProj" # The stub records "|": `dotnet format --include` resolves paths against the CURRENT # DIRECTORY (an absolute path matches 0 files, silently), so the cwd is part of the contract. +# shellcheck disable=SC2016 # $PWD and $* belong to the stub, expanded when it runs printf '#!/bin/sh\necho "$PWD|$*" >> "%s/dotnet-calls"\n[ -n "${HOOKTEST_HANG:-}" ] && sleep 60\nexit 0\n' "$WORK" > "$WORK/bin/dotnet"; chmod +x "$WORK/bin/dotnet" printf 'x=1\n' > "$WORK/repo/build_tools/a.py" printf 'x=1\n' > "$WORK/repo/build_tools/sub/b.py" @@ -142,7 +144,68 @@ blocked 'dotnet clean' blocked 'dotnet stryker' blocked 'echo start; dotnet build' blocked 'bash -c "dotnet build"' +# Measured bypasses of the pre-2026-11-20 hook (each exited 0): a path-qualified binary, a raw +# call beside a mention of the wrapper, and the vstest verb. +blocked '/root/.dotnet/dotnet build' +# shellcheck disable=SC2016 # expanded by the hook, not this shell +blocked '"$HOME/.dotnet/dotnet" test' +blocked 'echo dotnet-serialized; dotnet test' +blocked '.claude/scripts/dotnet-serialized build sharpy.sln && dotnet test --no-build' +blocked 'dotnet vstest src/X/bin/Debug/net10.0/X.dll' +blocked 'DOTNET_CLI_TELEMETRY_OPTOUT=1 dotnet build' +blocked 'timeout 600 env X=1 dotnet test' +blocked 'ls *.csproj | xargs -n1 dotnet build' +# shellcheck disable=SC2016 # the substitution is the command under test +blocked 'echo "$(dotnet build)"' +blocked "bash -lc 'cd src && dotnet test'" +blocked 'dotnet --diagnostics build' +# Launchers (each exited 0 at 48f71558a; the pre-2026-11-20 regex hook blocked them). +blocked 'time -p dotnet test' +blocked "find src -name '*.csproj' -exec dotnet build {} \\;" +blocked "find src -name '*.csproj' -execdir dotnet build {} +" +blocked 'ionice -c3 dotnet test' +blocked 'taskset -c 0 dotnet build' +blocked 'flock /tmp/l dotnet build' +blocked "flock -w 5 /tmp/l -c 'dotnet test'" +blocked 'watch -n 5 dotnet test' +blocked 'strace -f -o /tmp/s dotnet build' +blocked 'parallel -j2 dotnet build ::: a b' +blocked 'chrt -i 0 dotnet build' +blocked "env -S 'dotnet test --no-build'" +blocked $'(( n = 1 << 4 ))\ndotnet test' +blocked 'b=($(dotnet test))' +blocked 'echo ${x:-<(dotnet test)}' +blocked 'a=( <(dotnet build) )' +allowed 'a=( <(dotnet --version) )' +blocked "$(python3 -c 'c="dotnet test" +for _ in range(9): c = "echo $(" + c + ")" +print(c)')" +allowed 'b=($(dotnet --version))' +blocked 'echo ${x:-$(dotnet test)}' +allowed 'echo ${x:-$(dotnet --version)}' +blocked 'echo $(( $(dotnet build | wc -l) + 1 ))' +allowed $'(( n = 1 << 4 ))\ndotnet --version' +# Here-documents: a body with an odd quote must not hide the call beside it. +HDC=$(cat <<'EOS' +dotnet test && git commit -m "$(cat <<'EOF' +fix: don't skip +EOF +)" +EOS +) +blocked "$HDC" +allowed "cat <<'EOF' > .claude/tmp/n.txt +dotnet build +EOF" +# Unparseable by shell_commands but bash runs it: the whole-string fallback judges it. +blocked 'dotnet test; echo "${x:-"it'"'"'s"}"' +allowed 'ls; echo "${x:-"it'"'"'s"}"' allowed '.claude/scripts/dotnet-serialized build sharpy.sln' +allowed '.claude/scripts/dotnet-serialized vstest src/X/bin/Debug/net10.0/X.dll' +allowed '.claude/scripts/dotnet-serialized build sharpy.sln && .claude/scripts/dotnet-serialized test --no-build' +allowed 'grep -rn "dotnet build" docs/' +allowed 'echo dotnet test' +allowed 'dotnet src/X/bin/Debug/net10.0/X.dll' allowed '.claude/scripts/dotnet-serialized run --project src/Sharpy.Cli -- run file.spy' allowed 'dotnet --version' allowed 'dotnet --list-sdks' @@ -151,11 +214,635 @@ allowed 'dotnet tool list' allowed 'bash build_tools/regenerate_spy_stdlib.sh' allowed 'src/Sharpy.Cli/bin/Debug/net10.0/sharpyc run file.spy' allowed 'ls' -# Known false positive, NOT asserted either way: `grep "dotnet build" docs/` is blocked because -# `"` is a delimiter so that `bash -c "dotnet build"` is caught. The hook errs toward blocking; -# the workaround is single quotes. +allowed "dotnet build 'unterminated" +# A script the text runs but does not show is pattern-checked; a literal one is walked. +blocked $'bash < run.sh <<\'EOF\'\ndotnet test\nEOF\nbash run.sh' +blocked 'echo "dotnet test --no-build" > .claude/tmp/r.sh; sh .claude/tmp/r.sh' +blocked "printf 'dotnet test\\n' > .claude/tmp/t.sh && . .claude/tmp/t.sh" +allowed 'eval "$X"' +allowed 'echo "dotnet --info" | bash' +allowed $'cat < .claude/tmp/n.md\nrun dotnet test\nEOF' +# The hook fails closed (review round 6): unreadable input, a python3 that cannot start, and a +# command past the 128 KiB argv/env string cap (it used to exit 126, which does not block). +# big HOOK STDIN RC NAME: the case name stands in for the 200 KB+ input. +big() { run "$1" "$2"; if [ "$RC" -eq "$3" ]; then ok "$4"; else bad "$4" "rc=$RC err=${ERR:0:300}"; fi; } +nopy() { printf '%s' "$2" | PATH=/nonexistent "$HOOKS/$1" 2>/dev/null; RC=$?; if [ "$RC" -eq 2 ]; then ok "$1: python3 missing: deny"; else bad "$1: python3 missing: deny" "rc=$RC"; fi; } +BIG=$(python3 - <<'PY' +print("cat <<'EOF'\n" + "a long here-document body line, $(not run) \"quoted\" 'single'\n" * 4000 + "EOF") +PY +) +if [ "${#BIG}" -gt 200000 ]; then ok "BIG is ${#BIG} bytes"; else bad "BIG is over 200 KB" "${#BIG}"; fi +big enforce-dotnet-serialized.sh "$(json Bash command "$BIG"$'\n''dotnet test')" 2 "block: a 200 KB+ command ending in dotnet test" +big enforce-dotnet-serialized.sh "$(json Bash command "$BIG"$'\n''echo done')" 0 "allow: a 200 KB+ command ending in echo done" run enforce-dotnet-serialized.sh 'garbage' -if [ "$RC" -eq 0 ]; then ok "bad stdin: allow (Bash hook fails open by design; the lock is the safety net)"; else bad "bad stdin: allow" "rc=$RC"; fi +if [ "$RC" -eq 2 ] && [ -n "$ERR" ]; then ok "bad stdin: block"; else bad "bad stdin: block" "rc=$RC"; fi +run enforce-dotnet-serialized.sh '{"tool_name":"Bash","tool_input":{}}' +if [ "$RC" -eq 2 ] && [ -n "$ERR" ]; then ok "no command string: block"; else bad "no command string: block" "rc=$RC"; fi +nopy enforce-dotnet-serialized.sh "$(json Bash command 'ls')" + +echo "== guard-shared-tree.sh" +# A scratch repository with the session layout: MAIN (the shared main worktree), a linked worktree +# under MAIN/.claude/worktrees (as an isolated agent gets), one outside it (a scratchpad worktree), +# a .NET project with build outputs, and build_tools/bin/ (tracked source, not a build output). +G="$WORK/g"; MAIN="$G/main"; WT="$MAIN/.claude/worktrees/wt1"; SWT="$G/scratch/wt2" +mkdir -p "$G" +git init -q -b dev "$MAIN" +mkdir -p "$MAIN/src/P/bin" "$MAIN/src/P/obj" "$MAIN/build_tools/bin" "$MAIN/.claude/tmp/x" +echo x > "$MAIN/src/a.txt"; echo '' > "$MAIN/src/P/P.csproj"; echo t > "$MAIN/build_tools/bin/tool" +git -C "$MAIN" add src build_tools +git -C "$MAIN" -c user.email=t@t -c user.name=t commit -qm init +git -C "$MAIN" -c user.email=t@t -c user.name=t commit -q --allow-empty -m second +mkdir -p "$MAIN/.claude/worktrees/stale/src" # a leftover directory, not a registered worktree +git init -q "$G/other" # a scratch repository: never guarded +ln -s "$MAIN" "$G/link" # a symlink to the main worktree +git -C "$MAIN" worktree add -q "$WT" -b claude/x +git -C "$MAIN" worktree add -q "$SWT" -b claude/y +mkdir -p "$WT/obj" +# Existing scripts the session runs (untracked here): a script the text does not write is a program. +mkdir -p "$MAIN/.venv" "$MAIN/.claude/hooks" +for f in .venv/sharpy-env.sh build_tools/setup_env.sh build_tools/regenerate_spy_stdlib.sh .claude/hooks/test-hooks.sh .claude/tmp/old.sh; do + echo ':' > "$MAIN/$f" +done +git -C "$MAIN" update-ref refs/remotes/origin/dev HEAD +git -C "$MAIN" update-ref refs/remotes/origin/claude/remote-only HEAD +# gjson COMMAND CWD [AGENT_ID]: a non-empty AGENT_ID is the input a subagent's tool call carries. +gjson() { printf '%s' "$1" | python3 -c 'import json,sys; d={"session_id":"t","hook_event_name":"PreToolUse","cwd":sys.argv[1],"tool_name":"Bash","tool_input":{"command":sys.stdin.read()}}; d.update({"agent_id":sys.argv[2],"agent_type":"general-purpose"} if sys.argv[2] else {}); print(json.dumps(d))' "$2" "${3:-}"; } +gname() { local c="${1//$'\n'/\\n}"; printf '%s%s @ %s' "${3:+[agent] }" "${c//"$G"\//}" "${2#"$G"/}"; } +gdeny() { CLAUDE_PROJECT_DIR="$MAIN" run guard-shared-tree.sh "$(gjson "$1" "$2" "${3:-}")"; if [ "$RC" -eq 2 ] && [ -n "$ERR" ]; then ok "deny: $(gname "$1" "$2" "${3:-}")"; else bad "deny: $(gname "$1" "$2" "${3:-}")" "rc=$RC err=$ERR"; fi; } +gallow() { CLAUDE_PROJECT_DIR="$MAIN" run guard-shared-tree.sh "$(gjson "$1" "$2" "${3:-}")"; if [ "$RC" -eq 0 ] && [ -z "$ERR" ]; then ok "allow: $(gname "$1" "$2" "${3:-}")"; else bad "allow: $(gname "$1" "$2" "${3:-}")" "rc=$RC err=$ERR"; fi; } +# 1a. The LEAD (no agent_id) in MAIN: branch moves and creation are allowed — these are the +# skills' own set-up lines (create-plan, verify-plan, bump-version), and git itself refuses them +# when they would overwrite local changes — and so is unstaging ... +L_ALLOW=('git fetch origin dev && git switch -c claude/x origin/dev' + 'git switch claude/x && git merge --ff-only' + 'git checkout dev' + 'git stash list' + 'git switch -c claude/bump-1.2.3 origin/dev' + 'git switch dev' + 'git switch --detach HEAD' + 'git checkout -b claude/new origin/dev' + 'git checkout claude/remote-only' + 'git checkout -' + 'git stash show' + 'git reset --soft HEAD' + 'git clean -n -d' + 'git clean --dry-run') +for c in "${L_ALLOW[@]}"; do gallow "$c" "$MAIN"; done +L_UNSTAGE=('git restore --staged src/a.txt' + 'git restore -S src/a.txt' + 'git reset src/a.txt' + 'git reset -q HEAD -- src/a.txt' + 'git reset HEAD src/a.txt' + 'git reset -- src/a.txt') +for c in "${L_UNSTAGE[@]}"; do gallow "$c" "$MAIN"; done +# ... the forms that destroy uncommitted work are not. +L_DENY=('git checkout -- src/a.cs' + 'git checkout .' + 'git checkout HEAD -- x' + 'git checkout src/a.cs' + 'git checkout dev src/a.txt' + 'git switch -f dev' + 'git switch --discard-changes dev' + 'git checkout --force dev' + 'git checkout -m dev' + 'git checkout -p' + 'git checkout --theirs src/a.txt' + 'git restore x' + 'git restore --staged --worktree src/a.txt' + 'git restore -SW src/a.txt' + 'git stash' + 'git stash push -m wip' + 'git stash pop' + 'git stash drop' + 'git reset --hard' + 'git reset --merge' + 'git reset --keep HEAD' + 'git reset' + 'git reset HEAD~1' + 'git clean -fd') +for c in "${L_DENY[@]}"; do gdeny "$c" "$MAIN"; done +# The worktree is found from -C, --work-tree, --git-dir, GIT_DIR/GIT_WORK_TREE, cd (cd -, +# pushd/popd), compound lists, nested commands and launchers. +gdeny "git -C $MAIN reset --hard" "$WT" +gdeny "git --work-tree=$MAIN checkout ." "$G" +gdeny "git --git-dir=$MAIN/.git reset --hard" "$G" +gdeny "GIT_DIR=$MAIN/.git GIT_WORK_TREE=$MAIN git reset --hard" "$G" +gdeny "GIT_DIR=$MAIN/.git git stash" "$G/scratch" +gdeny "export GIT_WORK_TREE=$MAIN; git reset --hard" "$G" +gallow "GIT_DIR=$G/other/.git git reset --hard" "$G" +gdeny "cd $MAIN && git checkout -- src/a.txt" "$WT" +gdeny "cd $MAIN && cd $WT && cd - && git reset --hard" "$G" +gallow "cd $WT && cd $MAIN && cd - && git reset --hard" "$G" +gdeny "pushd $WT && popd && git reset --hard" "$MAIN" +gdeny "cd src; git restore a.txt" "$MAIN" +gdeny 'FOO=1 git -c core.pager=cat --no-pager checkout -f dev' "$MAIN" +gdeny 'git status && git diff --stat || git stash' "$MAIN" +gdeny 'echo start +git reset --hard' "$MAIN" +gdeny '(git stash)' "$MAIN" +gdeny "bash -c 'git reset --hard'" "$MAIN" +# shellcheck disable=SC2016 # the $(...) is the command under test, not this shell's +gdeny 'echo "$(git stash)"' "$MAIN" +gdeny 'git status | cat; timeout 60 git clean -fdx' "$MAIN" +gdeny 'time -p git reset --hard' "$MAIN" +gdeny 'find . -maxdepth 0 -exec git reset --hard \;' "$MAIN" +gdeny 'ionice -c3 nice -n 5 git clean -fd' "$MAIN" +# 1b. A SUBAGENT (agent_id set) in MAIN: §9's verbs (checkout, restore, clean, stash, reset) in +# every form but stash list/show; `git switch` is judged by the lead's rules, so /plan-flow's stage +# agents can cut and move their branch (create-plan, verify-plan set-up lines). +A_ALLOW=('git fetch origin dev && git switch -c claude/x origin/dev' + 'git switch claude/x && git merge --ff-only' + 'git fetch origin && git switch claude/x' + 'git switch -c claude/bump-1.2.3 origin/dev' + 'git switch --detach HEAD' + 'git stash list' + 'git stash show') +for c in "${A_ALLOW[@]}"; do gallow "$c" "$MAIN" agent-1; done +A_DENY=('git checkout dev' + 'git checkout -b claude/new origin/dev' + 'git checkout -' + 'git reset --soft HEAD' + 'git clean -n -d' + 'git restore --staged src/a.txt' + 'git reset src/a.txt' + 'git stash' + 'git switch -f dev' + 'git switch --discard-changes dev' + 'git checkout -- src/a.cs') +for c in "${A_DENY[@]}"; do gdeny "$c" "$MAIN" agent-1; done +# 1c. Linked worktrees (an owner's own), scratch repos and mere mentions: never judged. +for v in 'switch -c y' 'checkout dev' 'reset --hard' 'stash' 'restore src/a.txt' 'clean -fd' 'checkout -- src/a.txt'; do + gallow "git $v" "$WT" + gallow "git $v" "$WT" agent-1 +done +gallow 'git reset --hard HEAD' "$SWT" +gallow "cd $WT && git reset --hard" "$MAIN" +gallow "git -C $WT stash" "$MAIN" agent-1 +gallow "(cd $WT && git restore src/a.txt)" "$MAIN" +gallow 'git status --short; git diff --stat; git log --oneline -1; git worktree list' "$MAIN" agent-1 +gallow 'echo "git reset --hard"; grep -n "git checkout -- x" docs.md' "$MAIN" +gallow 'git reset --hard' "$G/other" +gallow 'git reset --hard' "$G/other" agent-1 +# a subshell's cd does not leak: the trailing reset runs in MAIN again +gdeny "(cd $WT && git switch -c z2); git reset --hard" "$MAIN" +# 1d. Here-documents: a body is text, never commands, even inside "$(...)" and with an odd quote. +HD_ADD=$(cat <<'EOS' +git add -A && git commit -m "$(cat <<'EOF' +fix: don't break +EOF +)" +EOS +) +HD_BODY1=$(cat <<'EOS' +git commit -m "$(cat <<'EOF' +1) deny "git status; git reset --hard" by agents +EOF +)" +EOS +) +HD_BODY2=$(cat <<'EOS' +git commit -m "$(cat <<'EOF' +a) run "cd src && rm -rf obj" first +EOF +)" +EOS +) +HD_LINE=$(cat <<'EOS' +cat <<'EOF' > .claude/tmp/note.txt +git reset --hard +rm -rf src +EOF +EOS +) +gdeny "$HD_ADD" "$WT" +gdeny "$HD_ADD" "$WT" agent-1 +gallow "$HD_BODY1" "$MAIN" +gallow "$HD_BODY1" "$MAIN" agent-1 +gallow "$HD_BODY2" "$MAIN" +gallow "$HD_LINE" "$MAIN" +gallow "$HD_LINE" "$MAIN" agent-1 +gallow "git commit -m \"\$(cat <<'EOF' +fix: say why git reset --hard and rm -rf src are denied +EOF +)\"" "$MAIN" +# Unparseable by shell_commands but bash runs it: the whole-string fallback judges it. +# shellcheck disable=SC2016 # the ${...} is the command under test +ODD='echo "${x:-"it'"'"'s"}"' +gdeny "git reset --hard; $ODD" "$MAIN" +gallow "git reset --hard; $ODD" "$WT" +gallow "ls; $ODD" "$MAIN" +# 1e. Review round 3. +# $PWD / $OLDPWD are the command's (input cwd, then each cd), never the hook process's own: the +# hook runs here from MAIN (pushd), where a $PWD read from its environment would mis-judge. +pushd "$MAIN" >/dev/null || exit 1 +gallow 'rm -rf "$PWD/obj/junk"' "$WT" agent-1 +gallow "cd $WT && rm -rf \"\$PWD/src\"" "$MAIN" +popd >/dev/null || exit 1 +pushd "$G" >/dev/null || exit 1 +gdeny 'rm -rf "$PWD/src"' "$MAIN" +gdeny "cd $WT && cd - && rm -rf \"\$PWD/src\"" "$MAIN" +gdeny "cd $MAIN && cd $WT && rm -rf \"\$OLDPWD/src\"" "$G" +popd >/dev/null || exit 1 +# (( )) and for (( )) are arithmetic: their << is a shift, not a here-document. +gdeny $'(( y = 1 << 2 ))\ngit reset --hard' "$MAIN" +gdeny $'(( y = 1 << 2 ))\ngit reset --hard' "$MAIN" agent-1 +gdeny $'(( y <<= 1 ))\ngit reset --hard' "$MAIN" +gdeny $'for ((i=0; i<<2; i++)); do :; done\ngit reset --hard' "$MAIN" +gallow $'(( y = 1 << 2 ))\ngit status' "$MAIN" +gallow $'(( y = 1 ))\ncat <(git stash) )' "$MAIN" +gallow 'a=( <(git status) )' "$MAIN" agent-1 +# $'...' with \' inside $(...) and ${...}. +D1=$(cat <<'EOS' +echo $(echo $'it\'s'); git push --force origin dev +EOS +) +D2=$(cat <<'EOS' +echo ${x:-$'\''}; git stash list +EOS +) +D3=$(cat <<'EOS' +echo $(echo $'it\'s'); git -C MAINDIR reset --hard +EOS +) +gdeny "$D1" "$WT" +gdeny "${D3/MAINDIR/$MAIN}" "$WT" # out of the fallback's reach +gallow "$D2" "$MAIN" +# _match_brace skips a $(...) whole: its } does not close the ${. +E1=$(cat <<'EOS' +echo ${x:-$(echo })}; git push --force origin dev +EOS +) +E2=$(cat <<'EOS' +echo ${x:-$(echo }; git -C MAINDIR reset --hard)} +EOS +) +gdeny "$E1" "$WT" +gdeny "${E2/MAINDIR/$MAIN}" "$WT" # out of the fallback's reach +# 1h. Review round 6. +# Whenever the hook cannot judge, it denies: a 200 KB+ command, a python3 that cannot start, an +# internal error (here a NUL byte reaching a path call: every pattern, in any worktree). +CLAUDE_PROJECT_DIR="$MAIN" big guard-shared-tree.sh "$(gjson "$BIG"$'\n''git reset --hard' "$MAIN" agent-1)" 2 "deny: [agent] a 200 KB+ command ending in git reset --hard @ main" +CLAUDE_PROJECT_DIR="$MAIN" big guard-shared-tree.sh "$(gjson "$BIG"$'\n''git status' "$MAIN" agent-1)" 0 "allow: [agent] a 200 KB+ command ending in git status @ main" +nopy guard-shared-tree.sh "$(gjson 'git status' "$MAIN")" +CLAUDE_PROJECT_DIR="$MAIN" run guard-shared-tree.sh "{\"cwd\":\"$MAIN\",\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"git -C \\u0000x reset --hard\"}}" +if [ "$RC" -eq 2 ] && printf '%s' "$ERR" | grep -q 'the hook failed'; then ok "internal error: pattern deny"; else bad "internal error: pattern deny" "rc=$RC err=$ERR"; fi +CLAUDE_PROJECT_DIR="$MAIN" run guard-shared-tree.sh "{\"cwd\":\"$MAIN\",\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"git -C \\u0000x status\"}}" +if [ "$RC" -eq 0 ]; then ok "internal error: pattern allow"; else bad "internal error: pattern allow" "rc=$RC err=$ERR"; fi +# A git directory or work tree the text names but cannot resolve is the main one; env -C and +# sudo -D set the command's directory (the last -C of one env wins, as in GNU env). +gdeny 'GIT_DIR="$X" git reset --hard' "$WT" agent-1 +gdeny 'export GIT_DIR=$(cat .git-path); git stash' "$WT" agent-1 +gdeny 'git --git-dir="$X" reset --hard' "$WT" +gdeny 'GIT_WORK_TREE="$X" git checkout -- src/a.txt' "$WT" +gdeny 'git --work-tree="$X" clean -fd' "$WT" +gallow 'GIT_DIR="$X" git status' "$WT" agent-1 +gdeny "env -C $MAIN git reset --hard" "$WT" agent-1 +gdeny "env --chdir=$MAIN git stash" "$WT" agent-1 +gdeny "env -C .. -C ../../.. git stash" "$WT" agent-1 # ../../.. from wt1 is main +gdeny "sudo -D $MAIN git reset --hard" "$WT" +gdeny 'env -C "$X" git reset --hard' "$WT" agent-1 +gallow "env -C .claude -C .claude/worktrees/wt1 git stash" "$MAIN" agent-1 +gallow "env -C $WT git reset --hard" "$MAIN" agent-1 +gallow 'env -C src git status' "$MAIN" agent-1 +# A shell's literal here-string or here-document script is walked; one read from a pipe, a file, +# -s or <(...), and eval / bash -c / $X of a string the text does not show, is pattern-checked +# over the whole text where it runs (an unknown directory: as the main worktree). +gdeny $'bash < .claude/tmp/x.sh <<\'EOF\'\ngit reset --hard\nEOF\nbash .claude/tmp/x.sh' "$MAIN" agent-1 +gdeny 'echo "git stash" > .claude/tmp/x.sh; source .claude/tmp/x.sh' "$MAIN" agent-1 +# pushd/popd: OLDPWD moves only when bash changes directory (pushd +0 does), and after any -n the +# stack below the top is unknown. Each case ends where real bash ends (main, main, main, wt1). +gdeny "pushd -n $SWT; popd -n +1; pushd -n $WT; { pushd $G/other; }; pushd $SWT; pushd -1; git reset --hard" "$MAIN" agent-1 +gdeny "pushd $WT; pushd +2; popd -n -0; cd -; git reset --hard" "$MAIN" agent-1 +gdeny "pushd $WT; popd +1; cd -; git reset --hard" "$MAIN" agent-1 +gallow "pushd $WT; pushd +0; cd -; git reset --hard" "$MAIN" agent-1 +# Past the parse limit, from a linked worktree: rules 3-4's patterns. +gdeny "$(nest 'git push --force-with-lease --force-if-includes origin dev' 9)" "$WT" +gallow "$(nest 'git push --force-with-lease --force-if-includes origin claude/x' 9)" "$WT" +gdeny "$(nest 'git commit -am x' 9)" "$WT" +gdeny "$(nest 'git commit -a -m x' 9)" "$WT" +# 1j. Review round 8: a script file is opaque only when the text writes it (>, >>, tee, a +# cp/mv/install destination) or it does not exist yet; an existing script the text does not write +# is a program like any other (CLAUDE.md's own `. .venv/sharpy-env.sh &&` prefix). +B4_ALLOW=('. .venv/sharpy-env.sh && git stash list' + '. .venv/sharpy-env.sh && git switch -c claude/x origin/dev' + 'bash build_tools/setup_env.sh && git stash list' + '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 && rm -rf .claude/tmp/probe') +for c in "${B4_ALLOW[@]}"; do gallow "$c" "$MAIN"; done +gdeny 'echo "git reset --hard" > .claude/tmp/old.sh; bash .claude/tmp/old.sh' "$MAIN" agent-1 +gdeny 'echo "git stash" | tee .claude/tmp/old.sh; sh .claude/tmp/old.sh' "$MAIN" agent-1 +gdeny "printf 'git stash\\n' > .claude/tmp/a.sh; cp .claude/tmp/a.sh .claude/tmp/old.sh && bash .claude/tmp/old.sh" "$MAIN" agent-1 +gdeny "printf 'git stash\\n' > .claude/tmp/a.sh && mv .claude/tmp/a.sh .claude/tmp/old.sh && source .claude/tmp/old.sh" "$MAIN" agent-1 +gdeny "printf 'git stash\\n' > .claude/tmp/n/old.sh && install -m 755 -t .claude/tmp/ .claude/tmp/n/old.sh && . .claude/tmp/old.sh" "$MAIN" agent-1 +gallow "printf 'git stash\\n' > .claude/tmp/a.sh && cp .claude/tmp/a.sh .claude/tmp/b.sh && . .claude/tmp/old.sh" "$MAIN" agent-1 +gdeny '. <(echo git stash)' "$MAIN" agent-1 +gdeny "python3 -c 'open(\".claude/tmp/o.sh\", \"w\").write(\"git reset --hard\")'; bash .claude/tmp/o.sh" "$MAIN" agent-1 +pushd "$MAIN" >/dev/null || exit 1 +allowed '. .venv/sharpy-env.sh && git commit -m "fix: dotnet test flake" -- src/a.cs' +allowed '. .venv/sharpy-env.sh && grep -rn "dotnet build" docs/' +blocked 'echo "dotnet test" > .claude/tmp/old.sh; bash .claude/tmp/old.sh' +blocked 'source <(echo dotnet test)' +popd >/dev/null || exit 1 +# Hook C reads paths against the input's cwd, not its own process directory (Claude Code runs +# hooks from the session's directory; a subagent's input cwd may be a linked worktree). +# cdir PROCESS_CWD INPUT_CWD RC COMMAND +cdir() { + pushd "$1" >/dev/null || exit 1 + run enforce-dotnet-serialized.sh "$(gjson "$4" "$2")" + popd >/dev/null || exit 1 + local name="${4//$'\n'/\\n} (input cwd ${2#"$G"/}, hook run from ${1#"$G"/})" + if [ "$RC" -eq "$3" ]; then ok "rc $3: $name"; else bad "rc $3: $name" "rc=$RC err=$ERR"; fi +} +cdir "$G/other" "$MAIN" 0 '. .venv/sharpy-env.sh && echo "dotnet test"' +cdir "$MAIN" "$G/other" 2 '. .venv/sharpy-env.sh && echo "dotnet test"' +cdir "$MAIN" "$G/other" 2 'echo "dotnet test" > r.sh; bash r.sh' +cdir "$G/other" "$MAIN" 2 'cd src && echo "dotnet test" > ../.claude/tmp/old.sh && bash ../.claude/tmp/old.sh' +# 1i. Review round 7. +# B1: in a bundle each o / O takes the next argument, as bash reads it. +gdeny "bash -euo pipefail -c 'git reset --hard'" "$MAIN" agent-1 +gdeny $'bash -eo pipefail <<\'EOF\'\ngit reset --hard\nEOF' "$MAIN" agent-1 +gdeny "bash -euxo pipefail -c 'git stash'" "$MAIN" agent-1 +gdeny "bash -co pipefail 'git reset --hard'" "$MAIN" agent-1 +gdeny "bash -Oc extglob 'git reset --hard'" "$MAIN" agent-1 +gdeny "bash -euo pipefail -c 'cd $MAIN && git reset --hard'" "$WT" agent-1 # walked only +# R8: with -s, stdin is the script and the operands are its arguments (walked: the cd to main is +# out of the pattern check's reach from a linked worktree). +gdeny $'bash -s -- a b </dev/null 2>&1; RC=$? +ms=$(( ($(date +%s%N) - t0) / 1000000 )) +if [ "$RC" -eq 2 ] && [ "$ms" -lt 5000 ]; then ok "deny under 5 s: 2,000 x git add x on one line + an opaque forced push (${ms} ms)"; else bad "deny under 5 s: 2,000 x git add x + an opaque forced push" "rc=$RC ${ms} ms"; fi +# $(mktemp ...) is a fresh path in $TMPDIR, $(git rev-parse --show-toplevel) the cwd's toplevel, +# and a directory git init/clone creates (absent or empty) is a new repository. +gallow 'D=$(mktemp -d); cd "$D"; git init -q; echo x > f; git add -A; git commit -qm init' "$MAIN" agent-1 +gallow 'T=$(mktemp -d) && git init -q "$T" && git -C "$T" add -A' "$MAIN" agent-1 +gallow 'cd "$(git rev-parse --show-toplevel)" && git checkout -- src/a.cs' "$WT" agent-1 +gdeny 'cd "$(git rev-parse --show-toplevel)" && git checkout -- src/a.cs' "$MAIN" agent-1 +gdeny 'cd "$(git rev-parse --show-toplevel)" && git checkout -- src/a.cs' "$MAIN" +gdeny 'cd "$(git rev-parse --show-toplevel)/src" && git stash' "$MAIN" agent-1 +gdeny "TMPDIR=$MAIN/.claude/tmp; D=\$(mktemp -d); cd \"\$D\" && git add -A" "$MAIN" +gallow 'mkdir -p .claude/tmp/n && cd .claude/tmp/n && git init -q && git add -A' "$MAIN" agent-1 +gallow "git clone -q $G/other .claude/tmp/c && git -C .claude/tmp/c add -A" "$MAIN" agent-1 +gdeny 'git init -q && git add -A' "$MAIN" +gdeny 'git init -q src && git -C src clean -fdx' "$MAIN" +# 2. rm: denied inside MAIN, allowed for .claude/tmp/, .NET bin/obj, stale .claude/worktrees/* +# directories, linked worktrees, outside, and targets the text cannot resolve. +gdeny 'rm src/a.txt' "$MAIN" +gdeny "rm -rf $MAIN/src" "$G" +gdeny 'cd src && rm -f a.txt' "$MAIN" +gdeny 'rm -rf build_tools/bin' "$MAIN" +gdeny "rm -rf $WT" "$MAIN" +gdeny 'rm -rf .claude/worktrees/wt1' "$MAIN" +gdeny 'rm -rf -- src/a.txt' "$MAIN" +gdeny 'sudo rm -rf src' "$MAIN" +gdeny 'D=src; rm -rf "$D"' "$MAIN" +gdeny 'export D=src/a.txt; rm -f "$D"' "$MAIN" +gdeny "find src -name '*.txt' -delete" "$MAIN" +gdeny "find src -name '*.txt' -exec rm -f {} +" "$MAIN" +gallow 'rm -rf .claude/tmp/x' "$MAIN" +gallow 'find .claude/tmp -name "*.log" -delete' "$MAIN" +gallow 'rm -rf src/P/bin src/P/obj/Debug' "$MAIN" +gallow 'rm -rf src/*/obj' "$MAIN" +gallow 'rm -rf .claude/worktrees/stale' "$MAIN" +gallow 'rm -rf .claude/worktrees/stale/src' "$MAIN" agent-1 +gallow "rm -f $WT/src/a.txt" "$MAIN" +gallow 'rm src/a.txt' "$WT" +gallow "rm -rf $G/scratch/junk /tmp/sharpy-hook-nonexistent" "$MAIN" +gallow 'grep -rn "rm -rf" src' "$MAIN" +unset OUT +# shellcheck disable=SC2016 # variables of the command under test +U_ALLOW=('tmp=$(mktemp -d); rm -rf "$tmp"' + 'rm -f "${OUT}"' + 'rm -f "${OUT}.log"' + 'tmp=$(mktemp -d); rm -rf "$tmp"/*' + 'for f in src/a.txt src/P/P.csproj; do rm -f "$f"; done' + 'for f in a.txt b.txt; do rm -f "src/$f"; done' + 'RESULTS=.claude/tmp/ps-1; mkdir -p "$RESULTS"; rm -rf "$RESULTS"' + 'rm -rf "$(mktemp -d)"' + 'cd "$(mktemp -d)" && rm -rf x') +for c in "${U_ALLOW[@]}"; do gallow "$c" "$MAIN"; done +# The main worktree itself, or a directory above it: denied for anyone, however it is spelled. +for c in 'rm -rf .' 'rm -rf ./' 'cd src && rm -rf ..' "rm -rf $MAIN" 'rm -rf ../main' "rm -rf $G/mai*" "rm -rf $G"; do + gdeny "$c" "$MAIN" + gdeny "$c" "$MAIN" agent-1 +done +gdeny "rm -rf $MAIN" "$G" +gallow "rm -rf $G/other" "$MAIN" +# 3. staging without per-file pathspecs: denied in every worktree of this repository. +for a in 'add -A' 'add --all' 'add .' 'add ./' 'add -u' 'add --update' 'add -Av' 'commit -am wip' 'commit --all -m wip' 'commit -a'; do + gdeny "git $a" "$WT" +done +gdeny 'git add .' "$MAIN" +gdeny "git -C $WT add -A" "$G" +gallow 'git add src/a.txt' "$WT" +gallow 'git add -- src/a.txt src/P/P.csproj' "$MAIN" +gallow 'git commit -m "fix -a and --all handling"' "$WT" +gallow 'git commit -m wip -- src/a.txt' "$WT" +gallow 'git add -A' "$G/other" +# 4. forced push: only lease + includes, only claude/* refs. +gdeny 'git push --force origin claude/x' "$WT" +gdeny 'git push -f origin claude/x' "$WT" +gdeny 'git push -uf origin claude/x' "$WT" +gdeny 'git push origin +claude/x' "$WT" +gdeny 'git push --force-with-lease origin claude/x' "$WT" +gdeny 'git push --force-if-includes origin +claude/x' "$WT" +gdeny 'git push --force --force-with-lease --force-if-includes origin claude/x' "$WT" +gdeny 'git push --force-with-lease --force-if-includes origin dev' "$WT" +gdeny 'git push --force-with-lease --force-if-includes origin mainline' "$WT" +gdeny 'git push --force-with-lease --force-if-includes origin claude/x:dev' "$WT" +gdeny 'git push --force-with-lease --force-if-includes origin HEAD:refs/heads/mainline' "$WT" +gdeny 'git push --force-with-lease --force-if-includes origin feature/x' "$WT" +gdeny 'git push --force-with-lease --force-if-includes origin claude/x dev' "$WT" +gdeny 'git push --force-with-lease --force-if-includes origin' "$MAIN" +gdeny 'git push --mirror origin' "$WT" +gallow 'git push --force-with-lease --force-if-includes origin claude/x' "$WT" +gallow 'git push --force-with-lease=claude/x:abc123 --force-if-includes origin claude/x' "$WT" +gallow 'git push --force-with-lease --force-if-includes origin HEAD' "$WT" +gallow 'git push --force-with-lease --force-if-includes -u origin HEAD:refs/heads/claude/x' "$WT" +gallow 'git push -u origin claude/x' "$WT" +# unparseable text bash refuses too: allowed (nothing runs); unreadable input: denied. +gallow "git reset --hard 'unterminated" "$MAIN" +run guard-shared-tree.sh 'garbage' +if [ "$RC" -eq 2 ] && [ -n "$ERR" ]; then ok "bad stdin: deny"; else bad "bad stdin: deny" "rc=$RC"; fi +run guard-shared-tree.sh '{"tool_name":"Bash","tool_input":{}}' +if [ "$RC" -eq 2 ] && [ -n "$ERR" ]; then ok "no command string: deny"; else bad "no command string: deny" "rc=$RC"; fi + +echo "== require-agent-brief.sh" +# The block as contract §9 holds it today: a brief that pastes it must pass (drift between the +# hook's key sentences and the contract turns this red). +BLOCK=$(python3 -c 'import re,sys; s=open(sys.argv[1],encoding="utf-8").read(); print(re.search(r"^## 9\.[^\n]*\n(?:(?!> )[^\n]*\n)*?((?:> [^\n]*\n)+)", s, re.M).group(1), end="")' "$HOOKS/../../docs/design/verification-contract.md") +ajson() { printf '%s' "$2" | python3 -c 'import json,sys; ti={"description":"d","prompt":sys.stdin.read()}; ti.update({"subagent_type":sys.argv[2]} if sys.argv[2] else {}); print(json.dumps({"session_id":"t","hook_event_name":"PreToolUse","tool_name":sys.argv[1],"tool_input":ti}))' "$1" "$3"; } +adeny() { run require-agent-brief.sh "$(ajson "$1" "$2" "$3")"; if [ "$RC" -eq 2 ] && printf '%s' "$ERR" | grep -qF 'never from git.'; then ok "deny: $4"; else bad "deny: $4" "rc=$RC err=$ERR"; fi; } +aallow() { run require-agent-brief.sh "$(ajson "$1" "$2" "$3")"; if [ "$RC" -eq 0 ] && [ -z "$ERR" ]; then ok "allow: $4"; else bad "allow: $4" "rc=$RC err=$ERR"; fi; } +if [ -n "$BLOCK" ]; then ok "contract §9 block found"; else bad "contract §9 block found" "no '> ' block under '## 9.'"; fi +TASK='Implement task 3 of the plan in src/Sharpy.Compiler/Semantic.' +PARA='Shared tree: never run git checkout, restore, clean, stash, reset or rm on repo paths; restore a mutation with cp; use .claude/scripts/dotnet-serialized.' +UNQUOTED=$(printf '%s\n' "$BLOCK" | sed 's/^> //') +ONELINE=$(printf '%s' "$UNQUOTED" | tr '\n' ' ') +INDENTED=$(printf '%s\n' "$UNQUOTED" | sed 's/^/ /') +HALF=$(printf '%s\n' "$UNQUOTED" | grep -vF 'never from git') +adeny Agent "$TASK" general-purpose "general-purpose brief without the block" +adeny Agent "$TASK" "" "no subagent_type (general-purpose) without the block" +adeny Agent "$TASK" implementer "implementer brief without the block" +adeny Agent "$TASK" Explore "Explore brief without the block" +adeny Agent "$TASK +$PARA" general-purpose "a paraphrase of the block" +adeny Agent "$TASK +$HALF" general-purpose "the block with its cp/restore line dropped" +adeny Task "$TASK" general-purpose "the Task tool name" +if printf '%s' "$ERR" | grep -qF '> with ' && ! printf '%s' "$ERR" | grep -q '^## 10'; then + ok "denial carries the §9 block and only it"; else bad "denial carries the §9 block and only it" "err=$ERR"; fi +aallow Agent "$TASK + +$BLOCK" general-purpose "the block as quoted in the contract" +aallow Agent "$UNQUOTED +$TASK" implementer "the block unquoted" +aallow Agent "$TASK $ONELINE" "" "the block re-wrapped onto one line" +aallow Agent "SHARED TREE: +$INDENTED +$TASK" test-expert "the block indented" +for t in fork web-fetch claude-code-guide statusline-setup; do + aallow Agent "$TASK" "$t" "exempt subagent_type $t" +done +BIGP=$(python3 -c 'print("Context the agent needs, repeated to pass 200 KB.\n" * 4500, end="")') +big require-agent-brief.sh "$(ajson Agent "$BIGP" general-purpose)" 2 "deny: a 200 KB+ brief without the block" +big require-agent-brief.sh "$(ajson Agent "$BIGP"$'\n'"$BLOCK" general-purpose)" 0 "allow: a 200 KB+ brief with the block" +run require-agent-brief.sh '{"tool_name":"Agent","tool_input":{"subagent_type":"general-purpose"}}' +if [ "$RC" -eq 2 ] && [ -n "$ERR" ]; then ok "no prompt string: deny"; else bad "no prompt string: deny" "rc=$RC"; fi +run require-agent-brief.sh 'garbage' +if [ "$RC" -eq 2 ] && [ -n "$ERR" ]; then ok "bad stdin: deny"; else bad "bad stdin: deny" "rc=$RC"; fi +nopy require-agent-brief.sh "$(ajson Agent "$TASK" general-purpose)" echo echo "hooks: $pass passed, $fail failed, $skip skipped" diff --git a/.claude/settings.json b/.claude/settings.json index 0267a758dc..c03a28979f 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -8,6 +8,21 @@ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/enforce-dotnet-serialized.sh\"", "timeout": 5 + }, + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/guard-shared-tree.sh\"", + "timeout": 5 + } + ] + }, + { + "matcher": "Agent|Task", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/require-agent-brief.sh\"", + "timeout": 2 } ] }, diff --git a/.claude/skills/commit/SKILL.md b/.claude/skills/commit/SKILL.md index 75809394d1..08c208edf2 100644 --- a/.claude/skills/commit/SKILL.md +++ b/.claude/skills/commit/SKILL.md @@ -23,8 +23,7 @@ Run these in parallel: ### 2. Stage files If there are unstaged or untracked changes: -- Stage specific files by explicit per-file pathspec — **never** use `git add -A` or `git add .` -- The working tree may be shared with other agents: `git add ` also stages a peer's uncommitted hunks in that file. Check `git diff --cached --stat` before committing; if a file mixes your work with a peer's, ask before staging it. Never `git checkout`/`restore`/`stash`/`reset`/`clean` to tidy the tree. +- Stage per-file pathspecs (`.claude/hooks/guard-shared-tree.sh` denies `-A`, `.`, `-u`). `git add ` also stages a peer's uncommitted hunks in that file: check `git diff --cached --stat` before committing; if a file mixes your work with a peer's, ask before staging it. Never tidy the tree (contract §9). - Do **not** stage files that likely contain secrets (`.env`, `credentials.json`, etc.) — warn the user if such files are present - If only some files are relevant (e.g., mix of unrelated changes), ask the user which to include diff --git a/.claude/skills/compiler-audit/SKILL.md b/.claude/skills/compiler-audit/SKILL.md index a93bfd31fb..0ff8a381f6 100644 --- a/.claude/skills/compiler-audit/SKILL.md +++ b/.claude/skills/compiler-audit/SKILL.md @@ -12,7 +12,7 @@ If `$ARGUMENTS` is non-empty, narrow to that focus area (e.g. `semantic`, `codeg ## Ground rules for every agent -- **Read-only.** Read files, search, run tests. No edits, no `git` mutations. Shared-tree block (contract §9): *The working tree is shared. Never run `git checkout`, `git restore`, `git clean`, `git stash`, `git reset`, or `rm` on repo paths. REPORT `git status`; do not "make it clean".* +- **Read-only.** Read files, search, run tests. No edits, no `git` mutations. Paste contract §9's block verbatim into every brief (`.claude/hooks/require-agent-brief.sh` denies a spawn without it). - **dotnet only via the wrapper**, with `dangerouslyDisableSandbox: true` (a PreToolUse hook blocks raw `dotnet`; sandboxed callers exit 125): `.claude/scripts/dotnet-serialized test --filter "FullyQualifiedName~X" --no-build`. Filtered runs are for the agent's own probes. - **The whole-solution run happens once**, started by the lead in the background before spawning: `/ci-gate` by default (~20 min), or the local `.claude/scripts/dotnet-serialized test --filter "Category!=Benchmark" --logger "console;verbosity=normal"` when it exits 3. Hand every agent the run id (`gh run view --log`, `gh run download -p 'trx-*'`) or the log path the wrapper printed (`dotnet-serialized: log -> `) — agents read it, they do not re-run it. A run must be at HEAD; a local log's binaries must postdate HEAD's build, and a log older than the last build is not a measurement. - **Every count carries its sha**: `value @ (measured)`, never derived. `git rev-parse --short HEAD` first. diff --git a/.claude/skills/create-plan/SKILL.md b/.claude/skills/create-plan/SKILL.md index 4f45c294f1..7a8c9f5f08 100644 --- a/.claude/skills/create-plan/SKILL.md +++ b/.claude/skills/create-plan/SKILL.md @@ -127,7 +127,7 @@ Before writing the plan: - Find mirrored/parallel sites: if the fix lands in one arm of a switch, dispatch table, or per-position handler, enumerate the other arms — a plan that patches one arm without a completeness scan is not a plan - Note which generated artifacts the change reaches (spy-stdlib C#, spy-test C#, stdlib docs, oracle ledger) and which test projects (CLAUDE.md › Testing › Commit gate) -Research `dotnet` runs go through `.claude/scripts/dotnet-serialized` with `dangerouslyDisableSandbox: true` (raw `dotnet` is hook-blocked); prefer `/spy-run`, `/spy-emit`, `/quick-check`. +Research `dotnet` runs: the wrapper (hook-enforced) with `dangerouslyDisableSandbox: true`; prefer `/spy-run`, `/spy-emit`, `/quick-check`. ### 2.1. Stage 0 (generator groups) diff --git a/.claude/skills/dogfood-analyze/SKILL.md b/.claude/skills/dogfood-analyze/SKILL.md index 04f272d023..552536a91a 100644 --- a/.claude/skills/dogfood-analyze/SKILL.md +++ b/.claude/skills/dogfood-analyze/SKILL.md @@ -11,7 +11,8 @@ Use the `dogfood-analyst` agent via the Task tool to perform the analysis: ``` Task tool: subagent_type: dogfood-analyst - prompt: (see below) + prompt: (see below), then the contract §9 block verbatim (docs/design/verification-contract.md; + .claude/hooks/require-agent-brief.sh denies a prompt without it) ``` If `$ARGUMENTS` is empty (no specific directory given), analyze all results: diff --git a/.claude/skills/implement-plan/SKILL.md b/.claude/skills/implement-plan/SKILL.md index f812eea559..4f0a7b460f 100644 --- a/.claude/skills/implement-plan/SKILL.md +++ b/.claude/skills/implement-plan/SKILL.md @@ -90,7 +90,7 @@ Break the plan into commit-sized tasks (via `TaskCreate` or the plan-file checkl 4. **Class tasks** — if the plan has a **Defect Class** section: create the **matrix/sweep task** (the sibling cells the plan enumerated go green, or the standing harness gains the cells) and the **drain task** (every allowlist row the fix drains is deleted, stale rows fail; with stage 0, the plan's known-red rows, never a matrix re-derived from the plan), both blocked by the fix tasks. A bug-fix plan with a Defect Class section but no matrix task is incomplete — add it. 5. **Regen task** — immediately after the **first** task that touches `Semantic/`, `Lowering/`, or `CodeGen/`, not at the end: regenerate spy-stdlib C# (`build_tools/regenerate_spy_stdlib.sh`), spy-test C#, stdlib docs (`build_tools stdlib generate --force`), and the oracle ledger (`/regenerate-snapshots` covers the C# snapshots). Read the regen diff as **findings**: a newly red regenerated test is a live regression until disproven. 6. **Excluded sections**: skip any sections listed in `--exclude` -7. **Final tasks**: a "Run final verification" task (lead + standalone `verification-expert`) and a "Run dotnet format whitespace" task, both blocked by all implementation tasks +7. **Final tasks**: a "Run final verification" task (lead + standalone `verification-expert`) and a "Run /format" task, both blocked by all implementation tasks ## Implementation Workflow diff --git a/.claude/skills/plan-flow/SKILL.md b/.claude/skills/plan-flow/SKILL.md index 52ed050900..5c11da9c12 100644 --- a/.claude/skills/plan-flow/SKILL.md +++ b/.claude/skills/plan-flow/SKILL.md @@ -54,8 +54,8 @@ Spawn one `general-purpose` agent per stage, in the background, with no model ov - the stage's `SKILL.md` to read and follow, the plan path, the branch and its tip sha; - the owner rulings that apply, as comment ids to read, never as your paraphrase; - for a verifier, the previous agent's notable claims **listed as claims to grade, not as facts**, with what it said it measured and what it said it inferred. Hand over the code and the question, not your conclusion: an agent given a hypothesis tends to return it confirmed; -- the environment rules from CLAUDE.md the agent will otherwise trip on: `.claude/scripts/dotnet-serialized` for every dotnet call, the cloud-session prefixes, `run` not `emit` for a crash claim, the CPython oracle version; -- the shared-tree contract (contract §9): a temporary mutation is copied aside first and restored with `cp` and checked with `cmp`; never `git checkout`, `restore`, `clean`, `stash`, `reset` or `rm` on repo paths; never `--no-build` after an edit; scratch files in a named scratchpad directory; +- the environment rules from CLAUDE.md the agent will otherwise trip on: the cloud-session prefixes, `run` not `emit` for a crash claim, the CPython oracle version; +- the contract §9 block, verbatim (`.claude/hooks/require-agent-brief.sh` denies a brief without it), plus: check a `cp`-restored mutation with `cmp`; never `--no-build` after an edit; scratch files in a named scratchpad directory; - its limits: which files it may commit, the branch it pushes, and that it opens no pull request, posts nothing on GitHub, files no issue and merges nothing. What its skill would have it post, it lists as owed; - what to report: the verdict or result, each finding with its measurement (command, sha, output), what it measured against what it inferred, what it did not run, the sha it pushed and `git status --short`. diff --git a/.claude/skills/push/SKILL.md b/.claude/skills/push/SKILL.md index d535601108..0f5cd251b0 100644 --- a/.claude/skills/push/SKILL.md +++ b/.claude/skills/push/SKILL.md @@ -77,7 +77,7 @@ Then run the matching regeneration checks (use `dangerouslyDisableSandbox` — t git push -u origin ``` -If the push fails due to diverged history, **do not force push**: report the error and suggest `git pull --rebase` or ask the user how to proceed. The one exception is CLAUDE.md › Git & Release: `git push --force-with-lease --force-if-includes` on a `claude/*` branch this session created, after it rewrote its own unmerged commits. A `GH013: Repository rule violations` refusal on `dev` is the PR-only ruleset, not a transient: move the commits to a lane branch (`git branch claude/` then open the PR) rather than retrying. +If the push fails due to diverged history, **do not force push**: report the error and suggest `git pull --rebase` or ask the user how to proceed. The one exception is CLAUDE.md › Git & Release (its flags and refs enforced by `.claude/hooks/guard-shared-tree.sh`). A `GH013: Repository rule violations` refusal on `dev` is the PR-only ruleset, not a transient: move the commits to a lane branch (`git branch claude/` then open the PR) rather than retrying. ### 3. Report diff --git a/.claude/skills/verify-plan/SKILL.md b/.claude/skills/verify-plan/SKILL.md index 4a866737c0..2e55e698cc 100644 --- a/.claude/skills/verify-plan/SKILL.md +++ b/.claude/skills/verify-plan/SKILL.md @@ -29,7 +29,7 @@ Read the plan file completely before proceeding. Record `git rev-parse --short H ## Probing rules -- Never run `dotnet` directly — `.claude/scripts/dotnet-serialized` (drop-in wrapper; needs `dangerouslyDisableSandbox: true`), or the `/spy-run` / `/spy-emit` / `/quick-check` skills for inline Sharpy source. +- `dotnet` via `.claude/scripts/dotnet-serialized` (hook-enforced; `dangerouslyDisableSandbox: true`), or `/spy-run` / `/spy-emit` / `/quick-check` for inline Sharpy source. - An ICE claim (SPY0908 / CS-leak) is confirmed or refuted with **`run`**, never `emit` — `emit csharp` succeeds on broken C#, and `emit diagnostics` cannot see the C# stage. A failing `run` cannot show warnings; use `emit diagnostics` for those. - `python3 -c "..."` for every claimed Python behavior; `print(x)` is never a type probe — bind to a deliberately wrong annotation (`b: bool = expr`). - `gh` needs `dangerouslyDisableSandbox: true` (TLS in the sandbox). diff --git a/.github/workflows/python-build-tools.yml b/.github/workflows/python-build-tools.yml index f3fa18c2c4..c389059277 100644 --- a/.github/workflows/python-build-tools.yml +++ b/.github/workflows/python-build-tools.yml @@ -209,9 +209,9 @@ jobs: python -m build_tools stdlib generate --check # The falsification harness for the Claude Code hooks (W0.1, 7c9567288; run in CI since #2458, - # W0.4): 61 cases in about 13 s locally, needing bash and python3 only (each hook's `dotnet` is a - # stub). Its python branch of format-on-save.sh SKIPS without ruff or black on PATH, so ruff is - # installed and the step fails on any skip: a runner without it would otherwise pass 59 cases. + # W0.4): 532 cases in about 45 s locally, needing bash, git and python3 only (each hook's `dotnet` + # is a stub). Its python branch of format-on-save.sh SKIPS without ruff or black on PATH, so ruff + # is installed and the step fails on any skip: a runner without it would otherwise pass 529 cases. hooks: needs: changes if: ${{ needs.changes.outputs.relevant == 'true' }} diff --git a/CLAUDE.md b/CLAUDE.md index 03820b8e23..4ee1a8793a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,8 +31,8 @@ src/Sharpy.Cli/bin/Debug/net10.0/sharpyc project x.spyproj ## Operational Contracts -- **Serialized dotnet:** never call `dotnet build`/`test`/`run` directly; use `.claude/scripts/dotnet-serialized` (same args, output, exit code), enforced by a PreToolUse hook. -- **Parallel agents share one working tree.** Tell agents *never run `git checkout` / `restore` / `clean` / `stash` / `reset` / `rm` on repo paths*. Commit in small slices; re-check `git diff --stat` after each wave. +- **Serialized dotnet:** `dotnet` only via `.claude/scripts/dotnet-serialized` (same args, output, exit code; hook-enforced). +- **Parallel agents share one working tree:** contract §9; its block goes in every brief (hook-enforced, as are its git/`rm` bans in the main worktree). Commit in small slices; re-check `git diff --stat` after each wave. - **Test logs:** each wrapper call tees to its own `.claude/tmp/dotnet-serialized-*.log` and first prints `dotnet-serialized: log -> `. Grep your own printed path (`-latest.path` may be a peer's) instead of re-running. ## Critical Rules @@ -102,4 +102,4 @@ Report `passed/failed/skipped @ sha (measured)`; a red needs a control run at th ## Git & Release -Work on `claude/` cut from `origin/dev`; land it by PR into `dev`, merged on green by its opening session (never over a red, nor before a required independent review: Process item 6). Plan stages: `docs/process/plans/.md` commits and a `full` generator's stage 0 (§11); `full`: one plan PR, `light`: the implementation PR. A ruled `band` bug (or no charter row, no §12 letter) with a contained fix needs no plan: a PR with a generated or differential test and its mutation record. Implementation and no-plan PRs list issues closed and filed. `mainline` takes only the owner's merge of `dev`, after the bump lane. Force-push only with `--force-with-lease --force-if-includes`, and only a `claude/*` branch this session created, to rewrite its own unmerged commits (an over-long subject); never `dev`, `mainline` or a branch holding another session's commits. Say so on the PR; its review line stays current only if `git diff ` is empty. [Process](docs/process/README.md). +Work on `claude/` cut from `origin/dev`; land it by PR into `dev`, merged on green by its opening session (never over a red, nor before a required independent review: Process item 6). Plan stages: `docs/process/plans/.md` commits and a `full` generator's stage 0 (§11); `full`: one plan PR, `light`: the implementation PR. A ruled `band` bug (or no charter row, no §12 letter) with a contained fix needs no plan: a PR with a generated or differential test and its mutation record. Implementation and no-plan PRs list issues closed and filed. `mainline` takes only the owner's merge of `dev`, after the bump lane. Force-push (flags, `claude/*` only: hook-enforced) only a branch this session created, to rewrite its own unmerged commits (an over-long subject), never one holding another session's commits. Say so on the PR; its review line stays current only if `git diff ` is empty. [Process](docs/process/README.md). diff --git a/build_tools/scorecard-baseline.json b/build_tools/scorecard-baseline.json index 116927bd08..02759411aa 100644 --- a/build_tools/scorecard-baseline.json +++ b/build_tools/scorecard-baseline.json @@ -1,6 +1,6 @@ { - "procedure_bytes": 145556, - "claude_md_bytes": 9304, + "procedure_bytes": 145065, + "claude_md_bytes": 9205, "allowlist_rows_outside_seed": 2184, "allowlist_rows_seed": 2368 }