diff --git a/agents/override-reviewer.md b/agents/override-reviewer.md index 1c4bd339..fcc6ac58 100644 --- a/agents/override-reviewer.md +++ b/agents/override-reviewer.md @@ -4,7 +4,7 @@ description: "Use this agent for larv-review's overrides pass." tools: Read, Grep, Glob --- -You rule on each override of a rule `~/.claude/bin/rule-hook` enforces. The prompt gives you the lines `rule-hook overrides` printed, each with its rule and reason, and the branch diff. Read `rule-hook --help` (its text is in `~/.claude/bin/rule_hook/rules.py` → `RULES`) for each rule and its stated exceptions, and the project's `README.md` → "Goals" and "Audience". +You rule on each override of a rule `~/.claude/bin/rule-hook` enforces. The prompt gives you the lines `rule-hook overrides` printed, each with its rule and reason, and the branch diff. Read each rule and its stated exceptions in `~/.claude/bin/rule_hook/rules.py` → `RULES`, how an override is written and logged in the docstring of `~/.claude/bin/rule_hook/main.py`, and the project's `README.md` → "Goals" and "Audience". For each override: diff --git a/bin/rule_hook/git.py b/bin/rule_hook/git.py new file mode 100644 index 00000000..a71f64d2 --- /dev/null +++ b/bin/rule_hook/git.py @@ -0,0 +1,24 @@ +import os +import pathlib +import subprocess + +from failure import Failure + +# A -c given here outranks the checkout's own config, which may allow one transport by name; GIT_NO_LAZY_FETCH needs git 2.44. +GUARDS = [option for setting in ["core.fsmonitor=false", "log.showSignature=false", "protocol.allow=never", *(f"protocol.{name}.allow=never" for name in ("ext", "file", "git", "http", "https", "ssh"))] for option in ("-c", setting)] + + +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, no signature check, and no fetch of a partial clone's missing objects through its transport. + try: + ran = subprocess.run(["git", *GUARDS, "-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) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 6122b034..5482bb9d 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -29,26 +29,18 @@ override cannot be logged; 0 otherwise. `rule-hook overrides` exits 1 when git c checkout or the branch's reflog. 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 rule_hook.override_log import Log, log_path, logged, print_overrides, write_override from shell_command import simple_commands -from utc_stamp import utc - -LOG = "rule-overrides.tsv" -# A -c given here outranks the checkout's own config, which may allow one transport by name; GIT_NO_LAZY_FETCH needs git 2.44. -GUARDS = [option for setting in ["core.fsmonitor=false", "log.showSignature=false", "protocol.allow=never", *(f"protocol.{name}.allow=never" for name in ("ext", "file", "git", "http", "https", "ssh"))] for option in ("-c", setting)] +from rule_hook.todo_check import todo_breaches def main(argv: list[str], stdin: str) -> int: @@ -97,7 +89,7 @@ def answer(judged: Verdict, what: str, now: float) -> int: 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 + unwritten = write_override(log, logged(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) @@ -109,115 +101,6 @@ def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]: 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) - head = git(directory, "rev-parse", "HEAD") - # A reflog missing HEAD is off or expired, and would hide this chunk's overrides. - if isinstance(reflog, Failure) or isinstance(head, Failure) or head not in reflog.split(): - reason = reflog.reason if isinstance(reflog, Failure) else head.reason if isinstance(head, Failure) else "it does not hold HEAD" - print(f"rule-hook overrides cannot read the branch's reflog, so it cannot tell which overrides are this chunk's: {reason}", file=sys.stderr) - return 1 - walked = set(reflog.split()) - 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, no signature check, and no fetch of a partial clone's missing objects through its transport. - try: - ran = subprocess.run(["git", *GUARDS, "-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") diff --git a/bin/rule_hook/override_log.py b/bin/rule_hook/override_log.py new file mode 100644 index 00000000..5017819f --- /dev/null +++ b/bin/rule_hook/override_log.py @@ -0,0 +1,115 @@ +import dataclasses +import os +import pathlib +import stat +import sys +import typing + +from rule_hook.rules import Breach +from failure import Failure +from rule_hook.git import existing, git +from utc_stamp import utc + +LOG = "rule-overrides.tsv" + + +@dataclasses.dataclass(frozen=True) +class Entry: + """One line of the log, its fields tab-separated in this order.""" + at: str + branch: str + # The commit checked out when the override let its call through; empty on a branch with no commit yet. + commit: str + rule: str + reason: str + what: str + + def line(self) -> str: + return "\t".join(" ".join(field.split()) for field in dataclasses.astuple(self)) + "\n" + + +def parsed_entry(line: str) -> Entry | None: + fields = line.rstrip("\n").split("\t") + return Entry(*fields) if len(fields) == len(dataclasses.fields(Entry)) else None + + +def this_chunks(entry: Entry, reflog: set[str], branch: str, on_default: typing.Callable[[str], bool]) -> bool: + """Whether the override is the current branch's: its commit is in the branch's reflog, which keeps a commit an amend or a rebase replaced, follows `git branch -m`, and holds no other branch's commit.""" + if entry.commit == "": + return True + # The default branch's commits are in every branch's reflog, so such a line counts only under the branch's own name: one logged before the branch's first commit. + return entry.commit in reflog and (entry.branch == branch or not on_default(entry.commit)) + + +@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 + head = git(directory, "rev-parse", "--verify", "--quiet", "HEAD") + return Log(pathlib.Path(str(common)) / LOG, str(branch) or "HEAD", "" if isinstance(head, Failure) else head) + + +def write_override(log: Log, entry: Entry) -> Failure | None: + 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, entry.line().encode("utf-8")) + except OSError as failure: + return Failure(str(failure)) + finally: + os.close(descriptor) + return None + + +def logged(log: Log, breach: Breach, reason: str, what: str, now: float) -> Entry: + return Entry(utc(now), log.branch, log.head, breach.rule, reason, what) + + +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 + found = git(directory, "branch", "--show-current") + branch = found if isinstance(found, str) and found else "HEAD" + reflog = git(directory, "reflog", "show", "--format=%H", branch) + head = git(directory, "rev-parse", "HEAD") + # A reflog missing HEAD is off or expired, and would hide this chunk's overrides. + unread = reflog if isinstance(reflog, Failure) else head if isinstance(head, Failure) else None if head in reflog.split() else Failure("it does not hold HEAD") + if unread: + print(f"rule-hook overrides cannot read the branch's reflog, so it cannot tell which overrides are this chunk's: {unread.reason}", file=sys.stderr) + return 1 + default = default_branch(directory) + log = pathlib.Path(common) / LOG + entries = [parsed_entry(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.is_file() else [] + on_default = (lambda commit: holds(directory, default, commit)) if default else (lambda commit: False) + for entry in entries: + if entry and this_chunks(entry, set(str(reflog).split()), branch, on_default): + print(entry.line(), end="") + 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) diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index c0a7c197..d3196cec 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -10,6 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from rule_hook.rules import blocks, Breach, command_breaches, Commit, commit_message, commits, file_breaches, overrides, verdict from test_rank_todo import DECISIONS, README, TODO +from rule_hook.override_log import Entry, parsed_entry, this_chunks from test_env import isolated_env from shell_command import simple_commands @@ -136,6 +137,20 @@ class Overrides(unittest.TestCase): self.assertIn("``", verdict([Breach("no-ai-attribution", "x", "/r")], "", True, False).messages[0]) +class OverrideLog(unittest.TestCase): + def test_an_entry_reads_back_as_written(self): + entry = Entry("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor\ttags no patch", "Dockerfile") + self.assertEqual(parsed_entry(entry.line()), Entry("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor tags no patch", "Dockerfile")) + self.assertIsNone(parsed_entry("a\tb")) + + def test_an_override_is_the_chunk_s_by_its_reflog_and_name(self): + on_default = {"base"}.__contains__ + cases = [("chunk", "c1", True), ("other", "c1", True), ("other", "c9", False), ("chunk", "base", True), ("other", "base", False), ("other", "", True)] + for branch, commit, expected in cases: + with self.subTest(branch=branch, commit=commit): + self.assertEqual(this_chunks(Entry("t", branch, commit, "image-pin", "r", "w"), {"base", "c1"}, "chunk", on_default), expected) + + class Hook(unittest.TestCase): def setUp(self): self.repo = tempfile.mkdtemp() diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py new file mode 100644 index 00000000..8f64d80a --- /dev/null +++ b/bin/rule_hook/todo_check.py @@ -0,0 +1,25 @@ +import hashlib +import pathlib + +from rule_hook.rules import Breach +from failure import Failure +from rule_hook.git import git +import rank_todo + + +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