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

This commit is contained in:
2026-10-12 23:45:36 +02:00
parent 7cf4f54c90
commit f3bfff1af4
17 changed files with 504 additions and 289 deletions
+1
View File
@@ -43,6 +43,7 @@
!bin/rule-hook !bin/rule-hook
!bin/rule_hook/ !bin/rule_hook/
!bin/rule_hook/*.py !bin/rule_hook/*.py
!bin/shell_command.py
!bin/statusline.py !bin/statusline.py
!bin/test_*.py !bin/test_*.py
!bin/todo_table.py !bin/todo_table.py
+1
View File
@@ -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` - 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: 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 - 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 <rule>: <reason>` marker overrides one, and larv-review's overrides pass rules on each override before merge
## Working rules ## Working rules
+1 -1
View File
@@ -2,7 +2,7 @@
## Unreleased ## 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 <rule>: <reason>`. 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 <rule>: <reason>`. 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 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. - 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. - The stability reviewer keeps its scratch work in a directory it creates for the run, deletes that directory afterwards, and deletes nothing else.
+2 -2
View File
@@ -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. - 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"). - 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. - 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 ## Naming files & folders
- Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. - 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 ## Git, commits, and PRs
- Mark no commit, PR, issue comment or file as the work of Claude, Anthropic or an agent. - 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). - 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. - 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`. - Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`.
+1 -1
View File
@@ -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'` 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 ## Tracking a new file
+16
View File
@@ -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.
+1 -1
View File
@@ -1,7 +1,7 @@
import re import re
CAP = 3 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) ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
+2 -1
View File
@@ -3,7 +3,8 @@ import dataclasses
import re import re
from claude_code.entries import assistant_parts, parse_entry, tool_call 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") COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b")
+5 -46
View File
@@ -2,8 +2,8 @@
import dataclasses import dataclasses
import posixpath import posixpath
import re import re
import shlex
import typing from shell_command import resolved, simple_commands
NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$") NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$")
# Their first operand is a pattern or a program, unless -e or -f gives it. # 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: def shell_reads(command: str, cwd: str, home: str) -> Reads:
read: list[str] = [] read: list[str] = []
added: list[str] = [] added: list[str] = []
base = cwd for simple in simple_commands(command, cwd, home):
for tokens in shell_lines(command): read += [resolved(simple.directory, word, home) for word in operands(simple.words)]
for words in segments(tokens): added += [resolved(simple.directory, path, home) for path in worktree_added(simple.words)]
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)]
return Reads(read, added) 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]: def operands(words: list[str]) -> list[str]:
program = posixpath.basename(words[0]) program = posixpath.basename(words[0])
if program not in READERS or (program == "sed" and any(word.startswith("-i") for word in words)): 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("-"): elif not word.startswith("-"):
return [word] return [word]
return [] 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))
+1 -1
View File
@@ -15,5 +15,5 @@ class Types(unittest.TestCase):
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`") self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if shutil.which("uv") is None: if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line") 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) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+95 -89
View File
@@ -1,24 +1,14 @@
"""Block a Claude Code tool call that breaks a checkable rule, unless the call overrides the rule. """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) 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 settings.json runs it before each Bash, Edit, MultiEdit and Write call, in every session and
subagent. The rules: subagent. The rules:
action-pin a workflow's or action.yml's `uses:` names a semver tag, such as @v3 or @v3.1.2 {rules}
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
action-pin, ignorefile-sorted, image-pin and no-ai-attribution check only what an Edit, MultiEdit or A file a Bash command writes, such as through `cat > Dockerfile`, is not checked.
Write call writes, not a file a Bash command writes.
A call overrides a rule with `# rule-override <rule>: <reason>`: A call overrides a rule with `# rule-override <rule>: <reason>`:
@@ -26,14 +16,17 @@ A call overrides a rule with `# rule-override <rule>: <reason>`:
- in a file, as a comment line in the text the edit writes - in a file, as a comment line in the text the edit writes
- in Markdown, as `<!-- rule-override <rule>: <reason> -->` - in Markdown, as `<!-- rule-override <rule>: <reason> -->`
Each override that let a call through is appended to Each override that let a call through is appended to rule-overrides.tsv in the git directory of
rule-overrides.tsv in the checkout's git directory: UTC time, branch, rule, reason, and the file the checkout it touched: UTC time, branch, the commit checked out, rule, reason, and the file
written or the command's first line. `rule-hook overrides` prints the lines for the current branch. 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. 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 2 with the rule, why it holds and how to override it, when a rule blocks the call, or when an
Exit 1, a non-blocking error to Claude Code, on input it cannot read. override cannot be logged; 0 otherwise. Exit 1, a non-blocking error to Claude Code, on input it
cannot read.
""" """
import json import json
import os import os
@@ -41,10 +34,11 @@ import pathlib
import subprocess import subprocess
import sys import sys
import time 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 import rank_todo
from shell_command import simple_commands
from utc_stamp import utc from utc_stamp import utc
LOG = "rule-overrides.tsv" LOG = "rule-overrides.tsv"
@@ -52,7 +46,7 @@ LOG = "rule-overrides.tsv"
def main(argv: list[str], stdin: str) -> int: def main(argv: list[str], stdin: str) -> int:
if argv in (["-h"], ["--help"]) or not argv and not stdin: if argv in (["-h"], ["--help"]) or not argv and not stdin:
print(__doc__.strip()) print(__doc__.strip().replace("{rules}", rules_help()))
return 0 return 0
if argv == ["overrides"]: if argv == ["overrides"]:
return print_overrides(os.getcwd()) 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) print(f"unknown arguments: {' '.join(argv)}; see rule-hook --help", file=sys.stderr)
return 1 return 1
try: try:
call = json.loads(stdin) call = parsed_call(json.loads(stdin))
tool, given, cwd = call["tool_name"], call["tool_input"], call["cwd"] except json.JSONDecodeError as failure:
if not isinstance(given, dict): call = Failure(str(failure))
raise TypeError("tool_input is no object") if isinstance(call, Failure):
except (json.JSONDecodeError, KeyError, TypeError) as failure: print(f"rule-hook cannot read the hook input: {call.reason}", file=sys.stderr)
print(f"rule-hook cannot read the hook input: {failure}", file=sys.stderr)
return 1 return 1
checked = checked_call(tool, given, cwd) home = os.path.expanduser("~")
if checked is None: bash = call.tool == "Bash"
return 0 path = text(call.given, "file_path")
text, directory, breaches = checked if bash:
what = text.split("\n", 1)[0] if tool == "Bash" else str(given.get("file_path")) written = text(call.given, "command")
granted, malformed = overrides(text) breaches = bash_breaches(written, call.cwd, home)
for breach in breaches: what = written.split("\n", 1)[0]
if breach.rule in granted: elif call.tool in FILE_TOOLS and path:
log_override(directory, breach.rule, granted[breach.rule], what) before = read(path)
blocking = [breach for breach in breaches if breach.rule not in granted] written, after = applied(call, before)
if not blocking: breaches = file_breaches(path, before, written, after)
return 0 what = path
where = "the command" if tool == "Bash" else "the text you write, as a comment line"
markdown = tool != "Bash" and str(given.get("file_path")).endswith(".md")
for marker in malformed:
print(f"`{marker}` names no rule below, or gives no reason.", file=sys.stderr)
for rule in sorted({breach.rule for breach in blocking}):
details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
print(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule]}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.", file=sys.stderr)
return 2
def checked_call(tool: str, given: dict[str, typing.Any], cwd: str) -> tuple[str, str, list[Breach]] | None:
"""The text that may carry an override, the directory whose checkout logs it, and the call's breaches."""
if tool == "Bash":
command = str(given.get("command") or "")
todo = [breach for commit in commits(command, cwd) for breach in todo_breaches(commit.directory)]
return command, cwd, command_breaches(command, cwd) + todo
path = str(given.get("file_path") or "")
if tool not in ("Edit", "MultiEdit", "Write") or not path:
return None
before = read(path)
edits = [given] if tool == "Edit" else [edit for edit in given.get("edits") or [] if isinstance(edit, dict)]
if tool == "Write":
added = after = str(given.get("content") or "")
else: else:
after = before return 0
for edit in edits: judged = verdict(breaches, written, path.endswith(".md"), bash)
old, new = str(edit.get("old_string") or ""), str(edit.get("new_string") or "") for message in judged.messages:
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1) print(message, file=sys.stderr)
added = "\n".join(str(edit.get("new_string") or "") for edit in edits) if judged.blocked:
return added, os.path.dirname(path), file_breaches(path, before, added, after) 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]: def todo_breaches(directory: str) -> list[Breach]:
top = git(directory, "rev-parse", "--show-toplevel") 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 [] return []
# Any change, staged or not: the hook runs before a `git add` earlier in the same command. # 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"): changed = git(top, "status", "--porcelain", "--", "todo.md")
return [] if isinstance(changed, Failure):
return [Breach("todo-rank-check", line) for line in rank_todo.check_failures(pathlib.Path(top) / "todo.md")] 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: def log_override(breach: Breach, reason: str, what: str, now: float) -> Failure | None:
common = git(existing(directory), "rev-parse", "--path-format=absolute", "--git-common-dir") directory = existing(breach.directory)
if not common: if not any((parent / ".git").exists() for parent in [pathlib.Path(directory), *pathlib.Path(directory).parents]):
return return None
branch = git(existing(directory), "branch", "--show-current") or "HEAD" common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
with open(pathlib.Path(common) / LOG, "a", encoding="utf-8") as log: branch = git(directory, "branch", "--show-current")
log.write("\t".join([utc(time.time()), branch, rule, " ".join(reason.split()), " ".join(what.split())]) + "\n") 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: def print_overrides(directory: str) -> int:
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir") common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
branch = git(directory, "branch", "--show-current") if isinstance(common, Failure):
if not common or not branch: print(f"rule-hook overrides runs in a git checkout: {common.reason}", file=sys.stderr)
print("rule-hook overrides runs on a branch of a git checkout", file=sys.stderr)
return 1 return 1
start = branch_start(directory)
log = pathlib.Path(common) / LOG log = pathlib.Path(common) / LOG
lines = log.read_text(encoding="utf-8").splitlines() if log.is_file() else [] lines = log.read_text(encoding="utf-8").splitlines() if log.is_file() else []
for line in lines: 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) print(line)
return 0 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: try:
ran = subprocess.run(["git", "-C", directory, *args], capture_output=True, text=True) ran = subprocess.run(["git", "-c", "core.fsmonitor=false", "-C", directory, *args], capture_output=True, text=True)
except OSError: except OSError as failure:
return "" return Failure(f"git could not start: {failure}")
return ran.stdout.strip() if ran.returncode == 0 else "" return ran.stdout.strip() if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
def existing(directory: str) -> str: def existing(directory: str) -> str:
+176 -104
View File
@@ -1,15 +1,45 @@
import dataclasses import dataclasses
import os import posixpath
import re import re
import shlex import typing
RULES = { from failure import Failure
"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", from shell_command import resolved, Simple
"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", RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]
"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", @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"(?:#|<!--)\s*rule-override ([a-z-]+):([^\n]*?)(?=[ \t]*(?:#|<!--)\s*rule-override |$)", re.MULTILINE) OVERRIDE = re.compile(r"(?:#|<!--)\s*rule-override ([a-z-]+):([^\n]*?)(?=[ \t]*(?:#|<!--)\s*rule-override |$)", re.MULTILINE)
# [-] keeps this file from matching itself. # [-] keeps this file from matching itself.
@@ -20,142 +50,180 @@ 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) FROM = re.compile(r"^[ \t]*FROM[ \t]+(?:--\S+[ \t]+)*(\S+)(?:[ \t]+AS[ \t]+(\S+))?", re.IGNORECASE | re.MULTILINE)
COPIED = re.compile(r"^[ \t]*COPY[ \t].*?--from=(\S+)", re.IGNORECASE | 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) IMAGE = re.compile(r"^[ \t]*(?:-[ \t]+)?(?:image|container):[ \t]*[\"']?([^\s\"'#{]+)", re.MULTILINE)
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
USES = re.compile(r"^[ \t]*(?:-[ \t]+)?uses:[ \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_]*=")
SEPARATING = set("\n();&|")
# git's global options that take a value as the next word. # git's global options that take a value as the next word.
GIT_VALUED = {"-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"} 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) @dataclasses.dataclass(frozen=True)
class Breach: class Breach:
rule: str rule: RuleName
detail: str detail: str
# The checkout whose log records an override of this breach.
directory: str
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class Commit: class Commit:
"""A `git commit` in a command: the directory it runs in, and its messages."""
directory: str directory: str
messages: list[str] messages: list[str]
from_file: bool from_file: bool
def overrides(text: str) -> tuple[dict[str, str], list[str]]: @dataclasses.dataclass(frozen=True)
class Verdict:
messages: list[str]
blocked: bool
# Each breach an override let through, with its reason; logged only when the call goes through.
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.""" """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)] 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} 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] 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: def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Verdict:
"""The command's simple commands as words, with each heredoc's body dropped, or None when it does not parse.""" granted, malformed = overrides(written)
lexer = shlex.shlex(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command), posix=True, punctuation_chars="();<>|&\n") blocking = [breach for breach in breaches if breach.rule not in granted]
lexer.whitespace = " \t\r" messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else []
lexer.whitespace_split = True where = "the command" if bash else "the text you write, as a comment line"
# 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. for rule in sorted({breach.rule for breach in blocking}):
try: details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
words = list(lexer) marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
except ValueError: 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 None return Verdict(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
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 commits(command: str, cwd: str) -> list[Commit]: def commits(simples: list[Simple], home: str) -> list[Commit]:
directory = cwd
found = [] found = []
for segment in segments(command) or []: for simple in simples:
if segment[0] == "cd" and len(segment) > 1: invoked = git_subcommand(simple.words, simple.directory, home)
directory = os.path.join(directory, os.path.expanduser(segment[1])) if invoked and invoked[0] == "commit":
assignments = next((at for at, word in enumerate(segment) if not ASSIGNMENT.match(word)), len(segment)) found.append(Commit(invoked[2], *commit_message(invoked[1])))
words = segment[assignments:]
commit = git_commit(words[1:], directory) if words[:1] == ["git"] else None
if commit:
found.append(commit)
return found return found
def git_commit(args: list[str], directory: str) -> Commit | None: def git_subcommand(words: list[str], directory: str, home: str) -> tuple[str, list[str], str] | None:
at = 0 """A git command's subcommand, its arguments and the directory it runs in, after git's own options such as -C."""
while at < len(args) and args[at].startswith("-"): if words[:1] != ["git"]:
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 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 from_file = False
rest = args[at + 1:] words = iter(args)
at = 0 for word in words:
while at < len(rest):
word = rest[at]
if word == "--": if word == "--":
break break
if word in ("--message", "--file") and at + 1 < len(rest): name, equals, value = word.partition("=")
messages += [rest[at + 1]] if word == "--message" else [] if name in ("--message", "--file"):
from_file = from_file or word == "--file" given = value if equals else next(words, "")
at += 2 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 continue
if word.startswith("--message="): messages += [given] if name == "--message" else []
messages.append(word.removeprefix("--message=")) from_file = from_file or name == "--file"
elif word.startswith("--file="): return messages, from_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)
def command_breaches(command: str, cwd: str) -> list[Breach]: def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]:
breaches = [] breaches = []
parsed = segments(command) or [] found = commits(simples, home)
if any(word in ("gh", "git", "tea") for segment in parsed for word in segment[:1]): if simples and any(simple.words[0] in ("gh", "git", "tea") for simple in simples) and ATTRIBUTION.search(command):
if ATTRIBUTION.search(command): directory = found[0].directory if found else simples[0].directory
breaches.append(Breach("no-ai-attribution", "the command carries an attribution")) breaches.append(Breach("no-ai-attribution", "the command carries an attribution", directory))
for commit in commits(command, cwd): for commit in found:
if commit.from_file: if commit.from_file:
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', not from a file")) breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', not from a file", commit.directory))
elif len(commit.messages) > 1 or any("\n" in message.strip() for message in commit.messages): elif len(commit.messages) > 1 or any("\n" in message.strip() for message in commit.messages):
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', with no heredoc, second -m or newline")) breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', with no heredoc, second -m or newline", commit.directory))
return breaches 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]: 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 in an edit of path: added is the text the edit writes, after the whole file it leaves."""
name = os.path.basename(path) breaches = [Breach("no-ai-attribution", f"{path} would carry an attribution", posixpath.dirname(path))] if ATTRIBUTION.search(added) else []
breaches = [] return breaches + image_breaches(path, before, added, after) + action_breaches(path, added) + ignore_breaches(path, before, after)
if ATTRIBUTION.search(added):
breaches.append(Breach("no-ai-attribution", f"{path} would carry an attribution"))
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")): if name.startswith(("Dockerfile", "Containerfile")) or name.endswith((".dockerfile", ".Dockerfile", ".containerfile")):
stages = {stage.lower() for _, stage in FROM.findall(before + "\n" + after) if stage} stages = {stage.lower() for _, stage in FROM.findall(before + "\n" + after) if stage} | {"scratch"}
images = [image for image, _ in FROM.findall(added)] + COPIED.findall(added) 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()]
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)] elif "compose" in name and name.endswith((".yml", ".yaml")) or workflow(path):
workflow = any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or name in ("action.yml", "action.yaml") images = IMAGE.findall(added)
if "compose" in name and name.endswith((".yml", ".yaml")) or workflow: else:
breaches += [Breach("image-pin", f"{path}: {image}") for image in IMAGE.findall(added) if not pinned(image)] images = []
if workflow: return [Breach("image-pin", f"{path}: {image}", posixpath.dirname(path)) for image in images 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"):
already = [block for block in blocks(before) if block != sorted(block)] def action_breaches(path: str, added: str) -> list[Breach]:
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] actions = USES.findall(added) if workflow(path) else []
return breaches 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: 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 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.""" """An ignore file's runs of patterns, split at each blank line and comment."""
runs: list[list[str]] = [[]] runs: list[list[str]] = [[]]
for line in text.splitlines(): for line in written.splitlines():
if line.strip() and not line.startswith("#"): if line.strip() and not line.startswith("#"):
runs[-1].append(line) runs[-1].append(line)
elif runs[-1]: elif runs[-1]:
runs.append([]) runs.append([])
return [run for run in runs if run] 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())
+79 -39
View File
@@ -7,9 +7,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) 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_rank_todo import DECISIONS, README, TODO
from test_env import isolated_env from test_env import isolated_env
from shell_command import simple_commands
HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook" HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook"
# Built from parts, so this file carries no attribution of its own. # 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] 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: 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) 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): class Commits(unittest.TestCase):
def test_cd_and_dash_capital_c_move_the_commit(self): 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): 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): def test_a_file_message_is_seen(self):
self.assertTrue(commits("git commit -F - <<EOF\nx\nEOF", "/r")[0].from_file) self.assertEqual(commit_message(["-F", "-"]), ([], True))
self.assertEqual(commit_message(["--file=x"]), ([], True))
def test_other_git_commands_are_no_commit(self): def test_other_git_commands_are_no_commit(self):
self.assertEqual(commits("git log --grep commit; echo git commit", "/r"), []) self.assertEqual(committed("git log --grep commit; echo git commit"), [])
def test_a_line_break_or_a_comment_separates_commands(self):
self.assertEqual(committed("cd a # go there\nGIT_EDITOR=true git commit -m x"), [Commit("/r/a", ["x"], False)])
def test_a_commit_after_a_heredoc_or_a_blank_line_is_seen(self): def test_a_commit_after_a_heredoc_or_a_blank_line_is_seen(self):
self.assertEqual(len(commits("cat <<EOF > notes\nhello\nEOF\ngit commit -m a", "/r")), 1) self.assertEqual(len(committed("cat <<EOF > notes\nhello\nEOF\ngit commit -m a")), 1)
self.assertEqual(len(commits("git status &&\n\ngit commit -m a", "/r")), 1) self.assertEqual(len(committed("git status &&\n\ngit commit -m a")), 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): 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): def test_a_line_that_does_not_parse_hides_only_itself(self):
self.assertEqual(commits("cd a\nGIT_EDITOR=true git commit -m x", "/r"), [Commit("/r/a", ["x"], False)]) self.assertEqual(len(committed("echo 'open\ngit commit -m a")), 1)
class CommandBreaches(unittest.TestCase): class CommandBreaches(unittest.TestCase):
def test_one_line_passes(self): 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): 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): 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): 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(checked(f"tea pr create --description '{TRAILER}'"), ["no-ai-attribution"])
self.assertEqual(command_breaches(f"grep -rn '{TRAILER}' .", "/r"), []) self.assertEqual(checked(f"grep -rn '{TRAILER}' ."), [])
def test_a_heredoc_body_is_no_shell_text(self): def test_a_commit_breach_names_the_commit_s_checkout(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(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")
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): 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" 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): 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"), []) 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): 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: "])) 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): def test_markdown_takes_an_html_comment(self):
self.assertEqual(overrides("<!-- rule-override no-ai-attribution: quotes the banned line -->")[0], {"no-ai-attribution": "quotes the banned line"}) self.assertEqual(overrides("<!-- rule-override no-ai-attribution: quotes the banned line -->")[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("`<!-- rule-override no-ai-attribution: <reason> -->`", verdict([Breach("no-ai-attribution", "x", "/r")], "", True, False).messages[0])
class Hook(unittest.TestCase): class Hook(unittest.TestCase):
def setUp(self): def setUp(self):
self.repo = tempfile.mkdtemp() self.repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", self.repo]) 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): 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) 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("Blocked by rule image-pin: ", ran.stderr)
self.assertIn("`# rule-override image-pin: <reason>`", ran.stderr) self.assertIn("`# rule-override image-pin: <reason>`", 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" 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) 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, "")) 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(self.listed(), r"^\S+Z\tchunk\t[0-9a-f]{40}\timage-pin\tthe vendor tags no patch versions\t\S+/sub/Dockerfile\n$")
self.assertRegex(listed, r"^\S+Z\tchunk\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): def test_an_edit_is_judged_on_the_file_it_leaves(self):
pathlib.Path(self.repo, ".gitignore").write_text("a\nc\n") 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): def test_a_commit_while_an_unranked_todo_has_changes_is_blocked(self):
pathlib.Path(self.repo, "docs").mkdir() pathlib.Path(self.repo, "docs").mkdir()
for name, text in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]: for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]:
pathlib.Path(self.repo, name).write_text(text) pathlib.Path(self.repo, name).write_text(content)
git(self.repo, "add", "README.md", "docs", "todo.md") git(self.repo, "add", "README.md", "docs", "todo.md")
git(self.repo, "commit", "-qm", "x", "--no-verify") 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"} 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) 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) 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("`<!-- rule-override no-ai-attribution: <reason> -->`", ran.stderr)
def test_a_missing_field_breaks_nothing(self): 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"}]: 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): with self.subTest(given):
tool = "Bash" if "command" in given else "Write" if "content" in given else "MultiEdit" 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": 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): def test_unreadable_input_does_not_block(self):
ran = subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input="{", text=True) for given in ["{", json.dumps({"cwd": ".", "tool_input": None, "tool_name": "Bash"})]:
self.assertEqual(ran.returncode, 1) 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)
+89
View File
@@ -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))
+22
View File
@@ -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/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/claude_code/trust.py:10` `trust`: effects in a package documented as shapes
- `bin/larv_review/git.py:8` `git`: git run five ways - `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
+4
View File
@@ -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 ## 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. 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 <rule>: <reason>` 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.
+8 -4
View File
@@ -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 | | 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 | | 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 | | 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 | | 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 | | 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 | | 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). **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 ### 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. 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 ## 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. 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. 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. 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. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". 4. Stop. The next chunk gets a fresh session.
5. Stop. The next chunk gets a fresh session.
## 6. Wrap up ## 6. Wrap up