Merge remote-tracking branch 'origin/main' into item-293

# Conflicts:
#	AGENTS.md
#	agents/stability-reviewer.md
#	docs/reading-cost.md
#	todo.md
This commit is contained in:
2026-11-11 19:24:50 +01:00
57 changed files with 1319 additions and 381 deletions
+60
View File
@@ -0,0 +1,60 @@
import dataclasses
import posixpath
from rule_hook.rules import Breach, file_breaches
from failure import Failure
from git_cli import git_repo
from rule_hook.git import guarded_git
from rule_hook.file_text import read
# settings.json gives rule-hook 30 seconds; a file past this size is not source code, and reading it would use them up.
MAX_BYTES = 1_000_000
def committed_file_breaches(directory: str) -> list[Breach]:
"""The breaches of file_breaches in the files a commit in directory's checkout would commit.
A file a Bash command wrote reaches no Edit or Write check, so the commit checks the file instead. The files are those that differ from HEAD in the index or the work tree, or that are untracked and not ignored: the hook runs before a `git add` earlier in the same command, so the index alone would miss those files. A tracked file is checked as the index holds it and as the work tree does, since the commit takes the index. A deleted file, or one that is not UTF-8 text, has no added text. A breach carries the lines its file adds, so a marker among them overrides it, as in a Write; a marker the file already held doesn't."""
top = guarded_git(directory, "rev-parse", "--show-toplevel")
if isinstance(top, Failure):
return []
tracked = tracked_names(top)
untracked = guarded_git(top, "ls-files", "-z", "--others", "--exclude-standard")
breaches: list[Breach] = []
for name in sorted(tracked | (set() if isinstance(untracked, Failure) else names_in(untracked))):
path = posixpath.join(top, name)
# An untracked file has neither a version in HEAD nor one in the index. A tracked file costs two git calls, about 4 ms each: a commit of 3000 changed files uses 13 of the hook's 30 seconds.
before = blob(top, "HEAD", name) if name in tracked else ""
for after in dict.fromkeys([read(path) if size(path) <= MAX_BYTES else "", blob(top, "", name) if name in tracked else ""]):
known = set(before.splitlines())
added = "\n".join(line for line in after.splitlines() if line not in known)
breaches += [dataclasses.replace(breach, marked=added) for breach in file_breaches(path, before, added, after)]
# The index copy and the work-tree copy of a file can breach the same way; the first stands.
return list({(breach.rule, breach.detail): breach for breach in reversed(breaches)}.values())[::-1]
def tracked_names(top: str) -> set[str]:
"""The tracked files that differ from HEAD in the index or the work tree, deleted ones left out. It lists with diff-index, which neither hashes the work tree nor enters a submodule: either would run a clean filter that the checkout's config names, before the call is allowed."""
listings = [guarded_git(top, "diff-index", "-z", "--name-only", "--no-renames", "--diff-filter=d", "--ignore-submodules", *cached, "HEAD") for cached in ([], ["--cached"])]
if any(isinstance(listing, Failure) for listing in listings):
# A checkout with no commit has no HEAD: every file in its index is new.
listing = guarded_git(top, "ls-files", "-z")
return set() if isinstance(listing, Failure) else names_in(listing)
return {name for listing in listings if not isinstance(listing, Failure) for name in names_in(listing)}
def names_in(listing: str) -> set[str]:
return {name for name in listing.split("\0") if name}
def blob(top: str, commit: str, name: str) -> str:
"""name's text in the commit, or in the index where commit is empty; "" where there is none."""
shown = git_repo.git("show", f"{commit}:{name}", cwd=top, guarded=True)
return "" if isinstance(shown, Failure) or len(shown) > MAX_BYTES else shown
def size(path: str) -> int:
try:
return posixpath.getsize(path)
except OSError:
return 0
+12
View File
@@ -0,0 +1,12 @@
import os
import stat
def read(path: str) -> str:
"""path's text, or "" for anything but a regular file: a FIFO would hang the hook and a device such as /dev/zero would flood it."""
try:
# O_NONBLOCK opens a FIFO without waiting for a writer; fstat then judges the file opened, not one swapped in after a stat.
with open(os.open(path, os.O_RDONLY | os.O_NONBLOCK), encoding="utf-8") as opened:
return opened.read() if stat.S_ISREG(os.fstat(opened.fileno()).st_mode) else ""
except (OSError, UnicodeDecodeError):
return ""
+11 -14
View File
@@ -8,14 +8,18 @@ subagent. The rules:
{rules}
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked.
A call overrides a rule with `# rule-override <rule>: <reason>`:
- anywhere in a Bash command, such as a trailing comment
- in a file, as a comment line in the text the edit writes
- in Markdown, as `<!-- rule-override <rule>: <reason> -->`
A file a Bash command writes, such as through `cat > Dockerfile`, is checked when a `git commit` runs, not when written.
The commit checks every file that differs from HEAD, in the index or the work tree, and every untracked file that is
not ignored, even one the commit leaves out. It holds each to the rules that name a file (action-pin, image-pin,
ignorefile-sorted, no-ai-attribution), judged on the lines the file adds. A marker among those lines, or in the commit
command, overrides the file's breach.
Each override that let a call through is appended to rule-overrides.tsv in the git directory of
the checkout it touched: UTC time, branch, the commit checked out, rule, reason, and the file
written or the command's first line. An override outside any git checkout is not logged.
@@ -31,7 +35,6 @@ cannot read.
"""
import json
import os
import stat
import sys
import time
import typing
@@ -39,8 +42,10 @@ import typing
from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
from git_cli.git_command import commits
from rule_hook.committed_files import committed_file_breaches
from failure import Failure
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
from rule_hook.file_text import read
from rule_hook.repeat_read import read_breaches
from rule_hook.reviewer_report import report_breaches
from rule_hook.reviewer_rung import reviewer_breaches, skill_breaches
@@ -110,14 +115,6 @@ def answer(checked: Checked, what: str, now: float) -> int:
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 round_cap_breaches(commit) + todo_breaches(commit.directory)]
def read(path: str) -> str:
"""path's text, or "" for anything but a regular file: a FIFO would hang the hook and a device such as /dev/zero would flood it."""
try:
# O_NONBLOCK opens a FIFO without waiting for a writer; fstat then judges the file opened, not one swapped in after a stat.
with open(os.open(path, os.O_RDONLY | os.O_NONBLOCK), encoding="utf-8") as opened:
return opened.read() if stat.S_ISREG(os.fstat(opened.fileno()).st_mode) else ""
except (OSError, UnicodeDecodeError):
return ""
found = commits(simples, home)
in_files = [breach for directory in dict.fromkeys(commit.directory for commit in found) for breach in committed_file_breaches(directory)]
return command_breaches(command, simples, home) + [breach for commit in found for breach in round_cap_breaches(commit) + todo_breaches(commit.directory)] + in_files
+6 -2
View File
@@ -104,6 +104,8 @@ class Breach:
detail: str
# The checkout whose log records an override of this breach.
directory: str
# The lines a commit adds to the breach's file: its markers override this breach, as a Write's text overrides its own file's.
marked: str = ""
@dataclasses.dataclass(frozen=True)
@@ -124,7 +126,9 @@ def overrides(written: str) -> tuple[dict[str, str], list[str]]:
def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Checked:
granted, malformed = overrides(written)
blocking = [breach for breach in breaches if breach.rule not in granted]
# A marker overrides a breach when it is in the call's own text or in the breach's file.
grants = [granted | overrides(breach.marked)[0] for breach in breaches]
blocking = [breach for breach, grant in zip(breaches, grants) if breach.rule not in grant]
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}):
@@ -134,7 +138,7 @@ def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> C
continue
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 Checked(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
return Checked(messages, bool(blocking), [(breach, grant[breach.rule]) for breach, grant in zip(breaches, grants) if breach.rule in grant])
def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]:
+121
View File
@@ -913,6 +913,127 @@ class TodoRankCheck(unittest.TestCase):
self.assertNotIn("own script", " ".join(reasons))
class CommittedFiles(unittest.TestCase):
"""A git commit holds the files it would commit to the file rules, as an Edit or Write of each would be."""
UNPINNED = "jobs:\n a:\n steps:\n - uses: actions/checkout@main\n"
def setUp(self):
self.repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", self.repo])
git(self.repo, "init", "-q", "-b", "main")
git(self.repo, "commit", "-q", "--allow-empty", "-m", "base")
def write(self, name: str, content: str) -> None:
path = pathlib.Path(self.repo, name)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
def commit(self, command: str = "git add -A && git commit -m x") -> subprocess.CompletedProcess:
return hook({"cwd": self.repo, "tool_input": {"command": command}, "tool_name": "Bash"}, self.repo)
def test_a_file_a_command_wrote_is_checked_at_the_commit(self):
self.write(".github/workflows/ci.yml", self.UNPINNED)
self.write("Dockerfile", "FROM node:24\n")
self.write(".gitignore", "b\na\n")
self.write("NOTES.md", "Co-Authored-" + "By: Claude <noreply@anthropic.com>\n")
ran = self.commit()
self.assertEqual(ran.returncode, 2)
for rule in ["action-pin", "image-pin", "ignorefile-sorted", "no-ai-attribution"]:
with self.subTest(rule):
self.assertIn(f"Blocked by rule {rule}: ", ran.stderr)
def test_a_staged_file_is_checked_and_a_clean_tree_passes(self):
self.assertEqual(self.commit().returncode, 0)
self.write(".github/workflows/ci.yml", self.UNPINNED)
git(self.repo, "add", "-A")
self.assertEqual(self.commit("git commit -m x").returncode, 2)
def test_a_breach_the_head_already_holds_is_left_alone(self):
self.write("Dockerfile", "FROM node:24\n")
self.write(".gitignore", "b\na\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
self.write("Dockerfile", "FROM node:24\nRUN true\n")
self.write(".gitignore", "b\na\n\n# more\nc\n")
self.assertEqual(self.commit().returncode, 0)
self.write("Dockerfile", "FROM node:24\nRUN true\nFROM node:25\n")
self.assertIn("image-pin: ", self.commit().stderr)
def test_a_marker_in_the_command_or_the_file_lets_the_commit_through(self):
self.write("Dockerfile", "FROM vendor/tool:2\n")
self.assertEqual(self.commit("git add -A && git commit -m x # rule-override image-pin: the vendor tags no patch versions").returncode, 0)
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n")
self.assertEqual(self.commit().returncode, 0)
def test_a_staged_breach_blocks_the_commit_after_the_work_tree_is_fixed(self):
self.write("Dockerfile", "FROM node:24\n")
git(self.repo, "add", "Dockerfile")
self.write("Dockerfile", "FROM node:24.18.1\n")
self.assertIn("image-pin: ", self.commit("git commit -m x").stderr)
def test_a_stat_dirty_file_runs_no_clean_filter(self):
self.write("a.txt", "a\n")
self.write(".gitattributes", "a.txt filter=planted\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
git(self.repo, "config", "filter.planted.clean", f"touch {self.repo}/ran; cat")
pathlib.Path(self.repo, "ran").unlink(missing_ok=True)
os.utime(pathlib.Path(self.repo, "a.txt"), (1, 1))
self.assertEqual(self.commit("git commit -m x").returncode, 0)
self.assertFalse(pathlib.Path(self.repo, "ran").exists())
def test_a_submodule_runs_no_clean_filter(self):
inner = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", inner])
git(inner, "init", "-q", "-b", "main")
pathlib.Path(inner, "b.txt").write_text("b\n")
pathlib.Path(inner, ".gitattributes").write_text("b.txt filter=planted\n")
git(inner, "add", "-A")
git(inner, "commit", "-qm", "x", "--no-verify")
git(self.repo, "-c", "protocol.file.allow=always", "submodule", "add", "-q", inner, "sub")
git(self.repo, "commit", "-qm", "x", "--no-verify")
git(f"{self.repo}/sub", "config", "filter.planted.clean", f"touch {self.repo}/ran; cat")
os.utime(pathlib.Path(self.repo, "sub", "b.txt"), (1, 1))
self.assertEqual(self.commit("git commit -m x").returncode, 0)
self.assertFalse(pathlib.Path(self.repo, "ran").exists())
def test_a_checkout_with_no_commit_checks_its_index_and_untracked_files(self):
fresh = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", fresh])
git(fresh, "init", "-q", "-b", "main")
pathlib.Path(fresh, "Dockerfile").write_text("FROM node:24\n")
git(fresh, "add", "Dockerfile")
pathlib.Path(fresh, "NOTES.md").write_text(TRAILER + "\n")
ran = hook({"cwd": fresh, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}, fresh)
for rule in ["image-pin", "no-ai-attribution"]:
self.assertIn(f"Blocked by rule {rule}: ", ran.stderr)
def test_a_change_that_only_reorders_an_ignore_file_is_checked(self):
self.write(".gitignore", "a\nb\nc\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
self.write(".gitignore", "c\nb\na\n")
self.assertIn("ignorefile-sorted: ", self.commit().stderr)
def test_a_marker_the_head_already_holds_does_not_override_a_new_breach(self):
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\nFROM node:24\n")
self.assertIn("image-pin: ", self.commit().stderr)
def test_a_marker_in_another_file_does_not_override_a_breach(self):
self.write("Dockerfile", "FROM vendor/tool:2\n")
self.write("NOTES.md", "# rule-override image-pin: quoted in a note\n")
self.assertIn("Blocked by rule image-pin: ", self.commit().stderr)
def test_an_ignored_or_binary_file_is_left_alone(self):
self.write(".gitignore", "build/\n")
self.write("build/Dockerfile", "FROM node:24\n")
pathlib.Path(self.repo, "image.png").write_bytes(b"\xff\xfe\x00FROM node:24\n")
self.assertEqual(self.commit().returncode, 0)
class RuleNames(unittest.TestCase):
def test_every_rule_name_has_a_rule_and_every_rule_a_name(self):
self.assertEqual(set(RULES), set(typing.get_args(RuleName)))