Enforce the checkable rules in a hook, with one override marker a judge rules on, and drop them from CLAUDE.md

This commit is contained in:
2026-10-12 23:06:23 +02:00
parent 50a98c2262
commit 39437cef6a
13 changed files with 503 additions and 20 deletions
View File
+158
View File
@@ -0,0 +1,158 @@
"""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 branch's overrides)
settings.json runs it before each Bash, Edit, MultiEdit and Write call, in every session and
subagent. The rules:
action-pin a workflow's `uses:` names a semver tag, such as @v3 or @v3.1.2
commit-one-line git commit takes its message as one -m with no newline
ignorefile-sorted each block of a .*ignore file is sorted; a blank line or comment ends a block
image-pin a Dockerfile FROM or YAML `image:` names a full patch version or a digest
no-ai-attribution no Claude or Anthropic co-author or generated-with line, in a file written or
in a git, gh or tea command
todo-rank-check a commit that stages todo.md, or commits with -a while todo.md has changes,
needs rank_todo.py --check to pass on it
A call overrides a rule with `# rule-override <rule>: <reason>`: in a Bash command, as a trailing
comment; in a file, as a comment line in the text the edit writes. Each override that let a call
through is appended to rule-overrides.tsv in the checkout's git directory: UTC time, branch, rule,
reason. `rule-hook overrides` prints the lines for the current branch.
Exit 2 with the rule, why it holds and how to override it, when a rule blocks the call; 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
import typing
from failure import Failure
import rank_todo
from rule_hook.rules import Breach, command_breaches, commits, file_breaches, overrides, RULES
from utc_stamp import utc
LOG = "rule-overrides.tsv"
def main(argv: list[str], stdin: str) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
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 = json.loads(stdin)
tool, given, cwd = call["tool_name"], call["tool_input"], call["cwd"]
except (json.JSONDecodeError, KeyError, TypeError) as failure:
print(f"rule-hook cannot read the hook input: {failure}", file=sys.stderr)
return 1
checked = checked_call(tool, given, cwd)
if checked is None:
return 0
text, directory, breaches = checked
granted = overrides(text)
for breach in breaches:
if breach.rule in granted:
log_override(directory, breach.rule, granted[breach.rule])
blocking = [breach for breach in breaches if breach.rule not in granted]
if not blocking:
return 0
where = "the command, as a trailing comment" if tool == "Bash" else "the text you write, as a comment line"
for rule in sorted({breach.rule for breach in blocking}):
details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
print(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule]}. Where it does not fit this case, add `# rule-override {rule}: <reason>` to {where}; larv-review's judge rules on the reason.", file=sys.stderr)
return 2
def checked_call(tool: str, given: dict[str, typing.Any], cwd: str) -> tuple[str, str, list[Breach]] | None:
"""The text that may carry an override, the directory whose checkout logs it, and the call's breaches."""
if tool == "Bash":
command = given.get("command", "")
todo = [breach for commit in commits(command, cwd) for breach in todo_breaches(commit.directory, commit.all)]
return command, cwd, command_breaches(command, cwd) + todo
path = given.get("file_path", "")
if tool not in ("Edit", "MultiEdit", "Write") or not path:
return None
before = read(path)
edits = [given] if tool == "Edit" else given.get("edits", [])
if tool == "Write":
added = after = given.get("content", "")
else:
after = before
for edit in edits:
old, new = edit.get("old_string", ""), edit.get("new_string", "")
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1)
added = "\n".join(edit.get("new_string", "") for edit in edits)
return added, os.path.dirname(path), file_breaches(path, before, added, after)
def todo_breaches(directory: str, staged_all: bool) -> list[Breach]:
top = git(directory, "rev-parse", "--show-toplevel")
if not top or not (pathlib.Path(top) / "todo.md").is_file():
return []
changed = git(top, "diff", "--cached", "--name-only", "--", "todo.md") or (staged_all and git(top, "diff", "--name-only", "--", "todo.md"))
if not changed:
return []
todo = pathlib.Path(top) / "todo.md"
texts = rank_todo.read_all(todo)
if isinstance(texts, Failure):
return [Breach("todo-rank-check", texts.reason)]
ranked = rank_todo.rank(*texts)
if isinstance(ranked, Failure):
return [Breach("todo-rank-check", ranked.reason)]
if ranked.text != texts[0]:
return [Breach("todo-rank-check", f"{todo} is not ranked")]
return [Breach("todo-rank-check", line) for line in ranked.under_bar]
def log_override(directory: str, rule: str, reason: str) -> None:
common = git(existing(directory), "rev-parse", "--path-format=absolute", "--git-common-dir")
if not common:
return
branch = git(existing(directory), "branch", "--show-current") or "HEAD"
with open(pathlib.Path(common) / LOG, "a", encoding="utf-8") as log:
log.write("\t".join([utc(time.time()), branch, rule, " ".join(reason.split())]) + "\n")
def print_overrides(directory: str) -> int:
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
branch = git(directory, "branch", "--show-current")
if not common or not branch:
print("rule-hook overrides runs on a branch of a git checkout", file=sys.stderr)
return 1
log = pathlib.Path(common) / LOG
lines = log.read_text(encoding="utf-8").splitlines() if log.is_file() else []
for line in lines:
if line.split("\t")[1:2] == [branch]:
print(line)
return 0
def git(directory: str, *args: str) -> str:
try:
ran = subprocess.run(["git", "-C", directory, *args], capture_output=True, text=True)
except OSError:
return ""
return ran.stdout.strip() if ran.returncode == 0 else ""
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 ""
+176
View File
@@ -0,0 +1,176 @@
import dataclasses
import os
import re
import shlex
# Each rule's why, which the block message gives.
RULES = {
"action-pin": "a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never a commit SHA or a branch; SHA-pin only in a pipeline that tests our own specific builds",
"commit-one-line": "a commit message is one line, prefixed with the ticket ID when the work has one",
"ignorefile-sorted": "each block of an ignore file is sorted, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment",
"image-pin": "a container image is pinned to its full patch version, such as node:24.18.1-bookworm-slim, so the same commit builds the same image on every day; a bot such as Renovate raises the bumps as reviewable PRs",
"no-ai-attribution": "no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line",
"todo-rank-check": "a committed todo.md passes ~/.claude/bin/rank_todo.py --check; run rank_todo.py on it",
}
OVERRIDE = re.compile(r"#\s*rule-override ([a-z-]+):[ \t]*(\S[^\n]*)")
# [-] keeps this file from matching itself.
ATTRIBUTION = re.compile(r"co-authored[-]by:[^\n]*\b(?:claude|anthropic)\b|generated with \[?claude code", re.IGNORECASE)
SEMVER = re.compile(r"v?\d+(?:\.\d+){0,2}")
PATCH = re.compile(r"v?\d+\.\d+\.\d+(?:[-+_.].*)?")
FROM = re.compile(r"^[ \t]*FROM[ \t]+(?:--\S+[ \t]+)*(\S+)(?:[ \t]+AS[ \t]+(\S+))?", re.IGNORECASE | re.MULTILINE)
IMAGE = re.compile(r"^[ \t]*(?:-[ \t]+)?image:[ \t]*[\"']?([^\s\"'#]+)", re.MULTILINE)
USES = re.compile(r"^[ \t]*(?:-[ \t]+)?uses:[ \t]*[\"']?([^\s\"'#]+)", re.MULTILINE)
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
SEPARATORS = {"\n", "&&", "||", ";", "|", "&", "(", ")", ";;", "|&"}
# git's global options that take a value as the next word.
GIT_VALUED = {"-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"}
@dataclasses.dataclass(frozen=True)
class Breach:
rule: str
detail: str
@dataclasses.dataclass(frozen=True)
class Commit:
"""A `git commit` in a command: the directory it runs in, its messages and whether it stages tracked changes."""
directory: str
messages: list[str]
from_file: bool
all: bool
def overrides(text: str) -> dict[str, str]:
return {rule: reason.strip() for rule, reason in OVERRIDE.findall(text) if rule in RULES}
def segments(command: str) -> list[list[str]] | None:
"""The command's simple commands as words, or None when it does not parse."""
lexer = shlex.shlex(command, posix=True, punctuation_chars="();<>|&\n")
lexer.whitespace = " \t\r"
lexer.whitespace_split = True
try:
words = list(lexer)
except ValueError:
return None
split: list[list[str]] = [[]]
for word in words:
if word in SEPARATORS:
split.append([])
else:
split[-1].append(word)
return [segment for segment in split if segment]
def commits(command: str, cwd: str) -> list[Commit]:
directory = cwd
found = []
for segment in segments(command) or []:
if segment[0] == "cd" and len(segment) > 1:
directory = os.path.join(directory, os.path.expanduser(segment[1]))
assignments = next((at for at, word in enumerate(segment) if not ASSIGNMENT.match(word)), len(segment))
words = segment[assignments:]
commit = git_commit(words[1:], directory) if words[:1] == ["git"] else None
if commit:
found.append(commit)
return found
def git_commit(args: list[str], directory: str) -> Commit | None:
at = 0
while at < len(args) and args[at].startswith("-"):
if args[at] == "-C" and at + 1 < len(args):
directory = os.path.join(directory, os.path.expanduser(args[at + 1]))
at += 2 if args[at] == "-C" or args[at] in GIT_VALUED else 1
if args[at:at + 1] != ["commit"]:
return None
messages: list[str] = []
from_file = staged_all = False
rest = args[at + 1:]
at = 0
while at < len(rest):
word = rest[at]
if word == "--":
break
if word in ("--message", "--file") and at + 1 < len(rest):
messages += [rest[at + 1]] if word == "--message" else []
from_file = from_file or word == "--file"
at += 2
continue
if word.startswith("--message="):
messages.append(word.removeprefix("--message="))
elif word.startswith("--file="):
from_file = True
elif word == "--all":
staged_all = True
elif word.startswith("-") and not word.startswith("--"):
# A cluster such as -am: a valued flag takes the rest of the word, or else the next word.
for place, flag in enumerate(word[1:], 1):
if flag in "mF":
value = word[place + 1:]
if not value and at + 1 < len(rest):
at += 1
value = rest[at]
messages += [value] if flag == "m" else []
from_file = from_file or flag == "F"
break
staged_all = staged_all or flag == "a"
at += 1
return Commit(directory, messages, from_file, staged_all)
def command_breaches(command: str, cwd: str) -> list[Breach]:
breaches = []
parsed = segments(command) or []
if any(word in ("gh", "git", "tea") for segment in parsed for word in segment[:1]):
if ATTRIBUTION.search(command):
breaches.append(Breach("no-ai-attribution", "the command carries an attribution"))
for commit in commits(command, cwd):
if commit.from_file:
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', not from a file"))
elif len(commit.messages) > 1 or any("\n" in message.strip() for message in commit.messages):
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', with no heredoc, second -m or newline"))
return breaches
def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
"""Breaches in an edit of path: added is the text the edit writes, after the whole file it leaves."""
name = os.path.basename(path)
breaches = []
if ATTRIBUTION.search(added):
breaches.append(Breach("no-ai-attribution", f"{path} would carry an attribution"))
if name.startswith(("Dockerfile", "Containerfile")) or name.endswith((".dockerfile", ".Dockerfile", ".containerfile")):
stages = {stage.lower() for _, stage in FROM.findall(before + "\n" + after) if stage}
images = [image for image, _ in FROM.findall(added) if image.lower() not in stages | {"scratch"}]
breaches += [Breach("image-pin", f"{path}: FROM {image}") for image in images if not pinned(image)]
if name.endswith((".yml", ".yaml")):
breaches += [Breach("image-pin", f"{path}: image: {image}") for image in IMAGE.findall(added) if not pinned(image)]
breaches += [Breach("action-pin", f"{path}: uses: {action}") for action in USES.findall(added) if not tagged(action)]
if name.startswith(".") and name.endswith("ignore"):
breaches += [Breach("ignorefile-sorted", f"{path}: {block[0]!r} through {block[-1]!r} are out of order") for block in blocks(after) if block != sorted(block)]
return breaches
def pinned(image: str) -> bool:
if "$" in image or "{{" in image or "@sha256:" in image:
return True
tail = image.rsplit("/", 1)[-1]
return ":" in tail and PATCH.fullmatch(tail.split(":", 1)[1]) is not None
def tagged(action: str) -> bool:
if action.startswith(("./", "docker://")) or "$" in action or "{{" in action:
return True
return "@" in action and SEMVER.fullmatch(action.rsplit("@", 1)[1]) is not None
def blocks(text: str) -> list[list[str]]:
"""An ignore file's runs of patterns, split at each blank line and comment."""
runs: list[list[str]] = [[]]
for line in text.splitlines():
if line.strip() and not line.startswith("#"):
runs[-1].append(line)
elif runs[-1]:
runs.append([])
return [run for run in runs if run]
+130
View File
@@ -0,0 +1,130 @@
import json
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from rule_hook.rules import blocks, Breach, command_breaches, Commit, commits, file_breaches, overrides
from test_env import isolated_env
from test_rank_todo import DECISIONS, README, TODO
HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook"
# Built from parts, so this file carries no attribution of its own.
TRAILER = "Co-Authored-" + "By: Claude <noreply@anthropic.com>"
def rules(breaches: list[Breach]) -> list[str]:
return [breach.rule for breach in breaches]
def hook(call: dict, cwd: str) -> subprocess.CompletedProcess:
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env(), input=json.dumps(call), text=True)
def git(cwd: str, *args: str) -> str:
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=cwd, env=isolated_env(), text=True).stdout
class Commits(unittest.TestCase):
def test_cd_and_dash_capital_c_move_the_commit(self):
self.assertEqual(commits("cd a && git -C b commit -am 'x'", "/r"), [Commit("/r/a/b", ["x"], False, True)])
def test_each_message_spelling_is_read(self):
self.assertEqual(commits("git commit --message=a -m b=c --message c -mz", "/r")[0].messages, ["a", "b=c", "c", "z"])
def test_a_file_message_is_seen(self):
self.assertTrue(commits("git commit -F - <<EOF\nx\nEOF", "/r")[0].from_file)
def test_other_git_commands_are_no_commit(self):
self.assertEqual(commits("git log --grep commit; echo git commit", "/r"), [])
def test_a_line_break_separates_commands(self):
self.assertEqual(commits("cd a\nGIT_EDITOR=true git commit -m x", "/r"), [Commit("/r/a", ["x"], False, False)])
class CommandBreaches(unittest.TestCase):
def test_one_line_passes(self):
self.assertEqual(command_breaches("git add . && git commit -m 'ABC-1 - Fix it'", "/r"), [])
def test_a_heredoc_a_second_message_or_a_file_breaks_commit_one_line(self):
for command in ["git commit -m \"$(cat <<'EOF'\nTitle\nEOF\n)\"", "git commit -m a -m b", "git commit -F msg.txt"]:
with self.subTest(command):
self.assertEqual(rules(command_breaches(command, "/r")), ["commit-one-line"])
def test_an_attribution_breaks_only_in_a_git_gh_or_tea_command(self):
self.assertEqual(rules(command_breaches(f"tea pr create --description '{TRAILER}'", "/r")), ["no-ai-attribution"])
self.assertEqual(command_breaches(f"grep -rn '{TRAILER}' .", "/r"), [])
def test_a_command_that_does_not_parse_breaks_nothing(self):
self.assertEqual(command_breaches("git commit -m 'open", "/r"), [])
class FileBreaches(unittest.TestCase):
def test_an_image_needs_a_patch_version_or_a_digest(self):
added = "FROM node:24 AS build\nFROM node:24.18.1-bookworm-slim\nFROM alpine@sha256:ab\nFROM build\nFROM scratch\nFROM ${BASE}\nFROM python\n"
self.assertEqual([breach.detail for breach in file_breaches("Dockerfile", "", added, added)], ["Dockerfile: FROM node:24", "Dockerfile: FROM python"])
def test_a_stage_named_outside_the_edit_is_no_image(self):
self.assertEqual(file_breaches("app.dockerfile", "FROM node:24.1.0 AS base\n", "FROM base\n", "FROM node:24.1.0 AS base\nFROM base\n"), [])
def test_yaml_images_and_actions_are_checked(self):
added = " image: mysql:8.4\n - image: 'mysql:8.4.7'\n - uses: actions/checkout@v4\n - uses: a/b@0123456789abcdef0123456789abcdef01234567\n - uses: ./local\n"
self.assertEqual(rules(file_breaches("ci.yml", "", added, added)), ["image-pin", "action-pin"])
def test_an_ignore_file_sorts_each_block_split_by_blank_lines_and_comments(self):
self.assertEqual(blocks("b\na\n\n# c\nd\n# e\nf\n"), [["b", "a"], ["d"], ["f"]])
self.assertEqual(rules(file_breaches(".dockerignore", "", "x", "b\na\n")), ["ignorefile-sorted"])
self.assertEqual(file_breaches(".gitignore", "", "x", "*\n\n!a\n!b\n"), [])
def test_an_attribution_in_any_file_breaks(self):
self.assertEqual(rules(file_breaches("notes.md", "", TRAILER, TRAILER)), ["no-ai-attribution"])
class Overrides(unittest.TestCase):
def test_a_marker_names_a_known_rule_and_a_reason(self):
self.assertEqual(overrides("x # rule-override image-pin: vendor ships floating tags only\n# rule-override nope: x\n# rule-override action-pin:"), {"image-pin": "vendor ships floating tags only"})
class Hook(unittest.TestCase):
def setUp(self):
self.repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", self.repo])
git(self.repo, "init", "-q", "-b", "chunk")
def test_a_breach_exits_2_naming_the_rule_and_the_override(self):
ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": "FROM node:24\n"}, "tool_name": "Write"}, self.repo)
self.assertEqual(ran.returncode, 2)
self.assertIn("Blocked by rule image-pin: ", ran.stderr)
self.assertIn("`# rule-override image-pin: <reason>`", ran.stderr)
def test_an_override_passes_and_is_listed_for_its_branch(self):
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/sub/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
self.assertEqual((ran.returncode, ran.stderr), (0, ""))
listed = subprocess.run([str(HOOK), "overrides"], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout
self.assertRegex(listed, r"^\S+Z\tchunk\timage-pin\tthe vendor tags no patch versions\n$")
def test_an_edit_is_judged_on_the_file_it_leaves(self):
pathlib.Path(self.repo, ".gitignore").write_text("a\nc\n")
call = {"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/.gitignore", "new_string": "d", "old_string": "a"}, "tool_name": "Edit"}
self.assertEqual(hook(call, self.repo).returncode, 2)
def test_a_commit_staging_an_unranked_todo_is_blocked(self):
pathlib.Path(self.repo, "docs").mkdir()
for name, text in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]:
pathlib.Path(self.repo, name).write_text(text)
git(self.repo, "add", "README.md")
call = {"cwd": self.repo, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}
self.assertEqual(hook(call, self.repo).returncode, 0)
self.assertEqual(hook({**call, "tool_input": {"command": "git commit -am x"}}, self.repo).returncode, 0, "-a stages tracked files only")
git(self.repo, "add", "todo.md")
ran = hook(call, self.repo)
self.assertEqual(ran.returncode, 2)
self.assertIn("todo.md is not ranked", ran.stderr)
def test_unreadable_input_does_not_block(self):
ran = subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input="{", text=True)
self.assertEqual(ran.returncode, 1)