Compare commits

..

43 Commits

Author SHA1 Message Date
lilleman a845c91217 Rescore: the paired ruling at 7598584 against 4cc9953 is same 2026-10-13 00:10:44 +02:00
lilleman 7598584ed5 Answer architecture round 5: give the override log one entry format and a pure test of which overrides are the chunk's, move the todo check and the git guards into modules of their own, and point the override reviewer at where the override syntax lives 2026-10-13 00:08:48 +02:00
lilleman 0721bd13e8 Answer security round 4: in the architecture round 4 commit, turn off signature checks and each transport by name in every hook git call, since the checkout's own config may allow one 2026-10-13 00:03:36 +02:00
lilleman 95fb95350b Answer architecture round 4: fail rule-hook overrides when the branch's reflog cannot be read or does not hold HEAD, so a git error never reads as a clean review 2026-10-13 00:03:36 +02:00
lilleman 6dff757ff4 Answer security round 3: in the architecture round 3 commit, run every hook git call with no lazy fetch and no transport, so a partial clone's config runs no program 2026-10-12 23:53:46 +02:00
lilleman e560a74445 Answer architecture round 3: list an override only when the current branch's reflog holds its commit, so no sibling or squash-merged branch's override returns, open the log without blocking on a FIFO, and unpack the call's breaches by name 2026-10-12 23:53:46 +02:00
lilleman 6a054159ae Answer security round 2: in the architecture round 2 commit, hash todo.md and its index entry so no git status runs a planted clean filter, and open the override log with no symlink followed 2026-10-12 23:50:41 +02:00
lilleman 11e613d083 Answer architecture round 2: list an override by its branch or by a commit the default branch lacks, so an amend or a rebase hides none, split main into reading, judging and answering, move the hook input into call.py, strip comments with one pattern, and log overrides only once each can be 2026-10-12 23:50:41 +02:00
lilleman f3bfff1af4 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 2026-10-12 23:45:36 +02:00
lilleman 7cf4f54c90 Answer prose round 1: name the override reviewer apart from loop-claude's judge, list the override forms, and say each rule as it holds 2026-10-12 23:29:02 +02:00
lilleman cf9f6b9e7a Answer product-owner round 2: in the stability round 3 commit, a Markdown file is told the HTML-comment override, the todo rule says any change waits on --check, and each malformed override is named 2026-10-12 23:26:07 +02:00
lilleman 0292c1a55c Answer stability round 3: an empty argument separates no command, and two overrides on one line are read apart 2026-10-12 23:26:07 +02:00
lilleman 5c306fdd51 Answer product-owner round 1: in 2d3f3ad, a judge rules each override once and asks when a rule cannot be kept, block messages name the accepted pins and the sort order, a change to todo.md before git add is checked, a malformed override is named, Markdown takes an HTML-comment override, and help states what the file rules see 2026-10-12 23:21:03 +02:00
lilleman 2d3f3adebc Answer stability round 2: keep the line break that ends a heredoc, read a run of separators as one, check every untagged compose image, and reject a non-object tool input 2026-10-12 23:20:57 +02:00
lilleman 2f2a770392 Answer stability round 1: sort imports, share rank_todo's check, scope YAML to compose and workflows, judge only newly unsorted ignore blocks, cut heredoc bodies, check COPY --from and container:, log what each override let through, keep CLAUDE.md lines for what the hook cannot see 2026-10-12 23:15:49 +02:00
lilleman 3ef8c196cd Answer security round 1: no finding 2026-10-12 23:15:49 +02:00
lilleman 39437cef6a Enforce the checkable rules in a hook, with one override marker a judge rules on, and drop them from CLAUDE.md 2026-10-12 23:06:23 +02:00
lilleman 50a98c2262 Merge pull request 'Plan 0.1.0 as the CLAUDE.md router, the hook-enforced rules, the narrower reviewers and the measured scoring, and move every other item one release later' (#240) from plan-harness-rework into main 2026-10-12 22:54:29 +02:00
lilleman 37dfa0fd5a Answer prose round 1: the floor entry says what each release holds, an override goes in the PR body, item 97's tagline states its purpose, and items 95, 96, 98 and 99 read in one pass 2026-10-12 22:54:06 +02:00
lilleman fcdc008977 Bring items 87 and 98 into 0.1.0, fold item 86 into 95, have a judge rule on overrides, narrow later review rounds, and file item 99 to drop the comprehension gate 2026-10-12 22:49:06 +02:00
lilleman 569456f24e Plan 0.1.0 as the CLAUDE.md router, the hook-enforced rules and the narrower reviewers, and move every other item one release later 2026-10-12 22:36:24 +02:00
lilleman 346f56b193 Merge pull request 'Ship task routing in 0.1.0, and move every other item one release later' (#239) from release-shift into main 2026-10-12 21:37:33 +02:00
lilleman 201aa02c3e Answer prose round 1: item 62's detail drops its release, and the floor entry's dated sentence names which merge waits 2026-10-12 21:37:32 +02:00
lilleman 87287dcb71 Ship task routing in 0.1.0, and move every other item one release later 2026-10-12 21:36:34 +02:00
lilleman 9e64f834df Merge pull request 'Plan a token and routing review every 20th cycle across all projects' (#238) from plan-token-review into main 2026-10-12 21:31:03 +02:00
lilleman f8fbf3a4d4 Answer prose round 1: a shorter tagline, the item's own filing flow, a named interrupt condition, and tokens split by project 2026-10-12 21:31:01 +02:00
lilleman e7c505bf60 Plan a token and routing review every 20th cycle across all projects 2026-10-12 21:29:50 +02:00
lilleman fe5a6a4391 Merge pull request 'Plan task routing: a complexity score per item, one model-and-effort ladder, and routes for the judge, reviewers, worker and subagents' (#237) from plan-routing into main 2026-10-12 21:04:02 +02:00
lilleman e5c5970915 Answer prose round 1: one ladder holds every project's model, R + C names its scorer for the judge and subagents, stepping down is item 93, and item 92 compares its figures as measured 2026-10-12 21:03:52 +02:00
lilleman dcd4dad0eb Plan task routing: a complexity score per item, one model-and-effort ladder, and routes for the judge, reviewers, worker and subagents 2026-10-12 21:02:06 +02:00
lilleman 1ce34e2084 Merge pull request 'Let a project decision opt out of the architect, the product-owner pass or the comprehension check' (#236) from pass-opt-out into main 2026-10-11 20:59:39 +02:00
lilleman 996e33d550 Answer prose round 1: the opt-out reads as labelled bullets, its pointers name where it sits, the closing chunk removes the comprehension check from the entry, CLAUDE.md keeps its measurement sentence, and the decision argues for all three reviewers without naming the research repo 2026-10-11 20:58:11 +02:00
lilleman d31cec5118 Answer product-owner round 3: no findings 2026-10-11 20:56:22 +02:00
lilleman 86fda17c88 Answer product-owner round 2: the chunk ending an opt-out runs a scoring run alone, an opt-out names no ending item, and CLAUDE.md's measurement qualifier names the comprehension check 2026-10-11 20:56:03 +02:00
lilleman 1ee4bdbcdb Answer product-owner round 1: an opt-out is an entry titled review opt-out:, it ends with a chunk shipping an item naming the floor, a 🔀 cannot reach an opted-out reviewer, and CLAUDE.md's measurement and floor guarantees name the opt-out 2026-10-11 20:55:18 +02:00
lilleman a1dff580c5 Let a project decision opt out of the architect, the product-owner pass or the comprehension check 2026-10-11 20:53:22 +02:00
lilleman e149e70608 Merge pull request 'Goals state aim and intent; how a goal is met goes in a method section below them' (#235) from goals-state-aim into main 2026-10-11 12:26:26 +02:00
lilleman 229a77ddcb Answer prose round 1: define a step of the work by example, and file the cited sections' findings as item 86 2026-10-11 12:25:17 +02:00
lilleman fee0422a0d Answer product-owner round 3: no findings 2026-10-11 12:24:11 +02:00
lilleman db459982ee Answer product-owner round 2: keep standing choices out of the method section, drop the repeated ban on steps, and say met as the README section does 2026-10-11 12:23:53 +02:00
lilleman 6f8d9aacd5 Answer product-owner round 1: ban working steps in goals outright, tie the examples to the method section, and say what changed in the changelog 2026-10-11 12:23:23 +02:00
lilleman 9b219c402e Goals state aim and intent; methods and standing rules go below them 2026-10-11 12:22:22 +02:00
lilleman 4cc9953836 Merge pull request 'Group bin/ by tool, and lift its comprehension scores towards the floor' (#234) from floor-restructure into main 2026-10-09 15:23:55 +02:00
26 changed files with 1147 additions and 90 deletions
+4
View File
@@ -40,6 +40,10 @@
!bin/reading_cost/*.py
!bin/repo_checks/
!bin/repo_checks/*.py
!bin/rule-hook
!bin/rule_hook/
!bin/rule_hook/*.py
!bin/shell_command.py
!bin/statusline.py
!bin/test_*.py
!bin/todo_table.py
+3 -1
View File
@@ -8,12 +8,13 @@ Decisions live in `docs/decisions.md`:
- loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
- bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
- bin/: the tools and their tests run on the host's Python, with no container
- comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it
- comprehension floor: every dimension and the overall at 7.0 or above, and 0.3.0 waits on it
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
- review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human
- review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose trigger names fixes like it; a fix for a 🟢, a ❓ or a prose finding reruns none
- review: a paired ruling against the last measured commit decides the ratchet, and counts as worse when a dimension it rules fallen is under the floor; the four-seat scoring run checks the floor when a release's items run out or an item names the floor, and also runs when a ruling names a fallen dimension
- review: a project decision may suspend the comprehension check for the plan items it names
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check
- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
- loop-claude: a `claude` that cannot start is a failed worker run, retried
@@ -27,6 +28,7 @@ Decisions live in `docs/decisions.md`:
- todo.md: one table of items scored by the formula and goal weights it states, held to its bar, ranked by `bin/rank_todo.py`
- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
- rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides one, and larv-review's overrides pass rules on each override before merge
## Working rules
+3
View File
@@ -2,6 +2,9 @@
## 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's new overrides pass, run before stability, accepts or rejects each override the chunk logged, and the PR body lists each with its ruling; a rejected override means the chunk keeps the rule. An override that touches a credential, a security rule or a production system, or cannot be undone, is asked of you.
- A project may opt out of larv-review's architect, product-owner pass or comprehension check in every chunk, through a `docs/decisions.md` entry titled `review opt-out: …` that names the goal that skipping them serves. A project without such an entry is reviewed as before. Opting out of the comprehension check also skips the scoring run due at a release's end, so the floor blocks nothing; the opt-out ends with a chunk that ships a plan item naming the floor, which removes the comprehension check from the entry. The principles audit always runs.
- A README goal states the project's aim and intent, and no longer names a step of the work, such as "kill weak candidates early". Such steps go in a method section further down the README and name the goal they serve.
- The stability reviewer keeps its scratch work in a directory it creates for the run, deletes that directory afterwards, and deletes nothing else.
- larv-review's mechanical rules run in the new, tested `bin/larv-review`: the paired ruling's base (`ruling-base`), each pass's round count (`round-count`, which ignores case in a round's commit title, counts a repeated round number as a round of its own, and says to ask you before another round once a pass is at or past the cap), the scoring run's trigger (`needs-scoring-run <item ID>...`), and the vote count, means and history format (`record-ruling <votes file> [<scores file>]` and `record-scoring <scores file> [<item ID>...]`, which append to `docs/comprehension-history.md` and refuse a second entry on what a seats file's first line reads; `record-scoring` refuses a run the plan does not call, and prints `Floor:` naming each mean under the floor). The skill says when to run each and what its answer means. A seats file line the tool cannot read fails the run, so a mistyped vote never counts as same. The base search compares the history before and after each merged change, so it no longer depends on how a line is worded, and orders a change's rulings by their headings' times. A release whose last plan item moves to another release is due a scoring run too, once work has landed towards it. A seats file must name commits the checkout holds. When origin cannot be fetched, the tool reads it as last fetched and says so.
- The new `bin/metric-bench` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest: cognitive complexity, length, shared state and change spread, each scored by how well it ranks the named functions above the rest. No metric enters review yet.
+6 -7
View File
@@ -5,7 +5,7 @@
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
- **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count.
- **Goals** are the project's aims, not promises: one numbered line each, like slogans, in priority order; a sub-goal is indented under its goal — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves.
- **Goals** state the project's aim and intent, not promises: one numbered line each, like slogans, in priority order; a sub-goal is indented under its goal — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal names no step of the work, such as a check to run first, and rarely an implementation. How a goal is met goes in a method section further down the README and names the goal it serves. BANNED as a goal: `Kill weak candidates early, with the cheap checks first.` GOOD: the goal `Keep research on a budget, so it scales in both time and cost.`, with the cheap checks moved to the method section, naming that goal.
- **Audience** names who depends on the project and what they may rely on.
- **Plan `todo.md` as one scored table**, per "Todo items": every item names the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it.
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
@@ -21,7 +21,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
### Todo items (`todo.md`, tickets, plans)
- **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. Cite an item by its ID. The formula, bar and weights are the project's own to tune.
- **Score an item when it is filed or edited, then run `rank_todo.py`.** Each of R, S, A and G is a whole number from 1 to 10:
- **Score an item when it is filed or edited.** Each of R, S, A and G is a whole number from 1 to 10:
- **R** — the risk that the change creates serious bugs or issues.
- **S** — the size of the change.
- **A** — its value to the audience in `README.md` → `## Audience`.
@@ -37,7 +37,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
Quality is proven by review. Every change is reviewed as a diff. The whole project is measured when a change carries an architectural decision, and before each release, because a project can drift from the principles one clean diff at a time. `larv-review` §3 says which review runs when. Quality has three parts. When two pull against each other, the earlier one wins.
1. **Correct.** The work does what the goals and the plan say, and tests prove it.
2. **True to the technical principles** (`~/.claude/principles/technical-principles.md`). The `comprehension-panel` skill measures KISS in `larv-review`'s comprehension check (§3 → "Architecture"), which a project decision may suspend, unlike any other review. **Comprehension never falls:** when readers comparing the chunk with the last commit the panel scored or ruled better rule that it reads worse, improve what they named and rule again. After three such rounds, stop and ask the human. At a release's end, or for an item naming it, a score under the comprehension floor blocks a merge.
2. **True to the technical principles** (`~/.claude/principles/technical-principles.md`). The `comprehension-panel` skill measures KISS in `larv-review`'s comprehension check (§3 → "Architecture"), which a project decision may suspend or opt out of. **Comprehension never falls:** when readers comparing the chunk with the last commit the panel scored or ruled better rule that it reads worse, improve what they named and rule again. After three such rounds, stop and ask the human. At a release's end, or for an item naming it, a score under the comprehension floor blocks a merge.
3. **Plainly written**, per "Prose".
## Prose
@@ -117,9 +117,8 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`,
- Tear down test containers after a run.
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create.
- Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match").
- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first.
- Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds.
- Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.)
- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows and line-based file lists. Exception: `id` goes first.
- Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest, a `docker run` line or a file a Bash command writes, pin a container image to its full patch version and a GitHub Action to a semver tag.
## Naming files & folders
- Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`.
@@ -130,7 +129,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`,
The rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before writing, designing or reviewing code.
## Git, commits, and PRs
- Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else.
- Mark no commit, PR, issue comment or file as the work of Claude, Anthropic or an agent.
- Commit message and PR title: **one line**, prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context.
- PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title).
- When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it.
+2 -1
View File
@@ -72,11 +72,12 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Bash, Edit, MultiEdit and Write call, and `rule-hook --help` states the rules and the override.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'`
`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
+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 each rule and its stated exceptions in `~/.claude/bin/rule_hook/rules.py` → `RULES`, how an override is written and logged in the docstring of `~/.claude/bin/rule_hook/main.py`, and the project's `README.md` → "Goals" and "Audience".
For each override:
- **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
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)
+18 -1
View File
@@ -91,6 +91,11 @@ def main(argv: list[str]) -> int:
if isinstance(args, Failure):
return fail(args)
check, todo = args
if check:
failures = check_failures(todo)
for line in failures:
print(line, file=sys.stderr)
return 1 if failures else 0
texts = read_all(todo)
if isinstance(texts, Failure):
return fail(texts)
@@ -98,7 +103,7 @@ def main(argv: list[str]) -> int:
if isinstance(ranked, Failure):
return fail(ranked)
if ranked.text != texts[0]:
unwritten = Failure(f"{todo}: not ranked; run rank_todo.py on it") if check else write(todo, ranked.text)
unwritten = write(todo, ranked.text)
if unwritten:
return fail(unwritten)
for line in ranked.under_bar:
@@ -106,6 +111,18 @@ def main(argv: list[str]) -> int:
return 1 if ranked.under_bar else 0
def check_failures(todo: pathlib.Path) -> list[str]:
"""Why --check fails on todo, empty when it passes."""
texts = read_all(todo)
if isinstance(texts, Failure):
return [texts.reason]
ranked = rank(*texts)
if isinstance(ranked, Failure):
return [ranked.reason]
unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"]
return unranked + [f"{todo}: {line}" for line in ranked.under_bar]
def fail(failure: Failure) -> int:
print(failure.reason, file=sys.stderr)
return 1
+2 -1
View File
@@ -3,7 +3,8 @@ import dataclasses
import re
from claude_code.entries import assistant_parts, parse_entry, tool_call
from reading_cost.shell_reads import Reads, resolved, shell_reads
from reading_cost.shell_reads import Reads, shell_reads
from shell_command import resolved
COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b")
+5 -46
View File
@@ -2,8 +2,8 @@
import dataclasses
import posixpath
import re
import shlex
import typing
from shell_command import resolved, simple_commands
NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$")
# Their first operand is a pattern or a program, unless -e or -f gives it.
@@ -21,49 +21,12 @@ class Reads:
def shell_reads(command: str, cwd: str, home: str) -> Reads:
read: list[str] = []
added: list[str] = []
base = cwd
for tokens in shell_lines(command):
for words in segments(tokens):
if words[0] == "cd" and len(words) == 2:
base = resolved(base, words[1], home)
read += [resolved(base, word, home) for word in operands(words)]
added += [resolved(base, path, home) for path in worktree_added(words)]
for simple in simple_commands(command, cwd, home):
read += [resolved(simple.directory, word, home) for word in operands(simple.words)]
added += [resolved(simple.directory, path, home) for path in worktree_added(simple.words)]
return Reads(read, added)
def shell_lines(command: str) -> typing.Iterator[list[str]]:
"""Each line's tokens, skipping a heredoc's body, which feeds a program."""
ends = None
for line in command.splitlines():
if ends is not None:
ends = None if line.strip() == ends else ends
continue
try:
lexer = shlex.shlex(line, posix=True, punctuation_chars=True)
lexer.whitespace_split = True
tokens = list(lexer)
except ValueError:
continue
# The lexer splits <<-EOF into << and -EOF.
ends = next((tokens[index + 1].removeprefix("-") for index, token in enumerate(tokens[:-1]) if token == "<<"), None)
yield tokens
def segments(tokens: list[str]) -> list[list[str]]:
found: list[list[str]] = [[]]
target = False
for token in tokens:
if target:
target = False
elif all(char in "();<>|&" for char in token):
# A redirect's target is not an operand, so it does not count as a read.
target = "<" in token or ">" in token
found.append([])
else:
found[-1].append(token)
return [words for words in found if words]
def operands(words: list[str]) -> list[str]:
program = posixpath.basename(words[0])
if program not in READERS or (program == "sed" and any(word.startswith("-i") for word in words)):
@@ -85,7 +48,3 @@ def worktree_added(words: list[str]) -> list[str]:
elif not word.startswith("-"):
return [word]
return []
def resolved(base: str, path: str, home: str) -> str:
return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path))
+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`")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line")
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-p", "rule_hook", "-m", "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)
Executable
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from rule_hook import main
sys.exit(main.main(sys.argv[1:], "" if sys.argv[1:] or sys.stdin.isatty() else sys.stdin.read()))
View File
+40
View File
@@ -0,0 +1,40 @@
import dataclasses
import typing
from failure import Failure
FILE_TOOLS = ("Edit", "MultiEdit", "Write")
@dataclasses.dataclass(frozen=True)
class Call:
tool: str
given: dict[str, typing.Any]
cwd: str
def parsed_call(hook_input: object) -> Call | Failure:
if not isinstance(hook_input, dict):
return Failure("the hook input is no object")
tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd")
if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str):
return Failure("the hook input has no string tool_name and cwd and object tool_input")
return Call(tool, given, cwd)
def text(given: dict[str, typing.Any], key: str) -> str:
value = given.get(key)
return value if isinstance(value, str) else ""
def applied(call: Call, before: str) -> tuple[str, str]:
"""The text a file call writes, and the whole file it leaves."""
if call.tool == "Write":
content = text(call.given, "content")
return content, content
edits = [call.given] if call.tool == "Edit" else [edit for edit in call.given.get("edits") or [] if isinstance(edit, dict)]
after = before
for edit in edits:
old, new = text(edit, "old_string"), text(edit, "new_string")
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1)
return "\n".join(text(edit, "new_string") for edit in edits), after
+24
View File
@@ -0,0 +1,24 @@
import os
import pathlib
import subprocess
from failure import Failure
# A -c given here outranks the checkout's own config, which may allow one transport by name; GIT_NO_LAZY_FETCH needs git 2.44.
GUARDS = [option for setting in ["core.fsmonitor=false", "log.showSignature=false", "protocol.allow=never", *(f"protocol.{name}.allow=never" for name in ("ext", "file", "git", "http", "https", "ssh"))] for option in ("-c", setting)]
def git(directory: str, *args: str) -> str | Failure:
# The hook runs git in a checkout the call has not yet been allowed to touch, whose config could name a program: no fsmonitor, no signature check, and no fetch of a partial clone's missing objects through its transport.
try:
ran = subprocess.run(["git", *GUARDS, "-C", directory, *args], capture_output=True, env={**os.environ, "GIT_NO_LAZY_FETCH": "1"}, text=True)
except OSError as failure:
return Failure(f"git could not start: {failure}")
return ran.stdout.strip() if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
def existing(directory: str) -> str:
path = pathlib.Path(directory or ".").absolute()
while not path.is_dir():
path = path.parent
return str(path)
+108
View File
@@ -0,0 +1,108 @@
"""Block a Claude Code tool call that breaks a checkable rule, unless the call overrides the rule.
usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin)
rule-hook overrides (prints this chunk's overrides)
settings.json runs it before each Bash, Edit, MultiEdit and Write call, in every session and
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> -->`
Each override that let a call through is appended to rule-overrides.tsv in the git directory of
the checkout it touched: UTC time, branch, the commit checked out, rule, reason, and the file
written or the command's first line. An override outside any git checkout is not logged.
`rule-hook overrides` prints the lines whose commit the current branch's reflog holds: those the
default branch lacks, and those logged under the branch's own name.
Run with no arguments in a terminal, it prints this help.
Exit 2 with the rule, why it holds and how to override it, when a rule blocks the call, or when an
override cannot be logged; 0 otherwise. `rule-hook overrides` exits 1 when git cannot read the
checkout or the branch's reflog. Exit 1, a non-blocking error to Claude Code, on input it
cannot read.
"""
import json
import os
import pathlib
import sys
import time
from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
from rule_hook.rules import Breach, command_breaches, commits, file_breaches, rules_help, verdict, Verdict
from failure import Failure
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
from shell_command import simple_commands
from rule_hook.todo_check import todo_breaches
def main(argv: list[str], stdin: str) -> int:
if argv in (["-h"], ["--help"]) or not argv and not stdin:
print(__doc__.strip().replace("{rules}", rules_help()))
return 0
if argv == ["overrides"]:
return print_overrides(os.getcwd())
if argv:
print(f"unknown arguments: {' '.join(argv)}; see rule-hook --help", file=sys.stderr)
return 1
try:
call = parsed_call(json.loads(stdin))
except json.JSONDecodeError as failure:
call = Failure(str(failure))
if isinstance(call, Failure):
print(f"rule-hook cannot read the hook input: {call.reason}", file=sys.stderr)
return 1
found = breaches_of(call, os.path.expanduser("~"))
if found is None:
return 0
written, what, breaches = found
return answer(verdict(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), what, time.time())
def breaches_of(call: Call, home: str) -> tuple[str, str, list[Breach]] | None:
"""The text that may carry an override, what the log names the call by, and its breaches; None for a call no rule checks."""
if call.tool == "Bash":
command = text(call.given, "command")
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home)
path = text(call.given, "file_path")
if call.tool not in FILE_TOOLS or not path:
return None
before = read(path)
added, after = applied(call, before)
return added, path, file_breaches(path, before, added, after)
def answer(judged: Verdict, what: str, now: float) -> int:
for message in judged.messages:
print(message, file=sys.stderr)
if judged.blocked:
return 2
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in judged.overridden]
# Resolve every log before writing any, so a call that ends blocked has logged nothing.
unloggable = [f"{breach.rule}: {log.reason}" for breach, _, log in logs if isinstance(log, Failure)]
if not unloggable:
for breach, reason, log in logs:
unwritten = write_override(log, logged(log, breach, reason, what, now)) if isinstance(log, Log) else None
unloggable += [f"{breach.rule}: {unwritten.reason}"] if unwritten else []
for unlogged in unloggable:
print(f"rule-hook cannot log the override of {unlogged}; unlogged, it would escape review.", file=sys.stderr)
return 2 if unloggable else 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 read(path: str) -> str:
try:
return pathlib.Path(path).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return ""
+115
View File
@@ -0,0 +1,115 @@
import dataclasses
import os
import pathlib
import stat
import sys
import typing
from rule_hook.rules import Breach
from failure import Failure
from rule_hook.git import existing, git
from utc_stamp import utc
LOG = "rule-overrides.tsv"
@dataclasses.dataclass(frozen=True)
class Entry:
"""One line of the log, its fields tab-separated in this order."""
at: str
branch: str
# The commit checked out when the override let its call through; empty on a branch with no commit yet.
commit: str
rule: str
reason: str
what: str
def line(self) -> str:
return "\t".join(" ".join(field.split()) for field in dataclasses.astuple(self)) + "\n"
def parsed_entry(line: str) -> Entry | None:
fields = line.rstrip("\n").split("\t")
return Entry(*fields) if len(fields) == len(dataclasses.fields(Entry)) else None
def this_chunks(entry: Entry, reflog: set[str], branch: str, on_default: typing.Callable[[str], bool]) -> bool:
"""Whether the override is the current branch's: its commit is in the branch's reflog, which keeps a commit an amend or a rebase replaced, follows `git branch -m`, and holds no other branch's commit."""
if entry.commit == "":
return True
# The default branch's commits are in every branch's reflog, so such a line counts only under the branch's own name: one logged before the branch's first commit.
return entry.commit in reflog and (entry.branch == branch or not on_default(entry.commit))
@dataclasses.dataclass(frozen=True)
class Log:
path: pathlib.Path
branch: str
head: str
def log_path(directory: str) -> Log | Failure | None:
"""Where an override in this directory is logged; None outside any git checkout."""
directory = existing(directory)
if not any((parent / ".git").exists() for parent in [pathlib.Path(directory), *pathlib.Path(directory).parents]):
return None
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
branch = git(directory, "branch", "--show-current")
for found in (common, branch):
if isinstance(found, Failure):
return found
head = git(directory, "rev-parse", "--verify", "--quiet", "HEAD")
return Log(pathlib.Path(str(common)) / LOG, str(branch) or "HEAD", "" if isinstance(head, Failure) else head)
def write_override(log: Log, entry: Entry) -> Failure | None:
try:
# No symlink, and no FIFO to hang on: the checkout, and so its git directory, may come from anyone.
descriptor = os.open(log.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
except OSError as failure:
return Failure(str(failure))
try:
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
return Failure(f"{log.path} is no regular file")
os.write(descriptor, entry.line().encode("utf-8"))
except OSError as failure:
return Failure(str(failure))
finally:
os.close(descriptor)
return None
def logged(log: Log, breach: Breach, reason: str, what: str, now: float) -> Entry:
return Entry(utc(now), log.branch, log.head, breach.rule, reason, what)
def print_overrides(directory: str) -> int:
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
if isinstance(common, Failure):
print(f"rule-hook overrides runs in a git checkout: {common.reason}", file=sys.stderr)
return 1
found = git(directory, "branch", "--show-current")
branch = found if isinstance(found, str) and found else "HEAD"
reflog = git(directory, "reflog", "show", "--format=%H", branch)
head = git(directory, "rev-parse", "HEAD")
# A reflog missing HEAD is off or expired, and would hide this chunk's overrides.
unread = reflog if isinstance(reflog, Failure) else head if isinstance(head, Failure) else None if head in reflog.split() else Failure("it does not hold HEAD")
if unread:
print(f"rule-hook overrides cannot read the branch's reflog, so it cannot tell which overrides are this chunk's: {unread.reason}", file=sys.stderr)
return 1
default = default_branch(directory)
log = pathlib.Path(common) / LOG
entries = [parsed_entry(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.is_file() else []
on_default = (lambda commit: holds(directory, default, commit)) if default else (lambda commit: False)
for entry in entries:
if entry and this_chunks(entry, set(str(reflog).split()), branch, on_default):
print(entry.line(), end="")
return 0
def default_branch(directory: str) -> str | None:
return next((name for name in ("origin/HEAD", "main", "master") if not isinstance(git(directory, "rev-parse", "--verify", "--quiet", name), Failure)), None)
def holds(directory: str, descendant: str, ancestor: str) -> bool:
return bool(ancestor) and not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)
+218
View File
@@ -0,0 +1,218 @@
import dataclasses
import posixpath
import re
import typing
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.
ATTRIBUTION = re.compile(r"co-authored[-]by:[^\n]*\b(?:claude|anthropic)\b|generated with \[?claude code", re.IGNORECASE)
SEMVER = re.compile(r"v?\d+(?:\.\d+){0,2}")
# Two-part tags such as postgres:16.4 stay blocked: the rule bans node:24.18, which reads the same, so such an image takes an override.
PATCH = re.compile(r"v?\d+\.\d+\.\d+(?:[-+_.].*)?|.*\d{8}.*")
FROM = re.compile(r"^[ \t]*FROM[ \t]+(?:--\S+[ \t]+)*(\S+)(?:[ \t]+AS[ \t]+(\S+))?", re.IGNORECASE | re.MULTILINE)
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)
class Breach:
rule: RuleName
detail: str
# The checkout whose log records an override of this breach.
directory: str
@dataclasses.dataclass(frozen=True)
class Commit:
directory: str
messages: list[str]
from_file: bool
@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 overrides(written: str) -> tuple[dict[str, str], list[str]]:
"""The rules the text overrides with their reasons, and the markers that name no rule or give no reason."""
given = [(rule, reason.strip().removesuffix("-->").strip()) for rule, reason in OVERRIDE.findall(written)]
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 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(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
def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]:
breaches = []
found = commits(simples, home)
publishing = [simple for simple in simples if simple.words[0] in ("gh", "git", "tea")]
if publishing and ATTRIBUTION.search(command):
breaches.append(Breach("no-ai-attribution", "the command carries an attribution", publishing[0].directory))
for commit in found:
if commit.from_file:
breaches.append(Breach("commit-one-line", "pass the message as one -m '<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", commit.directory))
return breaches
def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
"""Breaches in an edit of path: added is the text the edit writes, after the whole file it leaves."""
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} | {"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:
if "$" in image or "{{" in image or "@sha256:" in image:
return True
tail = image.rsplit("/", 1)[-1]
return ":" in tail and PATCH.fullmatch(tail.split(":", 1)[1]) is not None
def tagged(action: str) -> bool:
if action.startswith(("./", "docker://")) or "$" in action or "{{" in action:
return True
return "@" in action and SEMVER.fullmatch(action.rsplit("@", 1)[1]) is not None
def blocks(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 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())
+278
View File
@@ -0,0 +1,278 @@
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from rule_hook.rules import blocks, Breach, command_breaches, Commit, commit_message, commits, file_breaches, overrides, verdict
from test_rank_todo import DECISIONS, README, TODO
from rule_hook.override_log import Entry, parsed_entry, this_chunks
from test_env import isolated_env
from shell_command import simple_commands
HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook"
# Built from parts, so this file carries no attribution of its own.
TRAILER = "Co-Authored-" + "By: Claude <noreply@anthropic.com>"
def rules(breaches: list[Breach]) -> list[str]:
return [breach.rule for breach in breaches]
def committed(command: str, cwd: str = "/r") -> list[Commit]:
return commits(simple_commands(command, cwd, "/h"), "/h")
def checked(command: str) -> list[str]:
return rules(command_breaches(command, simple_commands(command, "/r", "/h"), "/h"))
def hook(call: dict, cwd: str) -> subprocess.CompletedProcess:
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env(), input=json.dumps(call), text=True)
def git(cwd: str, *args: str) -> str:
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=cwd, env=isolated_env(), text=True).stdout
class Commits(unittest.TestCase):
def test_cd_and_dash_capital_c_move_the_commit(self):
self.assertEqual(committed("cd a && git -C ~/b commit -am 'x'"), [Commit("/h/b", ["x"], False)])
self.assertEqual(committed("cd a && git -c x=y -C b commit -m x")[0].directory, "/r/a/b")
def test_each_message_spelling_is_read(self):
self.assertEqual(commit_message(["--message=a", "-m", "b=c", "--message", "c", "-mz", "-am", "d"]), (["a", "b=c", "c", "z", "d"], False))
def test_a_file_message_is_seen(self):
self.assertEqual(commit_message(["-F", "-"]), ([], True))
self.assertEqual(commit_message(["--file=x"]), ([], True))
def test_other_git_commands_are_no_commit(self):
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):
self.assertEqual(len(committed("cat <<EOF > notes\nhello\nEOF\ngit commit -m a")), 1)
self.assertEqual(len(committed("git status &&\n\ngit commit -m a")), 1)
def test_an_arithmetic_shift_is_no_heredoc(self):
self.assertEqual(len(committed("echo $((1<<2))\ngit commit -m a\n2")), 1)
def test_a_line_that_does_not_parse_hides_only_itself(self):
self.assertEqual(len(committed("echo 'open\ngit commit -m a")), 1)
class CommandBreaches(unittest.TestCase):
def test_one_line_passes(self):
self.assertEqual(checked("git add . && git commit -m 'ABC-1 - Fix #2'"), [])
def test_a_heredoc_a_second_message_or_a_file_breaks_commit_one_line(self):
for command in ["git commit -m \"$(cat <<'EOF'\nIt's one line\nEOF\n)\"", "git commit -m a -m b", "git commit -F - <<'EOF'\nTitle\n\nIt's the body\nEOF\necho done", "git commit --author '' -m a -m b"]:
with self.subTest(command):
self.assertEqual(checked(command), ["commit-one-line"])
def test_an_attribution_breaks_only_in_a_git_gh_or_tea_command(self):
self.assertEqual(checked(f"tea pr create --description '{TRAILER}'"), ["no-ai-attribution"])
self.assertEqual(checked(f"grep -rn '{TRAILER}' ."), [])
def test_a_commit_breach_names_the_commit_s_checkout(self):
self.assertEqual(command_breaches("cd w && git commit -m a -m b", simple_commands("cd w && git commit -m a -m b", "/r", "/h"), "/h")[0].directory, "/r/w")
class FileBreaches(unittest.TestCase):
def test_an_image_needs_a_patch_version_a_date_or_a_digest(self):
added = "FROM node:24 AS build\nFROM node:24.18.1-bookworm-slim\nFROM alpine@sha256:ab\nFROM debian:bookworm-20240926-slim\nFROM build\nFROM scratch\nFROM ${BASE}\nFROM python\nCOPY --from=build /a /a\nCOPY --from=0 /b /b\nCOPY --chown=1 --from=alpine:3 /c /c\n"
self.assertEqual([breach.detail for breach in file_breaches("/r/Dockerfile", "", added, added)], ["/r/Dockerfile: node:24", "/r/Dockerfile: python", "/r/Dockerfile: alpine:3"])
def test_a_stage_named_outside_the_edit_is_no_image(self):
self.assertEqual(file_breaches("app.dockerfile", "FROM node:24.1.0 AS base\n", "FROM base\n", "FROM node:24.1.0 AS base\nFROM base\n"), [])
def test_a_workflow_checks_its_images_and_actions(self):
added = " container: node:24\n image: mysql:8.4\n - image: 'mysql:8.4.7'\n - uses: actions/checkout@v4\n - uses: a/b@0123456789abcdef0123456789abcdef01234567\n - uses: ./local\n"
self.assertEqual(rules(file_breaches("/r/.gitea/workflows/ci.yml", "", added, added)), ["image-pin", "image-pin", "action-pin"])
def test_a_compose_file_checks_its_images(self):
self.assertEqual(rules(file_breaches("compose.yaml", "", " image: redis\n", " image: redis\n")), ["image-pin"])
def test_other_yaml_is_not_checked(self):
added = "image: /assets/og.png\nimage: { type: string }\nuses: a/b@main\n"
self.assertEqual(file_breaches("_config.yml", "", added, added), [])
def test_an_ignore_file_sorts_each_block_split_by_blank_lines_and_comments(self):
self.assertEqual(blocks("b\na\n\n# c\nd\n# e\nf\n"), [["b", "a"], ["d"], ["f"]])
self.assertEqual(rules(file_breaches(".dockerignore", "", "x", "b\na\n")), ["ignorefile-sorted"])
self.assertEqual(file_breaches(".gitignore", "", "x", "*\n\n!a\n!b\n"), [])
def test_a_block_unsorted_before_the_edit_is_left_alone(self):
self.assertEqual(file_breaches(".gitignore", "node_modules\n.env\n\ndist\n", "out", "node_modules\n.env\n\ndist\nout\n"), [])
def test_an_attribution_in_any_file_breaks(self):
self.assertEqual(rules(file_breaches("notes.md", "", TRAILER, TRAILER)), ["no-ai-attribution"])
class Overrides(unittest.TestCase):
def test_a_marker_names_a_known_rule_and_a_reason(self):
self.assertEqual(overrides("x # rule-override image-pin: vendor ships floating tags only\n# rule-override nope: x\n# rule-override action-pin:"), ({"image-pin": "vendor ships floating tags only"}, ["rule-override nope: x", "rule-override action-pin: "]))
def test_two_markers_on_a_line_are_read_apart(self):
self.assertEqual(overrides("git x # rule-override image-pin: a # rule-override nope: b")[1], ["rule-override nope: b"])
def test_markdown_takes_an_html_comment(self):
self.assertEqual(overrides("<!-- 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 OverrideLog(unittest.TestCase):
def test_an_entry_reads_back_as_written(self):
entry = Entry("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor\ttags no patch", "Dockerfile")
self.assertEqual(parsed_entry(entry.line()), Entry("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor tags no patch", "Dockerfile"))
self.assertIsNone(parsed_entry("a\tb"))
def test_an_override_is_the_chunk_s_by_its_reflog_and_name(self):
on_default = {"base"}.__contains__
cases = [("chunk", "c1", True), ("other", "c1", True), ("other", "c9", False), ("chunk", "base", True), ("other", "base", False), ("other", "", True)]
for branch, commit, expected in cases:
with self.subTest(branch=branch, commit=commit):
self.assertEqual(this_chunks(Entry("t", branch, commit, "image-pin", "r", "w"), {"base", "c1"}, "chunk", on_default), expected)
class Hook(unittest.TestCase):
def setUp(self):
self.repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", self.repo])
git(self.repo, "init", "-q", "-b", "main")
git(self.repo, "commit", "-q", "--allow-empty", "-m", "base")
git(self.repo, "checkout", "-q", "-b", "chunk")
def listed(self) -> str:
return subprocess.run([str(HOOK), "overrides"], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout
def test_a_breach_exits_2_naming_the_rule_and_the_override(self):
ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": "FROM node:24\n"}, "tool_name": "Write"}, self.repo)
self.assertEqual(ran.returncode, 2)
self.assertIn("Blocked by rule image-pin: ", ran.stderr)
self.assertIn("`# rule-override image-pin: <reason>`", ran.stderr)
def test_an_override_passes_and_is_listed_for_the_chunk(self):
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/sub/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
self.assertEqual((ran.returncode, ran.stderr), (0, ""))
self.assertRegex(self.listed(), r"^\S+Z\tchunk\t[0-9a-f]{40}\timage-pin\tthe vendor tags no patch versions\t\S+/sub/Dockerfile\n$")
git(self.repo, "checkout", "-q", "main")
git(self.repo, "commit", "-q", "--allow-empty", "-m", "elsewhere")
self.assertEqual(self.listed(), "", "the default branch holds no override of its own")
def test_an_override_outlives_an_amend(self):
git(self.repo, "commit", "-q", "--allow-empty", "-m", "work")
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
git(self.repo, "commit", "-q", "--amend", "--allow-empty", "-m", "reworded")
git(self.repo, "branch", "-m", "renamed")
self.assertIn("\timage-pin\t", self.listed(), "the reflog keeps the amended commit")
def test_an_unreadable_reflog_fails_the_listing(self):
unborn = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", unborn])
git(unborn, "init", "-q", "-b", "chunk")
ran = subprocess.run([str(HOOK), "overrides"], capture_output=True, cwd=unborn, env=isolated_env(), text=True)
self.assertEqual(ran.returncode, 1)
self.assertIn("cannot read the branch's reflog", ran.stderr)
git(self.repo, "reflog", "expire", "--expire=now", "--all")
self.assertEqual(subprocess.run([str(HOOK), "overrides"], capture_output=True, cwd=self.repo, env=isolated_env(), text=True).returncode, 1, "an expired reflog holds no HEAD")
def test_a_sibling_branch_s_override_is_not_listed(self):
git(self.repo, "checkout", "-q", "-b", "sibling")
git(self.repo, "commit", "-q", "--allow-empty", "-m", "sibling work")
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
git(self.repo, "checkout", "-q", "chunk")
self.assertEqual(self.listed(), "")
git(self.repo, "merge", "-q", "--squash", "sibling")
git(self.repo, "commit", "-q", "--allow-empty", "-m", "squashed")
self.assertEqual(self.listed(), "", "a squash merge brings in none of the sibling's commits")
def test_a_blocked_call_logs_no_override(self):
command = f"git commit -m a -m '{TRAILER}' # rule-override no-ai-attribution: quotes it"
self.assertEqual(hook({"cwd": self.repo, "tool_input": {"command": command}, "tool_name": "Bash"}, self.repo).returncode, 2)
self.assertEqual(self.listed(), "")
def test_a_commit_override_is_logged_in_the_commit_s_checkout(self):
outside = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", outside])
ran = hook({"cwd": outside, "tool_input": {"command": f"git -C {self.repo} commit -m a -m b # rule-override commit-one-line: a body is needed"}, "tool_name": "Bash"}, outside)
self.assertEqual(ran.returncode, 0)
self.assertIn("\tcommit-one-line\ta body is needed\t", self.listed())
def test_an_edit_is_judged_on_the_file_it_leaves(self):
pathlib.Path(self.repo, ".gitignore").write_text("a\nc\n")
call = {"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/.gitignore", "new_string": "d", "old_string": "a"}, "tool_name": "Edit"}
self.assertEqual(hook(call, self.repo).returncode, 2)
def test_a_commit_while_an_unranked_todo_has_changes_is_blocked(self):
pathlib.Path(self.repo, "docs").mkdir()
for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]:
pathlib.Path(self.repo, name).write_text(content)
git(self.repo, "add", "README.md", "docs", "todo.md")
git(self.repo, "commit", "-qm", "x", "--no-verify")
call = {"cwd": self.repo, "tool_input": {"command": "git add -A && git commit -m x"}, "tool_name": "Bash"}
self.assertEqual(hook(call, self.repo).returncode, 0, "todo.md is unchanged")
pathlib.Path(self.repo, "todo.md").write_text(TODO + "\n")
ran = hook(call, self.repo)
self.assertEqual(ran.returncode, 2)
self.assertIn("todo.md: not ranked", ran.stderr)
def test_a_staged_todo_change_is_checked_and_no_clean_filter_runs(self):
pathlib.Path(self.repo, "docs").mkdir()
for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO), (".gitattributes", "todo.md filter=planted\n")]:
pathlib.Path(self.repo, name).write_text(content)
git(self.repo, "add", "-A")
git(self.repo, "config", "filter.planted.clean", f"touch {self.repo}/ran; cat")
pathlib.Path(self.repo, "ran").unlink(missing_ok=True)
# A stat-dirty index entry, as extracting an archive leaves, is what makes `git status` re-run the filter.
os.utime(pathlib.Path(self.repo, "todo.md"), (1, 1))
ran = hook({"cwd": self.repo, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}, self.repo)
self.assertEqual(ran.returncode, 2, ran.stderr)
self.assertFalse(pathlib.Path(self.repo, "ran").exists())
def test_a_symlinked_log_is_refused(self):
target = pathlib.Path(self.repo, "elsewhere")
pathlib.Path(self.repo, ".git", "rule-overrides.tsv").symlink_to(target)
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
self.assertEqual(ran.returncode, 2)
self.assertFalse(target.exists())
def test_a_malformed_override_is_named(self):
ran = hook({"cwd": self.repo, "tool_input": {"command": f"git commit -m a -m b -m '{TRAILER}' # rule-override no-ai-attribution: quotes it # rule-override commit-oneline: x"}, "tool_name": "Bash"}, self.repo)
self.assertIn("`rule-override commit-oneline: x` names no rule below", ran.stderr)
def test_a_missing_field_breaks_nothing(self):
for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}, {"edits": [None], "file_path": f"{self.repo}/a.md"}]:
with self.subTest(given):
tool = "Bash" if "command" in given else "Write" if "content" in given else "MultiEdit"
self.assertEqual(hook({"cwd": self.repo, "tool_input": given, "tool_name": tool}, self.repo).returncode, 0)
def test_unreadable_input_does_not_block(self):
for given in ["{", json.dumps({"cwd": ".", "tool_input": None, "tool_name": "Bash"})]:
with self.subTest(given):
self.assertEqual(subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input=given, text=True).returncode, 1)
def test_help_lists_every_rule(self):
helped = subprocess.run([str(HOOK), "--help"], capture_output=True, check=True, env=isolated_env(), text=True).stdout
for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]:
self.assertIn(f" {rule}\n The rule: ", helped)
+25
View File
@@ -0,0 +1,25 @@
import hashlib
import pathlib
from rule_hook.rules import Breach
from failure import Failure
from rule_hook.git import git
import rank_todo
def todo_breaches(directory: str) -> list[Breach]:
top = git(directory, "rev-parse", "--show-toplevel")
if isinstance(top, Failure) or not (pathlib.Path(top) / "todo.md").is_file():
return []
todo = pathlib.Path(top) / "todo.md"
return [Breach("todo-rank-check", line, top) for line in rank_todo.check_failures(todo)] if changed(top, todo) else []
def changed(top: str, todo: pathlib.Path) -> bool:
"""Whether todo.md differs from the index or the index from HEAD: any change, staged or not, since the hook runs before a `git add` earlier in the same command."""
# Hashed here, never by `git status`, which would run a clean filter the checkout's own config names before the call is allowed.
staged, committed = git(top, "rev-parse", ":todo.md"), git(top, "rev-parse", "HEAD:todo.md")
algorithm = git(top, "rev-parse", "--show-object-format")
content = todo.read_bytes()
worktree = hashlib.new("sha1" if isinstance(algorithm, Failure) else algorithm, b"blob %d\0" % len(content) + content).hexdigest()
return isinstance(staged, Failure) or staged != worktree or staged != committed
+68
View File
@@ -0,0 +1,68 @@
"""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();&|<>")
# A quoted string or an escape is taken whole, so a # inside one starts no comment; a comment starts a word.
PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<![^\s;&|()])#[^\n]*""", re.DOTALL)
@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."""
return PIECE.sub(lambda piece: "" if piece.group(0).startswith("#") else piece.group(0), text)
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))
+47
View File
@@ -1128,3 +1128,50 @@ Inherited architect, would restructure first:
- `bin/larv_review/scoring.py:8` `fall_ruling`: a ruling rule in the scoring module
- `bin/claude_code/trust.py:10` `trust`: effects in a package documented as shapes
- `bin/larv_review/git.py:8` `git`: git run five ways
## 2026-10-12T21:36:23Z, PR #241 at 7cf4f54, against 4cc9953
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | same | worse | same | same |
| Inherited architect | same | worse | same | same | same |
Mid A, decided by:
- Shape: `bin/rule_hook/rules.py:140` `file_breaches`: four rules in one function, picked by file-name tests, each a comprehension of three or four conditions
- Shape: `bin/rule_hook/rules.py:86` `git_commit`: a hand-written git argument parser with two index-juggling loops and a nested loop that moves `at`
- Shape: `bin/rule_hook/main.py:1` module docstring: it and `RULES` each describe the six rules in their own words, as do CLAUDE.md, CHANGELOG.md and README.md
- Shape: `bin/rule_hook/main.py:93` `checked_call`: returns a 3-tuple or None, and its name hides that it replays a MultiEdit's edits
Inherited architect, decided by:
- Locality: `skills/larv-review/SKILL.md:58` "Opt-out": an opted-out chunk skips a scoring run `larv-review needs-scoring-run` still calls due, and "End" adds a third kind of run
- Locality: `bin/rule_hook/main.py:76` `main`: logs each granted override before it knows whether another rule still blocks the call, into an unversioned log keyed by branch name and never pruned
- Locality: `bin/rule_hook/main.py:115` `todo_breaches`: the hook imports `rank_todo.check_failures`, so editing rank_todo's messages changes what blocks a commit, while README calls rank_todo.py a tool of one file; the rule's logic sits in main.py, apart from the other rules in rules.py
## 2026-10-12T22:10:36Z, PR #241 at 7598584, against 4cc9953
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | same | worse | same | same |
| Inherited architect | same | worse | same | same | same |
Mid A, decided by:
- Shape: `bin/rule_hook/rules.py:8` `RULES`: the module holds the rule table, override parsing and git command-line parsing, while `git.py` only runs git
- Shape: `bin/rule_hook/override_log.py:82` `logged`: builds an Entry though it reads as a yes/no check; `holds` is an ancestry test and `what` says little
- Shape: `bin/rule_hook/main.py:66` `main`: passes `verdict` two bare booleans
- Locality: `bin/shell_command.py:20` `simple_commands`: shorter reading-cost parsing, against a parser change for the hook moving reading-cost figures; the two cancel
- Locality: `bin/rule_hook/main.py:99` `bash_breaches`: parses the command's commits twice
Inherited architect, decided by:
- Locality: `bin/shell_command.py:31` `segments`: one grown parser serves reading-cost and the hook, so tightening it for one moves the other
- Locality: `bin/rule_hook/override_log.py:36` `this_chunks`: chunk membership rests on reflog expiry and a default-branch guess, with three failures in one nested ternary at line 96
- Locality: `bin/rule_hook/main.py:82` `answer`: resolve-then-write order carried by one comment, and `Breach.directory` set deep in rules.py decides which log gets a line
- Locality: `bin/rule_hook/rules.py:108` `git_subcommand`: a second answer to "is this a git commit" beside `measure.py`'s `COMMIT` regex
- Locality: `bin/rule_hook/todo_check.py:7` `import rank_todo`: a change to rank_todo's check changes what the hook blocks
+10 -2
View File
@@ -34,9 +34,9 @@
2026-09-24, larv-review. Serves goals 1 and 2. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run on the same host Python the tools meet. Valid while claude runs on the host.
## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it
## comprehension floor: every dimension and the overall at 7.0 or above, and 0.3.0 waits on it
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. Valid while the scoring run keeps its four seats. The decisions to ship under the floor, listed below, stand until `todo.md` item 62 lifts the project to it.
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. Valid while the scoring run keeps its four seats. The decisions to ship under the floor, listed below, stand until `todo.md` item 62 lifts the project to it. 2026-10-12, lilleman: 0.1.0 holds the CLAUDE.md, hook, reviewer and scoring rework, 0.2.0 the task routing, and item 62 moves to 0.3.0. The chunk that ends 0.1.0 merges under the floor only once lilleman ships it under the floor, listed below.
lilleman decided to ship each of these under the floor on the day listed. Each line gives its last scores (Navigation, Locality, Shape, Self-sufficiency, overall):
@@ -77,6 +77,10 @@ lilleman decided to ship each of these under the floor on the day listed. Each l
2026-10-04, lilleman. Serves goal 1.4. In a restructure, each step's scoring run measures code the next step deletes. It costs a run and, below the floor, blocks the step, yet says nothing about what the restructure buys. The scoring run after the last step measures that. 2026-10-08: the paired ruling replaced the scoring run in most chunks, and the suspension covers it too; the ruling after the last step compares with the commit measured before the first step. Valid while such a decision names its items and the plan item that ends it.
## review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check
2026-10-11, lilleman. Serves goal 1.4. A research repo's PR, in a repo with no consumer for the product-owner pass and no product for the architect, spent rounds of both, and of the comprehension check, on a probe. The opt-out is the project's to make, and only an entry titled `review opt-out:` makes it, so a project without one is reviewed as before (goal 1.3). No opted-out reviewer works against a goal or a technical principle: the principles audit, which has no opt-out, still judges KISS and every other principle, so the entry names no plan item that ends it. An opt-out of the comprehension check ends with a chunk that ships an item naming the floor. That chunk runs a scoring run alone, so no ruling compares against a commit measured before the opt-out. Valid while the principles audit judges every chunk, and while the architect's and the product-owner's findings matter only to a product with consumers.
## review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
2026-09-30, lilleman. Serves goal 1: a decision the chunk writes is the chunk's own and unreviewed, and an unattended run has no human to catch it. Valid while a pass is the only reader of a chunk before merge.
@@ -130,3 +134,7 @@ lilleman decided to ship each of these under the floor on the day listed. Each l
## reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
2026-10-08, lilleman. Serves goal 1.1: comprehension never falls, so any rise counts. Per-chunk figures are noisy: a flat trend rises about every other chunk. So a rise refreshes the item and never refiles it, and a chunk that sees no rise leaves the item as it is. The chunk that ships the item resets the trend, so later figures do not refile it for work that chunk already did (goal 1.4). A median, because one chunk that ran a panel of readers before its first commit measured 2.99M tokens against a typical 80k–370k, and a mean let it decide the trend alone. No published standard sets this threshold. Valid while figures arrive once per chunk.
## rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <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`), which is the target itself here: this repo configures Claude Code. What the tie buys: the hook blocks before a write lands, Edit and Write calls included, in every project with no per-repo install; a git `commit-msg` hook sees only commits, and CI sees them only after the push. The hook checks each write, so the agent fixes the line it just wrote; checking the staged diff at commit time would also cover files a Bash command writes, at the cost of later feedback. The marker's spelling was picked by a panel of three fresh readers, two to one. Each override is logged in the checkout's git directory, which is never pushed (goal 4). The plan had loop-claude's judge to rule on overrides inside a loop; lilleman approved larv-review's overrides pass in every run, because it rules before merge and an outrageous override still reaches the human through its ask. Valid while a PreToolUse hook that exits 2 blocks the call and hands its stderr to the model, and while an agent commits through Claude Code's Bash tool.
+14
View File
@@ -33,6 +33,20 @@
}
}
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Edit|MultiEdit|Write",
"hooks": [
{
"type": "command",
"command": "~/.claude/bin/rule-hook",
"timeout": 30
}
]
}
]
},
"effortLevel": "xhigh",
"modelSettings": {
"claude-fable-5-1": {
+16 -3
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 |
| Full scan | the `claude-security` plugin at high effort: `/claude-security scan this branch's changes at high` | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface |
| Security | `/security-review` | changes code or config, unless the full scan runs on the same change; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto, and the full scan does not rerun on it |
| Overrides | override-reviewer | `~/.claude/bin/rule-hook overrides`, run in the chunk's worktree, prints a line no round of this pass has ruled on; a fix, only where the hook logged an override for it |
| Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour: what the code or its tests do |
| Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on |
| Prose | prose-reviewer | every chunk, one round |
@@ -50,12 +51,20 @@ Give a reviewer without Bash the branch diff and `git ls-files`'s output in its
- **Skip.** A precedent is a `docs/decisions.md` entry, or a plan item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, skip the pass and cite that entry or item.
- **Departure.** A change that departs from the precedent is unreviewed, however thorough the precedent is.
- **Ask.** Fired and not skipped → ask the user whether to run it, with the evidence and your recommendation; no user reachable → run it. For the full scan, give the evidence and your recommendation, then launch it: the plugin asks the user to confirm its cost, and that prompt is the ask.
- **Audit.** A precedent or the user's no skips only the architect, never the principles audit: no precedent checked the code this chunk writes. The comprehension check skips only as "Architecture" → "Suspended" says.
- **Audit.** A precedent or the user's no skips only the architect, never the principles audit: no precedent checked the code this chunk writes. The comprehension check skips only as "Opt-out" or "Architecture" → "Suspended" says.
**Opt-out** — for the architect, the product-owner pass and the comprehension check:
- **Entry.** A project opts out only through a `docs/decisions.md` entry, held before the chunk began, whose title opens `review opt-out:` and names one or more of the three. The entry names the project goal that skipping them serves.
- **Skip.** Every chunk skips each reviewer the entry names, even where its trigger, a 🔀 or a due scoring run calls for it, and the chunk's summary cites the entry. Unlike a suspension, an opt-out needs no plan item to end it.
- **Audit.** An architecture pass left without the architect and the comprehension check still runs the principles audit.
- **Malformed.** A title naming another reviewer, or an entry naming no goal, is a finding of the pass the chunk runs, and the chunk runs every pass its trigger fires.
- **End.** An opt-out of the comprehension check ends with the chunk that ships a plan item naming the floor, and that chunk removes the comprehension check from the entry. It runs the comprehension check as a scoring run alone, with no paired ruling. That scoring run's floor blocks the merge as at a release's end, and the run becomes the base of the next paired ruling.
**Round cap.**
- **Round.** A round is one launch of a pass's reviewer: the first, each re-entry, and the rerun after the architect returns Stage 0 questions ("Architecture" below). A rescore is a round only as "Architecture" → "Fresh" says.
- **Architecture round.** The architecture pass's first round is the architect (unless skipped), the principles audit and the comprehension check, which "Architecture" → "Suspended" may skip. A later round relaunches each reviewer whose 🔴 or 🟡 the previous round's fixes answer, the comprehension check only as "Architecture" → "Fresh" says. Where those fixes carry an architectural decision, the architect and the principles audit run again.
- **Architecture round.** The architecture pass's first round is the architect (unless skipped), the principles audit and the comprehension check, which "Opt-out" or "Architecture" → "Suspended" may skip. A later round relaunches each reviewer whose 🔴 or 🟡 the previous round's fixes answer, the comprehension check only as "Architecture" → "Fresh" says. Where those fixes carry an architectural decision, the architect and the principles audit run again.
- **Auto-reviewer.** The external auto-reviewer (§4) is a pass of its own, each review it posts a round.
- **Count.** Close each round with one commit that holds the round's fixes and is titled `Answer <pass> round <n>: …`, `<pass>` being the pass's name in lower case, such as `full scan`. A round that changed nothing gets an empty commit (`git commit --allow-empty`). Push the commits when §4 runs next, where there is a remote. `~/.claude/bin/larv-review round-count` prints each pass's count and marks a pass at the cap. The auto-reviewer's count is the number of its reviews on the PR, less its reviews of a `Rescore:` commit.
- **Later rounds.** A rerun pass reviews only what changed since it last reviewed: `git diff <the commit it last reviewed, or else the commit before this round's fixes> HEAD`, since the fixes may be unpushed. The comprehension check's seats still read the whole project. From round 2, prompt an agent under `~/.claude/agents/` with its own last round's findings verbatim too.
@@ -129,6 +138,10 @@ Only the user may answer `claude-security`'s cost prompt. `/security-review` or
**Do not over-read a clean result.** `/security-review` is single-repo and static: it does not trace authorization across services, does not run the application, and deliberately excludes dependency CVEs in third-party libraries — Renovate/Dependabot owns those, per `~/.claude/CLAUDE.md` → "Working with the codebase". Never point an automated reviewer or scan at an untrusted fork's PR content; a PR body is untrusted input to it (CVE-2025-59536, CVE-2026-21852).
### Overrides
Launch override-reviewer with each line `rule-hook overrides` prints that no earlier round ruled on, and the branch diff. A rejected override is a 🔴: keep the rule, or ask the user where the reviewer says it cannot be kept. An outrageous override is asked of the user. List each override in the PR body by its rule, its reason and the ruling, never by the command it let through.
### Stability and product-owner
Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code.
@@ -155,4 +168,4 @@ Launch prose-reviewer with what the diff touched and every section this review c
## 6. Wrap up
Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, principles files left out with why, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal or technical principle it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user.
Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, principles files left out with why, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal or technical principle it rests on — CI status, rule overrides with their rulings, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user.
+114 -26
View File
@@ -6,7 +6,7 @@
`Bar = 9`
`Next ID = 86`
`Next ID = 100`
| Goal | W |
|---|---|
@@ -24,33 +24,119 @@
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.1.0 | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 3 | 5 | 8 | 9 | 3, 4 | 27.0 |
| 62 | 0.1.0 | defect | **Lift Locality, Self-sufficiency and the overall to the comprehension floor, at the places the seats name.** | 4 | 6 | 6 | 8 | 1.1 | 22.3 |
| 21 | 0.1.0 | | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 1.3 | 21.8 |
| 49 | 0.1.0 | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 2 | 5 | 6 | 1.3 | 20.1 |
| 59 | 0.1.0 | | **Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.** | 3 | 3 | 6 | 6 | 1.4 | 19.8 |
| 12 | 0.1.0 | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 1.1 | 16.9 |
| 80 | 0.1.0 | | **State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.** | 1 | 1 | 5 | 5 | 4 | 16.8 |
| 5 | 0.1.0 | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 1.1 | 15.6 |
| 84 | 0.1.0 | | **Check, at each release's scoring run, that seats in a paired ruling agree more often than two scoring runs on near-identical code do, as the paired-ruling decision assumes.** | 2 | 2 | 4 | 5 | 1.4 | 15.1 |
| 67 | 0.1.0 | principle | **Point stability-reviewer at the technical principles in place of its own restatement of them.** | 2 | 3 | 4 | 5 | 1.3 | 14.9 |
| 66 | 0.1.0 | principle | **Hold systems-architect's method thresholds only while the comprehension panel finds the flagged code hard.** | 3 | 3 | 4 | 5 | 1.1 | 14.2 |
| 69 | 0.1.0 | principle | **Measure test coverage, so a chunk that lowers it is seen.** | 3 | 4 | 4 | 5 | 1.1 | 13.9 |
| 29 | 0.1.0 | | **Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.** | 2 | 2 | 3 | 5 | 1.1, 1.4 | 13.4 |
| 68 | 0.1.0 | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 4 | 3 | 5 | 1.1 | 12.9 |
| 65 | 0.1.0 | | **Archive each judge reply the loop rejects.** | 3 | 4 | 4 | 5 | 3 | 12.5 |
| 82 | 0.1.0 | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 1 | 2 | 3 | 4 | 1.3 | 12.3 |
| 73 | 0.1.0 | | **Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.** | 3 | 4 | 4 | 4 | 1.4 | 11.7 |
| 6 | 0.1.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 4 | 5 | 1.1 | 11.7 |
| 51 | 0.1.0 | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 3 | 5 | 3 | 5 | 1.1 | 11.7 |
| 50 | 0.1.0 | principle | **Grant the bench's runs only the tools a review needs, in place of skipping every permission.** | 2 | 2 | 3 | 4 | 4 | 9.9 |
| 81 | 0.1.0 | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 2 | 2 | 3 | 4 | 4 | 9.9 |
| 4 | 0.1.0 | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 3 | 9.6 |
| 52 | 0.1.0 | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 6 | 6 | 3 | 5 | 2 | 7.5 |
| 77 | 0.2.0 | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 3 | 6 | 6 | 7 | 1.1, 1.4 | 21.4 |
| 95 | 0.1.0 | | **Make `CLAUDE.md` a short router: only the rules every session needs, and a pointer to where each topic's rules load.** | 6 | 6 | 8 | 8 | 1.1, 1.3, 1.4 | 24.3 |
| 98 | 0.1.0 | | **Score R and S from a measurement wherever one exists, and calibrate each guessed score against the finished chunk's measured outcome.** | 2 | 5 | 6 | 7 | 1.1, 1.4 | 22.6 |
| 99 | 0.1.0 | | **Drop the comprehension panel as a merge gate, and keep recording its scores and the places in the code its seats found hard, for later measurement and for other reviewers and agents to improve.** | 4 | 5 | 7 | 7 | 1.1, 1.4, 1.5 | 22.6 |
| 87 | 0.1.0 | | **Score every `todo.md` item's complexity C from 1 to 10, and have `rank_todo.py` fail on an item without one.** | 3 | 4 | 6 | 7 | 1.1, 1.4 | 21.9 |
| 97 | 0.1.0 | | **Narrow each review pass to the findings worth a fix, so a pass converges in its second round.** | 5 | 4 | 7 | 7 | 1.1, 1.4, 1.5 | 21.9 |
| 93 | 0.2.0 | | **Let a chunk's worker start below the project's model, once the archive shows chunks on a lower rung took no more review rounds than chunks on the project's model.** | 3 | 2 | 6 | 7 | 1.1, 1.4 | 22.4 |
| 94 | 0.2.0 | | **Every 20th cycle, have loop-claude measure token spend and routing outcomes, file them here, and interrupt the human only when they call for a routing change.** | 3 | 5 | 6 | 7 | 1.1, 1.4 | 21.6 |
| 88 | 0.2.0 | | **Define one routing ladder of (model, effort) rungs ordered by a published ranking of their competence, and map a task's R + C to a rung relative to the project's model.** | 3 | 4 | 6 | 7 | 1.4 | 21.4 |
| 90 | 0.2.0 | | **Route each reviewer by the chunk's R + C, once a replay of past chunks shows the routed reviewer finds the 🔴 and 🟡 findings on record.** | 4 | 5 | 6 | 7 | 1.4 | 20.2 |
| 91 | 0.2.0 | | **Start each chunk's worker on the rung its item's R + C picks, never below the project's model, and step it one rung up after two unfinished verdicts on one chunk.** | 4 | 5 | 6 | 7 | 1.4 | 20.2 |
| 92 | 0.2.0 | | **Have the worker route each subagent by its task's R + C, and delegate a task only when the worker needs just its conclusion.** | 2 | 2 | 5 | 6 | 1.4 | 19.0 |
| 89 | 0.2.0 | | **Run the judge on the rung its chunk's R + C picks, once a replay of archived transcripts shows it returns the verdicts on record.** | 3 | 4 | 5 | 6 | 1.4 | 17.5 |
| 1 | 0.3.0 | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 3 | 5 | 8 | 9 | 3, 4 | 27.0 |
| 62 | 0.3.0 | defect | **Lift Locality, Self-sufficiency and the overall to the comprehension floor, at the places the seats name.** | 4 | 6 | 6 | 8 | 1.1 | 22.3 |
| 21 | 0.3.0 | | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 1.3 | 21.8 |
| 49 | 0.3.0 | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 2 | 5 | 6 | 1.3 | 20.1 |
| 59 | 0.3.0 | | **Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.** | 3 | 3 | 6 | 6 | 1.4 | 19.8 |
| 12 | 0.3.0 | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 1.1 | 16.9 |
| 80 | 0.3.0 | | **State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.** | 1 | 1 | 5 | 5 | 4 | 16.8 |
| 5 | 0.3.0 | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 1.1 | 15.6 |
| 84 | 0.3.0 | | **Check, at each release's scoring run, that seats in a paired ruling agree more often than two scoring runs on near-identical code do, as the paired-ruling decision assumes.** | 2 | 2 | 4 | 5 | 1.4 | 15.1 |
| 67 | 0.3.0 | principle | **Point stability-reviewer at the technical principles in place of its own restatement of them.** | 2 | 3 | 4 | 5 | 1.3 | 14.9 |
| 66 | 0.3.0 | principle | **Hold systems-architect's method thresholds only while the comprehension panel finds the flagged code hard.** | 3 | 3 | 4 | 5 | 1.1 | 14.2 |
| 69 | 0.3.0 | principle | **Measure test coverage, so a chunk that lowers it is seen.** | 3 | 4 | 4 | 5 | 1.1 | 13.9 |
| 29 | 0.3.0 | | **Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.** | 2 | 2 | 3 | 5 | 1.1, 1.4 | 13.4 |
| 68 | 0.3.0 | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 4 | 3 | 5 | 1.1 | 12.9 |
| 65 | 0.3.0 | | **Archive each judge reply the loop rejects.** | 3 | 4 | 4 | 5 | 3 | 12.5 |
| 82 | 0.3.0 | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 1 | 2 | 3 | 4 | 1.3 | 12.3 |
| 73 | 0.3.0 | | **Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.** | 3 | 4 | 4 | 4 | 1.4 | 11.7 |
| 6 | 0.3.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 4 | 5 | 1.1 | 11.7 |
| 51 | 0.3.0 | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 3 | 5 | 3 | 5 | 1.1 | 11.7 |
| 50 | 0.3.0 | principle | **Grant the bench's runs only the tools a review needs, in place of skipping every permission.** | 2 | 2 | 3 | 4 | 4 | 9.9 |
| 81 | 0.3.0 | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 2 | 2 | 3 | 4 | 4 | 9.9 |
| 4 | 0.3.0 | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 3 | 9.6 |
| 52 | 0.3.0 | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 6 | 6 | 3 | 5 | 2 | 7.5 |
| 77 | 0.4.0 | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 3 | 6 | 6 | 7 | 1.1, 1.4 | 21.4 |
## Details
### 95. Make `CLAUDE.md` a short router: only the rules every session needs, and a pointer to where each topic's rules load.
`CLAUDE.md` holds about 4,300 words and 150 or more rules, and every session loads it whole. Anthropic's memory docs (code.claude.com/docs/en/memory) say a longer file "reduce[s] adherence", and its best-practices page says to keep a line only if "removing this would cause Claude to make mistakes". IFScale (arxiv.org/abs/2507.11538) measures adherence falling as the instruction count grows, with earlier instructions followed more. Count instructions, not lines.
Keep in it only what every session needs and no other file loads: the vocabulary, the working loop's order, and one line per topic naming the skill, agent or doc that holds its rules. Move each topic's rules to the place that loads it when the topic comes up, such as "Prose" and "Comments and documentation" to what a writer or prose-reviewer loads, "Todo items" to `rank_todo.py --help` and larv-review. Delete every rule Claude already follows unasked. When a rule moves, repoint each reference to it in `skills/`, `agents/` and `bin/`, and have loop-claude's judge, which answers the worker from this file, read the rule where it now lives. The PR states the instruction count before and after. The prose pass of PR #235 found these in the text as it stands; fix each where its text survives:
- 🟡 "README" says a README covers "cross-cutting decisions no single file owns", while "Decisions: one home" makes `docs/decisions.md` the one home of a choice made in more than one place, and moves a README section that is neither a goal nor how one is met. Proposed: `**A README covers what a reader needs *before* opening the code**: how it meets its goals, and how to build, test, run, and deploy it.`
- 🟢 "Ask, don't guess": "If an answer is a goal and something else too, write the goal, and record a choice only for what the goal leaves open." Proposed: `When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open.`
- 🟢 "Decisions: one home" lists "a comment" as a wrong home, then names a comment as the destination. Proposed: `a comment away from the code it governs`.
### 98. Score R and S from a measurement wherever one exists, and calibrate each guessed score against the finished chunk's measured outcome.
A score that can be computed from the code it touches, such as the files an item names, comes from that computation. Otherwise size and risk are estimated from finished work, the way reference-class forecasting estimates a project from earlier projects like it. When a chunk merges, record its measured outcome beside the item's guessed R and S: lines and files changed, review rounds, 🔴 and 🟡 findings, and fixes the code needed later. Show the scorer, when it files an item, the finished items whose guessed scores sat nearest and what they measured. Once enough chunks are recorded, report how far each guess was from its outcome, so a scorer whose S runs high can be corrected. Item 87's C is scored and calibrated the same way.
### 99. Drop the comprehension panel as a merge gate, and keep recording its scores and the places in the code its seats found hard, for later measurement and for other reviewers and agents to improve.
No published study validates simulated reader panels as a measure of how easy code is to understand, and item 84's test of whether the panel's signal beats its noise has not run. Keep running the panel where it runs, and keep `docs/comprehension-history.md`: each run's scores, and each place a seat named with what it found hard there. No paired ruling, floor or ratchet blocks a merge. The architecture pass and the stability reviewer read the latest places named, and each chunk that touches one of them improves it or says in its PR summary why not. A worker filing items reads them too.
This revises the `comprehension floor:` decision and the `review:` decisions on the paired ruling, the scoring run, suspending and opting out of the comprehension check, and it turns item 62 from a defect into an ordinary item scored by its value. A project's own gate rule, such as the one in fejkdata's `AGENTS.md`, is that project's to change.
### 87. Score every `todo.md` item's complexity C from 1 to 10, and have `rank_todo.py` fail on an item without one.
C is how hard the change is to get right: novel design, subtle invariants, many interacting parts. It differs from R, the chance the change creates serious bugs, and from S, its size: a huge rename is low C, a ten-line lock fix can be high C. C routes work (items 88–92) and stays out of the Score formula. Add the column to `rank_todo.py`'s valid shape and its `--help`, backfill every item in this repo, and state in `CLAUDE.md` → "Todo items" that C is scored when an item is filed, like R, S, A and G, so no chunk starts on an unscored item.
### 97. Narrow each review pass to the findings worth a fix, so a pass converges in its second round.
Anthropic's best-practices page: "A reviewer prompted to find gaps will usually report some, even when the work is sound… Chasing every finding leads to over-engineering." 320 of this repo's 876 commits answer a review round.
Stability and product-owner report a defect, a broken requirement from the plan or the goals, or a breach of a technical principle, and nothing else. Prose runs when a chunk changes prose a reader reads, such as docs, comments, help text and the plan, and skips a code-only chunk. The architecture pass and the comprehension check keep their whole-project view, which guards goal 1.1 as a project grows. Each architecture finding names a concrete later change the PR makes harder, such as "a second forge needs edits in four modules", so a finding is checkable and a vague one is dropped.
From its second round on, a pass reviews only how the chunk answered the round before. Each finding should be fixed correctly or dismissed with a good reason, and the reviewer reports only a fix or a dismissal that is plainly wrong or worse than the change it answered. The pass then converges in its second round. This revises the decisions on reruns and the round cap in `docs/decisions.md`. A fix that opens an untrusted-input boundary still triggers the security pass.
### 93. Let a chunk's worker start below the project's model, once the archive shows chunks on a lower rung took no more review rounds than chunks on the project's model.
Goal 1.1 asks for proven quality, so stepping down waits on the archive's evidence.
Needs 91.
### 94. Every 20th cycle, have loop-claude measure token spend and routing outcomes, file them here, and interrupt the human only when they call for a routing change.
Count the cycles across all projects in loop-claude's archive, which holds every project's transcripts on the machine. Measure in code, as `bin/reading-cost` does, so the check itself costs no model run (goal 1.4): tokens by project, subagent type, rung and tool, and per routed chunk its review rounds and unfinished verdicts. A loop on another project cannot commit here, so it writes the figures to the archive, and this repo's next chunk files or refreshes one plan item from them. The ladder's thresholds and the delegation rule are decisions, so a change to them is the human's. Interrupt when chunks on a rung took more review rounds or unfinished verdicts than chunks on the rung above, or when subagent reports fill more of the worker's peak context than the searches they replaced would have; never twice for the same figures (goal 1.2).
Needs 88, 91, 92.
### 88. Define one routing ladder of (model, effort) rungs ordered by a published ranking of their competence, and map a task's R + C to a rung relative to the project's model.
One ladder, the same in every project (goal 1.3), read by loop-claude, larv-review and the worker. A rung is a model and an effort; the rungs run from Haiku at low effort to the strongest model at max effort. Order the rungs by a published source, cited in the decision recording the ladder; where no source orders two rungs, such as Sonnet at xhigh against Opus at medium, ask the human. R + C moves a task up or down from the rung holding the project's model at its default effort: a low sum steps down, a high sum steps up, the thresholds set in the decision. S never moves a rung: a huge task with low R and C runs cheap. Leave out the comprehension panel and the security pass, which stay on the project model. Record each route in loop-claude's archive, so the outcomes can tune the thresholds.
Needs 87.
### 90. Route each reviewer by the chunk's R + C, once a replay of past chunks shows the routed reviewer finds the 🔴 and 🟡 findings on record.
larv-review passes the rung through the Agent tool's `model` and `effort`. A reviewer never steps down when the worker has stepped down on the same chunk, so a cheap worker always meets a reviewer on the project model or above.
Needs 88.
### 91. Start each chunk's worker on the rung its item's R + C picks, never below the project's model, and step it one rung up after two unfinished verdicts on one chunk.
loop-claude reads the top item of the next release with `rank_todo.py` before starting a chunk's first cycle. Change the rung only when a chunk starts or steps up: every cycle resumes the chunk's session, and a model switch discards its prompt cache. When the worker bundles an item scoring a higher R + C than the one routed on, it says so in its transcript, and the judge's verdict steps the next cycle up.
Needs 88.
### 92. Have the worker route each subagent by its task's R + C, and delegate a task only when the worker needs just its conclusion.
State in `CLAUDE.md` when the worker delegates: a search or read that spans many files whose conclusion is all it needs, and work independent enough to run in parallel. Edits and anything the worker must verify line by line stay in the main thread, since a delegated diff is read again to check it. The worker scores R and C for each delegated task as it would for an item, and passes the rung's model and effort. In item 73's measurement, reports cost a median 8% of the worker's peak context, and `sed -n` and `grep` output made up 41% of its Bash results, so delegating searches saves the most context. The Agent tool sets a subagent's effort only when instructions ask, so the rule names both model and effort.
Needs 88.
### 89. Run the judge on the rung its chunk's R + C picks, once a replay of archived transcripts shows it returns the verdicts on record.
loop-claude starts the judge itself (`bin/loop_claude/cycle/judge.py`), so it routes without any skill change. Replay the judge on archived cycles at the candidate rung, and switch only when its interrupts and verdicts match those on record.
Needs 88.
### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.
It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read.
@@ -61,7 +147,7 @@ The README line covers the bench's transcripts in `workflow-bench/logs/` too (go
### 62. Lift Locality, Self-sufficiency and the overall to the comprehension floor, at the places the seats name.
Raised by the principles audit of PR #215 against KISS, in `principles/technical-principles.md`, and goal 1.1: 0.1.0 waits on the floor, and the `comprehension floor:` entry in `docs/decisions.md` lists each decision to ship under it.
Raised by the principles audit of PR #215 against KISS, in `principles/technical-principles.md`, and goal 1.1. The `comprehension floor:` entry in `docs/decisions.md` lists each decision to ship under it.
PR #234's last scoring run, at b2a277b, put Locality and Self-sufficiency at 6.50 and the overall at 6.75. Every seat named larv-review's rules, which cannot be followed without `skills/larv-review/SKILL.md` §3 open beside the code: "Round cap", "Re-entry", "Fresh" and "Suspended" point at each other; `bin/larv_review/record.py` `record_ruling` branches on split, worse, fell and a scores file, with its terms defined only in `larv-review --help` and the skill; the pass list lives in both `bin/larv_review/rounds.py` `PASSES` and the skill's table, which also counts the auto-reviewer; `bin/comprehension_history.py` is reader, writer and seat registry in one, and parses the history by regex for two tools. Also named: the judge's prompt assembled from `cycle/judge.py`, `cycle/prompts.py` and `project/records.py`; git run four ways, in `bin/larv_review/git.py`, `bin/metric_bench/main.py`, `bin/reading_cost/main.py` and `bin/loop_claude/effects.py`; `SeatsFile.read`, a field named like a method.
@@ -83,6 +169,8 @@ Raised by the product-owner review of PR #211. The resumed worker gets the judge
The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word.
When CI runs a rule check, such as one of `bin/rule-hook`'s, let `<!-- rule-override <rule>: <reason> -->` in the PR body override it.
### 80. State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.
Raised by the principles audit of PR #224. The `settings.json` decision is valid while every machine taking this checkout is a sandbox, but Install asks for a sandbox only for `loop-claude`, so a new machine is never told.