"""Block a Claude Code tool call that breaks a checkable rule, unless the call overrides the rule. usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin) rule-hook overrides (prints this chunk's overrides) settings.json runs it before each Bash, Edit, MultiEdit and Write call, in every session and subagent. The rules: {rules} A file a Bash command writes, such as through `cat > Dockerfile`, is not checked. A call overrides a rule with `# rule-override : `: - anywhere in a Bash command, such as a trailing comment - in a file, as a comment line in the text the edit writes - in Markdown, as `` Each override that let a call through is appended to rule-overrides.tsv in the git directory of the checkout it touched: UTC time, branch, the commit checked out, rule, reason, and the file written or the command's first line. An override outside any git checkout is not logged. `rule-hook overrides` prints the lines whose commit the current branch's reflog holds: those the default branch lacks, and those logged under the branch's own name. Run with no arguments in a terminal, it prints this help. Exit 2 with the rule, why it holds and how to override it, when a rule blocks the call, or when an override cannot be logged; 0 otherwise. Exit 1, a non-blocking error to Claude Code, on input it cannot read. """ import dataclasses import hashlib import json import os import pathlib import stat import subprocess import sys import time from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text from rule_hook.rules import Breach, command_breaches, commits, file_breaches, rules_help, verdict, Verdict from failure import Failure import rank_todo from shell_command import simple_commands from utc_stamp import utc LOG = "rule-overrides.tsv" def main(argv: list[str], stdin: str) -> int: if argv in (["-h"], ["--help"]) or not argv and not stdin: print(__doc__.strip().replace("{rules}", rules_help())) return 0 if argv == ["overrides"]: return print_overrides(os.getcwd()) if argv: print(f"unknown arguments: {' '.join(argv)}; see rule-hook --help", file=sys.stderr) return 1 try: call = parsed_call(json.loads(stdin)) except json.JSONDecodeError as failure: call = Failure(str(failure)) if isinstance(call, Failure): print(f"rule-hook cannot read the hook input: {call.reason}", file=sys.stderr) return 1 found = breaches_of(call, os.path.expanduser("~")) if found is None: return 0 written, what, breaches = found return answer(verdict(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), what, time.time()) def breaches_of(call: Call, home: str) -> tuple[str, str, list[Breach]] | None: """The text that may carry an override, what the log names the call by, and its breaches; None for a call no rule checks.""" if call.tool == "Bash": command = text(call.given, "command") return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) path = text(call.given, "file_path") if call.tool not in FILE_TOOLS or not path: return None before = read(path) added, after = applied(call, before) return added, path, file_breaches(path, before, added, after) def answer(judged: Verdict, what: str, now: float) -> int: for message in judged.messages: print(message, file=sys.stderr) if judged.blocked: return 2 logs = [(breach, reason, log_path(breach.directory)) for breach, reason in judged.overridden] # Resolve every log before writing any, so a call that ends blocked has logged nothing. unloggable = [f"{breach.rule}: {log.reason}" for breach, _, log in logs if isinstance(log, Failure)] if not unloggable: for breach, reason, log in logs: unwritten = write_override(log, breach, reason, what, now) if isinstance(log, Log) else None unloggable += [f"{breach.rule}: {unwritten.reason}"] if unwritten else [] for unlogged in unloggable: print(f"rule-hook cannot log the override of {unlogged}; unlogged, it would escape review.", file=sys.stderr) return 2 if unloggable else 0 def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]: simples = simple_commands(command, cwd, home) return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in todo_breaches(commit.directory)] def todo_breaches(directory: str) -> list[Breach]: top = git(directory, "rev-parse", "--show-toplevel") if isinstance(top, Failure) or not (pathlib.Path(top) / "todo.md").is_file(): return [] todo = pathlib.Path(top) / "todo.md" return [Breach("todo-rank-check", line, top) for line in rank_todo.check_failures(todo)] if changed(top, todo) else [] def changed(top: str, todo: pathlib.Path) -> bool: """Whether todo.md differs from the index or the index from HEAD: any change, staged or not, since the hook runs before a `git add` earlier in the same command.""" # Hashed here, never by `git status`, which would run a clean filter the checkout's own config names before the call is allowed. staged, committed = git(top, "rev-parse", ":todo.md"), git(top, "rev-parse", "HEAD:todo.md") algorithm = git(top, "rev-parse", "--show-object-format") content = todo.read_bytes() worktree = hashlib.new("sha1" if isinstance(algorithm, Failure) else algorithm, b"blob %d\0" % len(content) + content).hexdigest() return isinstance(staged, Failure) or staged != worktree or staged != committed @dataclasses.dataclass(frozen=True) class Log: path: pathlib.Path branch: str head: str def log_path(directory: str) -> Log | Failure | None: """Where an override in this directory is logged; None outside any git checkout.""" directory = existing(directory) if not any((parent / ".git").exists() for parent in [pathlib.Path(directory), *pathlib.Path(directory).parents]): return None common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir") branch = git(directory, "branch", "--show-current") for found in (common, branch): if isinstance(found, Failure): return found # Empty on a branch with no commit yet. head = git(directory, "rev-parse", "--verify", "--quiet", "HEAD") return Log(pathlib.Path(str(common)) / LOG, " ".join(str(branch).split()) or "HEAD", "" if isinstance(head, Failure) else head) def write_override(log: Log, breach: Breach, reason: str, what: str, now: float) -> Failure | None: line = "\t".join([utc(now), log.branch, log.head, breach.rule, " ".join(reason.split()), " ".join(what.split())]) + "\n" try: # No symlink, and no FIFO to hang on: the checkout, and so its git directory, may come from anyone. descriptor = os.open(log.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) except OSError as failure: return Failure(str(failure)) try: if not stat.S_ISREG(os.fstat(descriptor).st_mode): return Failure(f"{log.path} is no regular file") os.write(descriptor, line.encode("utf-8")) except OSError as failure: return Failure(str(failure)) finally: os.close(descriptor) return None def print_overrides(directory: str) -> int: common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir") if isinstance(common, Failure): print(f"rule-hook overrides runs in a git checkout: {common.reason}", file=sys.stderr) return 1 branch = git(directory, "branch", "--show-current") ref = branch if isinstance(branch, str) and branch else "HEAD" # The branch's reflog keeps a commit an amend or a rebase replaced, follows `git branch -m`, and holds no other branch's commit. reflog = git(directory, "reflog", "show", "--format=%H", ref) walked = set(reflog.split()) if isinstance(reflog, str) else set() default = default_branch(directory) log = pathlib.Path(common) / LOG for line in log.read_text(encoding="utf-8").splitlines() if log.is_file() else []: fields = line.split("\t") commit = fields[2] if len(fields) > 2 else "" # A commit the default branch holds is this branch's only while no commit of its own came yet, so the line must name the branch too. if commit == "" or commit in walked and (fields[1] == ref or default is None or not holds(directory, default, commit)): print(line) return 0 def default_branch(directory: str) -> str | None: return next((name for name in ("origin/HEAD", "main", "master") if not isinstance(git(directory, "rev-parse", "--verify", "--quiet", name), Failure)), None) def holds(directory: str, descendant: str, ancestor: str) -> bool: return bool(ancestor) and not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure) def git(directory: str, *args: str) -> str | Failure: # The hook runs git in a checkout the call has not yet been allowed to touch, whose config could name a program: no fsmonitor, and no fetch of a partial clone's missing objects through its transport. try: ran = subprocess.run(["git", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never", "-C", directory, *args], capture_output=True, env={**os.environ, "GIT_NO_LAZY_FETCH": "1"}, text=True) except OSError as failure: return Failure(f"git could not start: {failure}") return ran.stdout.strip() if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}") def existing(directory: str) -> str: path = pathlib.Path(directory or ".").absolute() while not path.is_dir(): path = path.parent return str(path) def read(path: str) -> str: try: return pathlib.Path(path).read_text(encoding="utf-8") except (OSError, UnicodeDecodeError): return ""