Files
claude-config/bin/rule_hook/main.py
T

174 lines
6.6 KiB
Python

"""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 <rule>: <reason>`:
- 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 `<!-- rule-override <rule>: <reason> -->`
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 holds, from where it left
the default branch on.
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 json
import os
import pathlib
import subprocess
import sys
import time
from rule_hook.rules import applied, Breach, command_breaches, commits, file_breaches, FILE_TOOLS, parsed_call, rules_help, text, 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
home = os.path.expanduser("~")
bash = call.tool == "Bash"
path = text(call.given, "file_path")
if bash:
written = text(call.given, "command")
breaches = bash_breaches(written, call.cwd, home)
what = written.split("\n", 1)[0]
elif call.tool in FILE_TOOLS and path:
before = read(path)
written, after = applied(call, before)
breaches = file_breaches(path, before, written, after)
what = path
else:
return 0
judged = verdict(breaches, written, path.endswith(".md"), bash)
for message in judged.messages:
print(message, file=sys.stderr)
if judged.blocked:
return 2
for breach, reason in judged.overridden:
unlogged = log_override(breach, reason, what, time.time())
if unlogged:
print(f"rule-hook cannot log the override of {breach.rule}, so it would escape review: {unlogged.reason}", file=sys.stderr)
return 2
return 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 []
# Any change, staged or not: the hook runs before a `git add` earlier in the same command.
changed = git(top, "status", "--porcelain", "--", "todo.md")
if isinstance(changed, Failure):
return [Breach("todo-rank-check", changed.reason, top)]
return [Breach("todo-rank-check", line, top) for line in rank_todo.check_failures(pathlib.Path(top) / "todo.md")] if changed else []
def log_override(breach: Breach, reason: str, what: str, now: float) -> Failure | None:
directory = existing(breach.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")
try:
with open(pathlib.Path(str(common)) / LOG, "a", encoding="utf-8") as log:
log.write("\t".join([utc(now), str(branch) or "HEAD", "" if isinstance(head, Failure) else head, breach.rule, " ".join(reason.split()), " ".join(what.split())]) + "\n")
except OSError as failure:
return Failure(str(failure))
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
start = branch_start(directory)
log = pathlib.Path(common) / LOG
lines = log.read_text(encoding="utf-8").splitlines() if log.is_file() else []
for line in lines:
commit = line.split("\t")[2:3]
if commit == [""] or commit and holds(directory, "HEAD", commit[0]) and (start is None or holds(directory, commit[0], start)):
print(line)
return 0
def branch_start(directory: str) -> str | None:
"""Where HEAD left the default branch, None when no default branch is known."""
for default in ("origin/HEAD", "main", "master"):
start = git(directory, "merge-base", "HEAD", default)
if not isinstance(start, Failure):
return start
return None
def holds(directory: str, descendant: str, ancestor: str) -> bool:
return not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)
def git(directory: str, *args: str) -> str | Failure:
# fsmonitor off: the hook runs git in a checkout the call has not yet been allowed to touch, whose config could name a program.
try:
ran = subprocess.run(["git", "-c", "core.fsmonitor=false", "-C", directory, *args], capture_output=True, 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 ""