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
+176 -104
View File
@@ -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"(?:#|<!--)\s*rule-override ([a-z-]+):([^\n]*?)(?=[ \t]*(?:#|<!--)\s*rule-override |$)", re.MULTILINE)
# [-] 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)
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)
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)
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_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)
class Breach:
rule: str
rule: RuleName
detail: str
# The checkout whose log records an override of this breach.
directory: str
@dataclasses.dataclass(frozen=True)
class Commit:
"""A `git commit` in a command: the directory it runs in, and its messages."""
directory: str
messages: list[str]
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."""
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}
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"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
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 '<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):
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
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())