From 11e613d083e3ca27bb27d684324420c0c4089d37 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:50:41 +0200 Subject: [PATCH] Answer architecture round 2: list an override by its branch or by a commit the default branch lacks, so an amend or a rebase hides none, split main into reading, judging and answering, move the hook input into call.py, strip comments with one pattern, and log overrides only once each can be --- bin/rule_hook/call.py | 40 +++++++++++ bin/rule_hook/main.py | 124 ++++++++++++++++++++------------ bin/rule_hook/rules.py | 42 +---------- bin/rule_hook/test_rule_hook.py | 32 ++++++++- bin/shell_command.py | 27 +------ docs/decisions.md | 2 +- 6 files changed, 157 insertions(+), 110 deletions(-) create mode 100644 bin/rule_hook/call.py diff --git a/bin/rule_hook/call.py b/bin/rule_hook/call.py new file mode 100644 index 00000000..c622a14c --- /dev/null +++ b/bin/rule_hook/call.py @@ -0,0 +1,40 @@ +import dataclasses +import typing + +from failure import Failure + +FILE_TOOLS = ("Edit", "MultiEdit", "Write") + + +@dataclasses.dataclass(frozen=True) +class Call: + tool: str + given: dict[str, typing.Any] + cwd: str + + +def parsed_call(hook_input: object) -> Call | Failure: + if not isinstance(hook_input, dict): + return Failure("the hook input is no object") + tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd") + if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str): + return Failure("the hook input has no string tool_name and cwd and object tool_input") + return Call(tool, given, cwd) + + +def text(given: dict[str, typing.Any], key: str) -> str: + value = given.get(key) + return value if isinstance(value, str) else "" + + +def applied(call: Call, before: str) -> tuple[str, str]: + """The text a file call writes, and the whole file it leaves.""" + if call.tool == "Write": + content = text(call.given, "content") + return content, content + edits = [call.given] if call.tool == "Edit" else [edit for edit in call.given.get("edits") or [] if isinstance(edit, dict)] + after = before + for edit in edits: + old, new = text(edit, "old_string"), text(edit, "new_string") + after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1) + return "\n".join(text(edit, "new_string") for edit in edits), after diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 413441d2..721b4182 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -19,8 +19,8 @@ A call overrides a rule with `# rule-override : `: 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. +`rule-hook overrides` prints the lines logged on the current branch, and those whose commit the +default branch does not hold. Run with no arguments in a terminal, it prints this help. @@ -28,14 +28,18 @@ Exit 2 with the rule, why it holds and how to override it, when a rule blocks th 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.rules import applied, Breach, command_breaches, commits, file_breaches, FILE_TOOLS, parsed_call, rules_help, text, verdict +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 @@ -60,31 +64,37 @@ def main(argv: list[str], stdin: str) -> int: 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" + found = breaches_of(call, os.path.expanduser("~")) + return answer(verdict(found[2], found[0], text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), found[1], time.time()) if found else 0 + + +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 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) + 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 - 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 + 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)] + for breach, reason, log in logs if not unloggable else []: + 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]: @@ -96,15 +106,30 @@ 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 [] + 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 log_override(breach: Breach, reason: str, what: str, now: float) -> Failure | None: - directory = existing(breach.directory) +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") @@ -114,11 +139,24 @@ def log_override(breach: Breach, reason: str, what: str, now: float) -> 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: - 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") + # No symlink: 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, 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 @@ -127,27 +165,23 @@ def print_overrides(directory: str) -> int: 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) + branch = git(directory, "branch", "--show-current") + default = default_branch(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)): + for line in log.read_text(encoding="utf-8").splitlines() if log.is_file() else []: + fields = line.split("\t") + # Too many beats too few: the overrides pass skips a line whose breach the branch no longer holds, while an amend or a rebase leaves a line's commit off HEAD. + if fields[1:2] == [branch] or default is None or not holds(directory, default, fields[2] if len(fields) > 2 else ""): 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 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 not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure) + return bool(ancestor) and not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure) def git(directory: str, *args: str) -> str | Failure: diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 337fcdd7..6af62975 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -3,7 +3,6 @@ import posixpath import re import typing -from failure import Failure from shell_command import resolved, Simple RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"] @@ -53,14 +52,6 @@ IMAGE = re.compile(r"^[ \t]*(?:-[ \t]+)?(?:image|container):[ \t]*[\"']?([^\s\"' USES = re.compile(r"^[ \t]*(?:-[ \t]+)?uses:[ \t]*[\"']?([^\s\"'#]+)", re.MULTILINE) # git's global options that take a value as the next word. GIT_VALUED = {"-C", "-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"} -FILE_TOOLS = ("Edit", "MultiEdit", "Write") - - -@dataclasses.dataclass(frozen=True) -class Call: - tool: str - given: dict[str, typing.Any] - cwd: str @dataclasses.dataclass(frozen=True) @@ -86,20 +77,6 @@ class Verdict: overridden: list[tuple[Breach, str]] -def parsed_call(hook_input: object) -> Call | Failure: - if not isinstance(hook_input, dict): - return Failure("the hook input is no object") - tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd") - if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str): - return Failure("the hook input has no string tool_name and cwd and object tool_input") - return Call(tool, given, cwd) - - -def text(given: dict[str, typing.Any], key: str) -> str: - value = given.get(key) - return value if isinstance(value, str) else "" - - def overrides(written: str) -> tuple[dict[str, str], list[str]]: """The rules the text overrides with their reasons, and the markers that name no rule or give no reason.""" given = [(rule, reason.strip().removesuffix("-->").strip()) for rule, reason in OVERRIDE.findall(written)] @@ -167,9 +144,9 @@ def commit_message(args: list[str]) -> tuple[list[str], bool]: def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]: breaches = [] found = commits(simples, home) - if simples and any(simple.words[0] in ("gh", "git", "tea") for simple in simples) and ATTRIBUTION.search(command): - directory = found[0].directory if found else simples[0].directory - breaches.append(Breach("no-ai-attribution", "the command carries an attribution", directory)) + publishing = [simple for simple in simples if simple.words[0] in ("gh", "git", "tea")] + if publishing and ATTRIBUTION.search(command): + breaches.append(Breach("no-ai-attribution", "the command carries an attribution", publishing[0].directory)) for commit in found: if commit.from_file: breaches.append(Breach("commit-one-line", "pass the message as one -m '', not from a file", commit.directory)) @@ -178,19 +155,6 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre return breaches -def applied(call: Call, before: str) -> tuple[str, str]: - """The text a file call writes, and the whole file it leaves.""" - if call.tool == "Write": - content = text(call.given, "content") - return content, content - edits = [call.given] if call.tool == "Edit" else [edit for edit in call.given.get("edits") or [] if isinstance(edit, dict)] - after = before - for edit in edits: - old, new = text(edit, "old_string"), text(edit, "new_string") - after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1) - return "\n".join(text(edit, "new_string") for edit in edits), after - - 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.""" breaches = [Breach("no-ai-attribution", f"{path} would carry an attribution", posixpath.dirname(path))] if ATTRIBUTION.search(added) else [] diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index b89745d0..16717082 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -1,4 +1,5 @@ import json +import os import pathlib import subprocess import sys @@ -159,7 +160,15 @@ class Hook(unittest.TestCase): self.assertRegex(self.listed(), r"^\S+Z\tchunk\t[0-9a-f]{40}\timage-pin\tthe vendor tags no patch versions\t\S+/sub/Dockerfile\n$") git(self.repo, "checkout", "-q", "main") git(self.repo, "commit", "-q", "--allow-empty", "-m", "elsewhere") - self.assertEqual(self.listed(), "", "the default branch, past the chunk's start, holds no override") + self.assertEqual(self.listed(), "", "the default branch holds no override of its own") + + def test_an_override_outlives_an_amend(self): + git(self.repo, "commit", "-q", "--allow-empty", "-m", "work") + content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n" + hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo) + git(self.repo, "commit", "-q", "--amend", "--allow-empty", "-m", "reworded") + git(self.repo, "checkout", "-q", "-b", "renamed") + self.assertIn("\timage-pin\t", self.listed(), "the default branch does not hold the commit") def test_a_blocked_call_logs_no_override(self): command = f"git commit -m a -m '{TRAILER}' # rule-override no-ai-attribution: quotes it" @@ -191,6 +200,27 @@ class Hook(unittest.TestCase): self.assertEqual(ran.returncode, 2) self.assertIn("todo.md: not ranked", ran.stderr) + def test_a_staged_todo_change_is_checked_and_no_clean_filter_runs(self): + pathlib.Path(self.repo, "docs").mkdir() + for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO), (".gitattributes", "todo.md filter=planted\n")]: + pathlib.Path(self.repo, name).write_text(content) + git(self.repo, "add", "-A") + git(self.repo, "config", "filter.planted.clean", f"touch {self.repo}/ran; cat") + pathlib.Path(self.repo, "ran").unlink(missing_ok=True) + # A stat-dirty index entry, as extracting an archive leaves, is what makes `git status` re-run the filter. + os.utime(pathlib.Path(self.repo, "todo.md"), (1, 1)) + ran = hook({"cwd": self.repo, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}, self.repo) + self.assertEqual(ran.returncode, 2, ran.stderr) + self.assertFalse(pathlib.Path(self.repo, "ran").exists()) + + def test_a_symlinked_log_is_refused(self): + target = pathlib.Path(self.repo, "elsewhere") + pathlib.Path(self.repo, ".git", "rule-overrides.tsv").symlink_to(target) + 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}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo) + self.assertEqual(ran.returncode, 2) + self.assertFalse(target.exists()) + def test_a_malformed_override_is_named(self): ran = hook({"cwd": self.repo, "tool_input": {"command": f"git commit -m a -m b -m '{TRAILER}' # rule-override no-ai-attribution: quotes it # rule-override commit-oneline: x"}, "tool_name": "Bash"}, self.repo) self.assertIn("`rule-override commit-oneline: x` names no rule below", ran.stderr) diff --git a/bin/shell_command.py b/bin/shell_command.py index 6c495e86..b39eae78 100644 --- a/bin/shell_command.py +++ b/bin/shell_command.py @@ -7,6 +7,8 @@ import shlex HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE) ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=") OPERATOR = set("\n();&|<>") +# A quoted string or an escape is taken whole, so a # inside one starts no comment; a comment starts a word. +PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(? list[str] | None: def uncommented(text: str) -> str: """The text without its comments; shlex's own would also swallow the line break that ends one, joining two commands.""" - kept = [] - quote = "" - at = 0 - while at < len(text): - char = text[at] - if quote: - if char == "\\" and quote == '"': - kept.append(text[at:at + 2]) - at += 2 - continue - quote = "" if char == quote else quote - elif char == "\\": - kept.append(text[at:at + 2]) - at += 2 - continue - elif char in "'\"": - quote = char - elif char == "#" and (at == 0 or text[at - 1] in " \t\n;&|()"): - end = text.find("\n", at) - at = len(text) if end < 0 else end - continue - kept.append(char) - at += 1 - return "".join(kept) + return PIECE.sub(lambda piece: "" if piece.group(0).startswith("#") else piece.group(0), text) def resolved(base: str, path: str, home: str) -> str: diff --git a/docs/decisions.md b/docs/decisions.md index f2da359f..7e6596b1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -137,4 +137,4 @@ lilleman decided to ship each of these under the floor on the day listed. Each l ## rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override : ` marker overrides one, and larv-review's overrides pass rules on each override before merge -2026-10-12, lilleman. Serves goals 1.2 and 1.3. Anthropic's best-practices page calls `CLAUDE.md` advisory and hooks deterministic, so a rule that must hold every time moves into `bin/rule-hook`, and `CLAUDE.md` keeps it only where the hook cannot check it. A Claude Code hook ties the check to one vendor ("Prefer the vendor-neutral option", `principles/technical-principles.md`). What the tie buys: the hook blocks before a write lands, Edit and Write calls included, in every project with no per-repo install; a git `commit-msg` hook sees only commits, and CI sees them only after the push. The hook checks each write, so the agent fixes the line it just wrote; checking the staged diff at commit time would also cover files a Bash command writes, at the cost of later feedback. The marker's spelling was picked by a panel of three fresh readers, two to one. Each override is logged in the checkout's git directory, which is never pushed (goal 4). The plan had loop-claude's judge to rule on overrides inside a loop; lilleman approved larv-review's overrides pass in every run, because it rules before merge and an outrageous override still reaches the human through its ask. Valid while a PreToolUse hook that exits 2 blocks the call and hands its stderr to the model, and while an agent commits through Claude Code's Bash tool. +2026-10-12, lilleman. Serves goals 1.2 and 1.3. Anthropic's best-practices page calls `CLAUDE.md` advisory and hooks deterministic, so a rule that must hold every time moves into `bin/rule-hook`, and `CLAUDE.md` keeps it only where the hook cannot check it. A Claude Code hook ties the check to one vendor ("Prefer the vendor-neutral option", `principles/technical-principles.md`), which is the target itself here: this repo configures Claude Code. What the tie buys: the hook blocks before a write lands, Edit and Write calls included, in every project with no per-repo install; a git `commit-msg` hook sees only commits, and CI sees them only after the push. The hook checks each write, so the agent fixes the line it just wrote; checking the staged diff at commit time would also cover files a Bash command writes, at the cost of later feedback. The marker's spelling was picked by a panel of three fresh readers, two to one. Each override is logged in the checkout's git directory, which is never pushed (goal 4). The plan had loop-claude's judge to rule on overrides inside a loop; lilleman approved larv-review's overrides pass in every run, because it rules before merge and an outrageous override still reaches the human through its ask. Valid while a PreToolUse hook that exits 2 blocks the call and hands its stderr to the model, and while an agent commits through Claude Code's Bash tool.