From 109fb27e00b6e5d2dc9198e8954901cb5aa6a352 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 13 Oct 2026 07:56:59 +0200 Subject: [PATCH] Answer architecture round 5: one shared git command parser for rule-hook and reading-cost, the reflog check unrolled, and rule-hook's Outcome and LogLine named apart from their namesakes --- .gitignore | 1 + bin/git_command.py | 58 ++++++++++++++++++++++++ bin/loop_claude/project/records.py | 2 +- bin/reading_cost/measure.py | 11 +++-- bin/reading_cost/test_reading_cost.py | 4 ++ bin/rule_hook/main.py | 5 ++- bin/rule_hook/override_log.py | 26 +++++++---- bin/rule_hook/rules.py | 63 +++------------------------ bin/rule_hook/test_rule_hook.py | 11 ++--- 9 files changed, 100 insertions(+), 81 deletions(-) create mode 100644 bin/git_command.py diff --git a/.gitignore b/.gitignore index 68fae050..85433283 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,7 @@ !bin/comprehension_history.py !bin/failure.py !bin/file_writes.py +!bin/git_command.py !bin/larv-review !bin/larv_review/ !bin/larv_review/*.py diff --git a/bin/git_command.py b/bin/git_command.py new file mode 100644 index 00000000..982c1e0e --- /dev/null +++ b/bin/git_command.py @@ -0,0 +1,58 @@ +import dataclasses + +from shell_command import resolved, Simple + +# git's global options that take a value as the next word. +GIT_VALUED = {"-C", "-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"} + + +@dataclasses.dataclass(frozen=True) +class Commit: + directory: str + messages: list[str] + from_file: bool + + +def commits(simples: list[Simple], home: str) -> list[Commit]: + found = [] + 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_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 + 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 + words = iter(args) + for word in words: + if word == "--": + break + 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 + messages += [given] if name == "--message" else [] + from_file = from_file or name == "--file" + return messages, from_file diff --git a/bin/loop_claude/project/records.py b/bin/loop_claude/project/records.py index ecf65480..11314d32 100644 --- a/bin/loop_claude/project/records.py +++ b/bin/loop_claude/project/records.py @@ -8,7 +8,7 @@ RECORD_FILES = ("AGENTS.md", "docs/decisions.md") # The human's rules for every project, under ~/.claude: CLAUDE.md, then each .md file in these folders, which a repo check keeps present. HUMAN_RULES_FILE = "CLAUDE.md" HUMAN_RULE_DIRS = ("rules", "skills/larv-review/standards") -HUMAN_RULE_NAMES = tuple(f"~/.claude/{name}" for name in (HUMAN_RULES_FILE, *(f"{folder}/" for folder in HUMAN_RULE_DIRS))) +HUMAN_RULE_NAMES = (f"~/.claude/{HUMAN_RULES_FILE}", *(f"~/.claude/{folder}/" for folder in HUMAN_RULE_DIRS)) def read_records(root: str, claude_dir: pathlib.Path) -> str | Stop: diff --git a/bin/reading_cost/measure.py b/bin/reading_cost/measure.py index 958528ab..b8fe8b13 100644 --- a/bin/reading_cost/measure.py +++ b/bin/reading_cost/measure.py @@ -1,12 +1,11 @@ import collections import dataclasses -import re from claude_code.entries import assistant_parts, parse_entry, tool_call +from git_command import commits from reading_cost.shell_reads import Reads, shell_reads -from shell_command import resolved +from shell_command import resolved, simple_commands -COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b") @@ -27,7 +26,7 @@ class Checkout: def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | None: worker, *subagents = [entries_of(thread) for thread in threads] - commit = commit_time(worker) + commit = commit_time(worker, home) if commit is None: return None before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)] @@ -41,11 +40,11 @@ def entries_of(raw: bytes) -> list[dict]: return [entry for line in raw.splitlines() if (entry := parse_entry(line))] -def commit_time(worker: list[dict]) -> str | None: +def commit_time(worker: list[dict], home: str) -> str | None: for entry in worker: for part in assistant_parts(entry): name, arguments = call_of(part) - if name == "Bash" and COMMIT.search(str(arguments.get("command", ""))): + if name == "Bash" and commits(simple_commands(str(arguments.get("command", "")), str(entry.get("cwd") or "/"), home), home): return str(entry.get("timestamp", "")) return None diff --git a/bin/reading_cost/test_reading_cost.py b/bin/reading_cost/test_reading_cost.py index 9af90473..8d683446 100644 --- a/bin/reading_cost/test_reading_cost.py +++ b/bin/reading_cost/test_reading_cost.py @@ -66,6 +66,10 @@ class Measure(unittest.TestCase): def test_measures_nothing_for_a_worker_that_never_committed(self): self.assertIsNone(measure.measure([jsonl([said("1", "m1", command="git log --grep commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h")) + self.assertIsNone(measure.measure([jsonl([said("1", "m1", command="echo git commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h")) + + def test_finds_a_commit_behind_git_options(self): + self.assertIsNotNone(measure.measure([jsonl([said("1", "m1", command="git -c user.name=t commit -m x")])], Checkout("/c/p", "/c/p", frozenset()), "/h")) def test_skips_a_usage_that_is_not_a_count(self): self.assertEqual(measure.tokens_in([{"message": {"id": "m", "usage": {"input_tokens": "7", "cache_creation_input_tokens": 2}}}]), 2) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 5482bb9d..418a38b6 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -36,7 +36,8 @@ import sys import time from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text -from rule_hook.rules import Breach, command_breaches, commits, file_breaches, rules_help, verdict, Verdict +from rule_hook.rules import Breach, command_breaches, file_breaches, Outcome, rules_help, verdict +from git_command import commits from failure import Failure from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override from shell_command import simple_commands @@ -79,7 +80,7 @@ def breaches_of(call: Call, home: str) -> tuple[str, str, list[Breach]] | None: return added, path, file_breaches(path, before, added, after) -def answer(judged: Verdict, what: str, now: float) -> int: +def answer(judged: Outcome, what: str, now: float) -> int: for message in judged.messages: print(message, file=sys.stderr) if judged.blocked: diff --git a/bin/rule_hook/override_log.py b/bin/rule_hook/override_log.py index 36fde2c1..d57ed0a2 100644 --- a/bin/rule_hook/override_log.py +++ b/bin/rule_hook/override_log.py @@ -14,7 +14,7 @@ LOG = "rule-overrides.tsv" @dataclasses.dataclass(frozen=True) -class Entry: +class LogLine: """One line of the log, its fields tab-separated in this order.""" at: str branch: str @@ -28,12 +28,12 @@ class Entry: return "\t".join(" ".join(field.split()) for field in dataclasses.astuple(self)) + "\n" -def parsed_entry(line: str) -> Entry | None: +def parsed_entry(line: str) -> LogLine | None: fields = line.rstrip("\n").split("\t") - return Entry(*fields) if len(fields) == len(dataclasses.fields(Entry)) else None + return LogLine(*fields) if len(fields) == len(dataclasses.fields(LogLine)) else None -def this_chunks(entry: Entry, reflog: set[str], branch: str, on_default: typing.Callable[[str], bool]) -> bool: +def this_chunks(entry: LogLine, reflog: set[str], branch: str, on_default: typing.Callable[[str], bool]) -> bool: """Whether the override is the current branch's: its commit is in the branch's reflog, which keeps a commit an amend or a rebase replaced, follows `git branch -m`, and holds no other branch's commit.""" if entry.commit == "": return True @@ -62,7 +62,7 @@ def log_path(directory: str) -> Log | Failure | None: return Log(pathlib.Path(str(common)) / LOG, str(branch) or "HEAD", "" if isinstance(head, Failure) else head) -def write_override(log: Log, entry: Entry) -> Failure | None: +def write_override(log: Log, entry: LogLine) -> Failure | None: try: # No symlink, and no FIFO to hang on: the checkout, and so its git directory, may come from anyone. descriptor = os.open(log.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) @@ -79,8 +79,8 @@ def write_override(log: Log, entry: Entry) -> Failure | None: return None -def logged(log: Log, breach: Breach, reason: str, what: str, now: float) -> Entry: - return Entry(utc(now), log.branch, log.head, breach.rule, reason, what) +def logged(log: Log, breach: Breach, reason: str, what: str, now: float) -> LogLine: + return LogLine(utc(now), log.branch, log.head, breach.rule, reason, what) def print_overrides(directory: str) -> int: @@ -92,8 +92,7 @@ def print_overrides(directory: str) -> int: branch = found if isinstance(found, str) and found else "HEAD" reflog = git(directory, "reflog", "show", "--format=%H", branch) head = git(directory, "rev-parse", "HEAD") - # A reflog missing HEAD is off or expired, and would hide this chunk's overrides. - unread = reflog if isinstance(reflog, Failure) else head if isinstance(head, Failure) else None if head in reflog.split() else Failure("it does not hold HEAD") + unread = unread_reflog(reflog, head) if unread: print(f"rule-hook overrides cannot read the branch's reflog, so it cannot tell which overrides are this chunk's: {unread.reason}", file=sys.stderr) return 1 @@ -107,6 +106,15 @@ def print_overrides(directory: str) -> int: return 0 +def unread_reflog(reflog: str | Failure, head: str | Failure) -> Failure | None: + if isinstance(reflog, Failure): + return reflog + if isinstance(head, Failure): + return head + # A reflog missing HEAD is off or expired, and would hide this chunk's overrides. + return None if head in reflog.split() else Failure("it does not hold HEAD") + + def default_branch(directory: str) -> str | None: return next((name for name in ("origin/HEAD", "main", "master") if not isinstance(git(directory, "rev-parse", "--verify", "--quiet", name), Failure)), None) diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 6af62975..6f93a8de 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -3,7 +3,8 @@ import posixpath import re import typing -from shell_command import resolved, Simple +from git_command import commits +from shell_command import Simple RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"] @@ -50,8 +51,6 @@ FROM = re.compile(r"^[ \t]*FROM[ \t]+(?:--\S+[ \t]+)*(\S+)(?:[ \t]+AS[ \t]+(\S+) 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) USES = re.compile(r"^[ \t]*(?:-[ \t]+)?uses:[ \t]*[\"']?([^\s\"'#]+)", re.MULTILINE) -# git's global options that take a value as the next word. -GIT_VALUED = {"-C", "-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"} @dataclasses.dataclass(frozen=True) @@ -63,14 +62,7 @@ class Breach: @dataclasses.dataclass(frozen=True) -class Commit: - directory: str - messages: list[str] - from_file: bool - - -@dataclasses.dataclass(frozen=True) -class Verdict: +class Outcome: messages: list[str] blocked: bool # Each breach an override let through, with its reason; logged only when the call goes through. @@ -84,7 +76,7 @@ def overrides(written: str) -> tuple[dict[str, str], list[str]]: return granted, [f"rule-override {rule}: {reason}" for rule, reason in given if rule not in granted] -def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Verdict: +def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Outcome: 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 [] @@ -93,52 +85,7 @@ def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> details = "; ".join(breach.detail for breach in blocking if breach.rule == rule) marker = f"" if markdown else f"# rule-override {rule}: " messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.") - return Verdict(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted]) - - -def commits(simples: list[Simple], home: str) -> list[Commit]: - found = [] - 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_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 - 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 - words = iter(args) - for word in words: - if word == "--": - break - 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 - messages += [given] if name == "--message" else [] - from_file = from_file or name == "--file" - return messages, from_file + return Outcome(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted]) def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]: diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index d3196cec..23e99a61 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -8,10 +8,11 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from rule_hook.rules import blocks, Breach, command_breaches, Commit, commit_message, commits, file_breaches, overrides, verdict +from rule_hook.rules import blocks, Breach, command_breaches, file_breaches, overrides, verdict +from git_command import Commit, commit_message, commits from test_rank_todo import DECISIONS, README, TODO -from rule_hook.override_log import Entry, parsed_entry, this_chunks from test_env import isolated_env +from rule_hook.override_log import LogLine, parsed_entry, this_chunks from shell_command import simple_commands HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook" @@ -139,8 +140,8 @@ class Overrides(unittest.TestCase): class OverrideLog(unittest.TestCase): def test_an_entry_reads_back_as_written(self): - entry = Entry("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor\ttags no patch", "Dockerfile") - self.assertEqual(parsed_entry(entry.line()), Entry("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor tags no patch", "Dockerfile")) + entry = LogLine("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor\ttags no patch", "Dockerfile") + self.assertEqual(parsed_entry(entry.line()), LogLine("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor tags no patch", "Dockerfile")) self.assertIsNone(parsed_entry("a\tb")) def test_an_override_is_the_chunk_s_by_its_reflog_and_name(self): @@ -148,7 +149,7 @@ class OverrideLog(unittest.TestCase): cases = [("chunk", "c1", True), ("other", "c1", True), ("other", "c9", False), ("chunk", "base", True), ("other", "base", False), ("other", "", True)] for branch, commit, expected in cases: with self.subTest(branch=branch, commit=commit): - self.assertEqual(this_chunks(Entry("t", branch, commit, "image-pin", "r", "w"), {"base", "c1"}, "chunk", on_default), expected) + self.assertEqual(this_chunks(LogLine("t", branch, commit, "image-pin", "r", "w"), {"base", "c1"}, "chunk", on_default), expected) class Hook(unittest.TestCase):