From 612d8b36ca9cd3cea9e7fff40f48d3086c81c121 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:12:52 +0000 Subject: [PATCH 01/14] build(hooks): enforce the shared-tree contract on Bash commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit guard-shared-tree.sh (PreToolUse, matcher Bash) denies, with exit 2 and a message naming contract §9 and the safe alternative: - git checkout/restore/clean/stash/reset/switch whose worktree is the repository's main worktree (git-dir = common-dir), resolved from git -C, --work-tree, a preceding cd/pushd, or the input cwd; linked worktrees (.claude/worktrees/*, scratchpad worktrees) are allowed; - rm of a path in the main worktree, except .claude/tmp/ and .NET bin/ obj/ beside a *proj (build_tools/bin/ is tracked source); - git add -A/--all/-u/--update/. and git commit -a/--all in any worktree of this repository (-u and commit -a stage a peer's hunks exactly as -A does); - a forced push unless it has --force-with-lease and --force-if-includes and every pushed ref is claude/* (never dev, mainline, --mirror). shell_commands.py splits a command into the simple commands bash runs (lists, pipes, subshells, $(...), backticks, bash -c, eval, VAR=v and env/sudo/timeout/xargs prefixes, heredoc bodies dropped). The header states what it cannot see. 78 new harness cases. Mutation record (bash .claude/hooks/test-hooks.sh, restored with cp+cmp): - break: main_tree() drops the git-dir = common-dir test -> 12 FAIL (every linked-worktree allow case); restore -> 0 FAIL - break: main_tree() returns False -> 29 FAIL (every main-tree deny); restore -> 0 FAIL - break: lease rule requires only --force-with-lease -> 1 FAIL (deny: git push --force-with-lease origin claude/x); restore -> 0 FAIL Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy --- .claude/hooks/guard-shared-tree.sh | 222 +++++++++++++++++ .claude/hooks/shell_commands.py | 377 +++++++++++++++++++++++++++++ .claude/hooks/test-hooks.sh | 105 ++++++++ .claude/settings.json | 5 + 4 files changed, 709 insertions(+) create mode 100755 .claude/hooks/guard-shared-tree.sh create mode 100644 .claude/hooks/shell_commands.py diff --git a/.claude/hooks/guard-shared-tree.sh b/.claude/hooks/guard-shared-tree.sh new file mode 100755 index 000000000..cc9dff7c4 --- /dev/null +++ b/.claude/hooks/guard-shared-tree.sh @@ -0,0 +1,222 @@ +#!/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. `git checkout|restore|clean|stash|reset|switch` (any form) whose worktree is the repository's +# MAIN worktree (`git rev-parse --git-dir` = `--git-common-dir`), the one parallel sessions +# share. A linked worktree (.claude/worktrees/*, a scratchpad `git worktree add`) is the +# session's own and is allowed. +# 2. `rm` of a path inside the main worktree, except under .claude/tmp/ and a .NET build output +# (a `bin/` or `obj/` directory beside a *.*proj file; build_tools/bin/ is source). A path +# in a linked worktree or outside the repository (scratchpad, /tmp) is allowed. The path's +# parent decides, so removing a linked worktree's root is denied: `git worktree remove`. +# 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. +# 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`, +# a preceding `cd `/`pushd`, 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: compound lists, pipes, subshells, +# `$(...)`, backticks, `bash -c '...'`, `eval`, leading VAR=v, `env`/`sudo`/`timeout`/`xargs`... +# +# Cannot see: a script file (`bash x.sh`), a function or alias, a python/node subprocess, `find +# -delete`, `xargs rm` input, `git rm`, `unlink`/`mv`, a path held in `$(...)`, a variable set +# earlier in the same command, a `git` alias, `--git-dir` without `--work-tree`. An unparseable +# command (unterminated quote) is allowed: bash refuses to run it as well. +# +# Hook input is JSON on stdin (tool_input.command, cwd). Falsified by .claude/hooks/test-hooks.sh. +input=$(cat) +read -r -d '' PROG <<'PY' +import glob, json, os, subprocess, sys +sys.dont_write_bytecode = True +sys.path.insert(0, os.environ["HOOKS_DIR"]) +import shell_commands as sc + +try: + data = json.loads(os.environ["HOOK_INPUT"]) + cmd = data.get("tool_input", {}).get("command", "") + cwd = data.get("cwd") or os.getcwd() +except Exception: + sys.exit(0) +if not isinstance(cmd, str) or not cmd: + sys.exit(0) + +_cache = {} +def repo_of(path): + """(toplevel, git_dir, common_dir) of the worktree holding path, or 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 = subprocess.run(["git", "-C", p, "rev-parse", "--path-format=absolute", + "--show-toplevel", "--git-dir", "--git-common-dir"], + capture_output=True, text=True) + 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] + +project = repo_of(os.environ.get("CLAUDE_PROJECT_DIR") or cwd) +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] + +def deny(msg): + sys.stderr.write("BLOCKED by .claude/hooks/guard-shared-tree.sh: " + msg + "\n") + sys.exit(2) + +SHARED = ("The main worktree is shared with parallel sessions (contract §9): REPORT `git status`, " + "do not make it clean; restore a mutation from your `cp` copy. To switch, reset or stash, " + "work in your own worktree (`git worktree add /wt `), where it is allowed.") +GIT_OPTS_WITH_ARG = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env", + "--exec-path", "--super-prefix"} + +def check_git(argv, cwd): + args, i, where = argv[1:], 0, cwd + while i < len(args) and args[i].startswith("-"): + a = args[i] + if a in GIT_OPTS_WITH_ARG and i + 1 < len(args): + if a == "-C": + where = sc.resolve(args[i + 1], where) + elif a == "--work-tree": + where = sc.resolve(args[i + 1], where) + i += 2 + continue + if a.startswith("--work-tree="): + where = sc.resolve(a.split("=", 1)[1], where) + i += 1 + if i >= len(args): + return + verb, rest = args[i], args[i + 1:] + info = repo_of(where) + if verb in ("checkout", "restore", "clean", "stash", "reset", "switch"): + if main_tree(info): + deny("`git %s` in the main worktree %s. %s" % (verb, 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": + check_push(rest, where, info) + +def check_push(rest, where, info): + 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": + out = subprocess.run(["git", "-C", where, "symbolic-ref", "--short", "-q", "HEAD"], + capture_output=True, text=True).stdout.strip() + dst = out or "HEAD" + 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): + 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) + for t in targets: + path = sc.resolve(t, cwd) + 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 rel == "." or not parts: + deny("`rm` of the main worktree itself.") + if parts[:2] == [".claude", "tmp"] and len(parts) > 2: + continue + 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). Contract §9." % (t, info[0])) + +def visit(argv, cwd): + name = os.path.basename(argv[0]) + if name == "git": + check_git(argv, cwd) + elif name == "rm": + check_rm(argv, cwd) + +try: + sc.walk(cmd, cwd, visit) +except sc.ParseError: + sys.exit(0) +sys.exit(0) +PY +HOOK_INPUT="$input" HOOKS_DIR="$(cd "$(dirname "$0")" && pwd)" exec python3 -c "$PROG" diff --git a/.claude/hooks/shell_commands.py b/.claude/hooks/shell_commands.py new file mode 100644 index 000000000..8b932744a --- /dev/null +++ b/.claude/hooks/shell_commands.py @@ -0,0 +1,377 @@ +"""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)`` calls ``visit(argv, cwd)`` for every simple command, in order, with: + +- separators split: ``;`` ``&&`` ``||`` ``|`` ``|&`` ``&`` and newlines; +- ``( ... )`` subshells and ``$( ... )`` / backtick substitutions walked as nested commands, their + ``cd`` not leaking out; ``bash|sh|zsh|dash -c '