Answer architecture round 1: share one shell parser with reading-cost, move each pure step into rules.py and split the long units, build --help from RULES, log an override only once its call goes through and in the checkout it touched, list overrides by commit, return git failures as values with fsmonitor off, make the override review a pass with its own agent, record the decision, and restate in CLAUDE.md what the hook cannot see

This commit is contained in:
2026-10-12 23:45:36 +02:00
parent 7cf4f54c90
commit f3bfff1af4
17 changed files with 504 additions and 289 deletions
+95 -89
View File
@@ -1,24 +1,14 @@
"""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)
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:
action-pin a workflow's or action.yml'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 an edit leaves each block of a .*ignore file sorted, unless the block was
unsorted before; a blank line or comment ends a block
image-pin a Dockerfile FROM or COPY --from, or a compose or workflow `image:` or
`container:`, names a full patch version, a date stamp 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 git commit while todo.md has changes, staged or not, needs
rank_todo.py --check to pass on it
{rules}
action-pin, ignorefile-sorted, image-pin and no-ai-attribution check only what an Edit, MultiEdit or
Write call writes, not a file a Bash command writes.
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked.
A call overrides a rule with `# rule-override <rule>: <reason>`:
@@ -26,14 +16,17 @@ A call overrides a rule with `# rule-override <rule>: <reason>`:
- 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 checkout's git directory: UTC time, branch, rule, reason, and the file
written or the command's first line. `rule-hook overrides` prints the lines for the current branch.
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; 0 otherwise.
Exit 1, a non-blocking error to Claude Code, on input it cannot read.
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
@@ -41,10 +34,11 @@ import pathlib
import subprocess
import sys
import time
import typing
from rule_hook.rules import Breach, command_breaches, commits, file_breaches, overrides, RULES
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"
@@ -52,7 +46,7 @@ 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())
print(__doc__.strip().replace("{rules}", rules_help()))
return 0
if argv == ["overrides"]:
return print_overrides(os.getcwd())
@@ -60,97 +54,109 @@ def main(argv: list[str], stdin: str) -> int:
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"]
if not isinstance(given, dict):
raise TypeError("tool_input is no object")
except (json.JSONDecodeError, KeyError, TypeError) as failure:
print(f"rule-hook cannot read the hook input: {failure}", file=sys.stderr)
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
checked = checked_call(tool, given, cwd)
if checked is None:
return 0
text, directory, breaches = checked
what = text.split("\n", 1)[0] if tool == "Bash" else str(given.get("file_path"))
granted, malformed = overrides(text)
for breach in breaches:
if breach.rule in granted:
log_override(directory, breach.rule, granted[breach.rule], what)
blocking = [breach for breach in breaches if breach.rule not in granted]
if not blocking:
return 0
where = "the command" if tool == "Bash" else "the text you write, as a comment line"
markdown = tool != "Bash" and str(given.get("file_path")).endswith(".md")
for marker in malformed:
print(f"`{marker}` names no rule below, or gives no reason.", file=sys.stderr)
for rule in sorted({breach.rule for breach in blocking}):
details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
print(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule]}. Where it does not fit this case, add `{marker}` to {where}; larv-review 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 = str(given.get("command") or "")
todo = [breach for commit in commits(command, cwd) for breach in todo_breaches(commit.directory)]
return command, cwd, command_breaches(command, cwd) + todo
path = str(given.get("file_path") or "")
if tool not in ("Edit", "MultiEdit", "Write") or not path:
return None
before = read(path)
edits = [given] if tool == "Edit" else [edit for edit in given.get("edits") or [] if isinstance(edit, dict)]
if tool == "Write":
added = after = str(given.get("content") or "")
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:
after = before
for edit in edits:
old, new = str(edit.get("old_string") or ""), str(edit.get("new_string") or "")
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1)
added = "\n".join(str(edit.get("new_string") or "") for edit in edits)
return added, os.path.dirname(path), file_breaches(path, before, added, after)
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 not top or not (pathlib.Path(top) / "todo.md").is_file():
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.
if not git(top, "status", "--porcelain", "--", "todo.md"):
return []
return [Breach("todo-rank-check", line) for line in rank_todo.check_failures(pathlib.Path(top) / "todo.md")]
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(directory: str, rule: str, reason: str, what: 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()), " ".join(what.split())]) + "\n")
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")
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)
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:
if line.split("\t")[1:2] == [branch]:
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 git(directory: str, *args: str) -> str:
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", directory, *args], capture_output=True, text=True)
except OSError:
return ""
return ran.stdout.strip() if ran.returncode == 0 else ""
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: