From 39437cef6aa7b707d5a5957778045cba2e8415d4 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:06:23 +0200 Subject: [PATCH 01/17] Enforce the checkable rules in a hook, with one override marker a judge rules on, and drop them from CLAUDE.md --- .gitignore | 3 + CHANGELOG.md | 1 + CLAUDE.md | 9 +- README.md | 1 + bin/repo_checks/test_types.py | 2 +- bin/rule-hook | 9 ++ bin/rule_hook/__init__.py | 0 bin/rule_hook/main.py | 158 ++++++++++++++++++++++++++++ bin/rule_hook/rules.py | 176 ++++++++++++++++++++++++++++++++ bin/rule_hook/test_rule_hook.py | 130 +++++++++++++++++++++++ settings.json | 14 +++ skills/larv-review/SKILL.md | 9 +- todo.md | 11 +- 13 files changed, 503 insertions(+), 20 deletions(-) create mode 100755 bin/rule-hook create mode 100644 bin/rule_hook/__init__.py create mode 100644 bin/rule_hook/main.py create mode 100644 bin/rule_hook/rules.py create mode 100644 bin/rule_hook/test_rule_hook.py diff --git a/.gitignore b/.gitignore index 678afcbe..1cb68cda 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,9 @@ !bin/reading_cost/*.py !bin/repo_checks/ !bin/repo_checks/*.py +!bin/rule-hook +!bin/rule_hook/ +!bin/rule_hook/*.py !bin/statusline.py !bin/test_*.py !bin/todo_table.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 09e2fdb7..7a8a0f1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- A hook blocks each Bash, Edit, MultiEdit and Write call that breaks a rule a program can check: a multi-line commit message, a Claude or Anthropic attribution, a container image short of a full patch version, an Action pinned to anything but a semver tag, an unsorted block in an ignore file, and a commit of a `todo.md` that `rank_todo.py --check` rejects. `CLAUDE.md` no longer states those rules; `~/.claude/bin/rule-hook --help` does. A call overrides a rule with `# rule-override : `. larv-review lists each override in the PR body, and a judge accepts it, or rejects it and the chunk keeps the rule; one that touches a credential, a security rule or a production system, or cannot be undone, is asked of you. - A project may opt out of larv-review's architect, product-owner pass or comprehension check in every chunk, through a `docs/decisions.md` entry titled `review opt-out: …` that names the goal that skipping them serves. A project without such an entry is reviewed as before. Opting out of the comprehension check also skips the scoring run due at a release's end, so the floor blocks nothing; the opt-out ends with a chunk that ships a plan item naming the floor, which removes the comprehension check from the entry. The principles audit always runs. - A README goal states the project's aim and intent, and no longer names a step of the work, such as "kill weak candidates early". Such steps go in a method section further down the README and name the goal they serve. - The stability reviewer keeps its scratch work in a directory it creates for the run, deletes that directory afterwards, and deletes nothing else. diff --git a/CLAUDE.md b/CLAUDE.md index a7141f5f..b54b8360 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,7 +21,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The ### Todo items (`todo.md`, tickets, plans) - **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. Cite an item by its ID. The formula, bar and weights are the project's own to tune. -- **Score an item when it is filed or edited, then run `rank_todo.py`.** Each of R, S, A and G is a whole number from 1 to 10: +- **Score an item when it is filed or edited.** Each of R, S, A and G is a whole number from 1 to 10: - **R** — the risk that the change creates serious bugs or issues. - **S** — the size of the change. - **A** — its value to the audience in `README.md` → `## Audience`. @@ -117,9 +117,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, - Tear down test containers after a run. - Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create. - Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). -- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. -- Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds. -- Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.) +- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports and table rows. Exception: `id` goes first. ## Naming files & folders - Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. @@ -130,8 +128,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, The rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before writing, designing or reviewing code. ## Git, commits, and PRs -- Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else. -- Commit message and PR title: **one line**, prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context. +- Commit message and PR title: prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context. - PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title). - When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it. - Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`. diff --git a/README.md b/README.md index bba003f6..b1c33ee0 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores. - `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format. - `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure. +- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Bash, Edit, MultiEdit and Write call, and `rule-hook --help` states the rules and the override. - `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it. Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'` diff --git a/bin/repo_checks/test_types.py b/bin/repo_checks/test_types.py index cac83003..dbe39fe3 100644 --- a/bin/repo_checks/test_types.py +++ b/bin/repo_checks/test_types.py @@ -15,5 +15,5 @@ class Types(unittest.TestCase): self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`") if shutil.which("uv") is None: self.fail("uv on PATH fetches mypy; see README.md's Test line") - ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True) + ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-p", "rule_hook", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) diff --git a/bin/rule-hook b/bin/rule-hook new file mode 100755 index 00000000..20c1ac3a --- /dev/null +++ b/bin/rule-hook @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from rule_hook import main + +sys.exit(main.main(sys.argv[1:], "" if sys.argv[1:] else sys.stdin.read())) diff --git a/bin/rule_hook/__init__.py b/bin/rule_hook/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py new file mode 100644 index 00000000..6b639fe8 --- /dev/null +++ b/bin/rule_hook/main.py @@ -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 : `: 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}: ` 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 "" diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py new file mode 100644 index 00000000..5c0f1428 --- /dev/null +++ b/bin/rule_hook/rules.py @@ -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 '', 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 '', 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] diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py new file mode 100644 index 00000000..b2c1c0de --- /dev/null +++ b/bin/rule_hook/test_rule_hook.py @@ -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 " + + +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 - <`", 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) diff --git a/settings.json b/settings.json index 17647abb..7ca96fdb 100644 --- a/settings.json +++ b/settings.json @@ -33,6 +33,20 @@ } } }, + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash|Edit|MultiEdit|Write", + "hooks": [ + { + "type": "command", + "command": "~/.claude/bin/rule-hook", + "timeout": 30 + } + ] + } + ] + }, "effortLevel": "xhigh", "modelSettings": { "claude-fable-5-1": { diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 21df1921..c70e9e55 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -157,10 +157,11 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 5. Goal alignment, then merge 1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; ask the human, stating the conflict. -2. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. -3. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". -4. Stop. The next chunk gets a fresh session. +2. **Overrides.** Run `~/.claude/bin/rule-hook overrides` in the chunk's worktree. When it prints a line, launch one general-purpose subagent as the judge, with no shell and no edits, given each line, the rule's text from `~/.claude/bin/rule-hook --help`, the README's goals and the diff each override let through. It accepts or rejects each reason by the goals, and calls an override outrageous when it touches a credential, a security rule or a production system, or cannot be undone. An accepted override stands. A rejected one is a 🔴 of this chunk: keep the rule, then re-enter per §3 → "Re-entry". An outrageous one is asked of the user. List each override with its ruling in the PR body. +3. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. +4. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". +5. Stop. The next chunk gets a fresh session. ## 6. Wrap up -Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, principles files left out with why, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal or technical principle it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. +Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, principles files left out with why, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal or technical principle it rests on — CI status, rule overrides with their rulings, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. diff --git a/todo.md b/todo.md index e2a62f65..69c86628 100644 --- a/todo.md +++ b/todo.md @@ -25,7 +25,6 @@ | ID | Release | Exempt | Item | R | S | A | G | Goals | Score | |---|---|---|---|---|---|---|---|---|---| | 95 | 0.1.0 | | **Make `CLAUDE.md` a short router: only the rules every session needs, and a pointer to where each topic's rules load.** | 6 | 6 | 8 | 8 | 1.1, 1.3, 1.4 | 24.3 | -| 96 | 0.1.0 | | **Enforce each rule a program can check in a hook or in CI, with one override marker the agent may use and the PR lists, and delete those rules from `CLAUDE.md`.** | 5 | 6 | 7 | 8 | 1.1, 1.3 | 23.3 | | 98 | 0.1.0 | | **Score R and S from a measurement wherever one exists, and calibrate each guessed score against the finished chunk's measured outcome.** | 2 | 5 | 6 | 7 | 1.1, 1.4 | 22.6 | | 99 | 0.1.0 | | **Drop the comprehension panel as a merge gate, and keep recording its scores and the places in the code its seats found hard, for later measurement and for other reviewers and agents to improve.** | 4 | 5 | 7 | 7 | 1.1, 1.4, 1.5 | 22.6 | | 87 | 0.1.0 | | **Score every `todo.md` item's complexity C from 1 to 10, and have `rank_todo.py` fail on an item without one.** | 3 | 4 | 6 | 7 | 1.1, 1.4 | 21.9 | @@ -74,14 +73,6 @@ Keep in it only what every session needs and no other file loads: the vocabulary - 🟢 "Ask, don't guess": "If an answer is a goal and something else too, write the goal, and record a choice only for what the goal leaves open." Proposed: `When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open.` - 🟢 "Decisions: one home" lists "a comment" as a wrong home, then names a comment as the destination. Proposed: `a comment away from the code it governs`. -Needs 96. - -### 96. Enforce each rule a program can check in a hook or in CI, with one override marker the agent may use and the PR lists, and delete those rules from `CLAUDE.md`. - -Anthropic's best-practices page: CLAUDE.md is advisory, hooks are deterministic, so a rule that must hold every time belongs in a hook. Candidates include one-line commit messages without authorship trailers, container images pinned to a full patch version, sorted ignore files, and `rank_todo.py --check` on `todo.md`. - -A blocking hook exits 2 with a message that names the rule, why it holds, and the override. The override is one marker, the same for every hook and check, that names the rule and gives a reason. A CI check accepts it too, in the PR body. larv-review's PR summary lists every override in the chunk, and a judge rules on each from the rule, the reason and the README's goals: loop-claude's judge in a loop, a judge subagent in a run of larv-review alone. A reason the judge accepts stands, and one it rejects sends the worker back to keep the rule (goal 1.2). The judge interrupts the human only for an outrageous override: one that touches a credential, a security rule or a production system, or that cannot be undone. A rule a project sets for itself, such as fejkdata's Go-only-in-compose, goes in that project's own hook. - ### 98. Score R and S from a measurement wherever one exists, and calibrate each guessed score against the finished chunk's measured outcome. A score that can be computed from the code it touches, such as the files an item names, comes from that computation. Otherwise size and risk are estimated from finished work, the way reference-class forecasting estimates a project from earlier projects like it. When a chunk merges, record its measured outcome beside the item's guessed R and S: lines and files changed, review rounds, 🔴 and 🟡 findings, and fixes the code needed later. Show the scorer, when it files an item, the finished items whose guessed scores sat nearest and what they measured. Once enough chunks are recorded, report how far each guess was from its outcome, so a scorer whose S runs high can be corrected. Item 87's C is scored and calibrated the same way. @@ -178,6 +169,8 @@ Raised by the product-owner review of PR #211. The resumed worker gets the judge The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word. +A rule check CI runs, such as one of `bin/rule-hook`'s, accepts `# rule-override : ` in the PR body. + ### 80. State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes. Raised by the principles audit of PR #224. The `settings.json` decision is valid while every machine taking this checkout is a sandbox, but Install asks for a sandbox only for `loop-claude`, so a new machine is never told. -- 2.52.0 From 3ef8c196cd7acfe5208100e4cb13aec612a9d739 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:15:49 +0200 Subject: [PATCH 02/17] Answer security round 1: no finding -- 2.52.0 From 2f2a7703923544850463f2146bcf62513f3b324c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:15:49 +0200 Subject: [PATCH 03/17] Answer stability round 1: sort imports, share rank_todo's check, scope YAML to compose and workflows, judge only newly unsorted ignore blocks, cut heredoc bodies, check COPY --from and container:, log what each override let through, keep CLAUDE.md lines for what the hook cannot see --- CLAUDE.md | 4 ++- bin/rank_todo.py | 19 +++++++++++- bin/rule_hook/main.py | 52 +++++++++++++++------------------ bin/rule_hook/rules.py | 30 ++++++++++++------- bin/rule_hook/test_rule_hook.py | 37 ++++++++++++++++++----- 5 files changed, 93 insertions(+), 49 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b54b8360..91fe7d6a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -117,7 +117,8 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, - Tear down test containers after a run. - Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create. - Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). -- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports and table rows. Exception: `id` goes first. +- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows and line-based file lists. Exception: `id` goes first. +- Pin a container image to its full patch version where `~/.claude/bin/rule-hook` does not check it, such as in a test fixture, a Kubernetes manifest or a `docker run` line. ## Naming files & folders - Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. @@ -128,6 +129,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, The rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before writing, designing or reviewing code. ## Git, commits, and PRs +- Mark no commit, PR, issue comment or file as the work of Claude, Anthropic or an agent. - Commit message and PR title: prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context. - PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title). - When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it. diff --git a/bin/rank_todo.py b/bin/rank_todo.py index 8cf636f7..6aea06d8 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -91,6 +91,11 @@ def main(argv: list[str]) -> int: if isinstance(args, Failure): return fail(args) check, todo = args + if check: + failures = check_failures(todo) + for line in failures: + print(line, file=sys.stderr) + return 1 if failures else 0 texts = read_all(todo) if isinstance(texts, Failure): return fail(texts) @@ -98,7 +103,7 @@ def main(argv: list[str]) -> int: if isinstance(ranked, Failure): return fail(ranked) if ranked.text != texts[0]: - unwritten = Failure(f"{todo}: not ranked; run rank_todo.py on it") if check else write(todo, ranked.text) + unwritten = write(todo, ranked.text) if unwritten: return fail(unwritten) for line in ranked.under_bar: @@ -106,6 +111,18 @@ def main(argv: list[str]) -> int: return 1 if ranked.under_bar else 0 +def check_failures(todo: pathlib.Path) -> list[str]: + """Why --check fails on todo, empty when it passes.""" + texts = read_all(todo) + if isinstance(texts, Failure): + return [texts.reason] + ranked = rank(*texts) + if isinstance(ranked, Failure): + return [ranked.reason] + unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"] + return unranked + [f"{todo}: {line}" for line in ranked.under_bar] + + def fail(failure: Failure) -> int: print(failure.reason, file=sys.stderr) return 1 diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 6b639fe8..73149cf4 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -6,19 +6,22 @@ usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin) 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 + 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 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 + ignorefile-sorted each block of a .*ignore file that an edit leaves unsorted is sorted; 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 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 : `: 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. +A call overrides a rule with `# rule-override : `: anywhere in a Bash command, such 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, and the file written or the command's first line. `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. @@ -31,9 +34,8 @@ 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 +import rank_todo from utc_stamp import utc LOG = "rule-overrides.tsv" @@ -58,14 +60,15 @@ def main(argv: list[str], stdin: str) -> int: 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 = overrides(text) for breach in breaches: if breach.rule in granted: - log_override(directory, breach.rule, granted[breach.rule]) + 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, as a trailing comment" if tool == "Bash" else "the text you write, as a comment line" + where = "the command" 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}: ` to {where}; larv-review's judge rules on the reason.", file=sys.stderr) @@ -75,22 +78,22 @@ def main(argv: list[str], stdin: str) -> int: 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", "") + command = str(given.get("command") or "") 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", "") + 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 given.get("edits", []) + edits = [given] if tool == "Edit" else [edit for edit in given.get("edits") or [] if isinstance(edit, dict)] if tool == "Write": - added = after = given.get("content", "") + added = after = str(given.get("content") or "") else: after = before for edit in edits: - old, new = edit.get("old_string", ""), edit.get("new_string", "") + 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(edit.get("new_string", "") for edit in edits) + 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) @@ -101,25 +104,16 @@ def todo_breaches(directory: str, staged_all: bool) -> list[Breach]: 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] + return [Breach("todo-rank-check", line) for line in rank_todo.check_failures(pathlib.Path(top) / "todo.md")] -def log_override(directory: str, rule: str, reason: str) -> None: +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())]) + "\n") + log.write("\t".join([utc(time.time()), branch, rule, " ".join(reason.split()), " ".join(what.split())]) + "\n") def print_overrides(directory: str) -> int: diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 5c0f1428..2f5b631a 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -10,15 +10,19 @@ RULES = { "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", + "todo-rank-check": "a committed todo.md passes ~/.claude/bin/rank_todo.py --check", } 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+(?:[-+_.].*)?") +# Two-part tags such as postgres:16.4 stay blocked: the rule bans node:24.18, which reads the same, so such an image takes an override. +PATCH = re.compile(r"v?\d+\.\d+\.\d+(?:[-+_.].*)?|.*\d{8}.*") 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) +COPIED = re.compile(r"^[ \t]*COPY[ \t].*?--from=(\S+)", re.IGNORECASE | re.MULTILINE) +IMAGE = re.compile(r"^[ \t]*(?:-[ \t]+)?(?:image|container):[ \t]*[\"']?([^\s\"'#{]+)", re.MULTILINE) +BUILD = re.compile(r"^[ \t]*build:", re.MULTILINE) +HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)(\w+)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | 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", "&&", "||", ";", "|", "&", "(", ")", ";;", "|&"} @@ -46,10 +50,11 @@ def overrides(text: str) -> dict[str, str]: 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") + """The command's simple commands as words, each heredoc's body cut to a line break, or None when it does not parse.""" + lexer = shlex.shlex(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0] + "\n", command), posix=True, punctuation_chars="();<>|&\n") lexer.whitespace = " \t\r" lexer.whitespace_split = True + # shlex also ends a word at a # inside it, as in fix#2, which bash does not; after lexing, a quoted # cannot be told apart. try: words = list(lexer) except ValueError: @@ -142,13 +147,18 @@ def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach 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)] + images = [image for image, _ in FROM.findall(added)] + COPIED.findall(added) + breaches += [Breach("image-pin", f"{path}: {image}") for image in images if image.lower() not in stages | {"scratch"} and not image.isdigit() and not pinned(image)] + workflow = any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or name in ("action.yml", "action.yaml") + if "compose" in name and name.endswith((".yml", ".yaml")) or workflow: + # A compose service that builds names its own image with image:, untagged. + built = "compose" in name and BUILD.search(after) is not None + breaches += [Breach("image-pin", f"{path}: {image}") for image in IMAGE.findall(added) if not pinned(image) and not (built and ":" not in image)] + if workflow: 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)] + already = [block for block in blocks(before) if block != sorted(block)] + 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) and block not in already] return breaches diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index b2c1c0de..cdf0ce61 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -8,8 +8,8 @@ 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 +from test_env import isolated_env HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook" # Built from parts, so this file carries no attribution of its own. @@ -58,27 +58,43 @@ class CommandBreaches(unittest.TestCase): 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_heredoc_body_is_no_shell_text(self): + self.assertEqual(rules(command_breaches("git commit -F - <<'EOF'\nTitle\n\nIt's the body\nEOF\necho done", "/r")), ["commit-one-line"]) + self.assertEqual(rules(command_breaches("git commit -m \"$(cat <<'EOF'\nIt's one line\nEOF\n)\"", "/r")), ["commit-one-line"]) + 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"]) + added = "FROM node:24 AS build\nFROM node:24.18.1-bookworm-slim\nFROM alpine@sha256:ab\nFROM debian:bookworm-20240926-slim\nFROM build\nFROM scratch\nFROM ${BASE}\nFROM python\nCOPY --from=build /a /a\nCOPY --from=0 /b /b\nCOPY --chown=1 --from=alpine:3 /c /c\n" + self.assertEqual([breach.detail for breach in file_breaches("Dockerfile", "", added, added)], ["Dockerfile: node:24", "Dockerfile: python", "Dockerfile: alpine:3"]) 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_a_workflow_checks_its_images_and_actions(self): + added = " container: node:24\n 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("/r/.gitea/workflows/ci.yml", "", added, added)), ["image-pin", "image-pin", "action-pin"]) + + def test_a_compose_file_checks_its_images_but_not_the_one_it_builds(self): + self.assertEqual(rules(file_breaches("compose.yaml", "", " image: redis\n", " image: redis\n")), ["image-pin"]) + after = " app:\n build: .\n image: myapp\n" + self.assertEqual(file_breaches("docker-compose.yml", "", after, after), []) + + def test_other_yaml_is_not_checked(self): + added = "image: /assets/og.png\nimage: { type: string }\nuses: a/b@main\n" + self.assertEqual(file_breaches("_config.yml", "", added, added), []) 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_a_block_unsorted_before_the_edit_is_left_alone(self): + self.assertEqual(file_breaches(".gitignore", "node_modules\n.env\n\ndist\n", "out", "node_modules\n.env\n\ndist\nout\n"), []) + def test_an_attribution_in_any_file_breaks(self): self.assertEqual(rules(file_breaches("notes.md", "", TRAILER, TRAILER)), ["no-ai-attribution"]) @@ -105,7 +121,7 @@ class Hook(unittest.TestCase): 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$") + self.assertRegex(listed, r"^\S+Z\tchunk\timage-pin\tthe vendor tags no patch versions\t\S+/sub/Dockerfile\n$") def test_an_edit_is_judged_on_the_file_it_leaves(self): pathlib.Path(self.repo, ".gitignore").write_text("a\nc\n") @@ -123,7 +139,12 @@ class Hook(unittest.TestCase): 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) + self.assertIn("todo.md: not ranked", ran.stderr) + + def test_a_missing_field_breaks_nothing(self): + for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}]: + with self.subTest(given): + self.assertEqual(hook({"cwd": self.repo, "tool_input": given, "tool_name": "Write" if "content" in given else "Bash"}, self.repo).returncode, 0) def test_unreadable_input_does_not_block(self): ran = subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input="{", text=True) -- 2.52.0 From 2d3f3adebc80260c42cd3ff6f516b4e74680d5fb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:20:57 +0200 Subject: [PATCH 04/17] Answer stability round 2: keep the line break that ends a heredoc, read a run of separators as one, check every untagged compose image, and reject a non-object tool input --- CHANGELOG.md | 2 +- bin/rule-hook | 2 +- bin/rule_hook/main.py | 30 ++++++++++++++++--------- bin/rule_hook/rules.py | 33 ++++++++++++--------------- bin/rule_hook/test_rule_hook.py | 40 ++++++++++++++++++++++----------- skills/larv-review/SKILL.md | 2 +- 6 files changed, 63 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a8a0f1b..a35a1366 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- A hook blocks each Bash, Edit, MultiEdit and Write call that breaks a rule a program can check: a multi-line commit message, a Claude or Anthropic attribution, a container image short of a full patch version, an Action pinned to anything but a semver tag, an unsorted block in an ignore file, and a commit of a `todo.md` that `rank_todo.py --check` rejects. `CLAUDE.md` no longer states those rules; `~/.claude/bin/rule-hook --help` does. A call overrides a rule with `# rule-override : `. larv-review lists each override in the PR body, and a judge accepts it, or rejects it and the chunk keeps the rule; one that touches a credential, a security rule or a production system, or cannot be undone, is asked of you. +- A hook blocks each Bash, Edit, MultiEdit and Write call that breaks a rule a program can check: a multi-line commit message, a Claude or Anthropic attribution, a container image short of a full patch version, an Action pinned to anything but a semver tag, an unsorted block in an ignore file, and a commit of a `todo.md` that `rank_todo.py --check` rejects. `CLAUDE.md` states those rules only where the hook cannot check them; `~/.claude/bin/rule-hook --help` states what it checks. A call overrides a rule with `# rule-override : `. larv-review lists each override in the PR body, and a judge accepts it, or rejects it and the chunk keeps the rule; one that touches a credential, a security rule or a production system, or cannot be undone, is asked of you. - A project may opt out of larv-review's architect, product-owner pass or comprehension check in every chunk, through a `docs/decisions.md` entry titled `review opt-out: …` that names the goal that skipping them serves. A project without such an entry is reviewed as before. Opting out of the comprehension check also skips the scoring run due at a release's end, so the floor blocks nothing; the opt-out ends with a chunk that ships a plan item naming the floor, which removes the comprehension check from the entry. The principles audit always runs. - A README goal states the project's aim and intent, and no longer names a step of the work, such as "kill weak candidates early". Such steps go in a method section further down the README and name the goal they serve. - The stability reviewer keeps its scratch work in a directory it creates for the run, deletes that directory afterwards, and deletes nothing else. diff --git a/bin/rule-hook b/bin/rule-hook index 20c1ac3a..2d10b2be 100755 --- a/bin/rule-hook +++ b/bin/rule-hook @@ -6,4 +6,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from rule_hook import main -sys.exit(main.main(sys.argv[1:], "" if sys.argv[1:] else sys.stdin.read())) +sys.exit(main.main(sys.argv[1:], "" if sys.argv[1:] or sys.stdin.isatty() else sys.stdin.read())) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 73149cf4..d5dbbccd 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -14,14 +14,18 @@ subagent. The rules: `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 commit that stages todo.md, or commits with -a while todo.md has changes, - needs rank_todo.py --check to pass on it + todo-rank-check a git commit while todo.md has changes, staged or not, needs + rank_todo.py --check to pass on it + +The file rules see what an Edit, MultiEdit or Write call writes, not a file a Bash command writes. A call overrides a rule with `# rule-override : `: anywhere in a Bash command, such 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, and the file written or the command's first line. `rule-hook overrides` -prints the lines for the current branch. +a trailing comment; in a file, as a comment line in the text the edit writes, or in Markdown as +``. 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. + +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. @@ -42,7 +46,7 @@ LOG = "rule-overrides.tsv" def main(argv: list[str], stdin: str) -> int: - if argv in (["-h"], ["--help"]): + if argv in (["-h"], ["--help"]) or not argv and not stdin: print(__doc__.strip()) return 0 if argv == ["overrides"]: @@ -53,6 +57,8 @@ def main(argv: list[str], stdin: str) -> int: 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) return 1 @@ -69,6 +75,8 @@ def main(argv: list[str], stdin: str) -> int: if not blocking: return 0 where = "the command" if tool == "Bash" else "the text you write, as a comment line" + if "rule-override" in text and not granted: + print("The rule-override in this call 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) print(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule]}. Where it does not fit this case, add `# rule-override {rule}: ` to {where}; larv-review's judge rules on the reason.", file=sys.stderr) @@ -79,7 +87,7 @@ def checked_call(tool: str, given: dict[str, typing.Any], cwd: str) -> tuple[str """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, commit.all)] + 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: @@ -97,12 +105,12 @@ def checked_call(tool: str, given: dict[str, typing.Any], cwd: str) -> tuple[str return added, os.path.dirname(path), file_breaches(path, before, added, after) -def todo_breaches(directory: str, staged_all: bool) -> list[Breach]: +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(): return [] - changed = git(top, "diff", "--cached", "--name-only", "--", "todo.md") or (staged_all and git(top, "diff", "--name-only", "--", "todo.md")) - if not changed: + # 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")] diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 2f5b631a..e5c2b6a7 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -8,11 +8,11 @@ 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", + "image-pin": "a container image is pinned to its full patch version, such as node:24.18.1-bookworm-slim, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day; a bot such as Renovate raises the bumps as reviewable PRs. An image that publishes no three-part tag, such as postgres:16.4, takes an override", "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", } -OVERRIDE = re.compile(r"#\s*rule-override ([a-z-]+):[ \t]*(\S[^\n]*)") +OVERRIDE = re.compile(r"(?:#|").strip() for rule, reason in OVERRIDE.findall(text)} + return {rule: reason for rule, reason in given.items() if rule in RULES and reason} def segments(command: str) -> list[list[str]] | None: """The command's simple commands as words, each heredoc's body cut to a line break, or None when it does not parse.""" - lexer = shlex.shlex(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0] + "\n", command), posix=True, punctuation_chars="();<>|&\n") + lexer = shlex.shlex(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command), posix=True, punctuation_chars="();<>|&\n") lexer.whitespace = " \t\r" lexer.whitespace_split = True # shlex also ends a word at a # inside it, as in fix#2, which bash does not; after lexing, a quoted # cannot be told apart. @@ -61,7 +60,8 @@ def segments(command: str) -> list[list[str]] | None: return None split: list[list[str]] = [[]] for word in words: - if word in SEPARATORS: + # Unquoted, a run such as "&&\n" lexes as one word. + if set(word) <= SEPARATING: split.append([]) else: split[-1].append(word) @@ -91,7 +91,7 @@ def git_commit(args: list[str], directory: str) -> Commit | None: if args[at:at + 1] != ["commit"]: return None messages: list[str] = [] - from_file = staged_all = False + from_file = False rest = args[at + 1:] at = 0 while at < len(rest): @@ -107,8 +107,6 @@ def git_commit(args: list[str], directory: str) -> Commit | None: 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): @@ -120,9 +118,8 @@ def git_commit(args: list[str], directory: str) -> Commit | None: 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) + return Commit(directory, messages, from_file) def command_breaches(command: str, cwd: str) -> list[Breach]: @@ -151,14 +148,12 @@ def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach breaches += [Breach("image-pin", f"{path}: {image}") for image in images if image.lower() not in stages | {"scratch"} and not image.isdigit() and not pinned(image)] workflow = any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or name in ("action.yml", "action.yaml") if "compose" in name and name.endswith((".yml", ".yaml")) or workflow: - # A compose service that builds names its own image with image:, untagged. - built = "compose" in name and BUILD.search(after) is not None - breaches += [Breach("image-pin", f"{path}: {image}") for image in IMAGE.findall(added) if not pinned(image) and not (built and ":" not in image)] + breaches += [Breach("image-pin", f"{path}: {image}") for image in IMAGE.findall(added) if not pinned(image)] if workflow: 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"): already = [block for block in blocks(before) if block != sorted(block)] - 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) and block not in already] + breaches += [Breach("ignorefile-sorted", f"{path}: sort the block {block[0]!r} through {block[-1]!r} in code-point order, as LC_ALL=C sort does: {', '.join(sorted(block))}") for block in blocks(after) if block != sorted(block) and block not in already] return breaches diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index cdf0ce61..ac0250f8 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -30,7 +30,7 @@ def git(cwd: str, *args: str) -> str: 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)]) + self.assertEqual(commits("cd a && git -C b commit -am 'x'", "/r"), [Commit("/r/a/b", ["x"], False)]) 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"]) @@ -41,8 +41,15 @@ class Commits(unittest.TestCase): def test_other_git_commands_are_no_commit(self): self.assertEqual(commits("git log --grep commit; echo git commit", "/r"), []) + def test_a_commit_after_a_heredoc_or_a_blank_line_is_seen(self): + self.assertEqual(len(commits("cat < notes\nhello\nEOF\ngit commit -m a", "/r")), 1) + self.assertEqual(len(commits("git status &&\n\ngit commit -m a", "/r")), 1) + + def test_an_arithmetic_shift_is_no_heredoc(self): + self.assertEqual(len(commits("echo $((1<<2))\ngit commit -m a\n2", "/r")), 1) + 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)]) + self.assertEqual(commits("cd a\nGIT_EDITOR=true git commit -m x", "/r"), [Commit("/r/a", ["x"], False)]) class CommandBreaches(unittest.TestCase): @@ -78,10 +85,8 @@ class FileBreaches(unittest.TestCase): added = " container: node:24\n 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("/r/.gitea/workflows/ci.yml", "", added, added)), ["image-pin", "image-pin", "action-pin"]) - def test_a_compose_file_checks_its_images_but_not_the_one_it_builds(self): + def test_a_compose_file_checks_its_images(self): self.assertEqual(rules(file_breaches("compose.yaml", "", " image: redis\n", " image: redis\n")), ["image-pin"]) - after = " app:\n build: .\n image: myapp\n" - self.assertEqual(file_breaches("docker-compose.yml", "", after, after), []) def test_other_yaml_is_not_checked(self): added = "image: /assets/og.png\nimage: { type: string }\nuses: a/b@main\n" @@ -103,6 +108,9 @@ 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"}) + def test_markdown_takes_an_html_comment(self): + self.assertEqual(overrides(""), {"no-ai-attribution": "quotes the banned line"}) + class Hook(unittest.TestCase): def setUp(self): @@ -128,23 +136,29 @@ class Hook(unittest.TestCase): 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): + def test_a_commit_while_an_unranked_todo_has_changes_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") + git(self.repo, "add", "README.md", "docs", "todo.md") + git(self.repo, "commit", "-qm", "x", "--no-verify") + call = {"cwd": self.repo, "tool_input": {"command": "git add -A && git commit -m x"}, "tool_name": "Bash"} + self.assertEqual(hook(call, self.repo).returncode, 0, "todo.md is unchanged") + pathlib.Path(self.repo, "todo.md").write_text(TODO + "\n") ran = hook(call, self.repo) self.assertEqual(ran.returncode, 2) self.assertIn("todo.md: not ranked", ran.stderr) + def test_a_malformed_override_is_named(self): + ran = hook({"cwd": self.repo, "tool_input": {"command": "git commit -m a -m b # rule-override commit-oneline: x"}, "tool_name": "Bash"}, self.repo) + self.assertIn("names no rule below, or gives no reason", ran.stderr) + def test_a_missing_field_breaks_nothing(self): - for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}]: + for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}, {"edits": [None], "file_path": f"{self.repo}/a.md"}]: with self.subTest(given): - self.assertEqual(hook({"cwd": self.repo, "tool_input": given, "tool_name": "Write" if "content" in given else "Bash"}, self.repo).returncode, 0) + tool = "Bash" if "command" in given else "Write" if "content" in given else "MultiEdit" + self.assertEqual(hook({"cwd": self.repo, "tool_input": given, "tool_name": tool}, self.repo).returncode, 0) + self.assertEqual(hook({"cwd": self.repo, "tool_input": None, "tool_name": "Bash"}, self.repo).returncode, 1) def test_unreadable_input_does_not_block(self): ran = subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input="{", text=True) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index c70e9e55..30de77be 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -157,7 +157,7 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 5. Goal alignment, then merge 1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; ask the human, stating the conflict. -2. **Overrides.** Run `~/.claude/bin/rule-hook overrides` in the chunk's worktree. When it prints a line, launch one general-purpose subagent as the judge, with no shell and no edits, given each line, the rule's text from `~/.claude/bin/rule-hook --help`, the README's goals and the diff each override let through. It accepts or rejects each reason by the goals, and calls an override outrageous when it touches a credential, a security rule or a production system, or cannot be undone. An accepted override stands. A rejected one is a 🔴 of this chunk: keep the rule, then re-enter per §3 → "Re-entry". An outrageous one is asked of the user. List each override with its ruling in the PR body. +2. **Overrides.** Run `~/.claude/bin/rule-hook overrides` in the chunk's worktree. When it prints a line no judge has ruled on in this chunk, launch one general-purpose subagent as the judge, with no shell and no edits, given those lines, the rules from `~/.claude/bin/rule-hook --help`, the README's goals and the branch diff. It rules nothing on an override whose breach the branch no longer holds. It accepts or rejects each other reason by the goals, and calls an override outrageous when it touches a credential, a security rule or a production system, or cannot be undone. An accepted override stands. A rejected one is a 🔴 of this chunk: keep the rule, such as by rewording the commit or pinning the image, then re-enter per §3 → "Re-entry"; where the rule cannot be kept, ask the user. An outrageous one is asked of the user. List each override with its ruling in the PR body. 3. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. 4. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". 5. Stop. The next chunk gets a fresh session. -- 2.52.0 From 5c306fdd513861ccb257e59bf6a95612983344e1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:21:03 +0200 Subject: [PATCH 05/17] Answer product-owner round 1: in 2d3f3ad, a judge rules each override once and asks when a rule cannot be kept, block messages name the accepted pins and the sort order, a change to todo.md before git add is checked, a malformed override is named, Markdown takes an HTML-comment override, and help states what the file rules see -- 2.52.0 From 0292c1a55c2da64e90bb24b977cabf037b7a3009 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:26:07 +0200 Subject: [PATCH 06/17] Answer stability round 3: an empty argument separates no command, and two overrides on one line are read apart --- bin/rule_hook/main.py | 10 ++++++---- bin/rule_hook/rules.py | 14 ++++++++------ bin/rule_hook/test_rule_hook.py | 15 +++++++++++---- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index d5dbbccd..5dc37fd7 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -67,7 +67,7 @@ def main(argv: list[str], stdin: str) -> int: return 0 text, directory, breaches = checked what = text.split("\n", 1)[0] if tool == "Bash" else str(given.get("file_path")) - granted = overrides(text) + granted, malformed = overrides(text) for breach in breaches: if breach.rule in granted: log_override(directory, breach.rule, granted[breach.rule], what) @@ -75,11 +75,13 @@ def main(argv: list[str], stdin: str) -> int: if not blocking: return 0 where = "the command" if tool == "Bash" else "the text you write, as a comment line" - if "rule-override" in text and not granted: - print("The rule-override in this call names no rule below, or gives no reason.", file=sys.stderr) + 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) - print(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule]}. Where it does not fit this case, add `# rule-override {rule}: ` to {where}; larv-review's judge rules on the reason.", file=sys.stderr) + marker = f"" if markdown else f"# rule-override {rule}: " + print(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule]}. Where it does not fit this case, add `{marker}` to {where}; larv-review's judge rules on the reason.", file=sys.stderr) return 2 diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index e5c2b6a7..6de83d01 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -10,9 +10,9 @@ RULES = { "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, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day; a bot such as Renovate raises the bumps as reviewable PRs. An image that publishes no three-part tag, such as postgres:16.4, takes an override", "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", + "todo-rank-check": "while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it", } -OVERRIDE = re.compile(r"(?:#|").strip() for rule, reason in OVERRIDE.findall(text)} - return {rule: reason for rule, reason in given.items() if rule in RULES and reason} +def overrides(text: 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(text)] + granted = {rule: reason for rule, reason in given if rule in RULES and reason} + return granted, [f"rule-override {rule}: {reason}" for rule, reason in given if rule not in granted] def segments(command: str) -> list[list[str]] | None: @@ -61,7 +63,7 @@ def segments(command: str) -> list[list[str]] | None: split: list[list[str]] = [[]] for word in words: # Unquoted, a run such as "&&\n" lexes as one word. - if set(word) <= SEPARATING: + if word and set(word) <= SEPARATING: split.append([]) else: split[-1].append(word) diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index ac0250f8..82ff29e4 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -45,6 +45,9 @@ class Commits(unittest.TestCase): self.assertEqual(len(commits("cat < notes\nhello\nEOF\ngit commit -m a", "/r")), 1) self.assertEqual(len(commits("git status &&\n\ngit commit -m a", "/r")), 1) + def test_an_empty_argument_separates_nothing(self): + self.assertEqual(rules(command_breaches("git commit --author '' -m a -m b", "/r")), ["commit-one-line"]) + def test_an_arithmetic_shift_is_no_heredoc(self): self.assertEqual(len(commits("echo $((1<<2))\ngit commit -m a\n2", "/r")), 1) @@ -106,10 +109,10 @@ class FileBreaches(unittest.TestCase): 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"}) + 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"}, ["rule-override nope: x", "rule-override action-pin: "])) def test_markdown_takes_an_html_comment(self): - self.assertEqual(overrides(""), {"no-ai-attribution": "quotes the banned line"}) + self.assertEqual(overrides("")[0], {"no-ai-attribution": "quotes the banned line"}) class Hook(unittest.TestCase): @@ -150,8 +153,12 @@ class Hook(unittest.TestCase): self.assertIn("todo.md: not ranked", ran.stderr) def test_a_malformed_override_is_named(self): - ran = hook({"cwd": self.repo, "tool_input": {"command": "git commit -m a -m b # rule-override commit-oneline: x"}, "tool_name": "Bash"}, self.repo) - self.assertIn("names no rule below, or gives no reason", ran.stderr) + 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) + + def test_a_markdown_file_is_told_the_html_comment(self): + ran = hook({"cwd": self.repo, "tool_input": {"content": TRAILER, "file_path": f"{self.repo}/a.md"}, "tool_name": "Write"}, self.repo) + self.assertIn("``", ran.stderr) def test_a_missing_field_breaks_nothing(self): for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}, {"edits": [None], "file_path": f"{self.repo}/a.md"}]: -- 2.52.0 From cf9f6b9e7a6fbf6f7ee23acad2d175ed99f95aa0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:26:07 +0200 Subject: [PATCH 07/17] Answer product-owner round 2: in the stability round 3 commit, a Markdown file is told the HTML-comment override, the todo rule says any change waits on --check, and each malformed override is named -- 2.52.0 From 7cf4f54c906b9d893b15ba66979a609a0f92ca3a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:29:02 +0200 Subject: [PATCH 08/17] Answer prose round 1: name the override reviewer apart from loop-claude's judge, list the override forms, and say each rule as it holds --- CHANGELOG.md | 2 +- CLAUDE.md | 2 +- bin/rule_hook/main.py | 19 ++++++++++++------- bin/rule_hook/rules.py | 7 +++---- skills/larv-review/SKILL.md | 2 +- todo.md | 2 +- 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a35a1366..e4d378d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- A hook blocks each Bash, Edit, MultiEdit and Write call that breaks a rule a program can check: a multi-line commit message, a Claude or Anthropic attribution, a container image short of a full patch version, an Action pinned to anything but a semver tag, an unsorted block in an ignore file, and a commit of a `todo.md` that `rank_todo.py --check` rejects. `CLAUDE.md` states those rules only where the hook cannot check them; `~/.claude/bin/rule-hook --help` states what it checks. A call overrides a rule with `# rule-override : `. larv-review lists each override in the PR body, and a judge accepts it, or rejects it and the chunk keeps the rule; one that touches a credential, a security rule or a production system, or cannot be undone, is asked of you. +- A hook blocks each Bash, Edit, MultiEdit and Write call that breaks a rule a program can check: a commit message that is not one line passed with `-m`, a Claude or Anthropic attribution, a container image short of a full patch version, an Action pinned to anything but a semver tag, an unsorted block in an ignore file, and a commit of a `todo.md` that `rank_todo.py --check` rejects. `CLAUDE.md` states those rules only where the hook cannot check them; `~/.claude/bin/rule-hook --help` states what it checks. A call overrides a rule with `# rule-override : `. larv-review lists each override in the PR body, and a reviewer accepts or rejects it; a rejected override means the chunk keeps the rule. An override that touches a credential, a security rule or a production system, or cannot be undone, is asked of you. - A project may opt out of larv-review's architect, product-owner pass or comprehension check in every chunk, through a `docs/decisions.md` entry titled `review opt-out: …` that names the goal that skipping them serves. A project without such an entry is reviewed as before. Opting out of the comprehension check also skips the scoring run due at a release's end, so the floor blocks nothing; the opt-out ends with a chunk that ships a plan item naming the floor, which removes the comprehension check from the entry. The principles audit always runs. - A README goal states the project's aim and intent, and no longer names a step of the work, such as "kill weak candidates early". Such steps go in a method section further down the README and name the goal they serve. - The stability reviewer keeps its scratch work in a directory it creates for the run, deletes that directory afterwards, and deletes nothing else. diff --git a/CLAUDE.md b/CLAUDE.md index 91fe7d6a..87e5438d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,7 +118,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, - Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create. - Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). - Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows and line-based file lists. Exception: `id` goes first. -- Pin a container image to its full patch version where `~/.claude/bin/rule-hook` does not check it, such as in a test fixture, a Kubernetes manifest or a `docker run` line. +- Pin a container image to its full patch version where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest or a `docker run` line. ## Naming files & folders - Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 5dc37fd7..8bd54466 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -8,8 +8,8 @@ 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 each block of a .*ignore file that an edit leaves unsorted is sorted; a blank - line or comment ends a block + 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 @@ -17,11 +17,16 @@ subagent. The rules: todo-rank-check a git commit while todo.md has changes, staged or not, needs rank_todo.py --check to pass on it -The file rules see what an Edit, MultiEdit or Write call writes, not a file a Bash command writes. +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 call overrides a rule with `# rule-override : `: anywhere in a Bash command, such as -a trailing comment; in a file, as a comment line in the text the edit writes, or in Markdown as -``. Each override that let a call through is appended to +A call overrides a rule with `# rule-override : `: + +- 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 `` + +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. @@ -81,7 +86,7 @@ def main(argv: list[str], stdin: str) -> int: for rule in sorted({breach.rule for breach in blocking}): details = "; ".join(breach.detail for breach in blocking if breach.rule == rule) marker = f"" if markdown else f"# rule-override {rule}: " - print(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule]}. Where it does not fit this case, add `{marker}` to {where}; larv-review's judge rules on the reason.", file=sys.stderr) + 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 diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 6de83d01..2f1a872b 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -3,12 +3,11 @@ 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", + "action-pin": "a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never to a branch, and to a commit SHA 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, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day; a bot such as Renovate raises the bumps as reviewable PRs. An image that publishes no three-part tag, such as postgres:16.4, takes an override", + "image-pin": "a container image is pinned to its full patch version, such as node:24.18.1-bookworm-slim, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day. An image that publishes no three-part tag, such as postgres:16.4, takes an override", "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": "while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it", } @@ -51,7 +50,7 @@ def overrides(text: str) -> tuple[dict[str, str], list[str]]: def segments(command: str) -> list[list[str]] | None: - """The command's simple commands as words, each heredoc's body cut to a line break, or None when it does not parse.""" + """The command's simple commands as words, with each heredoc's body dropped, or None when it does not parse.""" lexer = shlex.shlex(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command), posix=True, punctuation_chars="();<>|&\n") lexer.whitespace = " \t\r" lexer.whitespace_split = True diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 30de77be..50fcad94 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -157,7 +157,7 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 5. Goal alignment, then merge 1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; ask the human, stating the conflict. -2. **Overrides.** Run `~/.claude/bin/rule-hook overrides` in the chunk's worktree. When it prints a line no judge has ruled on in this chunk, launch one general-purpose subagent as the judge, with no shell and no edits, given those lines, the rules from `~/.claude/bin/rule-hook --help`, the README's goals and the branch diff. It rules nothing on an override whose breach the branch no longer holds. It accepts or rejects each other reason by the goals, and calls an override outrageous when it touches a credential, a security rule or a production system, or cannot be undone. An accepted override stands. A rejected one is a 🔴 of this chunk: keep the rule, such as by rewording the commit or pinning the image, then re-enter per §3 → "Re-entry"; where the rule cannot be kept, ask the user. An outrageous one is asked of the user. List each override with its ruling in the PR body. +2. **Overrides.** Run `~/.claude/bin/rule-hook overrides` in the chunk's worktree. When it prints a line not yet ruled on in this chunk, launch one general-purpose subagent, the override reviewer, with no shell and no edits, given those lines, the rules from `~/.claude/bin/rule-hook --help`, the README's goals and the branch diff. It skips an override whose breach the branch no longer holds. It accepts or rejects each other reason by the goals, and calls an override outrageous when it touches a credential, a security rule or a production system, or cannot be undone. An accepted override stands. A rejected one is a 🔴 of this chunk: keep the rule, such as by rewording the commit or pinning the image, then re-enter per §3 → "Re-entry"; where the rule cannot be kept, ask the user. An outrageous one is asked of the user. List each override with its ruling in the PR body. 3. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. 4. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". 5. Stop. The next chunk gets a fresh session. diff --git a/todo.md b/todo.md index 69c86628..17e4d9a7 100644 --- a/todo.md +++ b/todo.md @@ -169,7 +169,7 @@ Raised by the product-owner review of PR #211. The resumed worker gets the judge The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word. -A rule check CI runs, such as one of `bin/rule-hook`'s, accepts `# rule-override : ` in the PR body. +When CI runs a rule check, such as one of `bin/rule-hook`'s, let `` in the PR body override it. ### 80. State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes. -- 2.52.0 From f3bfff1af4aeeda8579c6af61742f22d6e877d6c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:45:36 +0200 Subject: [PATCH 09/17] 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 --- .gitignore | 1 + AGENTS.md | 1 + CHANGELOG.md | 2 +- CLAUDE.md | 4 +- README.md | 2 +- agents/override-reviewer.md | 16 ++ bin/larv_review/rounds.py | 2 +- bin/reading_cost/measure.py | 3 +- bin/reading_cost/shell_reads.py | 51 +----- bin/repo_checks/test_types.py | 2 +- bin/rule_hook/main.py | 184 +++++++++++---------- bin/rule_hook/rules.py | 280 ++++++++++++++++++++------------ bin/rule_hook/test_rule_hook.py | 118 +++++++++----- bin/shell_command.py | 89 ++++++++++ docs/comprehension-history.md | 22 +++ docs/decisions.md | 4 + skills/larv-review/SKILL.md | 12 +- 17 files changed, 504 insertions(+), 289 deletions(-) create mode 100644 agents/override-reviewer.md create mode 100644 bin/shell_command.py diff --git a/.gitignore b/.gitignore index 1cb68cda..b8232059 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,7 @@ !bin/rule-hook !bin/rule_hook/ !bin/rule_hook/*.py +!bin/shell_command.py !bin/statusline.py !bin/test_*.py !bin/todo_table.py diff --git a/AGENTS.md b/AGENTS.md index 26a67bf9..60d1c301 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,7 @@ Decisions live in `docs/decisions.md`: - todo.md: one table of items scored by the formula and goal weights it states, held to its bar, ranked by `bin/rank_todo.py` - reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR - reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item +- 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 ## Working rules diff --git a/CHANGELOG.md b/CHANGELOG.md index e4d378d4..4e665343 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- A hook blocks each Bash, Edit, MultiEdit and Write call that breaks a rule a program can check: a commit message that is not one line passed with `-m`, a Claude or Anthropic attribution, a container image short of a full patch version, an Action pinned to anything but a semver tag, an unsorted block in an ignore file, and a commit of a `todo.md` that `rank_todo.py --check` rejects. `CLAUDE.md` states those rules only where the hook cannot check them; `~/.claude/bin/rule-hook --help` states what it checks. A call overrides a rule with `# rule-override : `. larv-review lists each override in the PR body, and a reviewer accepts or rejects it; a rejected override means the chunk keeps the rule. An override that touches a credential, a security rule or a production system, or cannot be undone, is asked of you. +- A hook blocks each Bash, Edit, MultiEdit and Write call that breaks a rule a program can check: a commit message that is not one line passed with `-m`, a Claude or Anthropic attribution, a container image short of a full patch version, an Action pinned to anything but a semver tag, an unsorted block in an ignore file, and a commit of a `todo.md` that `rank_todo.py --check` rejects. `CLAUDE.md` states those rules only where the hook cannot check them; `~/.claude/bin/rule-hook --help` states what it checks. A call overrides a rule with `# rule-override : `. larv-review's new overrides pass, run before stability, accepts or rejects each override the chunk logged, and the PR body lists each with its ruling; a rejected override means the chunk keeps the rule. An override that touches a credential, a security rule or a production system, or cannot be undone, is asked of you. - A project may opt out of larv-review's architect, product-owner pass or comprehension check in every chunk, through a `docs/decisions.md` entry titled `review opt-out: …` that names the goal that skipping them serves. A project without such an entry is reviewed as before. Opting out of the comprehension check also skips the scoring run due at a release's end, so the floor blocks nothing; the opt-out ends with a chunk that ships a plan item naming the floor, which removes the comprehension check from the entry. The principles audit always runs. - A README goal states the project's aim and intent, and no longer names a step of the work, such as "kill weak candidates early". Such steps go in a method section further down the README and name the goal they serve. - The stability reviewer keeps its scratch work in a directory it creates for the run, deletes that directory afterwards, and deletes nothing else. diff --git a/CLAUDE.md b/CLAUDE.md index 87e5438d..b2955490 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,7 +118,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, - Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create. - Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). - Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows and line-based file lists. Exception: `id` goes first. -- Pin a container image to its full patch version where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest or a `docker run` line. +- Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest, a `docker run` line or a file a Bash command writes, pin a container image to its full patch version and a GitHub Action to a semver tag. ## Naming files & folders - Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. @@ -130,7 +130,7 @@ The rules every project follows, compose-not-entangle first: `~/.claude/principl ## Git, commits, and PRs - Mark no commit, PR, issue comment or file as the work of Claude, Anthropic or an agent. -- Commit message and PR title: prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context. +- Commit message and PR title: **one line**, prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context. - PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title). - When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it. - Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`. diff --git a/README.md b/README.md index b1c33ee0..5acaa0b1 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'` -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them, and `rule_hook` imports `rank_todo.py`'s check. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself. ## Tracking a new file diff --git a/agents/override-reviewer.md b/agents/override-reviewer.md new file mode 100644 index 00000000..1c4bd339 --- /dev/null +++ b/agents/override-reviewer.md @@ -0,0 +1,16 @@ +--- +name: override-reviewer +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". + +For each override: + +- **Skip** it when the branch no longer holds the breach, such as an image since pinned or a commit since reworded. Say so in one line. +- **Accept** it when the reason shows the rule does not fit this case, by the rule's own exceptions or by the goals. Name what in the reason or the goals settles it. +- **Reject** it as a 🔴 when the reason does not. Name how the chunk keeps the rule, such as rewording the commit or pinning the image, or say that it cannot. +- **Ask** it as a ❓ for the human when it is outrageous: it touches a credential, a security rule or a production system, or it cannot be undone. + +Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Quote an override by its rule and reason only; a command's text can hold a credential. diff --git a/bin/larv_review/rounds.py b/bin/larv_review/rounds.py index 41a58c9f..732e566e 100644 --- a/bin/larv_review/rounds.py +++ b/bin/larv_review/rounds.py @@ -1,7 +1,7 @@ import re CAP = 3 -PASSES = ("architecture", "full scan", "security", "stability", "product-owner", "prose") +PASSES = ("architecture", "full scan", "security", "overrides", "stability", "product-owner", "prose") ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE) diff --git a/bin/reading_cost/measure.py b/bin/reading_cost/measure.py index 9d63aedc..958528ab 100644 --- a/bin/reading_cost/measure.py +++ b/bin/reading_cost/measure.py @@ -3,7 +3,8 @@ import dataclasses import re from claude_code.entries import assistant_parts, parse_entry, tool_call -from reading_cost.shell_reads import Reads, resolved, shell_reads +from reading_cost.shell_reads import Reads, shell_reads +from shell_command import resolved COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b") diff --git a/bin/reading_cost/shell_reads.py b/bin/reading_cost/shell_reads.py index 268eb6f8..69593060 100644 --- a/bin/reading_cost/shell_reads.py +++ b/bin/reading_cost/shell_reads.py @@ -2,8 +2,8 @@ import dataclasses import posixpath import re -import shlex -import typing + +from shell_command import resolved, simple_commands NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$") # Their first operand is a pattern or a program, unless -e or -f gives it. @@ -21,49 +21,12 @@ class Reads: def shell_reads(command: str, cwd: str, home: str) -> Reads: read: list[str] = [] added: list[str] = [] - base = cwd - for tokens in shell_lines(command): - for words in segments(tokens): - if words[0] == "cd" and len(words) == 2: - base = resolved(base, words[1], home) - read += [resolved(base, word, home) for word in operands(words)] - added += [resolved(base, path, home) for path in worktree_added(words)] + for simple in simple_commands(command, cwd, home): + read += [resolved(simple.directory, word, home) for word in operands(simple.words)] + added += [resolved(simple.directory, path, home) for path in worktree_added(simple.words)] return Reads(read, added) -def shell_lines(command: str) -> typing.Iterator[list[str]]: - """Each line's tokens, skipping a heredoc's body, which feeds a program.""" - ends = None - for line in command.splitlines(): - if ends is not None: - ends = None if line.strip() == ends else ends - continue - try: - lexer = shlex.shlex(line, posix=True, punctuation_chars=True) - lexer.whitespace_split = True - tokens = list(lexer) - except ValueError: - continue - # The lexer splits <<-EOF into << and -EOF. - ends = next((tokens[index + 1].removeprefix("-") for index, token in enumerate(tokens[:-1]) if token == "<<"), None) - yield tokens - - -def segments(tokens: list[str]) -> list[list[str]]: - found: list[list[str]] = [[]] - target = False - for token in tokens: - if target: - target = False - elif all(char in "();<>|&" for char in token): - # A redirect's target is not an operand, so it does not count as a read. - target = "<" in token or ">" in token - found.append([]) - else: - found[-1].append(token) - return [words for words in found if words] - - def operands(words: list[str]) -> list[str]: program = posixpath.basename(words[0]) if program not in READERS or (program == "sed" and any(word.startswith("-i") for word in words)): @@ -85,7 +48,3 @@ def worktree_added(words: list[str]) -> list[str]: elif not word.startswith("-"): return [word] return [] - - -def resolved(base: str, path: str, home: str) -> str: - return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path)) diff --git a/bin/repo_checks/test_types.py b/bin/repo_checks/test_types.py index dbe39fe3..fcd2952c 100644 --- a/bin/repo_checks/test_types.py +++ b/bin/repo_checks/test_types.py @@ -15,5 +15,5 @@ class Types(unittest.TestCase): self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`") if shutil.which("uv") is None: self.fail("uv on PATH fetches mypy; see README.md's Test line") - ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-p", "rule_hook", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True) + ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-p", "rule_hook", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 8bd54466..413441d2 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -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 : `: @@ -26,14 +16,17 @@ A call overrides a rule with `# rule-override : `: - in a file, as a comment line in the text the edit writes - in Markdown, as `` -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"" if markdown else f"# rule-override {rule}: " - 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: diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 2f1a872b..337fcdd7 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -1,15 +1,45 @@ import dataclasses -import os +import posixpath import re -import shlex +import typing -RULES = { - "action-pin": "a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never to a branch, and to a commit SHA 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, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day. An image that publishes no three-part tag, such as postgres:16.4, takes an override", - "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": "while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it", +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"] + + +@dataclasses.dataclass(frozen=True) +class Rule: + holds: str + checked: str + + +RULES: dict[RuleName, Rule] = { + "action-pin": Rule( + "a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never to a branch, and to a commit SHA only in a pipeline that tests our own specific builds", + "`uses:` in a .github or .gitea workflow, or in action.yml", + ), + "commit-one-line": Rule( + "a commit message is one line, prefixed with the ticket ID when the work has one", + "git commit takes its message as one -m with no line break; -F, a second -m and a heredoc are blocked", + ), + "ignorefile-sorted": Rule( + "each block of an ignore file is sorted in code-point order, as LC_ALL=C sort does, 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", + "a .*ignore file; a block already unsorted before the edit is left alone", + ), + "image-pin": Rule( + "a container image is pinned to its full patch version, such as node:24.18.1-bookworm-slim, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day; an image that publishes no three-part tag, such as postgres:16.4, takes an override", + "a Dockerfile's FROM and COPY --from, and `image:` and `container:` in a compose file or workflow", + ), + "no-ai-attribution": Rule( + "no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line", + "a git, gh or tea command, and any file written", + ), + "todo-rank-check": Rule( + "while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it", + "a git commit in a checkout whose todo.md has changes", + ), } OVERRIDE = re.compile(r"(?:#|").strip()) for rule, reason in OVERRIDE.findall(text)] + given = [(rule, reason.strip().removesuffix("-->").strip()) for rule, reason in OVERRIDE.findall(written)] granted = {rule: reason for rule, reason in given if rule in RULES and reason} return granted, [f"rule-override {rule}: {reason}" for rule, reason in given if rule not in granted] -def segments(command: str) -> list[list[str]] | None: - """The command's simple commands as words, with each heredoc's body dropped, or None when it does not parse.""" - lexer = shlex.shlex(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command), posix=True, punctuation_chars="();<>|&\n") - lexer.whitespace = " \t\r" - lexer.whitespace_split = True - # shlex also ends a word at a # inside it, as in fix#2, which bash does not; after lexing, a quoted # cannot be told apart. - try: - words = list(lexer) - except ValueError: - return None - split: list[list[str]] = [[]] - for word in words: - # Unquoted, a run such as "&&\n" lexes as one word. - if word and set(word) <= SEPARATING: - split.append([]) - else: - split[-1].append(word) - return [segment for segment in split if segment] +def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Verdict: + granted, malformed = overrides(written) + blocking = [breach for breach in breaches if breach.rule not in granted] + messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else [] + where = "the command" if 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) + marker = f"" if markdown else f"# rule-override {rule}: " + messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.") + return Verdict(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted]) -def commits(command: str, cwd: str) -> list[Commit]: - directory = cwd +def commits(simples: list[Simple], home: str) -> list[Commit]: 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) + for simple in simples: + invoked = git_subcommand(simple.words, simple.directory, home) + if invoked and invoked[0] == "commit": + found.append(Commit(invoked[2], *commit_message(invoked[1]))) 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"]: +def git_subcommand(words: list[str], directory: str, home: str) -> tuple[str, list[str], str] | None: + """A git command's subcommand, its arguments and the directory it runs in, after git's own options such as -C.""" + if words[:1] != ["git"]: return None - messages: list[str] = [] + args = iter(words[1:]) + for word in args: + if word in GIT_VALUED: + value = next(args, "") + directory = resolved(directory, value, home) if word == "-C" else directory + elif not word.startswith("-"): + return word, list(args), directory + return None + + +def commit_message(args: list[str]) -> tuple[list[str], bool]: + """git commit's messages, and whether it reads one from a file.""" + messages = [] from_file = False - rest = args[at + 1:] - at = 0 - while at < len(rest): - word = rest[at] + words = iter(args) + for word in words: 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 + name, equals, value = word.partition("=") + if name in ("--message", "--file"): + given = value if equals else next(words, "") + elif word.startswith("-") and not word.startswith("--") and (flags := [flag for flag in word[1:] if flag in "mF"]): + # A cluster such as -am: the valued flag takes the rest of the word, or else the next word. + name = "--message" if flags[0] == "m" else "--file" + given = word[word.index(flags[0]) + 1:] or next(words, "") + else: continue - if word.startswith("--message="): - messages.append(word.removeprefix("--message=")) - elif word.startswith("--file="): - from_file = 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 - at += 1 - return Commit(directory, messages, from_file) + messages += [given] if name == "--message" else [] + from_file = from_file or name == "--file" + return messages, from_file -def command_breaches(command: str, cwd: str) -> list[Breach]: +def command_breaches(command: str, simples: list[Simple], home: 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): + 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)) + for commit in found: if commit.from_file: - breaches.append(Breach("commit-one-line", "pass the message as one -m '', not from a file")) + breaches.append(Breach("commit-one-line", "pass the message as one -m '', not from a file", commit.directory)) 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 '', with no heredoc, second -m or newline")) + breaches.append(Breach("commit-one-line", "pass the message as one -m '', with no heredoc, second -m or newline", commit.directory)) 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.""" - name = os.path.basename(path) - breaches = [] - if ATTRIBUTION.search(added): - breaches.append(Breach("no-ai-attribution", f"{path} would carry an attribution")) + breaches = [Breach("no-ai-attribution", f"{path} would carry an attribution", posixpath.dirname(path))] if ATTRIBUTION.search(added) else [] + return breaches + image_breaches(path, before, added, after) + action_breaches(path, added) + ignore_breaches(path, before, after) + + +def image_breaches(path: str, before: str, added: str, after: str) -> list[Breach]: + name = posixpath.basename(path) 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)] + COPIED.findall(added) - breaches += [Breach("image-pin", f"{path}: {image}") for image in images if image.lower() not in stages | {"scratch"} and not image.isdigit() and not pinned(image)] - workflow = any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or name in ("action.yml", "action.yaml") - if "compose" in name and name.endswith((".yml", ".yaml")) or workflow: - breaches += [Breach("image-pin", f"{path}: {image}") for image in IMAGE.findall(added) if not pinned(image)] - if workflow: - 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"): - already = [block for block in blocks(before) if block != sorted(block)] - breaches += [Breach("ignorefile-sorted", f"{path}: sort the block {block[0]!r} through {block[-1]!r} in code-point order, as LC_ALL=C sort does: {', '.join(sorted(block))}") for block in blocks(after) if block != sorted(block) and block not in already] - return breaches + stages = {stage.lower() for _, stage in FROM.findall(before + "\n" + after) if stage} | {"scratch"} + images = [image for image, _ in FROM.findall(added) if image.lower() not in stages] + [image for image in COPIED.findall(added) if image.lower() not in stages and not image.isdigit()] + elif "compose" in name and name.endswith((".yml", ".yaml")) or workflow(path): + images = IMAGE.findall(added) + else: + images = [] + return [Breach("image-pin", f"{path}: {image}", posixpath.dirname(path)) for image in images if not pinned(image)] + + +def action_breaches(path: str, added: str) -> list[Breach]: + actions = USES.findall(added) if workflow(path) else [] + return [Breach("action-pin", f"{path}: uses: {action}", posixpath.dirname(path)) for action in actions if not tagged(action)] + + +def ignore_breaches(path: str, before: str, after: str) -> list[Breach]: + name = posixpath.basename(path) + if not (name.startswith(".") and name.endswith("ignore")): + return [] + already = [block for block in blocks(before) if block != sorted(block)] + return [Breach("ignorefile-sorted", f"{path}: sort the block {block[0]!r} through {block[-1]!r} as {', '.join(sorted(block))}", posixpath.dirname(path)) for block in blocks(after) if block != sorted(block) and block not in already] + + +def workflow(path: str) -> bool: + return any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or posixpath.basename(path) in ("action.yml", "action.yaml") def pinned(image: str) -> bool: @@ -171,12 +239,16 @@ def tagged(action: str) -> bool: return "@" in action and SEMVER.fullmatch(action.rsplit("@", 1)[1]) is not None -def blocks(text: str) -> list[list[str]]: +def blocks(written: 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(): + for line in written.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] + + +def rules_help() -> str: + return "\n".join(f" {name}\n The rule: {rule.holds}.\n Checked in: {rule.checked}." for name, rule in RULES.items()) diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 82ff29e4..b89745d0 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -7,9 +7,10 @@ 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 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 test_env import isolated_env +from shell_command import simple_commands HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook" # Built from parts, so this file carries no attribution of its own. @@ -20,6 +21,14 @@ def rules(breaches: list[Breach]) -> list[str]: return [breach.rule for breach in breaches] +def committed(command: str, cwd: str = "/r") -> list[Commit]: + return commits(simple_commands(command, cwd, "/h"), "/h") + + +def checked(command: str) -> list[str]: + return rules(command_breaches(command, simple_commands(command, "/r", "/h"), "/h")) + + 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) @@ -30,56 +39,54 @@ def git(cwd: str, *args: str) -> str: 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)]) + self.assertEqual(committed("cd a && git -C ~/b commit -am 'x'"), [Commit("/h/b", ["x"], False)]) + self.assertEqual(committed("cd a && git -c x=y -C b commit -m x")[0].directory, "/r/a/b") 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"]) + self.assertEqual(commit_message(["--message=a", "-m", "b=c", "--message", "c", "-mz", "-am", "d"]), (["a", "b=c", "c", "z", "d"], False)) def test_a_file_message_is_seen(self): - self.assertTrue(commits("git commit -F - < notes\nhello\nEOF\ngit commit -m a", "/r")), 1) - self.assertEqual(len(commits("git status &&\n\ngit commit -m a", "/r")), 1) - - def test_an_empty_argument_separates_nothing(self): - self.assertEqual(rules(command_breaches("git commit --author '' -m a -m b", "/r")), ["commit-one-line"]) + self.assertEqual(len(committed("cat < notes\nhello\nEOF\ngit commit -m a")), 1) + self.assertEqual(len(committed("git status &&\n\ngit commit -m a")), 1) def test_an_arithmetic_shift_is_no_heredoc(self): - self.assertEqual(len(commits("echo $((1<<2))\ngit commit -m a\n2", "/r")), 1) + self.assertEqual(len(committed("echo $((1<<2))\ngit commit -m a\n2")), 1) - 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)]) + def test_a_line_that_does_not_parse_hides_only_itself(self): + self.assertEqual(len(committed("echo 'open\ngit commit -m a")), 1) class CommandBreaches(unittest.TestCase): def test_one_line_passes(self): - self.assertEqual(command_breaches("git add . && git commit -m 'ABC-1 - Fix it'", "/r"), []) + self.assertEqual(checked("git add . && git commit -m 'ABC-1 - Fix #2'"), []) 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"]: + for command in ["git commit -m \"$(cat <<'EOF'\nIt's one line\nEOF\n)\"", "git commit -m a -m b", "git commit -F - <<'EOF'\nTitle\n\nIt's the body\nEOF\necho done", "git commit --author '' -m a -m b"]: with self.subTest(command): - self.assertEqual(rules(command_breaches(command, "/r")), ["commit-one-line"]) + self.assertEqual(checked(command), ["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"), []) + self.assertEqual(checked(f"tea pr create --description '{TRAILER}'"), ["no-ai-attribution"]) + self.assertEqual(checked(f"grep -rn '{TRAILER}' ."), []) - def test_a_heredoc_body_is_no_shell_text(self): - self.assertEqual(rules(command_breaches("git commit -F - <<'EOF'\nTitle\n\nIt's the body\nEOF\necho done", "/r")), ["commit-one-line"]) - self.assertEqual(rules(command_breaches("git commit -m \"$(cat <<'EOF'\nIt's one line\nEOF\n)\"", "/r")), ["commit-one-line"]) - - def test_a_command_that_does_not_parse_breaks_nothing(self): - self.assertEqual(command_breaches("git commit -m 'open", "/r"), []) + def test_a_commit_breach_names_the_commit_s_checkout(self): + self.assertEqual(command_breaches("cd w && git commit -m a -m b", simple_commands("cd w && git commit -m a -m b", "/r", "/h"), "/h")[0].directory, "/r/w") class FileBreaches(unittest.TestCase): - def test_an_image_needs_a_patch_version_or_a_digest(self): + def test_an_image_needs_a_patch_version_a_date_or_a_digest(self): added = "FROM node:24 AS build\nFROM node:24.18.1-bookworm-slim\nFROM alpine@sha256:ab\nFROM debian:bookworm-20240926-slim\nFROM build\nFROM scratch\nFROM ${BASE}\nFROM python\nCOPY --from=build /a /a\nCOPY --from=0 /b /b\nCOPY --chown=1 --from=alpine:3 /c /c\n" - self.assertEqual([breach.detail for breach in file_breaches("Dockerfile", "", added, added)], ["Dockerfile: node:24", "Dockerfile: python", "Dockerfile: alpine:3"]) + self.assertEqual([breach.detail for breach in file_breaches("/r/Dockerfile", "", added, added)], ["/r/Dockerfile: node:24", "/r/Dockerfile: python", "/r/Dockerfile: alpine:3"]) 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"), []) @@ -111,15 +118,33 @@ 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"}, ["rule-override nope: x", "rule-override action-pin: "])) + def test_two_markers_on_a_line_are_read_apart(self): + self.assertEqual(overrides("git x # rule-override image-pin: a # rule-override nope: b")[1], ["rule-override nope: b"]) + def test_markdown_takes_an_html_comment(self): self.assertEqual(overrides("")[0], {"no-ai-attribution": "quotes the banned line"}) + def test_a_blocked_call_overrides_nothing_yet(self): + breaches = [Breach("image-pin", "x", "/r"), Breach("action-pin", "y", "/r")] + judged = verdict(breaches, "# rule-override image-pin: a", False, False) + self.assertTrue(judged.blocked) + passed = verdict(breaches[:1], "# rule-override image-pin: a", False, False) + self.assertEqual((passed.blocked, passed.overridden), (False, [(breaches[0], "a")])) + + def test_a_markdown_file_is_told_the_html_comment(self): + self.assertIn("``", verdict([Breach("no-ai-attribution", "x", "/r")], "", True, False).messages[0]) + 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") + git(self.repo, "init", "-q", "-b", "main") + git(self.repo, "commit", "-q", "--allow-empty", "-m", "base") + git(self.repo, "checkout", "-q", "-b", "chunk") + + def listed(self) -> str: + return subprocess.run([str(HOOK), "overrides"], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout 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) @@ -127,12 +152,26 @@ class Hook(unittest.TestCase): self.assertIn("Blocked by rule image-pin: ", ran.stderr) self.assertIn("`# rule-override image-pin: `", ran.stderr) - def test_an_override_passes_and_is_listed_for_its_branch(self): + def test_an_override_passes_and_is_listed_for_the_chunk(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\t\S+/sub/Dockerfile\n$") + 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") + + def test_a_blocked_call_logs_no_override(self): + command = f"git commit -m a -m '{TRAILER}' # rule-override no-ai-attribution: quotes it" + self.assertEqual(hook({"cwd": self.repo, "tool_input": {"command": command}, "tool_name": "Bash"}, self.repo).returncode, 2) + self.assertEqual(self.listed(), "") + + def test_a_commit_override_is_logged_in_the_commit_s_checkout(self): + outside = tempfile.mkdtemp() + self.addCleanup(subprocess.run, ["rm", "-rf", outside]) + ran = hook({"cwd": outside, "tool_input": {"command": f"git -C {self.repo} commit -m a -m b # rule-override commit-one-line: a body is needed"}, "tool_name": "Bash"}, outside) + self.assertEqual(ran.returncode, 0) + self.assertIn("\tcommit-one-line\ta body is needed\t", self.listed()) def test_an_edit_is_judged_on_the_file_it_leaves(self): pathlib.Path(self.repo, ".gitignore").write_text("a\nc\n") @@ -141,8 +180,8 @@ class Hook(unittest.TestCase): def test_a_commit_while_an_unranked_todo_has_changes_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) + for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]: + pathlib.Path(self.repo, name).write_text(content) git(self.repo, "add", "README.md", "docs", "todo.md") git(self.repo, "commit", "-qm", "x", "--no-verify") call = {"cwd": self.repo, "tool_input": {"command": "git add -A && git commit -m x"}, "tool_name": "Bash"} @@ -156,17 +195,18 @@ class Hook(unittest.TestCase): 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) - def test_a_markdown_file_is_told_the_html_comment(self): - ran = hook({"cwd": self.repo, "tool_input": {"content": TRAILER, "file_path": f"{self.repo}/a.md"}, "tool_name": "Write"}, self.repo) - self.assertIn("``", ran.stderr) - def test_a_missing_field_breaks_nothing(self): for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}, {"edits": [None], "file_path": f"{self.repo}/a.md"}]: with self.subTest(given): tool = "Bash" if "command" in given else "Write" if "content" in given else "MultiEdit" self.assertEqual(hook({"cwd": self.repo, "tool_input": given, "tool_name": tool}, self.repo).returncode, 0) - self.assertEqual(hook({"cwd": self.repo, "tool_input": None, "tool_name": "Bash"}, self.repo).returncode, 1) 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) + for given in ["{", json.dumps({"cwd": ".", "tool_input": None, "tool_name": "Bash"})]: + with self.subTest(given): + self.assertEqual(subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input=given, text=True).returncode, 1) + + def test_help_lists_every_rule(self): + helped = subprocess.run([str(HOOK), "--help"], capture_output=True, check=True, env=isolated_env(), text=True).stdout + for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]: + self.assertIn(f" {rule}\n The rule: ", helped) diff --git a/bin/shell_command.py b/bin/shell_command.py new file mode 100644 index 00000000..6c495e86 --- /dev/null +++ b/bin/shell_command.py @@ -0,0 +1,89 @@ +"""A shell command's simple commands, each as its words and the directory it runs in.""" +import dataclasses +import posixpath +import re +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();&|<>") + + +@dataclasses.dataclass(frozen=True) +class Simple: + words: list[str] + directory: str + + +def simple_commands(command: str, cwd: str, home: str) -> list[Simple]: + """Each simple command, without leading variable assignments or redirect targets, in the directory `cd` left it in.""" + directory = cwd + found = [] + for words in segments(command): + if words[0] == "cd" and len(words) == 2: + directory = resolved(directory, words[1], home) + found.append(Simple(words, directory)) + return found + + +def segments(command: str) -> list[list[str]]: + text = uncommented(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command)) + tokens = lexed(text) + if tokens is None: + # One unbalanced quote should not hide the other lines. + tokens = [token for line in text.splitlines() for token in (lexed(line) or []) + ["\n"]] + found: list[list[str]] = [[]] + target = False + for token in tokens: + if target: + target = False + elif set(token) <= OPERATOR and token: + # A redirect's target is not an operand. + target = "<" in token or ">" in token + found.append([]) + elif found[-1] or not ASSIGNMENT.match(token): + found[-1].append(token) + return [words for words in found if words] + + +def lexed(text: str) -> list[str] | None: + lexer = shlex.shlex(text, posix=True, punctuation_chars="();<>|&\n") + lexer.commenters = "" + lexer.whitespace = " \t\r" + lexer.whitespace_split = True + try: + return list(lexer) + except ValueError: + return 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) + + +def resolved(base: str, path: str, home: str) -> str: + return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path)) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 3c306326..2344f422 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -1128,3 +1128,25 @@ Inherited architect, would restructure first: - `bin/larv_review/scoring.py:8` `fall_ruling`: a ruling rule in the scoring module - `bin/claude_code/trust.py:10` `trust`: effects in a package documented as shapes - `bin/larv_review/git.py:8` `git`: git run five ways + +## 2026-10-12T21:36:23Z, PR #241 at 7cf4f54, against 4cc9953 + +Ruling: same + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | same | same | worse | same | same | +| Inherited architect | same | worse | same | same | same | + +Mid A, decided by: + +- Shape: `bin/rule_hook/rules.py:140` `file_breaches`: four rules in one function, picked by file-name tests, each a comprehension of three or four conditions +- Shape: `bin/rule_hook/rules.py:86` `git_commit`: a hand-written git argument parser with two index-juggling loops and a nested loop that moves `at` +- Shape: `bin/rule_hook/main.py:1` module docstring: it and `RULES` each describe the six rules in their own words, as do CLAUDE.md, CHANGELOG.md and README.md +- Shape: `bin/rule_hook/main.py:93` `checked_call`: returns a 3-tuple or None, and its name hides that it replays a MultiEdit's edits + +Inherited architect, decided by: + +- Locality: `skills/larv-review/SKILL.md:58` "Opt-out": an opted-out chunk skips a scoring run `larv-review needs-scoring-run` still calls due, and "End" adds a third kind of run +- Locality: `bin/rule_hook/main.py:76` `main`: logs each granted override before it knows whether another rule still blocks the call, into an unversioned log keyed by branch name and never pruned +- Locality: `bin/rule_hook/main.py:115` `todo_breaches`: the hook imports `rank_todo.check_failures`, so editing rank_todo's messages changes what blocks a commit, while README calls rank_todo.py a tool of one file; the rule's logic sits in main.py, apart from the other rules in rules.py diff --git a/docs/decisions.md b/docs/decisions.md index 5a844db5..f2da359f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -134,3 +134,7 @@ lilleman decided to ship each of these under the floor on the day listed. Each l ## reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item 2026-10-08, lilleman. Serves goal 1.1: comprehension never falls, so any rise counts. Per-chunk figures are noisy: a flat trend rises about every other chunk. So a rise refreshes the item and never refiles it, and a chunk that sees no rise leaves the item as it is. The chunk that ships the item resets the trend, so later figures do not refile it for work that chunk already did (goal 1.4). A median, because one chunk that ran a panel of readers before its first commit measured 2.99M tokens against a typical 80k–370k, and a mean let it decide the trend alone. No published standard sets this threshold. Valid while figures arrive once per chunk. + +## 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. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 50fcad94..33c580c5 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -35,6 +35,7 @@ A pass is one kind of review, a row of the table, named by its first column. Its | Architecture | systems-architect, then principles-auditor and the comprehension check | is due a scoring run ("Architecture" → "Scoring run"); or carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats, CLI flags and exit codes); a schema change beyond an additive column; a fix, only where it carries an architectural decision | | Full scan | the `claude-security` plugin at high effort: `/claude-security scan this branch's changes at high` | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface | | Security | `/security-review` | changes code or config, unless the full scan runs on the same change; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto, and the full scan does not rerun on it | +| Overrides | override-reviewer | `~/.claude/bin/rule-hook overrides`, run in the chunk's worktree, prints a line no round of this pass has ruled on; a fix, only where the hook logged an override for it | | Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour: what the code or its tests do | | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | prose-reviewer | every chunk, one round | @@ -137,6 +138,10 @@ Only the user may answer `claude-security`'s cost prompt. `/security-review` or **Do not over-read a clean result.** `/security-review` is single-repo and static: it does not trace authorization across services, does not run the application, and deliberately excludes dependency CVEs in third-party libraries — Renovate/Dependabot owns those, per `~/.claude/CLAUDE.md` → "Working with the codebase". Never point an automated reviewer or scan at an untrusted fork's PR content; a PR body is untrusted input to it (CVE-2025-59536, CVE-2026-21852). +### Overrides + +Launch override-reviewer with each line `rule-hook overrides` prints that no earlier round ruled on, and the branch diff. A rejected override is a 🔴: keep the rule, or ask the user where the reviewer says it cannot be kept. An outrageous override is asked of the user. List each override in the PR body by its rule, its reason and the ruling, never by the command it let through. + ### Stability and product-owner Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. @@ -157,10 +162,9 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 5. Goal alignment, then merge 1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; ask the human, stating the conflict. -2. **Overrides.** Run `~/.claude/bin/rule-hook overrides` in the chunk's worktree. When it prints a line not yet ruled on in this chunk, launch one general-purpose subagent, the override reviewer, with no shell and no edits, given those lines, the rules from `~/.claude/bin/rule-hook --help`, the README's goals and the branch diff. It skips an override whose breach the branch no longer holds. It accepts or rejects each other reason by the goals, and calls an override outrageous when it touches a credential, a security rule or a production system, or cannot be undone. An accepted override stands. A rejected one is a 🔴 of this chunk: keep the rule, such as by rewording the commit or pinning the image, then re-enter per §3 → "Re-entry"; where the rule cannot be kept, ask the user. An outrageous one is asked of the user. List each override with its ruling in the PR body. -3. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. -4. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". -5. Stop. The next chunk gets a fresh session. +2. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. +3. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". +4. Stop. The next chunk gets a fresh session. ## 6. Wrap up -- 2.52.0 From 11e613d083e3ca27bb27d684324420c0c4089d37 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:50:41 +0200 Subject: [PATCH 10/17] 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. -- 2.52.0 From 6a054159aef0b231cc6f85ee34cac95a856441da Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:50:41 +0200 Subject: [PATCH 11/17] Answer security round 2: in the architecture round 2 commit, hash todo.md and its index entry so no git status runs a planted clean filter, and open the override log with no symlink followed -- 2.52.0 From e560a74445586dff99dd3fa07ae580f4a2b66746 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:53:46 +0200 Subject: [PATCH 12/17] Answer architecture round 3: list an override only when the current branch's reflog holds its commit, so no sibling or squash-merged branch's override returns, open the log without blocking on a FIFO, and unpack the call's breaches by name --- bin/rule_hook/main.py | 33 +++++++++++++++++++++------------ bin/rule_hook/test_rule_hook.py | 15 +++++++++++++-- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 721b4182..802e365d 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 logged on the current branch, and those whose commit the -default branch does not hold. +`rule-hook overrides` prints the lines whose commit the current branch's reflog holds: those the +default branch lacks, and those logged under the branch's own name. Run with no arguments in a terminal, it prints this help. @@ -65,7 +65,10 @@ def main(argv: list[str], stdin: str) -> int: print(f"rule-hook cannot read the hook input: {call.reason}", file=sys.stderr) return 1 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 + if found is None: + return 0 + written, what, breaches = found + return answer(verdict(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), what, time.time()) def breaches_of(call: Call, home: str) -> tuple[str, str, list[Breach]] | None: @@ -89,9 +92,10 @@ def answer(judged: Verdict, what: str, now: float) -> int: 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 [] + if not unloggable: + for breach, reason, log in logs: + 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 @@ -145,8 +149,8 @@ def log_path(directory: str) -> Log | Failure | None: 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: 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) + # 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: @@ -166,12 +170,17 @@ def print_overrides(directory: str) -> int: 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) + walked = set(reflog.split()) if isinstance(reflog, str) else set() 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") - # 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 ""): + 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 @@ -185,9 +194,9 @@ def holds(directory: str, descendant: str, ancestor: str) -> bool: 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. + # The hook runs git in a checkout the call has not yet been allowed to touch, whose config could name a program: no fsmonitor, and no fetch of a partial clone's missing objects through its transport. try: - ran = subprocess.run(["git", "-c", "core.fsmonitor=false", "-C", directory, *args], capture_output=True, text=True) + ran = subprocess.run(["git", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never", "-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()}") diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 16717082..3c73a4d9 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -167,8 +167,19 @@ class Hook(unittest.TestCase): 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") + git(self.repo, "branch", "-m", "renamed") + self.assertIn("\timage-pin\t", self.listed(), "the reflog keeps the amended commit") + + def test_a_sibling_branch_s_override_is_not_listed(self): + git(self.repo, "checkout", "-q", "-b", "sibling") + git(self.repo, "commit", "-q", "--allow-empty", "-m", "sibling 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, "checkout", "-q", "chunk") + self.assertEqual(self.listed(), "") + git(self.repo, "merge", "-q", "--squash", "sibling") + git(self.repo, "commit", "-q", "--allow-empty", "-m", "squashed") + self.assertEqual(self.listed(), "", "a squash merge brings in none of the sibling's commits") def test_a_blocked_call_logs_no_override(self): command = f"git commit -m a -m '{TRAILER}' # rule-override no-ai-attribution: quotes it" -- 2.52.0 From 6dff757ff449a2987dadbeb4eac3de68f6edca6c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 12 Oct 2026 23:53:46 +0200 Subject: [PATCH 13/17] Answer security round 3: in the architecture round 3 commit, run every hook git call with no lazy fetch and no transport, so a partial clone's config runs no program -- 2.52.0 From 95fb95350b4b5d72222fb8c05af39dec113b0a7d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 13 Oct 2026 00:03:36 +0200 Subject: [PATCH 14/17] Answer architecture round 4: fail rule-hook overrides when the branch's reflog cannot be read or does not hold HEAD, so a git error never reads as a clean review --- bin/rule_hook/main.py | 17 +++++++++++++---- bin/rule_hook/test_rule_hook.py | 10 ++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 802e365d..6122b034 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -25,7 +25,8 @@ default branch lacks, and those logged under the branch's own name. 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 +override cannot be logged; 0 otherwise. `rule-hook overrides` exits 1 when git cannot read the +checkout or the branch's reflog. Exit 1, a non-blocking error to Claude Code, on input it cannot read. """ import dataclasses @@ -46,6 +47,8 @@ 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)] def main(argv: list[str], stdin: str) -> int: @@ -173,7 +176,13 @@ def print_overrides(directory: str) -> int: 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) - walked = set(reflog.split()) if isinstance(reflog, str) else set() + 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 []: @@ -194,9 +203,9 @@ def holds(directory: str, descendant: str, ancestor: str) -> bool: 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, and no fetch of a partial clone's missing objects through its transport. + # 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", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never", "-C", directory, *args], capture_output=True, env={**os.environ, "GIT_NO_LAZY_FETCH": "1"}, text=True) + 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()}") diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 3c73a4d9..c0a7c197 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -170,6 +170,16 @@ class Hook(unittest.TestCase): git(self.repo, "branch", "-m", "renamed") self.assertIn("\timage-pin\t", self.listed(), "the reflog keeps the amended commit") + def test_an_unreadable_reflog_fails_the_listing(self): + unborn = tempfile.mkdtemp() + self.addCleanup(subprocess.run, ["rm", "-rf", unborn]) + git(unborn, "init", "-q", "-b", "chunk") + ran = subprocess.run([str(HOOK), "overrides"], capture_output=True, cwd=unborn, env=isolated_env(), text=True) + self.assertEqual(ran.returncode, 1) + self.assertIn("cannot read the branch's reflog", ran.stderr) + git(self.repo, "reflog", "expire", "--expire=now", "--all") + self.assertEqual(subprocess.run([str(HOOK), "overrides"], capture_output=True, cwd=self.repo, env=isolated_env(), text=True).returncode, 1, "an expired reflog holds no HEAD") + def test_a_sibling_branch_s_override_is_not_listed(self): git(self.repo, "checkout", "-q", "-b", "sibling") git(self.repo, "commit", "-q", "--allow-empty", "-m", "sibling work") -- 2.52.0 From 0721bd13e8822d912c86ca571e91eee1aff7bea0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 13 Oct 2026 00:03:36 +0200 Subject: [PATCH 15/17] Answer security round 4: in the architecture round 4 commit, turn off signature checks and each transport by name in every hook git call, since the checkout's own config may allow one -- 2.52.0 From 7598584ed5442eef384edef435ad745c375f6d5e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 13 Oct 2026 00:08:48 +0200 Subject: [PATCH 16/17] Answer architecture round 5: give the override log one entry format and a pure test of which overrides are the chunk's, move the todo check and the git guards into modules of their own, and point the override reviewer at where the override syntax lives --- agents/override-reviewer.md | 2 +- bin/rule_hook/git.py | 24 +++++++ bin/rule_hook/main.py | 123 +------------------------------- bin/rule_hook/override_log.py | 115 +++++++++++++++++++++++++++++ bin/rule_hook/test_rule_hook.py | 15 ++++ bin/rule_hook/todo_check.py | 25 +++++++ 6 files changed, 183 insertions(+), 121 deletions(-) create mode 100644 bin/rule_hook/git.py create mode 100644 bin/rule_hook/override_log.py create mode 100644 bin/rule_hook/todo_check.py 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 -- 2.52.0 From a845c91217b35519ffc33eeb513d7292b628759c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 13 Oct 2026 00:10:44 +0200 Subject: [PATCH 17/17] Rescore: the paired ruling at 7598584 against 4cc9953 is same --- docs/comprehension-history.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 2344f422..1c64efd0 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -1150,3 +1150,28 @@ Inherited architect, decided by: - Locality: `skills/larv-review/SKILL.md:58` "Opt-out": an opted-out chunk skips a scoring run `larv-review needs-scoring-run` still calls due, and "End" adds a third kind of run - Locality: `bin/rule_hook/main.py:76` `main`: logs each granted override before it knows whether another rule still blocks the call, into an unversioned log keyed by branch name and never pruned - Locality: `bin/rule_hook/main.py:115` `todo_breaches`: the hook imports `rank_todo.check_failures`, so editing rank_todo's messages changes what blocks a commit, while README calls rank_todo.py a tool of one file; the rule's logic sits in main.py, apart from the other rules in rules.py + +## 2026-10-12T22:10:36Z, PR #241 at 7598584, against 4cc9953 + +Ruling: same + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | same | same | worse | same | same | +| Inherited architect | same | worse | same | same | same | + +Mid A, decided by: + +- Shape: `bin/rule_hook/rules.py:8` `RULES`: the module holds the rule table, override parsing and git command-line parsing, while `git.py` only runs git +- Shape: `bin/rule_hook/override_log.py:82` `logged`: builds an Entry though it reads as a yes/no check; `holds` is an ancestry test and `what` says little +- Shape: `bin/rule_hook/main.py:66` `main`: passes `verdict` two bare booleans +- Locality: `bin/shell_command.py:20` `simple_commands`: shorter reading-cost parsing, against a parser change for the hook moving reading-cost figures; the two cancel +- Locality: `bin/rule_hook/main.py:99` `bash_breaches`: parses the command's commits twice + +Inherited architect, decided by: + +- Locality: `bin/shell_command.py:31` `segments`: one grown parser serves reading-cost and the hook, so tightening it for one moves the other +- Locality: `bin/rule_hook/override_log.py:36` `this_chunks`: chunk membership rests on reflog expiry and a default-branch guess, with three failures in one nested ternary at line 96 +- Locality: `bin/rule_hook/main.py:82` `answer`: resolve-then-write order carried by one comment, and `Breach.directory` set deep in rules.py decides which log gets a line +- Locality: `bin/rule_hook/rules.py:108` `git_subcommand`: a second answer to "is this a git commit" beside `measure.py`'s `COMMIT` regex +- Locality: `bin/rule_hook/todo_check.py:7` `import rank_todo`: a change to rank_todo's check changes what the hook blocks -- 2.52.0