Compare commits

..

135 Commits

Author SHA1 Message Date
lilleman a76fba8408 Answer prose round 1: the tagline says what mutation testing checks, and the detail defines a mutant 2026-10-13 09:16:38 +02:00
lilleman b97685f238 File item 108: mutation-test the code each chunk changes, so every test must catch a real bug 2026-10-13 09:15:38 +02:00
lilleman 198a967e52 Merge pull request 'Say what lilleman widened the worker's test-first rule to' (#248) from test-first-note into main 2026-10-13 08:55:33 +02:00
lilleman 871b45e2de Say what lilleman widened the worker's test-first rule to 2026-10-13 08:55:28 +02:00
lilleman 8d9920a3a4 Merge pull request 'Write a failing test first wherever a test can check the change' (#247) from test-first into main 2026-10-13 08:55:16 +02:00
lilleman 4061f19dff Answer prose round 1: test first wherever a test can check the change, and name larv-review's reviewers 2026-10-13 08:55:15 +02:00
lilleman 6c6d411f9d Write a failing test first whenever there is something to test 2026-10-13 08:54:35 +02:00
lilleman 21b060e7ad Merge pull request 'Have the worker write the simplest change, test first, reading a principle only where named, and move the rules only reviewers apply to larv-review's standards' (#245) from item-104 into main 2026-10-13 08:49:50 +02:00
lilleman e67a25bdbf Rescore: the paired ruling at a796bb3 is same 2026-10-13 08:49:43 +02:00
lilleman a796bb31ee Answer stability round 3: no findings 2026-10-13 07:58:26 +02:00
lilleman 109fb27e00 Answer architecture round 5: one shared git command parser for rule-hook and reading-cost, the reflog check unrolled, and rule-hook's Outcome and LogLine named apart from their namesakes 2026-10-13 07:56:59 +02:00
lilleman b0cfe20952 Record the paired ruling at f6d5ea7: worse, Shape under the floor 2026-10-13 07:52:40 +02:00
lilleman f6d5ea7b98 Merge main into item-104, keeping item 107 and dropping the finished item 104 2026-10-13 07:41:11 +02:00
lilleman 6b4b5d188b Answer stability round 2: no findings 2026-10-13 01:49:42 +02:00
lilleman f07303cd09 Answer architecture round 4: prose.md holds the full prose rules, the prose reviewer's bar is a list, CLAUDE.md names where the reviewers' standards live, and one helper words the judge's sources 2026-10-13 01:47:55 +02:00
lilleman 16076fa40f Record the paired ruling at b568522: worse, Locality under the floor 2026-10-13 01:45:33 +02:00
lilleman 4719c9289e Merge pull request 'File item 107: loop-claude puts the README's Goals and Audience into every fresh worker prompt, and the item sets the scope' (#246) from item-107 into main 2026-10-13 01:37:56 +02:00
lilleman a7dbaaabb2 File item 107: loop-claude puts the README's Goals and Audience into every fresh worker prompt, and the item sets the scope 2026-10-13 01:37:22 +02:00
lilleman b5685225e0 Answer prose round 1: a finding against a principle names it, a plainer changelog, and the contrastive-tail exception in prose.md 2026-10-13 01:35:19 +02:00
lilleman cfdc10d78c Answer product-owner round 1: test first only where the item changes code, and a changelog in the owner's terms 2026-10-13 01:31:59 +02:00
lilleman fc7f3e96e2 Drop an unchecked clause from the judge decision's reason 2026-10-13 01:30:30 +02:00
lilleman 4734167be6 Answer stability round 1: restate why a write to the human's rules records no answer, and name HUMAN_RULES_FILE for what it holds 2026-10-13 01:30:25 +02:00
lilleman 01e0a35372 Answer architecture round 2: the worker: decision's title states the test-first rule and when the worker reads a principle 2026-10-13 01:28:06 +02:00
lilleman 4ebe36edef Answer architecture round 1: the worker writes the test first and reads a principle a finding or its record names; findings name their principle; one regex for citable rule files 2026-10-13 01:27:05 +02:00
lilleman ed1c62ac8a Append the reading-cost figure 2026-10-13 01:16:15 +02:00
lilleman 854747f68d Have the worker implement the simplest change without loading the technical principles, and move the rules only reviewers apply to larv-review's standards 2026-10-13 01:15:59 +02:00
lilleman 8bbc07d9e9 Merge pull request 'File item 104: the worker implements the simplest change and loads no technical principle; the reviewers refactor it to the bar' (#244) from item-101 into main 2026-10-13 01:02:15 +02:00
lilleman d9ea961ca6 Merge main into item-101, and fold item 103 into item 104, which answers it 2026-10-13 01:00:58 +02:00
lilleman 2feda33ec6 Merge pull request 'Make CLAUDE.md a short router, and move each topic's rules to a file under rules/ that loads when a session touches a matching file' (#242) from claude-md-router into main 2026-10-13 00:56:29 +02:00
lilleman f1a84307be Rescore: the paired ruling at f351e14 against 4cc9953 is same 2026-10-13 00:56:19 +02:00
lilleman f351e14683 Answer stability round 4: no findings 2026-10-13 00:53:25 +02:00
lilleman b2bc0a966f File item 104: the worker implements the simplest change and loads no technical principle; the reviewers refactor it to the bar 2026-10-13 00:53:05 +02:00
lilleman 27ebf64eeb Answer product-owner round 4: no findings 2026-10-13 00:52:25 +02:00
lilleman 3b322596c2 Answer product-owner round 3: point the decision-log rule from Ask, don't guess, and file item 103, whether the saving must reach loop-claude workers, as a question 2026-10-13 00:49:22 +02:00
lilleman 2020a4f04f Answer architecture round 2: keep test data out of the rule-file check, and state the judge's reason for reading rule files in one entry 2026-10-13 00:49:22 +02:00
lilleman 950f06c0be Answer architecture round 1: give the rules/ design its own decision with its premise, move where a choice goes into the comment rules, let each rule file's paths frontmatter be the one map and check every rule file named exists, pass the judge its rules folder, and file two findings outside the chunk 2026-10-13 00:46:11 +02:00
lilleman 63b0759e2a Merge main into claude-md-router
# Conflicts:
#	CHANGELOG.md
#	todo.md
2026-10-13 00:39:38 +02:00
lilleman de0dad7d58 Answer prose round 1: list the judge's rule files in the vocabulary, widen the stability reviewer's prose bar, and reword the router, the maintenance rules and the decision 2026-10-13 00:38:48 +02:00
lilleman 5a1a615f87 Merge pull request 'Add deep modules as a technical principle, and put functional core, imperative shell second' (#243) from deep-modules into main 2026-10-13 00:36:02 +02:00
lilleman be21dbc400 File item 100: the unsorted imports in override_log.py fail the test suite on main 2026-10-13 00:36:01 +02:00
lilleman 415f7752c0 Answer stability round 3: no findings 2026-10-13 00:34:23 +02:00
lilleman cb15824487 Answer product-owner round 2: no findings 2026-10-13 00:33:53 +02:00
lilleman b93c318080 Answer stability round 2: put the public API spec rule back in the prose reviewer's bar 2026-10-13 00:33:53 +02:00
lilleman 9f9dfc7245 Answer prose round 1: functional core is a rule no other principle overrides, the banned call order is one only memory enforces, the changelog states the principle's exception as written, and one list of injected inputs 2026-10-13 00:33:07 +02:00
lilleman 326b239b24 Answer security round 1: no findings 2026-10-13 00:31:58 +02:00
lilleman fdb13957ab Answer product-owner round 1: answered in the stability round 1 commit, with each topic file's trigger in the router and a smoke test showing a user-level rule loads on Read and after Write 2026-10-13 00:31:58 +02:00
lilleman 3766e880ca Answer stability round 1: cite the shortened false-claim heading, keep the API-spec and tagline rules in CLAUDE.md, load the comment rules with any file, and name the judge's two rule sources apart 2026-10-13 00:31:58 +02:00
lilleman 42b6caf2dc Record the reading cost of the last finished chunk 2026-10-13 00:31:42 +02:00
lilleman 15d53b37b8 Add the deep-modules principle, move functional core, imperative shell to second place, and point the architect at the principle 2026-10-13 00:31:24 +02:00
lilleman a1adbbfd8b Record the reading cost of the chunk before this one 2026-10-13 00:24:31 +02:00
lilleman 6f8a650ac0 Make CLAUDE.md a short router, and move each topic's rules to a file under rules/ that loads when a session touches a matching file 2026-10-13 00:24:17 +02:00
lilleman 72fd688d81 Merge pull request 'Enforce the checkable rules in a hook, with one override marker that larv-review's overrides pass rules on, and drop them from CLAUDE.md' (#241) from hook-rules into main 2026-10-13 00:11:18 +02:00
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
lilleman afa1fcf014 Rescore: record the paired ruling and scoring run at 7e13778, and give the floor decision its scores 2026-10-09 15:23:46 +02:00
lilleman 7e13778191 Answer prose round 1: fold round-count's changes into the larv-review changelog entry, revise the decisions citing item 83 and stating the floor, reword the help, docstrings and seat-prompts placeholder, drop the archive layout comment that restates --help, and test the past-the-cap line 2026-10-09 15:20:11 +02:00
lilleman 3c1cc85f34 Answer product-owner round 1: its nits land in the stability round 1 commit 2026-10-09 15:13:32 +02:00
lilleman 0aedb5f5e9 Answer stability round 1: ship item 83 out of the plan, test both scores-file refusals, mark a pass past the cap and only a pass, say how to retry a refused scores file, and sort the allowlist and mypy's modules 2026-10-09 15:13:32 +02:00
lilleman 3ec67085c5 Answer security round 1: no findings 2026-10-09 15:13:30 +02:00
lilleman 95566e7225 Ship PR #234 below the floor, as lilleman decided, and refresh item 62 with the places the seats name now 2026-10-09 15:05:58 +02:00
lilleman 13344170ef Rescore: record round 4's paired ruling and scoring run 2026-10-09 15:04:50 +02:00
lilleman b2a277b642 Answer architecture round 4: count a repeated round number, move larv-review's record commands to record.py, give the UTC stamp and the blockquote one home each, check the history's sample entry, and state why a split and a fall call more seats 2026-10-09 15:01:29 +02:00
lilleman 8f02d11096 Answer architecture round 3: record the third paired ruling and scoring run; both auditors approve with nits 2026-10-09 14:53:45 +02:00
lilleman b346a3572e Answer architecture round 2: keep the judge's rules beside its verdicts, name record_ruling's steps, file HistoryChange with the history, give read_utf8 its own module, count a mis-cased round title, and repair the tracked_places docstring 2026-10-09 14:49:34 +02:00
lilleman dde06fc465 Answer architecture round 1: give loop-claude's prompt text one home, split larv-review's plan trigger and ruling base out, share todo.md's table and the project key, and name the scoring run, the checkout roots and the test env for what they are 2026-10-09 14:43:19 +02:00
lilleman b1913ed65d Restructure bin/ so the project reads at the comprehension floor 2026-10-09 14:12:16 +02:00
lilleman 2157f5927d Merge pull request 'Rule each dimension in the paired ruling, and count a ruling as worse when a dimension that falls scores under the floor' (#232) from paired-dimensions into main 2026-10-09 13:16:06 +02:00
lilleman 97e76dd1ce Ship PR #232 below the ratchet, as lilleman decided, and drop main.py's unused decimal import 2026-10-09 13:15:58 +02:00
lilleman 53014f849c Answer product-owner round 4: its findings land in the architecture round 9 commit 2026-10-09 12:59:45 +02:00
lilleman bc2cc2c68e Answer stability round 4: its findings land in the architecture round 9 commit 2026-10-09 12:59:45 +02:00
lilleman 8cee26b1d6 Answer architecture round 9: refuse a repeat record before any output, count a fall's scores once in metric-bench, fetch origin for record-scoring as for needs-scoring-run, type fall_step's outcomes, and state the duplicate rule as the code holds it 2026-10-09 12:59:45 +02:00
lilleman 745818826a Answer product-owner round 3: the base rule, the Floor line, the fall's wording and reusing a fall's scores file land in the architecture round 8 commit 2026-10-09 12:29:37 +02:00
lilleman d18441ba89 Answer stability round 3: its two findings, the legacy entry and the stale base rule, land in the architecture round 8 commit 2026-10-09 12:29:37 +02:00
lilleman 2630291af2 Answer architecture round 8: refuse a scoring run the plan does not call and a second entry on one read, keep a fall's scoring places apart for metric-bench, let the history format write the Ruling line, decide the fall step in a pure function, and state the base rule as the code holds it 2026-10-09 12:29:37 +02:00
lilleman e694e4154e Answer architecture round 7: decide a fall inside record-ruling with the scoring seats' scores, give the history format one owner in comprehension_history, drop the moved Mean path, and plan the archive and judge restructures in items 83 and 62 2026-10-09 12:22:13 +02:00
lilleman b02bdd0bf4 Merge remote-tracking branch 'origin/main' into paired-dimensions
# Conflicts:
#	CHANGELOG.md
2026-10-09 11:55:21 +02:00
lilleman a83003980c Fix the auditors' round-6 nits: list the fall's reason last in the help, as it prints, and name the fall tests for the Fall state 2026-10-09 11:55:06 +02:00
lilleman 4cda8551b4 Answer architecture round 6: split rules into ruling, rounds, base and scoring modules, read the fall sequence as one Fall state, and give the plan's reasons and the fall's their own functions 2026-10-09 11:53:08 +02:00
lilleman 9ca791435f Record the rescore at 324d650: a same ruling in which Locality fell, and a scoring run that puts Locality at 6.50, so the ratchet stands 2026-10-09 11:47:36 +02:00
lilleman 298fb41fed Merge pull request 'Spell the reading-cost item's title on one read, and keep the stability reviewer's deletions to what it created' (#233) from clear-reading-cost-title-scratch-rule into main 2026-10-09 11:45:22 +02:00
lilleman affe56b074 Answer prose round 1: drop the changelog line for an unreleased title, and say the scratch directory is deleted when done 2026-10-09 11:44:17 +02:00
lilleman dd30a1199a Spell the reading-cost item's title on one read, and keep the stability reviewer's deletions to what it created 2026-10-09 11:43:25 +02:00
lilleman 324d65007f Answer stability round 2: no 🔴 or 🟡; its 🟢, the moved Mean's output, lands in the product-owner round 2 commit 2026-10-09 11:42:32 +02:00
lilleman e2e3569e1f Answer product-owner round 2: rewrap the help to 100 columns, and say a moved Mean run prints only its means 2026-10-09 11:42:32 +02:00
lilleman 4e728df7cc Answer product-owner round 1: print Floor and the item IDs read on lines of their own, say when a scoring run already answered the fall, and show a fall in the help's example (the fixes land in the architecture round 5 commit) 2026-10-09 11:40:20 +02:00
lilleman 885396370a Answer architecture round 5: give record_scoring's moved Mean its own path, and take pending_fall from a paired entry alone 2026-10-09 11:40:20 +02:00
lilleman 6a8bbcfff9 Answer prose round 1: split the record-scoring help into one idea per sentence, name the chunk's entries once, fold the changelog bullet into the bullets it changes, and give the decision's amendment its own paragraph 2026-10-09 11:31:17 +02:00
lilleman c386163a5f Answer architecture round 4: no 🔴 or 🟡; its two 🟢 fixes, the usage line and "opens with", land in the prose round's commit 2026-10-09 11:31:17 +02:00
lilleman 60a00ce54f Answer stability round 1: name the base rule's two conditions, skip the plan for a moved Mean run, and test the floor that blocks nothing 2026-10-09 11:27:20 +02:00
lilleman 030e29a52d Answer architecture round 3: open each place with the dimensions it moves, fail a scoring run nothing calls, test the base rule and a standing ratchet, and state the base rule whole 2026-10-09 11:07:12 +02:00
lilleman 9de87e04cf Answer architecture round 2: fail a place naming no dimension, keep a ratchet until a ruling follows, leave the base on a fall-called run, let record-scoring say whether the floor blocks, and name the missing dimension in a discounted vote 2026-10-09 11:04:01 +02:00
lilleman 75b0e46326 Answer architecture round 1: count a dimension's vote only where a place names it, take a fall on a same ruling too, block a fall-called run only on the fallen dimensions, read the chunk's own entries, and repeat a standing ratchet 2026-10-09 10:58:59 +02:00
lilleman 2c6e0633cf Rule each dimension in the paired ruling, and count a better ruling as worse when a dimension it rules fallen is under the floor 2026-10-09 10:51:09 +02:00
lilleman a984e98e0a Merge pull request 'Move larv-review's mechanical rules into a tested bin/larv-review, so the skill says only when to run it and what each answer means' (#231) from item-85 into main 2026-10-09 01:51:14 +02:00
106 changed files with 3870 additions and 1312 deletions
+20 -1
View File
@@ -17,8 +17,12 @@
!agents/
!agents/*.md
!bin/
!bin/claude_code/
!bin/claude_code/*.py
!bin/comprehension_history.py
!bin/failure.py
!bin/file_writes.py
!bin/git_command.py
!bin/larv-review
!bin/larv_review/
!bin/larv_review/*.py
@@ -26,25 +30,40 @@
!bin/loop_claude/
!bin/loop_claude/**/
!bin/loop_claude/**/*.py
!bin/markdown_sections.py
!bin/markdown_text.py
!bin/metric-bench
!bin/metric_bench/
!bin/metric_bench/*.py
!bin/project_key.py
!bin/rank_todo.py
!bin/reading-cost
!bin/reading_cost/
!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
!bin/transcript_archive/
!bin/transcript_archive/*.py
!bin/utc_stamp.py
!docs/
!docs/*.md
!principles/
!principles/*.md
!rules/
!rules/*.md
!skills/
!skills/comprehension-panel/
!skills/comprehension-panel/*.md
!skills/larv-review/
!skills/larv-review/*.md
!skills/larv-review/standards/
!skills/larv-review/standards/*.md
!workflow-bench/
!workflow-bench/bench.py
!workflow-bench/compare-prompt.md
+7 -3
View File
@@ -3,17 +3,18 @@
Decisions live in `docs/decisions.md`:
- larv-review: a project under the comprehension floor is fixed at the lowest dimension
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md` and `~/.claude/CLAUDE.md`, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- 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; the four-seat scoring run checks the floor when a release's items run out or an item names the floor
- 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,9 @@ 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
- rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
## Working rules
+13 -2
View File
@@ -2,9 +2,20 @@
## Unreleased
- 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`), the scoring run's trigger (`needs-scoring-run <item ID>...`), and the vote count, means and history format (`record-ruling` and `record-scoring`, which read a seats file and append to `docs/comprehension-history.md`). 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. Scores a `comprehension floor:` decision entry still holds move into the history through `record-scoring`, as a `Mean:` line. When origin cannot be fetched, the tool reads it as last fetched and says so.
- A session no longer reads the technical principles before writing code. It writes the simplest change that solves its item, test first wherever a test can check the change, and reads a principle only when the item changes it, a finding names it, or a decision or `todo.md` item it writes cites it. larv-review's reviewers hold the change to the principles, and a finding against one names it. Expect more findings from the prose and stability reviewers, since sessions no longer load the rules for comments and READMEs.
- The rules for comments and READMEs, "Quality" and the examples behind "Prose" moved to `skills/larv-review/standards/`, which the prose and stability reviewers and `loop-claude`'s judge read. `CLAUDE.md` keeps a short core of "Prose"; sorting where order carries no meaning lives only in the technical principles.
- A session no longer points out a preference you have repeated or asks you to write it up, and no longer restructures `CLAUDE.md` and `rules/` after changing them.
- A `todo.md` item names a release whose version bump fits the item under strict semver: a major for a change to what exists (a minor before 1.0.0), a minor for an addition, a patch for a fix.
- `CLAUDE.md` keeps only the rules no file path can scope. The rules for `todo.md` items, decisions and a README's Goals and Audience moved to files under `rules/`. Claude Code loads each one when a session reads or writes a matching file. `loop-claude`'s judge reads them beside `CLAUDE.md`.
- A README no longer holds cross-cutting decisions; `docs/decisions.md` does.
- A technical principle, "Prefer deep modules": a module puts a small, intuitive interface in front of a lot of hidden work, and hides how it works but never what it depends on. It wins over "Explicit over implicit" unless hiding the work makes it harder for someone new to the project to tell what a call does. "Functional core, imperative shell" moves up to second place, a core rule beside "Compose, do not entangle" that no other principle overrides. The systems architect holds every module to it.
- 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.
- larv-review blocks a merge when simulated readers rule that the PR makes the project read worse than the last measured commit: the default branch's newest merged change that added a scoring run to `docs/comprehension-history.md`, or whose last ruling there is better. A ruling of same leaves that commit in place, so a worse ruling may name places earlier chunks wrote. In each architecture pass Mid A and the inherited architect vote better, same or worse; when they disagree, the maintainability senior and Junior A vote too. A ruling needs a lead of two or more votes, else it is same, and a vote that names no place counts as same. A worse ruling never ships: after three rounds larv-review asks you for another round, a no leaves the PR unmerged, and so does an unattended run. The four-seat scoring run checks the comprehension floor only when a chunk ships or removes a release's last plan item, or ships an item naming the floor; between those runs the floor blocks nothing. A score under the floor blocks the merge until fixed or until you decide to ship; a decision in `docs/decisions.md` that lets every chunk ship under the floor counts as yours.
- larv-review blocks a merge when simulated readers rule that the PR makes the project read worse than the last measured commit: the default branch's newest merged change that added a scoring run to `docs/comprehension-history.md`, or whose last ruling there is better. A ruling of same leaves that commit in place, so a worse ruling may name places earlier chunks wrote. In each architecture pass Mid A and the inherited architect vote better, same or worse on each dimension and overall: `Navigation same, Locality worse, Shape same, Self-sufficiency same, Overall better`. When their overall votes differ, the maintainability senior and Junior A vote too. A ruling needs a lead of two or more votes, else it is same. Each place a seat names opens with the dimensions it moves, such as `Locality, Shape: `, or the run fails, and a vote that no place opens with counts as same. A dimension falls when its worse votes lead by two. When a dimension falls in a better or same ruling, `record-ruling` asks for the four scoring seats and, given their scores file, counts the ruling as worse when that dimension's mean is under the floor. A worse ruling never ships: after three rounds larv-review asks you for another round, a no leaves the PR unmerged, and so does an unattended run. The four-seat scoring run checks the comprehension floor only when a chunk ships or removes a release's last plan item, or ships an item naming the floor; between those runs, a score under the floor blocks a merge only through a fallen dimension, and that block counts as a worse ruling. On those runs, a score under the floor blocks the merge until fixed or until you decide to ship; a decision in `docs/decisions.md` that lets every chunk ship under the floor counts as yours.
- larv-review reruns fewer passes after a fix. A fix reruns the pass whose 🔴 or 🟡 it answers, plus stability when the fix changes behaviour, security when it opens an untrusted-input boundary or touches authn/authz, secrets or crypto, and architecture when it carries an architectural decision. A rerun reviews only what changed since that pass last reviewed. A fix for a 🟢, a ❓ or any prose finding reruns no pass, and prose takes one round.
- larv-review runs one security pass on each change: the full scan alone when it runs, else `/security-review`.
- larv-review runs the new `bin/reading-cost`, which measures each chunk `loop-claude` finished from its archive: the new input tokens the worker and its subagents took in before the worker's first commit, and the files git tracks that they read most. It appends each figure the project's `docs/reading-cost.md` lacks. Once 10 chunks are measured, and the last 5 chunks' median is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it. The chunk that ships it runs `reading-cost --reset`, so the trend counts only chunks that finished after it.
+26 -101
View File
@@ -5,110 +5,45 @@
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.
- **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.
- **Plan `todo.md` as one scored table**: 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.
- **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one.
- **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once.
- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they name one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md` per "Todo items". An item marked `question` waits for the human; take the next item.
- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. If an answer is a goal and something else too, write the goal, and record a choice only for what the goal leaves open.
- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they name one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`. An item marked `question` waits for the human; take the next item.
- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. 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.
- **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the README's `## Audience`, picks it.
- **Ship every chunk with `/larv-review`.**
- **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file under `~/.claude/principles/` only when the item changes it, a finding or a record you write names it, or you decline a finding.
- **Remove a finished item's row and detail from `todo.md`, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record.
- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision.
- **Releases follow semver read strictly** (`~/.claude/principles/technical-principles.md`).
### 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:
- **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`.
- **G** — its value to the goals it cites in the Goals column; W is the weight of the heaviest of them.
- **An item scoring under the bar is deleted, with every item that needs it, and a finding under the bar is not filed.** The chunk's summary names each, with its score.
- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding, `question` for a question only the human can answer, `decision` for an item `docs/decisions.md` cites, and, where no other reason fits, `principle` for a 🟡 finding against a file under `~/.claude/principles/`, whose item's detail names that principle. Every item `docs/decisions.md` cites carries one of these reasons.
- Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, under the next release, marked `security`, naming the exposure and the path it reaches. `rank_todo.py` ranks it first in its release. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
- **Unless the project has a reason to differ, weigh goals by position, the first heaviest.** When the weights stop listing the README's goals, `rank_todo.py` fails and prints those weights.
## Quality
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.
3. **Plainly written**, per "Prose".
- **Open each `todo.md` item or ticket with a bold one-sentence tagline**, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- **File a security finding the moment it is found.** A security finding — a leaked credential, secret or PII, an auth bypass, an injection — goes under the next release, marked `security`, naming the exposure and the path it reaches. `~/.claude/bin/rank_todo.py` ranks it first in its release. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
## Prose
Everything written — chat, commit messages, comments, docs, code — is in **English**. Prose meets four priorities, in this order. When two pull against each other, the higher one wins.
1. **Easy to understand.** A reader with little time gets it on one read. Keep each sentence to one idea. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work has landed towards it, plan it.`
2. **Most important first**, judged by what this document's reader wants to know first. Put the most important section first. Within each section, put the most important paragraph first, and within each list the most important item. Order matters most in long documents; in a short one, don't spend a fix on it.
3. **Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it. Adding words is a deliberate act: name what a reader could not understand without them.
1. **Easy to understand.** A reader with little time gets it on one read: one idea per sentence, and each term explained before it is used.
2. **Most important first**, judged by what the reader wants to know first.
3. **Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it.
4. **Short.** Cut whatever does not clearly help 1–3.
- **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone.
- **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader doing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`.
Write the thing, not an introduction to it. State what holds and stop; name a rejected alternative only where that stops a reader choosing it.
## Comments and documentation (`README.md`, `AGENTS.md`, `docs/`, API specs)
Reviewers hold prose to the full rules, with examples: `~/.claude/skills/larv-review/standards/prose.md`.
### What earns a place
## Public API specs
- Text in public API specs (OpenAPI `description`/`title` fields, in a spec file or in code, and the generated api-docs) is read by external consumers. Never leak internal references: no ticket IDs, internal URLs, repo/system code-names, "see ticket X". Describe behaviour in consumer terms. GOOD: `Deprecated alias for paymentAccountId`. BANNED: `…will be removed (ABC-123)`.
- Internal code comments, by contrast, *may* cite a ticket for a footgun or constraint.
The reader is a competent reader of THIS codebase. A comment or a paragraph earns its place by saying what that reader could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. Fix a redundant one by deleting it, never by trimming it: two copies drift, and the doc copy is the one nobody updates. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show.
## Topic rules
### A false claim is a bug — fix it where you find it
Claude Code loads a rule file when a session reads or writes a file its `paths:` frontmatter matches, and after a write only once the write is done. Read a rule file before you create a file it covers.
Docs, comments and what a program prints — `--help`, an error, a log line — assert checkable things: a command, a resolution rule, a path, a limit. Verify one before you repeat or build on it. When it is wrong, correct it in the same change: the claim — or the code, when consumers already rely on what the claim promises. Never work around it or record the discrepancy elsewhere.
- The decision log: `~/.claude/rules/decisions.md`.
- README goals and audience: `~/.claude/rules/goals-and-audience.md`.
- `todo.md` items, their scores and Exempt reasons: `~/.claude/rules/todo-items.md`.
### Comments
The rules below govern prose comments; doc comments a tool consumes — docstrings, godoc, JSDoc types — are outside them.
Default to NO comment. Delete one that is any of:
1. A **restatement** of the adjacent code. BANNED: `// Sanitized + bounded to 1000 chars` above `mb_substr(json_encode(LogSanitizer::body($x)), 0, 1000)`.
2. A **cross-cutting convention** used elsewhere (sanitization, the 1000-char Loki cap, "log so the source is recoverable"). Project-wide facts live in ONE doc, never repeated at call sites.
3. A **justification of self-evident code** (a log line is self-evidently for observing its value).
4. A **file preamble or arrangement rationale**: what a file holds, why it exists, why two things share it, why a check sits beside what it judges, why an order was chosen. The file name and the declarations are the index; a choice with no effect on the running program belongs in the commit that made it.
**What stays is one terse line, and only where the code cannot show it.** GOOD: `# Pinned to 7.x: hurl 8's jsonpath change breaks the nth-filter asserts.` A second line belongs in the commit message or the ticket. The one exception is a paragraph for an invariant a reader must hold before touching the code below; it stays with the code it guards.
**Density is a review signal.** Prose comment lines much past ~10% of a file's non-blank lines mean something is wrong — narrating comments, or code that fails to carry its own meaning. A defect to investigate.
### Negation, history and limitations: name the action, or say nothing
Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**.
### Links and pointers
**Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link. Don't summarize what's behind the link or restate the identifier's own name.
**A pointer is not a definition.** A definition the reader needs to follow the code — what a unit counts, what a term means, what invariant a cache rests on — sits at the code in one line. A pointer to it (`see AGENTS.md §11`) cannot be checked against the code beside it, so it rots invisibly. A pointer carrying rationale — a rejected alternative, the premise behind a standing choice — is correct and stays.
### Decisions: one home, each linked to a goal or a technical principle
**A choice that shapes what the code does, made in one place, is a comment there, with its reason. Made in more than one place, it is a decision, and the decision log owns it.** A decision's rejected alternative, or what it deliberately does not cover, stays out of every call site. **The decision log has one home: `docs/decisions.md`**. A title states the whole decision in one line: what holds at the commit it ships in, in words a reader finds in the code or the plan. `AGENTS.md` lists every title, so a session works by the decisions without loading their background. A session reads the entry under a title only to question, revise or add a decision. The entry holds the background: its date, who made it, the reasoning, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A choice found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves: to a comment at its one place, or, once made in more than one place, to the log, leaving its title in `AGENTS.md`'s list. A goal stays a goal in the README; the log records only what the goal leaves open.
**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — "Ask, don't guess" under "Working loop" says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it.
### README
**A README covers what a reader needs *before* opening the code**: how it meets its goals, how to build, test, run, and deploy it, and cross-cutting decisions no single file owns. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift.
**"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it.
### Package README (what someone finds on npm or GitHub)
- The public API is the contract, so the README documents it: options, results, events, everything exported. The rule against narrating a file or test case still holds.
- Sections, in order: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts. Each quick start opens with a line or two that links its in-depth section.
- Keep every documented behaviour, as facts, bullets and tables rather than paragraphs. Where the README is the only record of a behaviour, cutting it is a decision to ask about, not a tidy-up.
- Write for the app developer using the package.
- Top: badges (package version, CI), a one-line tagline that is also the package manifest's description, a feature list, a one-line table of contents. Near the bottom: a table of everything exported.
- A guide for migrating from an older major goes in `MIGRATION.md`, linked from one line in the README.
### Public API specs
- Text in public API specs (OpenAPI `description`/`title` fields and the generated api-docs) is read by external consumers. Never leak internal references: no ticket IDs, internal URLs, repo/system code-names, "see ticket X". Describe behaviour in consumer terms. GOOD: `Deprecated alias for paymentAccountId`. BANNED: `…will be removed (ABC-123)`.
- The opposite of internal code comments, which *may* cite a ticket for a footgun/constraint.
The rules only reviewers apply, for quality, comments, READMEs and prose, live in `~/.claude/skills/larv-review/standards/`.
## Working with the codebase
- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out.
@@ -116,24 +51,18 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`,
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app <tool> …`.
- 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.)
- Check `README.md` first for build, test, install, and codegen commands, and fix one that misbehaves in the same change. Refresh `README.md` whenever you change what it describes, keeping it true, not longer.
- 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/`.
- Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`.
## Technical principles
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.
- PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title).
- Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`.
- Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both.
@@ -143,16 +72,12 @@ The rules every project follows, compose-not-entangle first: `~/.claude/principl
## Web research
- **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible.
- Default to `WebSearch`/`WebFetch`. When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw <url> [options]` (see its README). Don't use claude-in-chrome for this.
## Maintaining this file
- When you spot a pattern in how I work that isn't written here — a preference I've repeated, a correction I've given more than once, a convention you inferred from my code — tell me and ask me to write it up here. Don't add it silently, and don't just keep it in a memory file.
- After every change to this file, re-read the whole thing and restructure it: merge overlapping rules, cut prose that restates a rule, move rules to the section they belong in, drop what's now covered elsewhere. Same information, easier to read and shorter.
- When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw <url> [options]` (see its README). Don't use claude-in-chrome for this.
## Vocabulary
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `AGENTS.md`, `docs/decisions.md` or `~/.claude/CLAUDE.md`.
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/`.
- **gate** — the merge gate: the checks a PR passes before it merges.
- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
+4 -1
View File
@@ -1,6 +1,6 @@
# Claude Code configuration
My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; and `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review.
My personal `~/.claude`, version controlled: `CLAUDE.md`, `AGENTS.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; and `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review.
## Goals
@@ -72,10 +72,13 @@ 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, 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
`.gitignore` is an allowlist. Track a file by negating it and its parent directories, then confirm with `git check-ignore -v <path>`:
+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.
+9 -3
View File
@@ -6,7 +6,13 @@ tools: Read, Grep, Glob
You read the prose as someone who did not write it: you see only what it says, never what the author meant.
The bar: `~/.claude/CLAUDE.md` → "Prose" and "Comments and documentation". Read both each time — they change. Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md.
The bar, read each time, since it changes:
- every file under `~/.claude/skills/larv-review/standards/`, of `quality.md` only "A false claim is a bug";
- `~/.claude/CLAUDE.md` → "Public API specs";
- each file under `~/.claude/rules/` whose `paths:` frontmatter matches a file the diff changes.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md.
## Checks, in priority order
@@ -14,10 +20,10 @@ Run them in this order. A fix for a later check never breaks an earlier one.
1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence.
2. **Most important first.** Name the document's reader and what they want to know first. Check that the sections run in that order, then the paragraphs within each section, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**.
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs ("A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs (`~/.claude/skills/larv-review/standards/comments.md` → "Links and pointers", "A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
4. **Short.** Words that do not clearly help 1–3 fail. Fix: **Cut**.
Also report a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
Also report a list whose order carries no meaning and is not sorted (`~/.claude/principles/technical-principles.md` → "Deterministic order"), a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
## Growth
+4 -4
View File
@@ -10,9 +10,9 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
## First Steps
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
2. **Read every file in the shared principles** at `~/.claude/principles/`. These are mandatory org guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently.
2. **Read every file under `~/.claude/principles/`**, the shared principles, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory org guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently.
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them.
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script in a temp dir, a targeted test run — before reporting it. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Put scratch work in a directory you create for this run, and delete it when done; delete nothing else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5. **Two passes minimum, then hunt absences.**
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
- *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity).
@@ -110,9 +110,9 @@ Every PR gets at least this sweep.
- Is naming precise and unambiguous?
- **Does every name in the diff still match its (possibly changed) contents?** When a change meaningfully shifts what a file/folder/package/service/variable does, its name must be updated in the same change — flag a stale name left behind by a content/purpose shift (e.g. a `webhook` test helper reworked into a JWT verifier but still called `webhook`/`WEBHOOK_URL`). The rename belongs in the PR, not "later."
- Are magic numbers/strings replaced with named constants?
- **Judge every comment and prose line the diff adds against `~/.claude/CLAUDE.md` → "Comments and documentation"**; report a density breach with the ratio and the files driving it.
- **Judge every comment and prose line the diff adds against `~/.claude/skills/larv-review/standards/comments.md`, against `readme.md` beside it for a README, and against every file under `~/.claude/rules/` whose `paths:` frontmatter matches its file**; report a density breach with the ratio and the files driving it.
- **Flag a caveat the diff has outlived**, anywhere in the repo: report the sentence's `file:line` and the behaviour that replaced it.
- **Flag a pointer standing where a definition belongs** — `~/.claude/CLAUDE.md` → "Comments and documentation", "A pointer is not a definition".
- **Flag a pointer standing where a definition belongs** — `~/.claude/skills/larv-review/standards/comments.md` → "Links and pointers", "A pointer is not a definition".
- **Never propose new documentation as a "nice to have".** Suggesting a doc paragraph is proposing bulk someone must maintain. Raise it as a 🟡 only when its absence would actively mislead someone, and say which mistake it prevents; otherwise don't raise it at all. Deleting redundant prose is always the cheaper fix.
- **Never let documentation stand in for a fix.** A finding is not closed by describing the defect in a README, and neither is one of yours: if the only available remedy is telling the reader, say so and mark it a decision for the human, so it lands in the PR or ticket where a decision record belongs. Naming a residual risk is your job; choosing to publish it in the repo is not yours to hand out.
+1 -1
View File
@@ -17,7 +17,7 @@ You are an elite Systems Architect with decades of experience designing software
**Question the requirement, not just the structure.** Complexity with a reason is not automatically worth its cost. For every complexity hotspot — reasoned or not — name the requirement that forces it and sketch the simpler design that drops or relaxes it. When a near-equivalent solution achieves almost the same result far more simply, propose the trade and name the delta precisely ("drop per-source ordering → the entire reorder buffer disappears") so the owner can accept or reject it. A small, named loss of functionality bought with a large complexity reduction is one of the best wins available — surfacing that option is your job; deciding it is the owner's.
**Simple to reason about, not merely simple to call.** A clean external API over a core you cannot follow to the bottom is a shallow win. Trace the key data structures and core abstractions down to their foundation and confirm the core is genuinely simple to *understand*, not just convenient to *implement against*. In Ousterhout's terms: prefer deep modules (simple interface, real work hidden) over shallow ones; complexity is dependencies + obscurity, and it surfaces as change amplification (one change touches many places) and cognitive load (a reader must hold too much in their head). Hunt both, all the way down.
**Simple to reason about, not merely simple to call.** A clean external API over a core you cannot follow to the bottom is a hollow win. Trace the key data structures and core abstractions down to their foundation and confirm the core is genuinely simple to *understand*, not just convenient to *implement against*. Hold every module to "Prefer deep modules" in `~/.claude/principles/technical-principles.md`. Complexity is dependencies + obscurity, and it surfaces as change amplification (one change touches many places) and cognitive load (a reader must hold too much in their head). Hunt both, all the way down.
**Be non-pragmatic about fundamentals.** You are deliberately uncompromising on architectural choices that shape the system for years. Do not bend on:
- Functional core, imperative shell separation
@@ -6,7 +6,6 @@ import shutil
import uuid
from failure import Failure
from loop_claude.paths import Paths
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@@ -19,10 +18,8 @@ class Session:
name: str
def session_for(project_key: str, paths: Paths) -> Session:
# "A " is the human's cue in the session picker that the session is the loop's.
name = f"A {project_key} loop-claude"
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
def session_named(name: str, claude_code_transcripts: pathlib.Path) -> Session:
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=claude_code_transcripts, name=name)
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
+93
View File
@@ -0,0 +1,93 @@
import json
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from claude_code import entries, transcript, trust
def assistant(*parts):
return {"type": "assistant", "message": {"content": list(parts)}}
def human(content):
return {"type": "user", "message": {"content": content}}
def queued(prompt, kind):
return {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": kind}, "prompt": prompt}}
class Render(unittest.TestCase):
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self):
said = transcript.render([
human("do it"),
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
assistant({"type": "text", "text": " "}),
human([{"type": "tool_result", "content": "not typed"}]),
human("<command-name>/exit</command-name>"),
human([{"type": "text", "text": "yes, "}, {"type": "text", "text": "merge it"}]),
queued("B, while you work", "human"),
queued("origin/main moved", "coordinator"),
{**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"},
])
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.')
class FirstTimestampedLine(unittest.TestCase):
def test_skips_the_lines_every_chunk_shares_and_else_takes_the_first(self):
self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\nnot JSON\n{"timestamp": "t"}\n{"timestamp": "u"}\n'), b'{"timestamp": "t"}')
self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\n[1]\n'), b'{"type": "custom-title"}')
self.assertEqual(transcript.first_timestamped_line(b""), b"")
class HumanTurns(unittest.TestCase):
def test_counts_typed_turns_and_not_tool_results(self):
self.assertEqual(transcript.human_turns([
human("typed"),
human([{"type": "text", "text": "typed as a block"}]),
human([{"type": "tool_result", "content": "not typed"}]),
human("<command-name>/model</command-name>"),
{**human("<3 merge it"), "promptSource": "typed"},
{**human("<task-notification>done</task-notification>"), "promptSource": "system"},
{**human([{"type": "text", "text": "<task-notification>done</task-notification>"}]), "promptSource": "system"},
{**human("peer message"), "isMeta": True},
{**human("the loop's own prompt"), "promptSource": "sdk"},
human([{"type": "text", "text": "[Request interrupted by user]"}]),
human([]),
queued("typed while claude worked", "human"),
queued("<task-notification>done</task-notification>", "task-notification"),
{"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "task-notification", "prompt": "<task-notification>done</task-notification>"}},
assistant({"type": "text", "text": "said"}),
]), 4)
class PartLine(unittest.TestCase):
def test_renders_text_and_tool_calls_and_nothing_else(self):
self.assertEqual(transcript.part_line({"type": "text", "text": "hi"}, 20), "hi")
self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}, 20), "")
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
self.assertEqual(transcript.part_line("not a part", 20), "")
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Write", "input": {"content": "Hälsa på"}}, 40), '[tool Write] {"content": "Hälsa på"}')
class Parse(unittest.TestCase):
def test_yields_only_json_objects(self):
self.assertEqual(entries.parse_entry('{"type": "user"}'), {"type": "user"})
self.assertIsNone(entries.parse_entry("not json"))
self.assertIsNone(entries.parse_entry("[1, 2]"))
class MarkTrusted(unittest.TestCase):
def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self):
config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}}
handed = json.dumps(config)
self.assertEqual(trust.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"]))
self.assertEqual(json.dumps(config), handed)
self.assertEqual(trust.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"]))
if __name__ == "__main__":
unittest.main()
@@ -1,6 +1,6 @@
import json
from loop_claude.claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call
from claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call
from failure import Failure
JUDGED_TOOL_INPUT = 400
+183
View File
@@ -0,0 +1,183 @@
import dataclasses
import decimal
import re
from failure import Failure
from markdown_text import sections
from utc_stamp import utc
ARCHITECT = "Inherited architect"
DECIDED_BY = "decided by"
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
HARDEST_FIRST = "hardest first"
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
HISTORY = "docs/comprehension-history.md"
JUNIOR = "Junior A"
MEAN = "Mean"
MID = "Mid A"
# `path:line` or `:line`, then the unit's name where one follows.
PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?")
RESTRUCTURE_FIRST = "would restructure first"
RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M)
RULED_PLACES = re.compile(rf"^.+, {DECIDED_BY}:$")
SCORED_PLACES = re.compile(rf"^.+, ({HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
SENIOR = "Maintainability senior"
TITLE = "# Comprehension history\n"
@dataclasses.dataclass(frozen=True)
class Seat:
name: str
said: str
places: list[str]
@dataclasses.dataclass(frozen=True)
class Place:
path: str
name: str | None
@dataclasses.dataclass(frozen=True)
class Entry:
"""One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither. A scoring run's places, or those of the scores a fall called into a ruling, are scored_places."""
heading: str
time: str
commit: str
against: str | None
ruling: str | None
ruled_places: list[Place]
scored_places: list[Place]
@property
def paired(self) -> bool:
return self.against is not None
@dataclasses.dataclass(frozen=True)
class HistoryChange:
"""A merged change on the default branch that touched the history, and the history before and after it."""
commit: str
before: str
after: str
@dataclasses.dataclass(frozen=True)
class Heading:
title: str
label: str
commit: str
against: str | None
@dataclasses.dataclass(frozen=True)
class ScoringRun:
"""The four scoring seats' lines, their scores as written and the means, in DIMENSIONS' order."""
seats: list[Seat]
scores: dict[str, list[str]]
means: list[decimal.Decimal]
# A paired ruling as entry_text writes it. A scoring run's heading has no `, against`; it has no Ruling line, ends its table with a Mean row, and labels each seat's places `<seat>, hardest first:` or, for the architect, `<seat>, would restructure first:`.
#
# ## 2026-10-09T09:47:25Z, PR #232 at 324d650, against 12d6d75
#
# Ruling: same
#
# | Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
# |---|---|---|---|---|---|
# | Mid A | better | worse | same | same | better |
#
# Mid A, decided by:
#
# - Locality: `bin/x.py:12` `run`: three branches to hold at once
def entries(history: str) -> list[Entry]:
"""Each paired ruling and scoring run in a comprehension history, in the order the file holds them; a section whose heading names no commit is left out."""
found = []
for heading, bodies in sections(history).items():
if named := HEADING.match(heading):
body = "\n".join(bodies)
ruling = RULING.search(body)
found.append(Entry(heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None, seat_places(body, RULED_PLACES), seat_places(body, SCORED_PLACES)))
return found
def recorded(history: str, read: str) -> bool:
"""Whether the history holds an entry on what a seats file's first line says the seats read."""
return any(entry.heading.partition(", ")[2] == read for entry in entries(history))
def seat_places(body: str, labels: re.Pattern[str]) -> list[Place]:
"""The places under each seat label labels matches."""
places = []
listing = False
for line in body.splitlines():
if labels.match(line):
listing = True
elif listing and line.startswith("- "):
places += bullet_places(line)
elif not line.startswith(" "):
listing = False
return places
def bullet_places(bullet: str) -> list[Place]:
"""A `:line` with no path is in the file named before it in the bullet."""
places = []
path = ""
for match in PLACE.finditer(bullet):
path = match.group(1) or path
if path:
places.append(Place(path, match.group(2)))
return places
def heading(at: float, read: str, paired: bool) -> Heading | Failure:
"""An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read."""
title = f"{utc(at)}, {read}"
if (named := HEADING.match(title)) and bool(named.group(4)) == paired:
return Heading(title, named.group(2), named.group(3), named.group(4))
return Failure(f"the seats file's first line is not `<PR or branch> at <commit>{', against <base>' if paired else ''}`: {read}")
def appended(history: str, entry: str) -> str:
"""The history with entry added last; an empty history gets the file's title first."""
text = history.rstrip("\n") + "\n" if history.strip() else TITLE
return f"{text}\n{entry}"
def ruling_entry(title: str, seats: list[Seat], said: dict[str, list[str]], counted: dict[str, list[str]], ruled: str, notes: list[str], scoring: ScoringRun | None) -> str:
"""A paired ruling's entry, with any notes, such as why a fall decided it, and the scores that decided a fall; a seat's vote that counted as same for want of a place says so."""
votes = [[seat.name, *map(vote_text, DIMENSIONS, said[seat.name], counted[seat.name])] for seat in seats]
tables = [[["Seat", *DIMENSIONS], *votes]] + ([scores_table(scoring)] if scoring else [])
labels = [(f"{seat.name}, {DECIDED_BY}:", seat.places) for seat in seats] + (scoring_labels(scoring.seats) if scoring else [])
return entry_text(title, [f"Ruling: {ruled}", *notes], tables, labels)
def vote_text(dimension: str, said: str, counted: str) -> str:
if counted == said:
return counted
return f"same (voted {said}, naming no place)" if dimension == DIMENSIONS[-1] else f"same (voted {said}, no place naming {dimension})"
def scoring_entry(title: str, scoring: ScoringRun) -> str:
return entry_text(title, [], [scores_table(scoring)], scoring_labels(scoring.seats))
def scores_table(scoring: ScoringRun) -> list[list[str]]:
return [["Seat", *DIMENSIONS], *([seat, *values] for seat, values in scoring.scores.items()), [MEAN, *map(str, scoring.means)]]
def scoring_labels(seats: list[Seat]) -> list[tuple[str, list[str]]]:
return [(f"{seat.name}, {RESTRUCTURE_FIRST if seat.name == ARCHITECT else HARDEST_FIRST}:", seat.places) for seat in seats]
def entry_text(title: str, lines: list[str], tables: list[list[list[str]]], seats: list[tuple[str, list[str]]]) -> str:
"""The heading, any lines such as `Ruling: same`, each table, whose first row is its header, and under each seat's label its places, one bullet each."""
parts = [f"## {title}", *lines, *("\n".join([row_text(header), "|" + "---|" * len(header), *map(row_text, rows)]) for header, *rows in tables)]
parts += [f"{label}\n\n" + "\n".join(f"- {place}" for place in places) for label, places in seats if places]
return "\n\n".join(parts) + "\n"
def row_text(cells: list[str]) -> str:
return "| " + " | ".join(cells) + " |"
+58
View File
@@ -0,0 +1,58 @@
import dataclasses
from shell_command import resolved, Simple
# git's global options that take a value as the next word.
GIT_VALUED = {"-C", "-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"}
@dataclasses.dataclass(frozen=True)
class Commit:
directory: str
messages: list[str]
from_file: bool
def commits(simples: list[Simple], home: str) -> list[Commit]:
found = []
for simple in simples:
invoked = git_subcommand(simple.words, simple.directory, home)
if invoked and invoked[0] == "commit":
found.append(Commit(invoked[2], *commit_message(invoked[1])))
return found
def git_subcommand(words: list[str], directory: str, home: str) -> tuple[str, list[str], str] | None:
"""A git command's subcommand, its arguments and the directory it runs in, after git's own options such as -C."""
if words[:1] != ["git"]:
return None
args = iter(words[1:])
for word in args:
if word in GIT_VALUED:
value = next(args, "")
directory = resolved(directory, value, home) if word == "-C" else directory
elif not word.startswith("-"):
return word, list(args), directory
return None
def commit_message(args: list[str]) -> tuple[list[str], bool]:
"""git commit's messages, and whether it reads one from a file."""
messages = []
from_file = False
words = iter(args)
for word in words:
if word == "--":
break
name, equals, value = word.partition("=")
if name in ("--message", "--file"):
given = value if equals else next(words, "")
elif word.startswith("-") and not word.startswith("--") and (flags := [flag for flag in word[1:] if flag in "mF"]):
# A cluster such as -am: the valued flag takes the rest of the word, or else the next word.
name = "--message" if flags[0] == "m" else "--file"
given = word[word.index(flags[0]) + 1:] or next(words, "")
else:
continue
messages += [given] if name == "--message" else []
from_file = from_file or name == "--file"
return messages, from_file
+1 -3
View File
@@ -2,9 +2,7 @@ import re
import subprocess
from failure import Failure
from larv_review.history import HistoryChange
HISTORY = "docs/comprehension-history.md"
from comprehension_history import HISTORY, HistoryChange
def git(*args: str) -> str | Failure:
-137
View File
@@ -1,137 +0,0 @@
import dataclasses
import re
import time
from larv_review.seats import ARCHITECT, DIMENSIONS, MEAN, Seat
from failure import Failure
from markdown_sections import sections
DATED = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}(?:T[0-9]{2}:[0-9]{2}:[0-9]{2}Z)?, ")
DECIDED_BY = "decided by"
HARDEST_FIRST = "hardest first"
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
# `path:line` or `:line`, then the unit's name where one follows.
PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?")
RESTRUCTURE_FIRST = "would restructure first"
RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M)
SEAT_PLACES = re.compile(rf"^.+, ({DECIDED_BY}|{HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
STAMP = "%Y-%m-%dT%H:%M:%SZ"
TITLE = "# Comprehension history\n"
@dataclasses.dataclass(frozen=True)
class Place:
path: str
name: str | None
@dataclasses.dataclass(frozen=True)
class Entry:
"""One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither."""
heading: str
time: str
commit: str
against: str | None
ruling: str | None
places: list[Place]
@property
def paired(self) -> bool:
return self.against is not None
@dataclasses.dataclass(frozen=True)
class Heading:
title: str
commit: str
against: str | None
@dataclasses.dataclass(frozen=True)
class HistoryChange:
"""A merged change on the default branch that touched the history, and the history before and after it."""
commit: str
before: str
after: str
def entries(history: str) -> list[Entry]:
"""Each paired ruling and scoring run in a comprehension history, in the order the file holds them; a section whose heading names no commit is left out."""
found = []
for heading, bodies in sections(history).items():
if named := HEADING.match(heading):
body = "\n".join(bodies)
ruling = RULING.search(body)
found.append(Entry(heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None, seat_places(body)))
return found
def seat_places(body: str) -> list[Place]:
places = []
listing = False
for line in body.splitlines():
if SEAT_PLACES.match(line):
listing = True
elif listing and line.startswith("- "):
places += bullet_places(line)
elif not line.startswith(" "):
listing = False
return places
def bullet_places(bullet: str) -> list[Place]:
"""A `:line` with no path is in the file named before it in the bullet."""
places = []
path = ""
for match in PLACE.finditer(bullet):
path = match.group(1) or path
if path:
places.append(Place(path, match.group(2)))
return places
def heading(at: float, read: str, paired: bool, moved: bool) -> Heading | Failure:
"""An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read. A run moved from a decision entry opens instead with the date or time that entry gives."""
if moved and not DATED.match(read):
return Failure(f"a seats file holding a {MEAN} line alone opens with YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ, then `, `: {read}")
if DATED.match(read) and not moved:
return Failure(f"only a seats file holding a {MEAN} line alone opens with a date: {read}")
title = read if moved else f"{time.strftime(STAMP, time.gmtime(at))}, {read}"
if (named := HEADING.match(title)) and bool(named.group(4)) == paired:
return Heading(title, named.group(3), named.group(4))
return Failure(f"the seats file's first line is not `<PR or branch> at <commit>{', against <base>' if paired else ''}`: {read}")
def appended(history: str, entry: str) -> str:
"""The history with entry added last; an empty history gets the file's title first."""
text = history.rstrip("\n") + "\n" if history.strip() else TITLE
return f"{text}\n{entry}"
def ruling_entry(title: str, seats: list[Seat], counted: dict[str, str], ruled: str) -> str:
"""A paired ruling's entry; a seat's vote that counted as same for naming no place says so."""
votes = [[seat.name, vote_text(seat, counted[seat.name])] for seat in seats]
return entry_text(title, [f"Ruling: {ruled}"], [["Seat", "Vote"], *votes], [(f"{seat.name}, {DECIDED_BY}:", seat.places) for seat in seats])
def vote_text(seat: Seat, counted: str) -> str:
return counted if counted == seat.said else f"same (voted {seat.said}, naming no place)"
def scoring_entry(title: str, seats: list[Seat], scores: dict[str, list[str]], means: list[str]) -> str:
"""A scoring run's entry; a run moved from a decision entry has its means alone."""
rows = [[seat, *values] for seat, values in scores.items()] + [[MEAN, *means]]
labels = [(f"{seat.name}, {RESTRUCTURE_FIRST if seat.name == ARCHITECT else HARDEST_FIRST}:", seat.places) for seat in seats]
return entry_text(title, [], [["Seat", *DIMENSIONS], *rows], labels)
def entry_text(title: str, lines: list[str], table: list[list[str]], seats: list[tuple[str, list[str]]]) -> str:
"""The heading, any lines such as `Ruling: same`, a table whose first row is its header, and under each seat's label its places, one bullet each."""
header, *rows = table
parts = [f"## {title}", *lines, "\n".join([row_text(header), "|" + "---|" * len(header), *map(row_text, rows)])]
parts += [f"{label}\n\n" + "\n".join(f"- {place}" for place in places) for label, places in seats if places]
return "\n\n".join(parts) + "\n"
def row_text(cells: list[str]) -> str:
return "| " + " | ".join(cells) + " |"
+76 -137
View File
@@ -1,11 +1,17 @@
"""Hold larv-review's mechanical rules: the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger, and the comprehension history's format.
usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <seats file> | record-scoring <seats file>
usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> [<scores file>] | record-scoring <scores file> [<item ID>...]
Run it inside a project checkout or one of its worktrees. ruling-base, round-count and
needs-scoring-run first fetch origin, when the checkout has that remote, and take origin's default
branch, or else the local main or master, as the default branch. When the fetch fails, round-count
reads origin as last fetched and says so on stderr; the other two exit 1. The history is
The comprehension check keeps a project from reading worse, two ways. In a paired ruling, simulated
readers, the seats, read
the branch's head beside a base and vote better, same or worse, overall and on each dimension; a
worse ruling blocks the merge, which is the ratchet. In a scoring run, four seats score the project
from 1 to 10; a mean under the floor of {floor} blocks the merge, unless you decide to ship.
Run it inside a project checkout or one of its worktrees. Each command but record-ruling first
fetches origin, when the checkout has that remote, and takes origin's default branch, or else the
local main or master, as the default branch. When the fetch fails, round-count reads origin as
last fetched and says so on stderr; the other three exit 1. The history is
docs/comprehension-history.md in the checkout.
ruling-base prints the commit a paired ruling reads against, then which of these found it. The last
@@ -14,9 +20,10 @@ history, or whose last added paired ruling, by heading time, is better; a merge
one change against its first parent. With none, the base is the one the history's first paired
ruling names; with no ruling either, it is the merge base of HEAD and the default branch.
round-count prints each pass's count: the highest <n> among the titles opening
`Answer <pass> round <n>:` of commits the default branch does not hold. It marks each pass at the
cap of {cap} rounds, and each name in such a title that is not a pass.
round-count prints each pass's round count among the commits not yet on the default branch whose
titles open `Answer <pass> round <n>:`, ignoring case. The count is the highest <n>, or the number of
such commits when that is more. At or past the cap of {cap} rounds, it says to ask the human before
another round. It also lists each name in such a title that is not a pass.
needs-scoring-run takes the IDs of the todo.md items the chunk ships, none when it ships none, and
prints why the chunk is due a scoring run, or `No scoring run due.` It is due when the chunk ships
@@ -26,59 +33,70 @@ landed when the chunk ships one of the release's items, or when the release is t
default branch's todo.md names and the default branch has a commit after its newest v* tag, or has
no v* tag.
record-ruling and record-scoring read a seats file: a first line naming what the seats read,
`<PR or branch> at <commit>`, ending `, against <base>` for a paired ruling, then each seat's
line, each followed by its places, one `- ` bullet each, as the history writes them. A seat's line
opens with its label, written exactly: `Junior A:`, `Mid A:`, `Maintainability senior:` or
`Inherited architect:`.
A seats file's first line names what the seats read, `<PR or branch> at <commit>`, ending
`, against <base>` in a votes file. Each seat's line follows, opening with its label written
exactly: `Junior A:`, `Mid A:`, `Maintainability senior:` or `Inherited architect:`. Its places
follow it, one `- ` bullet each, as the history writes them. A votes file:
PR #231 at abc1234, against def5678
Mid A: worse
Mid A: Navigation better, Locality worse, Shape same, Self-sufficiency same, Overall better
- `bin/x.py:12` `run`: three branches to hold at once
- Navigation, Overall: `README.md:40` "Tools": names the tool a symptom leads to
- Locality: `bin/x.py:12` `run`: three branches to hold at once
Inherited architect: worse
Inherited architect: Navigation better, Locality worse, Shape same, Self-sufficiency same, Overall better
- `bin/x.py:12` `run`: ...
- Navigation: `README.md:40` "Tools": ...
- Locality: `bin/x.py:12` `run`: ...
record-ruling takes Mid A's and the inherited architect's votes, better, same or worse; a better or
worse vote naming no place in backticks, `path:line`, counts as same, and the printed votes say so.
When the two counted votes differ, it appends nothing and prints `Split:`, saying to add the
maintainability senior's and Junior A's lines. Otherwise the ruling is the vote that leads each
other vote by two or more, else same; it prints `Ruling:` and appends the ruling.
A scores file holds Junior A's, Mid A's, the maintainability senior's and the inherited architect's
lines in that order, each `Navigation <n>, Locality <n>, Shape <n>, Self-sufficiency <n>, Overall
<n>`: each score from 1 to 10, and the overall at most 1 above the line's lowest dimension.
record-scoring takes Junior A's, Mid A's, the maintainability senior's and the inherited
architect's lines in that order, or a `Mean:` line alone for a run moved from a decision entry.
Each line is `Navigation <n>, Locality <n>, Shape <n>, Self-sufficiency <n>, Overall <n>`, each
score from 1 to 10 and the overall at most 1 above the line's lowest dimension. Its first line
names no `, against`. It appends the seats' scores and their means, rounded half up to two
decimals, and prints the means and each one under the floor of {floor}.
record-ruling takes Mid A's and the inherited architect's votes on each dimension and overall, each
better, same or worse. Each place opens with the names from the seat's line that it moves, joined by
`, ` and followed by `: `. A dimension's vote counts as same unless one of the seat's places opens
with that dimension and holds a `path:line` in backticks; the overall vote counts as same unless any
place holds one. The printed votes say so. When the two counted overall votes differ, it appends
nothing and prints `Split:`, saying to add the maintainability senior's and Junior A's lines.
Otherwise the ruling is the overall vote that leads each other vote by two or more, else same. A
dimension falls when its worse votes lead each other vote by two or more. When a better or same
ruling has a fallen dimension, it appends nothing and prints `Fell:`, saying to run the four
scoring seats on the same commit and run it again with their scores file. With that file, the
ruling counts as worse when a fallen dimension's mean is under the floor of {floor}, and stands
otherwise. It prints `Ruling:` and appends the ruling, with the scores where a fall called them.
record-scoring takes the scores file of a run needs-scoring-run calls, whose first line names no
`, against`, and the same item IDs, and exits 1 when they call no run: each scoring run moves the
ratchet's base. It appends the seats' scores and their means, rounded half up to two decimals,
prints the means and, when a mean is under the floor of {floor}, a line opening `Floor:` naming
each one, which blocks the merge.
Each record is appended to the history, created when missing, under a heading of the current UTC
time and the seats file's first line. A file holding a `Mean:` line alone opens with the date or
time its decision entry gives, and that line alone is the heading. Each commit the line names
must be in the checkout. Each run appends, so record a ruling or a run once.
time and the seats file's first line. Each commit that line names must be in the checkout. It exits 1
when the history already holds an entry on what that line reads.
Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that
breaks the shape above, or when git cannot start, finds no checkout or no default branch, cannot
fetch origin for ruling-base or needs-scoring-run, or cannot read or write the history or todo.md.
breaks the shape above, a scores file record-ruling did not call for or one naming another commit,
or when git cannot start, finds no checkout or no default branch, cannot
fetch origin for ruling-base, needs-scoring-run or record-scoring, or cannot read or write the history or todo.md.
"""
import pathlib
import re
import sys
import time
import typing
from larv_review.history import appended, heading, ruling_entry, scoring_entry, vote_text
from larv_review.rules import base, CAP, FLOOR, means, PASSES, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes
from larv_review.git import commit_exists, default_branch, file_at, git, HISTORY, history_changes, landed_since_release, top
from larv_review.seats import DIMENSIONS, MEAN, Report, report, score_line, scores
from larv_review.ruling_base import base
from larv_review.rounds import CAP, PASSES, round_counts
from larv_review.git import default_branch, file_at, git, history_changes
from failure import Failure
from rank_todo import ITEMS_HEADER
from file_writes import replace_file
from larv_review.scoring import FLOOR
from comprehension_history import HISTORY
from larv_review.plan import plan_reasons
from larv_review.record import record_ruling, record_scoring
USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <seats file> | record-scoring <seats file>"
USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> [<scores file>] | record-scoring <scores file> [<item ID>...]"
def main(argv: list[str]) -> int:
@@ -87,17 +105,18 @@ def main(argv: list[str]) -> int:
return 0
command, *given = argv or [""]
if command == "ruling-base" and not given:
done = with_default_branch(ruling_base, stale_ok=False)
done = with_default_branch(show_ruling_base, stale_ok=False)
elif command == "round-count" and not given:
done = with_default_branch(round_count, stale_ok=True)
elif command == "needs-scoring-run" and all(re.fullmatch(r"[0-9]+", id_) for id_ in given):
done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)
elif command == "record-ruling" and len(given) == 1:
done = record_ruling(pathlib.Path(given[0]))
elif command == "record-scoring" and len(given) == 1:
done = record_scoring(pathlib.Path(given[0]))
elif command == "needs-scoring-run":
print(f"needs-scoring-run takes item IDs, the numbers in todo.md's ID column: {' '.join(given)}", file=sys.stderr)
elif command == "record-ruling" and len(given) in (1, 2):
done = record_ruling(*map(pathlib.Path, given))
elif command == "record-scoring" and given and all(re.fullmatch(r"[0-9]+", id_) for id_ in given[1:]):
done = with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False)
elif command in ("needs-scoring-run", "record-scoring") and given:
named = given[1:] if command == "record-scoring" else given
print(f"{command} takes item IDs, the numbers in todo.md's ID column, not {' '.join(id_ for id_ in named if not re.fullmatch(r'[0-9]+', id_))}; {USAGE}", file=sys.stderr)
return 1
elif not argv:
print(USAGE, file=sys.stderr)
@@ -121,7 +140,7 @@ def with_default_branch(command: typing.Callable[[str], Failure | None], stale_o
return command(branch)
def ruling_base(default: str) -> Failure | None:
def show_ruling_base(default: str) -> Failure | None:
changes = history_changes(default)
if isinstance(changes, Failure):
return changes
@@ -143,99 +162,19 @@ def round_count(default: str) -> Failure | None:
if isinstance(titles, Failure):
return titles
for name, count in round_counts(titles.splitlines()).items():
print(f"{name}: {count}{', at the cap' if count >= CAP else ''}{'' if name in PASSES else ', not a pass: check the commit title'}")
print(f"{name}: {count}{cap_note(count) if name in PASSES else ', not a pass: check the commit title'}")
return None
def cap_note(count: int) -> str:
if count < CAP:
return ""
return f", {'at' if count == CAP else 'past'} the cap: ask the human before another round"
def needs_scoring_run(default: str, ids: list[int]) -> Failure | None:
checkout = top()
if isinstance(checkout, Failure):
return checkout
before = file_at(default, "todo.md")
if isinstance(before, Failure):
return before
try:
after = pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read todo.md: {failure}")
# While a chunk reshapes todo.md into one table, the default branch's todo.md has no items table.
planned = plan_items(before) if ITEMS_HEADER in before.splitlines() else []
if isinstance(planned, Failure):
return Failure(f"{default}'s todo.md: {planned.reason}")
chunk = plan_items(after)
if isinstance(chunk, Failure):
return Failure(f"the checkout's todo.md: {chunk.reason}")
landed = landed_since_release(default)
if isinstance(landed, Failure):
return landed
reasons = scoring_run_due(planned, chunk, ids, landed)
reasons = plan_reasons(default, ids)
if isinstance(reasons, Failure):
return reasons
print(f"Scoring run due: the chunk {' and '.join(reasons)}." if reasons else "No scoring run due.")
return None
def record_ruling(seats_file: pathlib.Path) -> Failure | None:
read = read_seats(seats_file, paired=True)
if isinstance(read, Failure):
return read
title, given = read
counted = votes(given.seats)
if isinstance(counted, Failure):
return counted
tally = ", ".join(f"{seat.name} {vote_text(seat, counted[seat.name])}" for seat in given.seats)
ruled = ruling(list(counted.values()))
if ruled is None:
print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.")
return None
print(f"Ruling: {ruled}. Votes as counted: {tally}.")
return append(ruling_entry(title, given.seats, counted, ruled))
def record_scoring(seats_file: pathlib.Path) -> Failure | None:
read = read_seats(seats_file, paired=False)
if isinstance(read, Failure):
return read
title, given = read
found = scores(given.seats) if given.moved_mean is None else {}
if isinstance(found, Failure):
return found
moved = [] if given.moved_mean is None else score_line(MEAN, given.moved_mean)
if isinstance(moved, Failure):
return moved
mean = means(list(found.values()) or [moved])
under = under_floor(mean)
print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, mean))}. {f'Under the floor of {FLOOR}: ' + ', '.join(under) if under else f'None under the floor of {FLOOR}'}.")
return append(scoring_entry(title, given.seats, found, [str(value) for value in mean]))
def read_seats(seats_file: pathlib.Path, paired: bool) -> tuple[str, Report] | Failure:
"""The seats file, and the heading its record goes under, once each commit it names is in the checkout."""
try:
given = report(seats_file.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {seats_file}: {failure}")
if isinstance(given, Failure):
return given
named = heading(time.time(), given.read, paired, given.moved_mean is not None)
if isinstance(named, Failure):
return named
if unknown := [commit for commit in (named.commit, named.against) if commit and not commit_exists(commit)]:
return Failure(f"the seats file names {', '.join(unknown)}, which is no commit in this checkout")
return named.title, given
def append(entry: str) -> Failure | None:
checkout = top()
if isinstance(checkout, Failure):
return checkout
history = pathlib.Path(checkout, HISTORY)
try:
text = history.read_text(encoding="utf-8") if history.exists() else ""
history.parent.mkdir(parents=True, exist_ok=True)
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {history}: {failure}")
if unwritten := replace_file(history, appended(text, entry).encode()):
return Failure(f"could not write {history}: {unwritten.reason}")
print(f"Appended to {history}.")
return None
+54
View File
@@ -0,0 +1,54 @@
import pathlib
from failure import Failure
from larv_review.git import file_at, landed_since_release, top
from todo_table import Item, items, ITEMS_HEADER
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool) -> list[str] | Failure:
"""Why the plan calls a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, and landed whether the default branch holds a commit after its newest release tag.
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. Work has landed when the chunk ships one of the release's items, or when the release is the earliest one `before` names and `landed` holds. That covers a release whose last item moved to another release.
"""
plan = {item.id: item for item in before + after}
if unknown := sorted(set(ships) - set(plan)):
return Failure(f"neither plan holds item {', '.join(map(str, unknown))}")
shipped = [plan[id_] for id_ in ships]
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if "comprehension floor" in item.tagline.lower()]
next_release = min((item.release for item in before), default=None)
for release in emptied(before, after, shipped):
if any(item.release == release for item in shipped) or (release == next_release and landed):
reasons.append(f"leaves release {'.'.join(map(str, release))} with no plan item")
return reasons
def emptied(before: list[Item], after: list[Item], shipped: list[Item]) -> list[tuple[int, int, int]]:
"""Each release the default branch's plan or a shipped item names that the chunk's plan, less the shipped items, names no longer."""
named = {item.release for item in before + shipped}
left = {item.release for item in after if item.id not in {ship.id for ship in shipped}}
return sorted(named - left)
def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
"""Why the plan calls a scoring run, from the default branch's todo.md and the checkout's."""
checkout = top()
if isinstance(checkout, Failure):
return checkout
before = file_at(default, "todo.md")
if isinstance(before, Failure):
return before
try:
after = pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read todo.md: {failure}")
# While a chunk reshapes todo.md into one table, the default branch's todo.md has no items table.
planned = items(before) if ITEMS_HEADER in before.splitlines() else []
if isinstance(planned, Failure):
return Failure(f"{default}'s todo.md: {planned.reason}")
chunk = items(after)
if isinstance(chunk, Failure):
return Failure(f"the checkout's todo.md: {chunk.reason}")
landed = landed_since_release(default)
if isinstance(landed, Failure):
return landed
return scoring_run_due(planned, chunk, ids, landed)
+135
View File
@@ -0,0 +1,135 @@
import pathlib
import time
from comprehension_history import appended, DIMENSIONS, heading, Heading, HISTORY, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
from larv_review.git import commit_exists, top
from larv_review.ruling import counted, fallen, overall, ruling, split, votes
from failure import Failure
from larv_review.scoring import fall_ruling, FLOOR, means, under_floor
from larv_review.plan import plan_reasons
from file_writes import replace_file
from larv_review.seats import scores, seats_file, SeatsFile
def record_ruling(votes_file: pathlib.Path, scores_file: pathlib.Path | None = None) -> Failure | None:
read = read_seats(votes_file, paired=True)
if isinstance(read, Failure):
return read
heading_read, seats_read = read
written = votes(seats_read.seats)
if isinstance(written, Failure):
return written
counts = counted(seats_read.seats, written)
tally = ", ".join(f"{seat.name} {vote_text(DIMENSIONS[-1], overall(written[seat.name]), overall(counts[seat.name]))}" for seat in seats_read.seats)
overall_votes = [overall(each) for each in counts.values()]
if split(overall_votes):
print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the votes file, and run this again.")
return None
ruled = ruling(overall_votes)
fell = fallen(counts) if ruled != "worse" else []
scoring = None
notes = []
if not fell and scores_file:
why = "a worse ruling takes no scores file" if ruled == "worse" else f"no dimension fell in this {ruled} ruling, so it takes no scores file"
return Failure(f"{why}; run record-ruling again with the votes file alone")
if fell and not scores_file:
print(f"Fell: {', '.join(fell)}, in a {ruled} ruling. Launch the four scoring seats on {heading_read.label} at {heading_read.commit}, write their lines to a scores file, and run this again with both files.")
return None
if fell and scores_file:
scored = read_fall_scores(scores_file, heading_read)
if isinstance(scored, Failure):
return scored
scoring = scored
ruled, why = fall_ruling(ruled, fell, scoring.means)
notes = [why]
print(f"Ruling: {ruled}. {' '.join(notes + [f'Overall votes as counted: {tally}.'])}")
return append(seats_read.read, ruling_entry(heading_read.title, seats_read.seats, written, counts, ruled, notes, scoring))
def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> Failure | None:
read = read_seats(scores_file, paired=False)
if isinstance(read, Failure):
return read
named, given = read
scoring = scored_seats(given)
if isinstance(scoring, Failure):
return scoring
reasons = plan_reasons(default, ids)
if isinstance(reasons, Failure):
return reasons
if not reasons:
return Failure("no plan item or release calls this scoring run; name the item IDs the chunk ships, as needs-scoring-run took them, or record a fall's scores with record-ruling")
print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, scoring.means))}.")
if under := under_floor(scoring.means):
print(f"Floor: {', '.join(under)} under the floor of {FLOOR} block the merge, as the chunk {' and '.join(reasons)}.")
return append(given.read, scoring_entry(named.title, scoring))
def read_fall_scores(scores_file: pathlib.Path, votes: Heading) -> ScoringRun | Failure:
"""The scores a fall called, once their file names what the votes file read."""
read = read_seats(scores_file, paired=False, refuse_recorded=False)
if isinstance(read, Failure):
return read
named, given = read
if (named.label, named.commit) != (votes.label, votes.commit):
return Failure(f"the scores file's first line is not `{votes.label} at {votes.commit}`, as the votes file reads: {given.read}")
return scored_seats(given)
def scored_seats(given: SeatsFile) -> ScoringRun | Failure:
found = scores(given.seats)
if isinstance(found, Failure):
return found
return ScoringRun(given.seats, found, means(list(found.values())))
def read_seats(path: pathlib.Path, paired: bool, refuse_recorded: bool = True) -> tuple[Heading, SeatsFile] | Failure:
"""The seats file and the heading its record goes under. Fails when the file names a commit the checkout lacks, or, when refuse_recorded, when the history already holds an entry on what it reads; it runs before anything is printed."""
try:
given = seats_file(path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {path}: {failure}")
if isinstance(given, Failure):
return given
named = heading(time.time(), given.read, paired)
if isinstance(named, Failure):
return named
if unknown := [commit for commit in (named.commit, named.against) if commit and not commit_exists(commit)]:
return Failure(f"the seats file names {', '.join(unknown)}, which is no commit in this checkout")
if refuse_recorded:
history = history_file()
if isinstance(history, Failure):
return history
if recorded(history[1], given.read):
return Failure(f"{history[0]} already holds an entry on {given.read}; record each ruling or run once")
return named, given
def history_file() -> tuple[pathlib.Path, str] | Failure:
"""The checkout's history and its text, empty when the file is missing."""
checkout = top()
if isinstance(checkout, Failure):
return checkout
history = pathlib.Path(checkout, HISTORY)
try:
return history, history.read_text(encoding="utf-8") if history.exists() else ""
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {history}: {failure}")
def append(read: str, entry: str) -> Failure | None:
"""Append entry unless the history already holds one on what the seats read."""
read_history = history_file()
if isinstance(read_history, Failure):
return read_history
history, text = read_history
if recorded(text, read):
return Failure(f"{history} already holds an entry on {read}; record each ruling or run once")
try:
history.parent.mkdir(parents=True, exist_ok=True)
except OSError as failure:
return Failure(f"could not create {history.parent}: {failure}")
if unwritten := replace_file(history, appended(text, entry).encode()):
return Failure(f"could not write {history}: {unwritten.reason}")
print(f"Appended to {history}.")
return None
+17
View File
@@ -0,0 +1,17 @@
import re
CAP = 3
PASSES = ("architecture", "full scan", "security", "overrides", "stability", "product-owner", "prose")
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
def round_counts(titles: list[str]) -> dict[str, int]:
"""Each pass's round count among the branch's `Answer <pass> round <n>:` commit titles: the highest <n>, or the number of such commits where that is more, so a repeated number still counts. A pass with none has 0, and a title naming no known pass adds its name. Case is ignored."""
highest: dict[str, int] = dict.fromkeys(PASSES, 0)
commits: dict[str, int] = dict.fromkeys(PASSES, 0)
for title in titles:
if named := ROUND.match(title):
name = named.group(1).lower()
highest[name] = max(highest.get(name, 0), int(named.group(2)))
commits[name] = commits.get(name, 0) + 1
return {name: max(highest[name], commits[name]) for name in highest}
-123
View File
@@ -1,123 +0,0 @@
import decimal
import re
from larv_review.seats import DIMENSIONS, FIRST_SEATS, Seat, SPLIT_SEATS
from larv_review.history import entries, Entry, HistoryChange, PLACE
from failure import Failure
from rank_todo import Item, ITEMS_HEADER, parse_row, table_rows
CAP = 3
FLOOR = decimal.Decimal("7.0")
PASSES = ("architecture", "full scan", "security", "stability", "product-owner", "prose")
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):")
VOTES = ("better", "same", "worse")
def votes(seats: list[Seat]) -> dict[str, str] | Failure:
"""Each seat's vote as it counts: a better or worse vote naming no `path:line` place counts as same."""
names = [seat.name for seat in seats]
if names[:2] != list(FIRST_SEATS) or names[2:] not in ([], list(SPLIT_SEATS)):
return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}")
if unknown := [seat for seat in seats if seat.said not in VOTES]:
return Failure(f"{unknown[0].name}'s vote {unknown[0].said!r} is not better, same or worse")
counted = {seat.name: seat.said if names_a_place(seat) else "same" for seat in seats}
first, second, *more = counted.values()
if more and first == second:
return Failure(f"{' and '.join(FIRST_SEATS)} both count as {first}, which settles the ruling; drop the other seats' lines")
return counted
def names_a_place(seat: Seat) -> bool:
return any(PLACE.search(place) for place in seat.places)
def ruling(counted: list[str]) -> str | None:
"""The vote that leads each other vote by two or more, else same; None when only the first two seats voted and they differ, so two more must vote."""
if len(counted) == 2 and counted[0] != counted[1]:
return None
for vote in VOTES:
if all(counted.count(vote) >= counted.count(other) + 2 for other in VOTES if other != vote):
return vote
return "same"
def means(lines: list[list[str]]) -> list[decimal.Decimal]:
"""The mean of each score across the lines, in DIMENSIONS' order, rounded half up to two decimals."""
return [mean([decimal.Decimal(score) for score in column]) for column in zip(*lines)]
def mean(values: list[decimal.Decimal]) -> decimal.Decimal:
return (sum(values, decimal.Decimal(0)) / len(values)).quantize(decimal.Decimal("0.01"), decimal.ROUND_HALF_UP)
def under_floor(found: list[decimal.Decimal]) -> list[str]:
return [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if value < FLOOR]
def round_counts(titles: list[str]) -> dict[str, int]:
"""Each pass's highest round among the branch's `Answer <pass> round <n>:` commit titles; a pass with none has 0, and a title naming no known pass adds its name."""
counts = dict.fromkeys(PASSES, 0)
for title in titles:
if named := ROUND.match(title):
counts[named.group(1)] = max(counts.get(named.group(1), 0), int(named.group(2)))
return counts
def measured_commit(changes: list[HistoryChange]) -> str | None:
"""The newest change, of changes given newest first, that adds a scoring run to the history, or whose last added paired ruling is better."""
for change in changes:
held = {entry.heading for entry in entries(change.before)}
added = [entry for entry in entries(change.after) if entry.heading not in held]
rulings = sorted((entry for entry in added if entry.paired), key=lambda entry: entry.time)
if any(not entry.paired for entry in added) or rulings and rulings[-1].ruling == "better":
return change.commit
return None
def first_ruling(history: str) -> Entry | None:
rulings = sorted((entry for entry in entries(history) if entry.paired), key=lambda entry: entry.time)
return rulings[0] if rulings else None
def base(changes: list[HistoryChange], history: str) -> tuple[str, str] | None:
"""The commit a paired ruling reads against, and which fallback found it; None leaves the merge base of HEAD and the default branch. history is the default branch's."""
if found := measured_commit(changes):
return found, "the last measured commit"
if (first := first_ruling(history)) and first.against:
return first.against, "the base the history's first paired ruling names"
return None
def plan_items(todo: str) -> list[Item] | Failure:
"""Each row of a todo.md's items table, read as `rank_todo.py` reads it."""
table = table_rows(todo.splitlines(), ITEMS_HEADER)
if isinstance(table, Failure):
return table
items = []
for row in table.rows:
item = parse_row(row)
if isinstance(item, Failure):
return item
items.append(item)
return items
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool) -> list[str] | Failure:
"""Why the chunk takes a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, and landed whether the default branch holds a commit after its newest release tag. Work has landed towards an emptied release when the chunk ships one of its items, or when it is the next release, the earliest before names, and landed holds."""
plan = {item.id: item for item in before + after}
if unknown := sorted(set(ships) - set(plan)):
return Failure(f"neither plan holds item {', '.join(map(str, unknown))}")
shipped = [plan[id_] for id_ in ships]
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if "comprehension floor" in item.tagline.lower()]
next_release = min((item.release for item in before), default=None)
for release in emptied(before, after, shipped):
if any(item.release == release for item in shipped) or (release == next_release and landed):
reasons.append(f"leaves release {'.'.join(map(str, release))} with no plan item")
return reasons
def emptied(before: list[Item], after: list[Item], shipped: list[Item]) -> list[tuple[int, int, int]]:
"""Each release the default branch's plan or a shipped item names that the chunk's plan, less the shipped items, names no longer."""
named = {item.release for item in before + shipped}
left = {item.release for item in after if item.id not in {ship.id for ship in shipped}}
return sorted(named - left)
+63
View File
@@ -0,0 +1,63 @@
from comprehension_history import DIMENSIONS, PLACE, Seat
from failure import Failure
from larv_review.seats import FIRST_SEATS, SPLIT_SEATS, vote_line
VOTES = ("better", "same", "worse")
def votes(seats: list[Seat]) -> dict[str, list[str]] | Failure:
"""Each seat's five votes as written, in DIMENSIONS' order."""
names = [seat.name for seat in seats]
if names[:2] != list(FIRST_SEATS) or names[2:] not in ([], list(SPLIT_SEATS)):
return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their overall votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}")
said = {}
for seat in seats:
line = vote_line(seat.name, seat.said)
if isinstance(line, Failure):
return line
if unnamed := [place for place in seat.places if not place_dimensions(place)]:
return Failure(f"{seat.name}'s place does not open with the dimensions it moves, each one of {', '.join(DIMENSIONS)}, then `: `: {unnamed[0]}")
said[seat.name] = line
first, second, *more = (overall(each) for each in counted(seats, said).values())
if more and first == second:
return Failure(f"{' and '.join(FIRST_SEATS)} both count as {first} overall, which settles the ruling; drop the other seats' lines")
return said
def overall(votes: list[str]) -> str:
"""The overall vote, which DIMENSIONS lists last."""
return votes[-1]
def counted(seats: list[Seat], said: dict[str, list[str]]) -> dict[str, list[str]]:
"""Each seat's votes as they count: a dimension's vote counts as same unless one of the seat's `path:line` places opens with that dimension, and the overall vote unless the seat names any such place."""
return {seat.name: [vote if names_a_place(seat, name) else "same" for name, vote in zip(DIMENSIONS, said[seat.name])] for seat in seats}
def names_a_place(seat: Seat, dimension: str) -> bool:
return any(PLACE.search(place) and (dimension == DIMENSIONS[-1] or dimension in place_dimensions(place)) for place in seat.places)
def place_dimensions(place: str) -> list[str]:
"""The dimensions a place opens with, as in `Locality, Shape: `path:line` ...`; empty when any name before the first `: ` is no dimension."""
named = place.partition(": ")[0].split(", ")
return named if all(name in DIMENSIONS for name in named) else []
def split(overall: list[str]) -> bool:
"""Whether only the first two seats voted overall and they differ, so two more must vote: two votes that differ cannot reach a lead of two."""
return len(overall) == 2 and overall[0] != overall[1]
def ruling(overall: list[str]) -> str:
return lead(overall) or "same"
def fallen(counted: dict[str, list[str]]) -> list[str]:
"""Each dimension, Overall aside, that the seats rule worse by a lead of two."""
return [name for name, column in zip(DIMENSIONS[:-1], zip(*counted.values())) if lead(list(column)) == "worse"]
def lead(votes: list[str]) -> str | None:
"""The vote that leads each other vote by two or more, if one does."""
return next((vote for vote in VOTES if all(votes.count(vote) >= votes.count(other) + 2 for other in VOTES if other != vote)), None)
+30
View File
@@ -0,0 +1,30 @@
from comprehension_history import entries, Entry, HistoryChange
def measured_commit(changes: list[HistoryChange]) -> str | None:
"""The newest change, of changes given newest first, that adds a scoring run to the history, or whose last added paired ruling is better.
It is the ratchet's base. A ruling of same leaves the base where it was, so a run of small falls each ruled same still adds up against one commit. Entry times are UTC stamps in ISO order, so they sort as text.
"""
for change in changes:
held = {entry.heading for entry in entries(change.before)}
added = [entry for entry in entries(change.after) if entry.heading not in held]
rulings = sorted((entry for entry in added if entry.paired), key=lambda entry: entry.time)
ruled_better = bool(rulings) and rulings[-1].ruling == "better"
if ruled_better or any(not entry.paired for entry in added):
return change.commit
return None
def first_ruling(history: str) -> Entry | None:
rulings = sorted((entry for entry in entries(history) if entry.paired), key=lambda entry: entry.time)
return rulings[0] if rulings else None
def base(changes: list[HistoryChange], history: str) -> tuple[str, str] | None:
"""The commit a paired ruling reads against, and which fallback found it; None leaves the merge base of HEAD and the default branch. history is the default branch's."""
if found := measured_commit(changes):
return found, "the last measured commit"
if (first := first_ruling(history)) and first.against:
return first.against, "the base the history's first paired ruling names"
return None
+25
View File
@@ -0,0 +1,25 @@
import decimal
from comprehension_history import DIMENSIONS
FLOOR = decimal.Decimal("7.0")
def fall_ruling(ruled: str, fell: list[str], found: list[decimal.Decimal]) -> tuple[str, str]:
"""The ruling once the scoring run has scored the dimensions that fell, and the line that says why: worse when one of their means is under the floor, so a chunk cannot trade one dimension below the floor for gains in the others."""
if under := [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if name in fell and value < FLOOR]:
return "worse", f"Fell: {', '.join(fell)}. Under the floor of {FLOOR}: {', '.join(under)}, so the {ruled} ruling counts as worse."
return ruled, f"Fell: {', '.join(fell)}, each at or above the floor of {FLOOR}, so the {ruled} ruling stands."
def means(lines: list[list[str]]) -> list[decimal.Decimal]:
"""The mean of each score across the lines, in DIMENSIONS' order, rounded half up to two decimals."""
return [mean([decimal.Decimal(score) for score in column]) for column in zip(*lines)]
def mean(values: list[decimal.Decimal]) -> decimal.Decimal:
return (sum(values, decimal.Decimal(0)) / len(values)).quantize(decimal.Decimal("0.01"), decimal.ROUND_HALF_UP)
def under_floor(found: list[decimal.Decimal]) -> list[str]:
return [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if value < FLOOR]
+15 -26
View File
@@ -2,50 +2,32 @@ import dataclasses
import decimal
import re
from comprehension_history import ARCHITECT, DIMENSIONS, JUNIOR, MID, Seat, SENIOR
from failure import Failure
ARCHITECT = "Inherited architect"
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
JUNIOR = "Junior A"
# A scoring run moved from a `comprehension floor:` decision entry kept only the seats' means.
MEAN = "Mean"
MID = "Mid A"
SCORES = re.compile(", ".join(rf"{name} ([0-9]+(?:\.[0-9]+)?)" for name in DIMENSIONS))
SENIOR = "Maintainability senior"
FIRST_SEATS = (MID, ARCHITECT)
SCORING_SEATS = (JUNIOR, MID, SENIOR, ARCHITECT)
SEAT_LINE = re.compile(rf"^({'|'.join(SCORING_SEATS)}): (.+)$")
SPLIT_SEATS = (SENIOR, JUNIOR)
VOTE_LINE = re.compile(", ".join(rf"{name} (better|same|worse)" for name in DIMENSIONS))
@dataclasses.dataclass(frozen=True)
class Seat:
name: str
said: str
places: list[str]
@dataclasses.dataclass(frozen=True)
class Report:
"""A seats file: what the seats read, `<PR or branch> at <commit>`, with `, against <base>` for a paired ruling, then each seat's line and its places, or, for a run moved from a decision entry, its Mean line alone."""
class SeatsFile:
"""What the seats read, `<PR or branch> at <commit>`, with `, against <base>` for a paired ruling, then each seat's line and its places."""
read: str
seats: list[Seat]
moved_mean: str | None
def report(text: str) -> Report | Failure:
def seats_file(text: str) -> SeatsFile | Failure:
lines = [line for line in text.splitlines() if line.strip()]
if not lines:
return Failure("the seats file is empty; its first line names what the seats read: <PR or branch> at <commit>")
seats: list[Seat] = []
moved_mean = None
for line in lines[1:]:
if line.startswith(f"{MEAN}: ") and not seats and moved_mean is None:
moved_mean = line[len(MEAN) + 2:].strip()
elif moved_mean is not None:
return Failure(f"a {MEAN} line stands alone in its seats file: {line}")
elif seat := SEAT_LINE.match(line):
if seat := SEAT_LINE.match(line):
if seat.group(1) in [known.name for known in seats]:
return Failure(f"{seat.group(1)} appears twice in the seats file")
seats.append(Seat(seat.group(1), seat.group(2).strip(), []))
@@ -55,13 +37,13 @@ def report(text: str) -> Report | Failure:
seats[-1].places[-1] += " " + line.strip()
else:
return Failure(f"the seats file has a line that is neither a seat's line, opening with one of {', '.join(SCORING_SEATS)} and a colon, nor one of its places: {line}")
return Report(lines[0].strip(), seats, moved_mean)
return SeatsFile(lines[0].strip(), seats)
def scores(seats: list[Seat]) -> dict[str, list[str]] | Failure:
"""Each seat's five scores as written, in DIMENSIONS' order."""
if [seat.name for seat in seats] != list(SCORING_SEATS):
return Failure(f"a scoring run's seats are {', '.join(SCORING_SEATS)}, in that order, or a {MEAN} line alone; the file has {', '.join(seat.name for seat in seats) or 'none'}")
return Failure(f"a scoring run's seats are {', '.join(SCORING_SEATS)}, in that order; the file has {', '.join(seat.name for seat in seats) or 'none'}")
found = {}
for seat in seats:
values = score_line(seat.name, seat.said)
@@ -81,3 +63,10 @@ def score_line(name: str, said: str) -> list[str] | Failure:
if values[-1] > min(values[:-1]) + 1:
return Failure(f"{name}'s overall exceeds the lowest dimension by more than 1; ask the seat to rescore: {said}")
return list(written.groups())
def vote_line(name: str, said: str) -> list[str] | Failure:
"""A paired seat's five votes, in DIMENSIONS' order."""
if not (written := VOTE_LINE.fullmatch(said)):
return Failure(f"{name}'s line is not {', '.join(vote + ' <better, same or worse>' for vote in DIMENSIONS)}: {said}")
return list(written.groups())
@@ -1,4 +1,5 @@
import decimal
import itertools
import os
import pathlib
import subprocess
@@ -7,16 +8,21 @@ import tempfile
import textwrap
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from larv_review.history import appended, entries, HistoryChange, Place, ruling_entry
from larv_review.rules import base, first_ruling, means, measured_commit, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes
from comprehension_history import appended, entries, HistoryChange, Place, recorded, ruling_entry, ScoringRun, Seat
from larv_review.ruling_base import base, first_ruling, measured_commit
import comprehension_history
from larv_review.ruling import counted, fallen, ruling, split, votes
from failure import Failure
from test_loop_claude_black_box import host_env
from rank_todo import Item
from larv_review.seats import report, score_line, scores, Seat
from larv_review.scoring import fall_ruling, means, under_floor
from test_env import isolated_env
from todo_table import Item, items
from larv_review.rounds import round_counts
from larv_review.seats import score_line, scores, seats_file
from larv_review.plan import scoring_run_due
TOOL = pathlib.Path(__file__).resolve().parent / "larv-review"
TOOL = pathlib.Path(__file__).resolve().parents[1] / "larv-review"
SCORING = "## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mean | 7.00 |\n"
@@ -24,6 +30,10 @@ def paired(time: str, verdict: str, commit: str = "bbbbbbb") -> str:
return f"## {time}, PR #2 at {commit}, against aaaaaaa\n\nRuling: {verdict}\n"
def said(overall: str, locality: str = "same") -> str:
return f"Navigation same, Locality {locality}, Shape same, Self-sufficiency same, Overall {overall}"
def item(id_: int, release: tuple[int, int, int], tagline: str = "**Do it.**") -> Item:
return Item(id_, release, "", tagline, {"R": 1, "S": 1, "A": 1, "G": 1}, ("1",))
@@ -34,28 +44,45 @@ def todo(*rows: str) -> str:
class Seats(unittest.TestCase):
def test_reads_each_seats_line_and_places_and_joins_a_wrapped_place(self):
given = report("PR #2 at abc1234, against def5678\n\nMid A: worse\n\n- `a.py:1` `f`: hard\n to read\n\nInherited architect: same\n")
given = seats_file(f"PR #2 at abc1234, against def5678\n\nMid A: {said('worse')}\n\n- `a.py:1` `f`: hard\n to read\n\nInherited architect: {said('same')}\n")
self.assertEqual(given.read, "PR #2 at abc1234, against def5678")
self.assertEqual(given.seats, [Seat("Mid A", "worse", ["`a.py:1` `f`: hard to read"]), Seat("Inherited architect", "same", [])])
self.assertEqual(given.seats, [Seat("Mid A", said("worse"), ["`a.py:1` `f`: hard to read"]), Seat("Inherited architect", said("same"), [])])
def test_refuses_a_line_that_is_neither_a_seat_nor_a_place_and_a_seat_twice(self):
self.assertIsInstance(report("PR #2 at abc1234\n\nMid A worse\n"), Failure)
self.assertIsInstance(report("PR #2 at abc1234\n\nMid A: worse\n\nMid A: same\n"), Failure)
self.assertIsInstance(report(""), Failure)
self.assertIsInstance(seats_file("PR #2 at abc1234\n\nMid A worse\n"), Failure)
self.assertIsInstance(seats_file("PR #2 at abc1234\n\nMid A: worse\n\nMid A: same\n"), Failure)
self.assertIsInstance(seats_file(""), Failure)
def test_counts_a_vote_naming_no_place_as_same(self):
seats = [Seat("Mid A", "worse", ["the whole skill"]), Seat("Inherited architect", "better", ["`a.py:3` `f`: shorter"])]
self.assertEqual(votes(seats), {"Mid A": "same", "Inherited architect": "better"})
def test_counts_each_vote_of_a_seat_naming_no_place_as_same(self):
seats = [Seat("Mid A", said("worse", "worse"), ["Locality: the whole skill"]), Seat("Inherited architect", said("better"), ["Overall: `a.py:3` `f`: shorter"])]
written = votes(seats)
self.assertEqual(written, {"Mid A": ["same", "worse", "same", "same", "worse"], "Inherited architect": ["same", "same", "same", "same", "better"]})
self.assertEqual(counted(seats, written)["Mid A"], ["same"] * 5)
def test_refuses_two_more_seats_once_the_first_two_agree(self):
seats = [Seat(name, vote, ["`f.py:1` `f`: x"]) for name, vote in (("Mid A", "worse"), ("Inherited architect", "worse"), ("Maintainability senior", "better"), ("Junior A", "better"))]
def test_counts_a_dimensions_vote_only_where_a_place_names_that_dimension(self):
seats = [Seat("Mid A", said("better", "worse"), ["Shape: `a.py:3` `f`: the Locality of it, reshaped"]), Seat("Inherited architect", said("better", "worse"), ["Locality, Shape: `a.py:3` `f`: held at once"])]
written = {seat.name: ["same", "worse", "same", "same", "better"] for seat in seats}
self.assertEqual(counted(seats, written), {"Mid A": ["same", "same", "same", "same", "better"], "Inherited architect": written["Inherited architect"]})
self.assertIsInstance(votes([Seat("Mid A", said("better"), ["Locality, self sufficiency: `a.py:3` `f`: x"]), seats[1]]), Failure)
self.assertIsInstance(votes([Seat("Mid A", said("better"), ["`a.py:3` `f`: Locality: x"]), seats[1]]), Failure)
self.assertEqual(votes(seats), {seat.name: written[seat.name] for seat in seats})
def test_refuses_two_more_seats_once_the_first_two_agree_overall(self):
seats = [Seat(name, said(vote), ["Overall: `f.py:1` `f`: x"]) for name, vote in (("Mid A", "worse"), ("Inherited architect", "worse"), ("Maintainability senior", "better"), ("Junior A", "better"))]
self.assertIsInstance(votes(seats), Failure)
def test_takes_the_first_two_seats_then_the_other_two_in_order(self):
first = [Seat("Mid A", "same", []), Seat("Inherited architect", "same", [])]
def test_takes_the_first_two_seats_then_the_other_two_in_order_and_each_dimensions_vote(self):
first = [Seat("Mid A", said("same"), []), Seat("Inherited architect", said("same"), [])]
self.assertIsInstance(votes(first[::-1]), Failure)
self.assertIsInstance(votes(first + [Seat("Junior A", "same", [])]), Failure)
self.assertIsInstance(votes([first[0], Seat("Inherited architect", "worst", [])]), Failure)
self.assertIsInstance(votes(first + [Seat("Junior A", said("same"), [])]), Failure)
self.assertIsInstance(votes([first[0], Seat("Inherited architect", said("worst"), [])]), Failure)
self.assertIsInstance(votes([first[0], Seat("Inherited architect", "same", [])]), Failure)
def test_finds_each_dimension_ruled_worse_by_a_lead_of_two(self):
self.assertEqual(fallen({"Mid A": ["same", "worse", "worse", "same", "better"], "Inherited architect": ["same", "worse", "same", "same", "better"]}), ["Locality"])
four = {name: ["same", vote, "same", "same", "better"] for name, vote in (("Mid A", "worse"), ("Inherited architect", "same"), ("Maintainability senior", "worse"), ("Junior A", "worse"))}
self.assertEqual(fallen(four), ["Locality"])
self.assertEqual(fallen({**four, "Junior A": ["same", "better", "same", "same", "better"]}), [])
def test_rules_by_a_lead_of_two_and_splits_two_seats_that_differ(self):
cases = [
@@ -69,7 +96,7 @@ class Seats(unittest.TestCase):
]
for counted, expected in cases:
with self.subTest(counted):
self.assertEqual(ruling(counted), expected)
self.assertEqual(None if split(counted) else ruling(counted), expected)
def test_reads_four_seats_scores_and_refuses_an_overall_above_the_lowest_by_more_than_one(self):
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
@@ -88,19 +115,39 @@ class Seats(unittest.TestCase):
class History(unittest.TestCase):
def test_writes_the_sample_entry_its_parser_shows(self):
source = pathlib.Path(comprehension_history.__file__).read_text(encoding="utf-8").splitlines()
start = next(index for index, line in enumerate(source) if line.startswith("# ## "))
sample = [line.removeprefix("#").removeprefix(" ") for line in itertools.takewhile(lambda line: line.startswith("#"), source[start:])]
seat = Seat("Mid A", said("better", "worse"), ["Locality: `bin/x.py:12` `run`: three branches to hold at once"])
votes = {"Mid A": ["better", "worse", "same", "same", "better"]}
self.assertEqual(ruling_entry("2026-10-09T09:47:25Z, PR #232 at 324d650, against 12d6d75", [seat], votes, votes, "same", [], None), "\n".join(sample) + "\n")
def test_reads_back_what_it_writes(self):
seats = [Seat("Mid A", "worse", ["`bin/a.py:3` `f`: hard, with `:9` `g`"]), Seat("Inherited architect", "worse", [])]
ruled = ruling_entry("2026-10-08T18:37:21Z, PR #2 at bbbbbbb, against aaaaaaa", seats, {"Mid A": "worse", "Inherited architect": "same"}, "worse")
seats = [Seat("Mid A", said("better", "worse"), ["`bin/a.py:3` `f`: hard, with `:9` `g`"]), Seat("Inherited architect", said("worse", "worse"), [])]
written = {"Mid A": ["same", "worse", "same", "same", "better"], "Inherited architect": ["same", "worse", "same", "same", "worse"]}
scoring = ScoringRun([Seat("Junior A", "", ["`bin/b.py:4` `h`: long"])], {"Junior A": ["7", "6.5", "7", "7", "7"]}, [decimal.Decimal(mean) for mean in ("7.00", "6.50", "7.00", "7.00", "7.00")])
ruled = ruling_entry("2026-10-08T18:37:21Z, PR #2 at bbbbbbb, against aaaaaaa", seats, written, {**written, "Inherited architect": ["same"] * 5}, "worse", ["Fell: Locality, under the floor."], scoring)
history = appended(appended("", SCORING), ruled)
self.assertTrue(history.startswith("# Comprehension history\n\n## 2026-10-08T12:00:00Z"))
self.assertNotIn("Inherited architect, decided by:", history)
self.assertIn("| Inherited architect | same (voted worse, naming no place) |", history)
self.assertIn("| Inherited architect | same | same (voted worse, no place naming Locality) | same | same | same (voted worse, naming no place) |", history)
found = entries(history)
self.assertEqual([(entry.commit, entry.against, entry.ruling) for entry in found], [("aaaaaaa", None, None), ("bbbbbbb", "aaaaaaa", "worse")])
self.assertEqual(found[1].places, [Place("bin/a.py", "f"), Place("bin/a.py", "g")])
self.assertEqual((found[1].ruled_places, found[1].scored_places), ([Place("bin/a.py", "f"), Place("bin/a.py", "g")], [Place("bin/b.py", "h")]))
self.assertTrue(recorded(history, "PR #2 at bbbbbbb, against aaaaaaa"))
self.assertFalse(recorded(history, "PR #2 at bbbbbbb"))
self.assertIn("| Mean | 7.00 | 6.50 | 7.00 | 7.00 | 7.00 |\n\nMid A, decided by:", history)
self.assertEqual([entry.paired for entry in found], [False, True])
class FallRuling(unittest.TestCase):
def test_counts_a_ruling_worse_when_a_fallen_dimensions_mean_is_under_the_floor(self):
found = [decimal.Decimal(score) for score in ("6", "6.5", "7", "6", "6")]
self.assertEqual(fall_ruling("better", ["Locality", "Shape"], found), ("worse", "Fell: Locality, Shape. Under the floor of 7.0: Locality 6.5, so the better ruling counts as worse."))
self.assertEqual(fall_ruling("same", ["Shape"], found), ("same", "Fell: Shape, each at or above the floor of 7.0, so the same ruling stands."))
class Base(unittest.TestCase):
def test_takes_the_newest_change_adding_a_scoring_run_or_ending_on_a_better_ruling(self):
older = HistoryChange("old", "", SCORING)
@@ -112,6 +159,8 @@ class Base(unittest.TestCase):
worse_last = HistoryChange("worse", SCORING, SCORING + paired("2026-10-08T13:00:00Z", "better") + paired("2026-10-08T14:00:00Z", "worse"))
self.assertEqual(measured_commit([worse_last, older]), "old")
self.assertIsNone(measured_commit([same]))
scored_fall = HistoryChange("same fell", SCORING, SCORING + paired("2026-10-08T13:00:00Z", "same\n\nFell: Locality, each at or above the floor.\n\n| Seat | Overall |\n|---|---|\n| Mean | 7.00 |"))
self.assertEqual(measured_commit([scored_fall, older]), "old")
def test_falls_back_to_the_first_rulings_base_then_to_none(self):
ruled = paired("2026-10-08T13:00:00Z", "worse")
@@ -130,12 +179,18 @@ class Rounds(unittest.TestCase):
counts = round_counts(["Answer prose round 1: x", "Answer full scan round 2: y", "Answer full scan round 1: z", "Answer stability: no round", "Answer stabilty round 1: typo", "Answer security round 1: rename round 2: x", "Rescore: w"])
self.assertEqual((counts["prose"], counts["full scan"], counts["stability"], counts["architecture"], counts["stabilty"], counts["security"]), (1, 2, 0, 0, 1, 1))
def test_counts_a_mis_cased_title_under_its_pass(self):
self.assertEqual(round_counts(["Answer Architecture round 4: x", "Answer architecture round 3: y"])["architecture"], 4)
def test_counts_a_repeated_round_number_as_a_round_of_its_own(self):
self.assertEqual(round_counts(["Answer stability round 3: x", "Answer stability round 3: y", "Answer stability round 2: z", "Answer stability round 1: w"])["stability"], 4)
class ScoringRunDue(unittest.TestCase):
def test_reads_each_rows_id_release_and_tagline(self):
self.assertEqual(plan_items(todo("| 3 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), [item(3, (0, 1, 0))])
self.assertIsInstance(plan_items("# todo\n"), Failure)
self.assertIsInstance(plan_items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), Failure)
self.assertEqual(items(todo("| 3 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), [item(3, (0, 1, 0))])
self.assertIsInstance(items("# todo\n"), Failure)
self.assertIsInstance(items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), Failure)
def test_is_due_for_an_item_naming_the_floor(self):
plan = [item(1, (0, 1, 0), "**Lift the project to the Comprehension floor.**"), item(2, (0, 1, 0))]
@@ -167,7 +222,7 @@ class LarvReviewTool(unittest.TestCase):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
root = pathlib.Path(os.path.realpath(temp.name))
self.env = {**host_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(root)}
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(root)}
self.checkout = root / "proj"
subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(root / "origin.git")], check=True, env=self.env)
subprocess.run(["git", "clone", "-q", str(root / "origin.git"), str(self.checkout)], check=True, env=self.env, capture_output=True)
@@ -190,8 +245,8 @@ class LarvReviewTool(unittest.TestCase):
def run_tool(self, *args):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
def seats_file(self, text):
path = self.checkout.parent / "seats.md"
def seats_file(self, text, name="seats.md"):
path = self.checkout.parent / name
path.write_text(textwrap.dedent(text))
return str(path)
@@ -213,7 +268,9 @@ class LarvReviewTool(unittest.TestCase):
self.commit("Answer prose round 1: c")
self.commit("Answer stability round 3: d")
ran = self.run_tool("round-count")
self.assertIn("stability: 3, at the cap\n", ran.stdout)
self.assertIn("stability: 3, at the cap: ask the human before another round\n", ran.stdout)
self.commit("Answer stability round 4: e")
self.assertIn("stability: 4, past the cap: ask the human before another round\n", self.run_tool("round-count").stdout)
self.assertIn("prose: 1\n", ran.stdout)
self.assertIn("architecture: 0\n", ran.stdout)
@@ -230,52 +287,86 @@ class LarvReviewTool(unittest.TestCase):
lines = """\
PR #2 at {start}, against {start}
Mid A: worse
Mid A: {worse}
- `bin/a.py:3` `f`: three branches
- Overall: `bin/a.py:3` `f`: three branches
Inherited architect: same
Inherited architect: {same}
"""
lines = lines.replace("{start}", self.start)
lines = lines.replace("{start}", self.start).replace("{worse}", said("worse")).replace("{same}", said("same"))
split = self.run_tool("record-ruling", self.seats_file(lines))
self.assertEqual(split.returncode, 0, split.stderr)
self.assertTrue(split.stdout.startswith("Split: Mid A worse, Inherited architect same."))
history = self.checkout / "docs" / "comprehension-history.md"
self.assertFalse(history.exists())
lines += "\n\t\t\tMaintainability senior: worse\n\n\t\t\t- `bin/a.py:3` `f`: hard\n\n\t\t\tJunior A: worse\n"
lines += f"\n\t\t\tMaintainability senior: {said('worse')}\n\n\t\t\t- Overall: `bin/a.py:3` `f`: hard\n\n\t\t\tJunior A: {said('worse')}\n"
ran = self.run_tool("record-ruling", self.seats_file(lines))
self.assertEqual(ran.stdout.splitlines()[0], "Ruling: same. Votes as counted: Mid A worse, Inherited architect same, Maintainability senior worse, Junior A same (voted worse, naming no place).")
self.assertEqual(ran.stdout.splitlines()[0], "Ruling: same. Overall votes as counted: Mid A worse, Inherited architect same, Maintainability senior worse, Junior A same (voted worse, naming no place).")
recorded = entries(history.read_text())
self.assertEqual([(entry.commit, entry.against, entry.ruling) for entry in recorded], [(self.start, self.start, "same")])
self.assertEqual(recorded[0].places, [Place("bin/a.py", "f")] * 2)
self.assertIn("| Junior A | same (voted worse, naming no place) |", history.read_text())
self.assertEqual(recorded[0].ruled_places, [Place("bin/a.py", "f")] * 2)
self.assertIn("| Junior A | same | same | same | same | same (voted worse, naming no place) |", history.read_text())
def test_asks_for_the_scoring_seats_when_a_dimension_falls_and_rules_with_their_scores(self):
place = "\n\n- Locality, Overall: `bin/a.py:3` `f`: shorter\n\n"
votes_file = self.seats_file(f"PR #2 at {self.start}, against {self.start}\n\nMid A: {said('better', 'worse')}{place}Inherited architect: {said('better', 'worse')}{place}", "votes.md")
asked = self.run_tool("record-ruling", votes_file)
self.assertEqual(asked.returncode, 0, asked.stderr)
self.assertTrue(asked.stdout.startswith(f"Fell: Locality, in a better ruling. Launch the four scoring seats on PR #2 at {self.start},"))
history = self.checkout / "docs" / "comprehension-history.md"
self.assertFalse(history.exists())
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 7, Overall 7"
scores_text = f"PR #2 at {self.start}\n" + "".join(f"\n{seat}: {line}\n\n- `bin/b.py:4` `h`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
ruled = self.run_tool("record-ruling", votes_file, self.seats_file(scores_text, "scores.md"))
self.assertEqual(ruled.returncode, 0, ruled.stderr)
self.assertTrue(ruled.stdout.startswith("Ruling: worse. Fell: Locality. Under the floor of 7.0: Locality 6.50, so the better ruling counts as worse."))
again = self.run_tool("record-ruling", votes_file, self.seats_file(scores_text, "scores.md"))
self.assertIn("already holds an entry on", again.stderr)
self.assertEqual(self.run_tool("record-ruling", votes_file).stdout, "")
recorded = entries(history.read_text())
self.assertEqual([entry.ruling for entry in recorded], ["worse"])
self.assertIn("| Mean | 7.00 | 6.50 | 7.00 | 7.00 | 7.00 |", history.read_text())
votes_file = self.seats_file(pathlib.Path(votes_file).read_text().replace("PR #2", "PR #3"), "votes.md")
scores_text = scores_text.replace("PR #2", "PR #3")
stands = self.run_tool("record-ruling", votes_file, self.seats_file(scores_text.replace("Locality 6.5", "Locality 7"), "scores.md"))
self.assertTrue(stands.stdout.startswith("Ruling: better. Fell: Locality, each at or above the floor of 7.0, so the better ruling stands."), stands.stderr)
votes_file = self.seats_file(pathlib.Path(votes_file).read_text().replace("PR #3", "PR #4"), "votes.md")
other = self.run_tool("record-ruling", votes_file, self.seats_file(scores_text.replace("PR #3", "PR #5"), "scores.md"))
self.assertIn("the scores file's first line is not", other.stderr)
def test_names_no_fall_on_a_worse_ruling_and_takes_no_scores_file_without_one(self):
place = "\n\n- Locality, Overall: `bin/a.py:3` `f`: longer\n\n"
ran = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}, against {self.start}\n\nMid A: {said('worse', 'worse')}{place}Inherited architect: {said('worse', 'worse')}{place}"))
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertNotIn("Fell:", ran.stdout + (self.checkout / "docs" / "comprehension-history.md").read_text())
extra = self.run_tool("record-ruling", self.seats_file(f"PR #3 at {self.start}, against {self.start}\n\nMid A: {said('worse')}{place}Inherited architect: {said('worse')}{place}"), self.seats_file("PR #2", "scores.md"))
self.assertIn("a worse ruling takes no scores file; run record-ruling again with the votes file alone", extra.stderr)
better = self.run_tool("record-ruling", self.seats_file(f"PR #5 at {self.start}, against {self.start}\n\nMid A: {said('better')}{place}Inherited architect: {said('better')}{place}"), self.seats_file("PR #5", "scores.md"))
self.assertIn("no dimension fell in this better ruling, so it takes no scores file", better.stderr)
def test_records_a_scoring_run_with_its_means(self):
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
seats = "".join(f"\n{seat}: {line}\n\n- `bin/a.py:3` `f`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
ran = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats))
uncalled = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats))
self.assertEqual(uncalled.returncode, 1)
self.assertIn("no plan item or release calls this scoring run", uncalled.stderr)
ran = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("Under the floor of 7.0: Locality 6.50, Self-sufficiency 6.50.", ran.stdout)
self.assertIn("\nFloor: Locality 6.50, Self-sufficiency 6.50 under the floor of 7.0 block the merge, as the chunk leaves release 0.1.0 with no plan item.\n", ran.stdout)
self.assertIn("not /", self.run_tool("record-scoring", "1", self.seats_file(f"PR #2 at {self.start}\n" + seats)).stderr)
text = (self.checkout / "docs" / "comprehension-history.md").read_text()
self.assertIn("| Mean | 7.00 | 6.50 | 7.00 | 6.50 | 7.00 |", text)
self.assertIn("Inherited architect, would restructure first:", text)
self.assertEqual([entry.places for entry in entries(text)], [[Place("bin/a.py", "f")] * 4])
self.assertEqual(entries(text)[0].scored_places, [Place("bin/a.py", "f")] * 4)
def test_refuses_a_ruling_file_that_names_no_base_or_a_commit_the_checkout_lacks(self):
ran = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}\n\nMid A: same\n\nInherited architect: same\n"))
ran = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}\n\nMid A: {said('same')}\n\nInherited architect: {said('same')}\n"))
self.assertEqual(ran.returncode, 1)
self.assertIn("against <base>", ran.stderr)
lacking = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}, against abcdef1\n\nMid A: same\n\nInherited architect: same\n"))
lacking = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}, against abcdef1\n\nMid A: {said('same')}\n\nInherited architect: {said('same')}\n"))
self.assertEqual(lacking.returncode, 1)
self.assertIn("abcdef1, which is no commit", lacking.stderr)
def test_moves_a_dated_mean_from_a_decision_entry_as_a_scoring_run(self):
mean = "Mean: Navigation 7.38, Locality 6.63, Shape 7.0, Self-sufficiency 6.88, Overall 6.88\n"
ran = self.run_tool("record-scoring", self.seats_file(f"2026-10-04, PR #1 merged at {self.start}\n\n{mean}"))
self.assertEqual(ran.returncode, 0, ran.stderr)
text = (self.checkout / "docs" / "comprehension-history.md").read_text()
self.assertIn(f"## 2026-10-04, PR #1 merged at {self.start}\n\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mean | 7.38 | 6.63 | 7.00 | 6.88 | 6.88 |\n", text)
def test_states_its_rules_and_finds_origins_default_branch_where_the_clone_recorded_none(self):
helped = self.run_tool("--help")
self.assertEqual(helped.returncode, 0, helped.stderr)
@@ -283,13 +374,6 @@ class LarvReviewTool(unittest.TestCase):
self.git("remote", "set-head", "origin", "--delete")
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
def test_refuses_a_dated_first_line_except_for_a_mean_alone_and_a_mean_without_one(self):
mean = "Mean: Navigation 7, Locality 7, Shape 7, Self-sufficiency 7, Overall 7\n"
self.assertEqual(self.run_tool("record-scoring", self.seats_file(f"PR #1 at {self.start}\n\n{mean}")).returncode, 1)
ruled = self.run_tool("record-ruling", self.seats_file(f"2026-10-08, PR #2 at {self.start}, against {self.start}\n\nMid A: same\n\nInherited architect: same\n"))
self.assertEqual(ruled.returncode, 1)
self.assertIn("only a seats file holding a Mean line alone", ruled.stderr)
def test_takes_a_local_main_without_origin_and_reads_origin_as_last_fetched_when_the_fetch_fails(self):
self.commit("Answer prose round 1: a")
self.git("remote", "set-url", "origin", str(self.checkout.parent / "gone.git"))
+1 -1
View File
@@ -9,4 +9,4 @@ sys.path.insert(0, str(LAUNCHER.parent))
from loop_claude import effects, paths
from loop_claude.loop import main
sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd(), effects.system_effects()))
sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, pathlib.Path.cwd(), effects.system_effects()))
+2 -2
View File
@@ -3,10 +3,10 @@ import uuid
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.claude_code.transcript import human_turns, read_transcript
from claude_code.transcript import human_turns, read_transcript
from loop_claude.stop import needs_human, needs_terminal, Stop
from loop_claude.paths import Paths
from loop_claude.claude_code.trust import trust
from claude_code.trust import trust
from loop_claude.project.checkout import worktrees
ANSWER_QUESTION = "answer the question above"
+98 -2
View File
@@ -1,15 +1,111 @@
import dataclasses
import json
import re
import typing
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, either
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
from loop_claude.cycle.judge_reply import Interrupt, JUDGE_RULES, JUDGE_SCHEMA, QuotedAnswer, Verdict, verdict_from
from claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
from loop_claude.project.records import HUMAN_RULE_NAMES
from loop_claude.cycle.retry import Limited, retried
from loop_claude.stop import Stop
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
JUDGE_PROMPT_CHARS = 400000
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
"- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither "
"README.md nor the records settle the matter\n"
"- it asks again a question a [loop] line already answered\n"
"- it carried on under an assumption that decides the deliverable, that the human could "
"reasonably reject and that neither README.md nor the records settle; a caveat about "
"transient state it then handled is not one\n"
"- it is blocked on something only the human can supply: a credential, a version bump, a choice "
"outside the repo, or a release ready to cut, which only the human may publish\n"
"- it flags that the goals, the plan in todo.md or the task itself is unclear, missing or in need of change\n"
"- it chose between alternatives that neither README.md nor the records discriminate "
"between - neither rules the rejected one out - and the choice materially changes the deliverable\n"
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
"where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
"is still open, never a question they already answered there. A [loop] line is what loop-claude told "
"the agent, such as an answer quoted from README.md or the records.\n"
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
"wording; never construct another from facts it stated.\n"
"Where README.md or the records answer the agent's own question and no [loop] line has "
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the agent is "
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
"outranks finished.\n"
"The chunk is the piece of work the agent is on, shipped as one pull request. "
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}. An answer counts as recorded "
f"where README.md or the records above hold it, {', '.join(HUMAN_RULE_NAMES)} included. It also counts where "
f"the transcript shows the agent writing it into {ANSWER_DESTINATIONS}; writing it into "
f"{either(HUMAN_RULE_NAMES)} does not count. finished=false when work remains that a further run can "
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
)
@dataclasses.dataclass(frozen=True)
class Reply:
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."})
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the agent's question; else what shows the chunk finished or the work remaining."})
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."})
REPLY_TYPES = typing.get_type_hints(Reply)
JSON_TYPES = {bool: "boolean", str: "string"}
JUDGE_SCHEMA = {
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
"required": list(REPLY_TYPES),
"type": "object",
}
@dataclasses.dataclass(frozen=True)
class Interrupt:
evidence: str
question: str
@dataclasses.dataclass(frozen=True)
class QuotedAnswer:
"""The agent asked a question that README.md or the records answer. The answer field quotes the passage."""
evidence: str
question: str
answer: str
@dataclasses.dataclass(frozen=True)
class Finished:
evidence: str
@dataclasses.dataclass(frozen=True)
class Unfinished:
evidence: str
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
def verdict_from(output: object) -> Verdict | Failure:
if not isinstance(output, dict):
return Failure("the judge returned no reply")
for name, kind in REPLY_TYPES.items():
if not isinstance(output.get(name), kind):
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
if output["interrupt"]:
if not output["question"].strip():
return Failure("the judge interrupted without a question")
return Interrupt(output["evidence"], output["question"])
if output["answer"].strip():
if not output["question"].strip():
return Failure("the judge quoted an answer without a question")
return QuotedAnswer(output["evidence"], output["question"], output["answer"])
return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"])
def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop:
-104
View File
@@ -1,104 +0,0 @@
import dataclasses
import typing
from failure import Failure
from loop_claude.project.records import HUMAN_RULES, RECORD_FILES
# Where the judge may quote an answer from, named as the human and the worker see them; of README.md the judge sees only the premises.
QUOTE_SOURCES = "README.md's Goals and Audience, " + ", ".join(RECORD_FILES) + " or " + HUMAN_RULES
# Where the worker may write an answer the human typed, so it counts as recorded.
ANSWER_DESTINATIONS = "README.md's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
"- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither "
"README.md nor the records settle the matter\n"
"- it asks again a question a [loop] line already answered\n"
"- it carried on under an assumption that decides the deliverable, that the human could "
"reasonably reject and that neither README.md nor the records settle; a caveat about "
"transient state it then handled is not one\n"
"- it is blocked on something only the human can supply: a credential, a version bump, a choice "
"outside the repo, or a release ready to cut, which only the human may publish\n"
"- it flags that the goals, the plan in todo.md or the task itself is unclear, missing or in need of change\n"
"- it chose between alternatives that neither README.md nor the records discriminate "
"between - neither rules the rejected one out - and the choice materially changes the deliverable\n"
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
"where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
"is still open, never a question they already answered there. A [loop] line is what loop-claude told "
"the agent, such as an answer quoted from README.md or the records.\n"
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
"wording; never construct another from facts it stated.\n"
"Where README.md or the records answer the agent's own question and no [loop] line has "
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the agent is "
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
"outranks finished.\n"
"The chunk is the piece of work the agent is on, shipped as one pull request. "
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}. An answer counts as recorded "
f"where README.md or the records above hold it, {HUMAN_RULES} included. It also counts where "
f"the transcript shows the agent writing it into {ANSWER_DESTINATIONS}; writing it into "
f"{HUMAN_RULES} does not count. finished=false when work remains that a further run can "
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
)
@dataclasses.dataclass(frozen=True)
class Reply:
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."})
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the agent's question; else what shows the chunk finished or the work remaining."})
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."})
REPLY_TYPES = typing.get_type_hints(Reply)
JSON_TYPES = {bool: "boolean", str: "string"}
JUDGE_SCHEMA = {
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
"required": list(REPLY_TYPES),
"type": "object",
}
@dataclasses.dataclass(frozen=True)
class Interrupt:
evidence: str
question: str
@dataclasses.dataclass(frozen=True)
class QuotedAnswer:
"""The agent asked a question that README.md or the records answer. The answer field quotes the passage."""
evidence: str
question: str
answer: str
@dataclasses.dataclass(frozen=True)
class Finished:
evidence: str
@dataclasses.dataclass(frozen=True)
class Unfinished:
evidence: str
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
def verdict_from(output: object) -> Verdict | Failure:
if not isinstance(output, dict):
return Failure("the judge returned no reply")
for name, kind in REPLY_TYPES.items():
if not isinstance(output.get(name), kind):
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
if output["interrupt"]:
if not output["question"].strip():
return Failure("the judge interrupted without a question")
return Interrupt(output["evidence"], output["question"])
if output["answer"].strip():
if not output["question"].strip():
return Failure("the judge quoted an answer without a question")
return QuotedAnswer(output["evidence"], output["question"], output["answer"])
return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"])
+31
View File
@@ -0,0 +1,31 @@
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
from markdown_text import quoted
def either(names: tuple[str, ...]) -> str:
"""The names as `a, b or c`."""
return f"{', '.join(names[:-1])} or {names[-1]}"
# Where the judge may quote an answer from, named as the human and the worker see them; of README.md the judge sees only the premises.
QUOTE_SOURCES = either(("README.md's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES))
# Where the worker may write an answer the human typed, so it counts as recorded.
ANSWER_DESTINATIONS = "README.md's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
def fresh(task: str) -> str:
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one."
def resumed(unfinished_evidence: str) -> str:
ruled = f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{quoted(unfinished_evidence)}\n\n" if unfinished_evidence else " "
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}."
def answered(question: str, answer: str) -> str:
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task."
def past_the_cap(question: str, answer: str, cap: int) -> str:
"""The question a quoted answer puts to the human once the cycle's quoted answers reach the cap."""
return f"{question}\n\n{QUOTE_SOURCES} says:\n{answer}\n\nThose files have answered {cap} questions this cycle, the most allowed, so this one comes to you."
+26 -21
View File
@@ -1,17 +1,19 @@
import dataclasses
import pathlib
import typing
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working
from loop_claude.transcript_archive import archive, FINISHED, UNFINISHED
from loop_claude.claude_code.session import delete_session, Session, session_open, transcript_file
from transcript_archive.write import archive
from claude_code.session import delete_session, Session, session_open, transcript_file
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.cycle.judge_reply import Finished, Interrupt, QUOTE_SOURCES, QuotedAnswer, Unfinished
from loop_claude.cycle.judge import Finished, Interrupt, judge, QuotedAnswer, Unfinished
from loop_claude.cycle.interrupt import interrupt
from loop_claude.cycle.judge import judge
from loop_claude.project.model_choice import Models
from transcript_archive import outcomes
from loop_claude.paths import Paths
from loop_claude.claude_code.transcript import read_transcript, render
from loop_claude.cycle import prompts
from claude_code.transcript import read_transcript, render
from loop_claude.cycle.retry import retried
from loop_claude.cycle.worker import run_worker, worker_args
from loop_claude.stop import Stop
@@ -23,13 +25,13 @@ class Cycle:
models: Models
paths: Paths
premises: str
project_key: str
project_archive: pathlib.Path
records: str
# The evidence of the previous cycle's unfinished verdict, empty after any other.
remaining: str
root: str
session: Session
task: str
# Empty when the previous cycle's verdict was not Unfinished.
unfinished_evidence: str
def run_cycle(cycle: Cycle) -> Stop | Finished | Unfinished:
@@ -47,7 +49,7 @@ def run_cycle(cycle: Cycle) -> Stop | Finished | Unfinished:
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
path = transcript_file(cycle.session)
failure = archive(cycle.project_key, path, cycle.task, f"Stopped: {why}", cycle.effects.now(), cycle.paths) if path else None
failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(why), cycle.effects.now()) if path else None
# A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once.
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
@@ -68,19 +70,27 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
def work(cycle: Cycle, answered: QuotedAnswer | None) -> WorkerRan | Stop:
if answered is not None:
print(f"\n=== {QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
if stop := keep_answer(cycle, answered):
return stop
# session_open runs inside the lambda: a failed attempt may have opened the session.
if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, session_open(cycle.session), answered, quoted(cycle.remaining)), cycle.effects), cycle.effects):
# worker_start runs inside the lambda: a failed attempt may have opened the session.
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered), cycle.effects), cycle.effects):
return stop
path = transcript_file(cycle.session)
return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}")
def worker_start(cycle: Cycle, answered: QuotedAnswer | None) -> list[str]:
if answered is not None:
return worker_args(cycle.session, cycle.models.worker, prompts.answered(answered.question, answered.answer), resume=True)
if session_open(cycle.session):
return worker_args(cycle.session, cycle.models.worker, prompts.resumed(cycle.unfinished_evidence), resume=True)
return worker_args(cycle.session, cycle.models.worker, prompts.fresh(cycle.task), resume=False)
def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None:
path = transcript_file(cycle.session)
if path and (failure := archive(cycle.project_key, path, cycle.task, f"Verdict: quoted answer\n\n{answered.question}\n\n{QUOTE_SOURCES} says:\n{quoted(answered.answer)}\n\nEvidence:\n{quoted(answered.evidence)}", cycle.effects.now(), cycle.paths)):
if path and (failure := archive(cycle.project_archive, path, cycle.task, outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence), cycle.effects.now())):
return Stop(1, failure.reason)
return None
@@ -96,7 +106,7 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | Stop:
question = question_for(ruling)
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: interrupt\n\n{question}\n\nEvidence:\n{quoted(ruling.evidence)}", cycle.effects.now(), cycle.paths):
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.interrupted(question, ruling.evidence), cycle.effects.now()):
return Stop(1, failure.reason)
return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or HumanAnswered()
@@ -104,18 +114,13 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
def question_for(ruling: Interrupt | QuotedAnswer) -> str:
if isinstance(ruling, Interrupt):
return ruling.question
return f"{ruling.question}\n\n{QUOTE_SOURCES} says:\n{ruling.answer}\n\nThose files have answered {QUOTED_ANSWERS_PER_CYCLE} questions this cycle, the most allowed, so this one comes to you."
return prompts.past_the_cap(ruling.question, ruling.answer, QUOTED_ANSWERS_PER_CYCLE)
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
finished = isinstance(verdict, Finished)
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"{FINISHED if finished else UNFINISHED}\n\nEvidence:\n{quoted(verdict.evidence)}", cycle.effects.now(), cycle.paths):
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.finished(verdict.evidence) if finished else outcomes.unfinished(verdict.evidence), cycle.effects.now()):
return Stop(1, failure.reason)
if finished and (failure := delete_session(cycle.session)):
return Stop(1, failure.reason)
return Archived()
# Blockquoted, so evidence holding blank lines still ends visibly where the text after it starts.
def quoted(passage: str) -> str:
return "\n".join(f"> {line}" for line in passage.splitlines())
+4 -2
View File
@@ -1,6 +1,6 @@
import dataclasses
from loop_claude.cycle.judge_reply import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
# A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records.
QUOTED_ANSWERS_PER_CYCLE = 3
@@ -72,7 +72,9 @@ def transition(state: State, event: Event) -> State:
return Judging(transcript_path, quoted_answers)
case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE:
return Working(answered, quoted_answers + 1)
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() | QuotedAnswer() as ruling):
case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer() as ruling) if quoted_answers >= QUOTED_ANSWERS_PER_CYCLE:
return Interrupting(transcript_path, ruling, quoted_answers)
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() as ruling):
return Interrupting(transcript_path, ruling, quoted_answers)
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
return Closing(transcript_path, verdict)
+7 -13
View File
@@ -1,10 +1,9 @@
from loop_claude.cycle.judge_reply import ANSWERS_RECORDED, QUOTE_SOURCES, QuotedAnswer
from loop_claude.claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
from claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.cycle.retry import Limited
from loop_claude.claude_code.transcript import part_line
from loop_claude.claude_code.session import Session
from claude_code.transcript import part_line
from claude_code.session import Session
PRINTED_TOOL_INPUT = 160
@@ -38,17 +37,12 @@ def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure
return None if result is not None else Failure("claude exited 0 without a result event")
def worker_args(task: str, session: Session, model: str, resuming: bool, answered: QuotedAnswer | None = None, remaining: str = "") -> list[str]:
if answered is not None:
start = ["-p", f"Your question: {answered.question}\n\n{QUOTE_SOURCES} answers it:\n\n{answered.answer}\n\nContinue the task.", "--resume", str(session.id)]
elif resuming:
ruled = f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{remaining}\n\n" if remaining else " "
start = ["-p", f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}.", "--resume", str(session.id)]
else:
# --session-id creates the session under the id loop-claude keeps; --resume continues that session.
start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.", "--name", session.name, "--session-id", str(session.id)]
def worker_args(session: Session, model: str, prompt: str, resume: bool) -> list[str]:
# --session-id creates the session under the id loop-claude keeps; --resume continues that session.
start = ["--resume", str(session.id)] if resume else ["--name", session.name, "--session-id", str(session.id)]
# -p fails without --verbose under stream-json.
return [
"-p", prompt,
*start,
"--output-format", "stream-json",
"--permission-mode", "bypassPermissions",
+20 -15
View File
@@ -4,10 +4,11 @@ usage: loop-claude <task>
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
premises; the task runs at the checkout root. Each cycle a worker runs the task. A judge then reads
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md
and the human's ~/.claude/CLAUDE.md, where they exist. It rules whether the chunk, the work of one
PR, is finished. A chunk stays unfinished until each answer the human typed in it that a later chunk
could need is recorded: the premises or the records hold it, or the transcript shows the worker
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md,
and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker
writing it into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the
worker made that the premises or the records settle is not asked about. When the worker asks a
question they answer, the judge quotes the answer, loop-claude prints it, and the worker resumes
@@ -44,8 +45,8 @@ loop-claude --help succeeds: the loop reloads into the edited script.
Exit 1, saying why, when:
- no task is given
- git cannot start or finds no checkout
- README.md, or AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md where they exist, cannot be
read or is not UTF-8
- README.md, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
~/.claude/skills/larv-review/standards/*.md where they exist, cannot be read or is not UTF-8
- README.md holds no premises
- the models file cannot be read or written
- claude leaves no transcript
@@ -77,17 +78,19 @@ import pathlib
import sys
import typing
from loop_claude.project.checkout import checkout_root, project_key
from loop_claude.project.checkout import checkout_root
from loop_claude.cycle.run import Cycle, run_cycle
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
from loop_claude.effects import Effects
from loop_claude.project.model_choice import get_or_ask_models
from loop_claude.paths import Paths
from transcript_archive.location import project_archive
from project_key import project_key
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from loop_claude.claude_code.session import session_for
from claude_code.session import session_named
from loop_claude.stop import Stop
from loop_claude.cycle.judge_reply import Unfinished
from loop_claude.cycle.judge import Unfinished
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
@@ -105,8 +108,10 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
if isinstance(loop_run, Stop):
return loop_run
baseline = fingerprint(launcher)
key = project_key(loop_run.root, paths.code)
session = session_for(key, paths)
key = project_key(loop_run.root, paths.home)
archive = project_archive(loop_run.root, paths.home, env)
# "A " is the human's cue in the session picker that the session is the loop's.
session = session_named(f"A {key} loop-claude", paths.claude_code_transcripts)
while True:
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
return stop
@@ -114,17 +119,17 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
premises = read_premises(loop_run.root)
if isinstance(premises, Stop):
return premises
records = read_records(loop_run.root, paths.claude_md)
records = read_records(loop_run.root, paths.claude_dir)
if isinstance(records, Stop):
return records
models = get_or_ask_models(key, paths, env, effects)
if isinstance(models, Stop):
return models
print(f"\n=== cycle {loop_run.cycle_number} ===", flush=True)
verdict = run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project_key=key, records=records, remaining=loop_run.remaining, root=loop_run.root, session=session, task=loop_run.task))
verdict = run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project_archive=archive, records=records, root=loop_run.root, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
if isinstance(verdict, Stop):
return verdict
loop_run = dataclasses.replace(loop_run, remaining=verdict.evidence if isinstance(verdict, Unfinished) else "")
loop_run = dataclasses.replace(loop_run, unfinished_evidence=verdict.evidence if isinstance(verdict, Unfinished) else "")
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
@@ -133,7 +138,7 @@ def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopR
if task in ("", "-h", "--help"):
return Stop(0 if task else 1, __doc__.strip())
root = checkout_root(cwd, effects)
return root if isinstance(root, Stop) else LoopRun(0, "", root, task)
return root if isinstance(root, Stop) else LoopRun(0, root, task, "")
loop_run = decode_handed(argv[1], LoopRun) if len(argv) == 2 else None
if not (loop_run and loop_run.root and loop_run.task):
return Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
+1 -1
View File
@@ -17,9 +17,9 @@ T = typing.TypeVar("T")
class LoopRun:
"""What a reload hands the edited script, as JSON on argv."""
cycle_number: int
remaining: str
root: str
task: str
unfinished_evidence: str
def decode_handed(handed: str, kind: type[T]) -> T | None:
+5 -8
View File
@@ -1,27 +1,24 @@
import dataclasses
import pathlib
import typing
@dataclasses.dataclass(frozen=True)
class Paths:
claude_code_transcripts: pathlib.Path
claude_dir: pathlib.Path
claude_json: pathlib.Path
claude_md: pathlib.Path
code: pathlib.Path
home: pathlib.Path
model_catalog: pathlib.Path
models_file: pathlib.Path
transcript_archive: pathlib.Path
def paths_from(home: pathlib.Path, env: typing.Mapping[str, str]) -> Paths:
def paths_from(home: pathlib.Path) -> Paths:
claude = home / ".claude"
return Paths(
claude_code_transcripts=claude / "projects",
claude_dir=claude,
claude_json=home / ".claude.json",
claude_md=claude / "CLAUDE.md",
code=home / "code",
home=home,
model_catalog=claude / "cache" / "model-catalog",
models_file=claude / "loop-claude-models.json",
transcript_archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
)
-14
View File
@@ -23,17 +23,3 @@ def worktrees(root: str, effects: Effects) -> list[str]:
if listing.returncode == 0:
found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")]
return sorted(set(found))
def project_key(root: str, code: pathlib.Path) -> str:
return root.removeprefix(f"{code}/").lstrip("/")
def read_utf8(folder: str, name: str, consequence: str) -> str | Stop:
try:
return pathlib.Path(folder, name).read_text(encoding="utf-8")
except OSError as failure:
return Stop(1, f"{name} in {folder}: {failure.strerror} - {consequence}.")
except UnicodeDecodeError as failure:
line = failure.object.count(b"\n", 0, failure.start) + 1
return Stop(1, f"{name} in {folder} is not UTF-8 on line {line} - {consequence}.")
+1 -1
View File
@@ -4,7 +4,7 @@ import pathlib
import sys
import typing
from loop_claude.claude_code.model_catalog import catalog_models
from claude_code.model_catalog import catalog_models
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.stop import needs_human, needs_terminal, Stop
+2 -2
View File
@@ -1,5 +1,5 @@
from loop_claude.project.checkout import read_utf8
from markdown_sections import sections
from loop_claude.project.text_file import read_utf8
from markdown_text import sections
from loop_claude.stop import Stop
+11 -6
View File
@@ -1,16 +1,21 @@
import pathlib
from loop_claude.project.checkout import read_utf8
from loop_claude.project.text_file import read_utf8
from loop_claude.stop import Stop
# The records: these project files and HUMAN_RULES; the judge reads them beside the README's premises.
# The records the judge reads beside the README's premises: these project files, then the human's rules below.
RECORD_FILES = ("AGENTS.md", "docs/decisions.md")
HUMAN_RULES = "~/.claude/CLAUDE.md"
# The human's rules for every project, under ~/.claude: CLAUDE.md, then each .md file in these folders, which a repo check keeps present.
HUMAN_RULES_FILE = "CLAUDE.md"
HUMAN_RULE_DIRS = ("rules", "skills/larv-review/standards")
HUMAN_RULE_NAMES = (f"~/.claude/{HUMAN_RULES_FILE}", *(f"~/.claude/{folder}/" for folder in HUMAN_RULE_DIRS))
def read_records(root: str, claude_md: pathlib.Path) -> str | Stop:
"""The project's record files, then the human's rules for every project, each headed by its name; a file that does not exist is left out."""
sources = [(root, name, name) for name in RECORD_FILES] + [(str(claude_md.parent), claude_md.name, HUMAN_RULES)]
def read_records(root: str, claude_dir: pathlib.Path) -> str | Stop:
"""The project's record files, then the human's rules for every project, CLAUDE.md first, each headed by its name; a file that does not exist is left out."""
rules = [claude_dir / HUMAN_RULES_FILE] + [rule for folder in HUMAN_RULE_DIRS for rule in sorted((claude_dir / folder).glob("*.md"))]
sources = [(root, name, name) for name in RECORD_FILES]
sources += [(str(rule.parent), rule.name, f"~/.claude/{rule.relative_to(claude_dir)}") for rule in rules]
records = []
for folder, name, heading in sources:
if not pathlib.Path(folder, name).exists():
+13
View File
@@ -0,0 +1,13 @@
import pathlib
from loop_claude.stop import Stop
def read_utf8(folder: str, name: str, consequence: str) -> str | Stop:
try:
return pathlib.Path(folder, name).read_text(encoding="utf-8")
except OSError as failure:
return Stop(1, f"{name} in {folder}: {failure.strerror} - {consequence}.")
except UnicodeDecodeError as failure:
line = failure.object.count(b"\n", 0, failure.start) + 1
return Stop(1, f"{name} in {folder} is not UTF-8 on line {line} - {consequence}.")
@@ -15,14 +15,14 @@ import tempfile
import time
import unittest
BIN = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from test_env import isolated_env
BIN = pathlib.Path(__file__).resolve().parents[1]
TASK = "Do the next chunk."
# A git hook's GIT_DIR, the host's LOOP_CLAUDE_* or PYTHONPATH would point the program under test at the host's own state.
def host_env() -> dict[str, str]:
return {name: value for name, value in os.environ.items() if not name.startswith(("GIT_", "LOOP_CLAUDE_", "PYTHON"))}
# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role,
# or none left, is Ctrl-C to loop-claude, which otherwise loops forever.
FAKE_CLAUDE = """#!{python}
@@ -160,7 +160,7 @@ class Checkout:
self.root.mkdir(parents=True)
(self.root / "README.md").write_text(PREMISES)
self.script = BIN / "loop-claude"
self.env = host_env()
self.env = isolated_env()
fake = self.temp / "fake-bin"
fake.mkdir()
(fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable))
@@ -687,12 +687,12 @@ class Reload(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge"] * 5)
self.assertIn("keeping the running script", run.stderr)
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
self.assertEqual(reloads, [{"cycle_number": cycle, "remaining": "working", "root": str(checkout.root), "task": TASK} for cycle in (2, 3, 4)])
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working"} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5 ===", run.stdout)
outside = checkout.temp / "outside"
outside.mkdir()
state = {"cycle_number": 3, "remaining": "", "root": str(checkout.root), "task": TASK}
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": ""}
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)], cwd=outside)
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"]))
self.assertEqual(run.calls[0]["cwd"], str(checkout.root))
@@ -1,7 +1,6 @@
import ast
import contextlib
import dataclasses
import hashlib
import io
import json
import os
@@ -14,18 +13,18 @@ import time
import unittest
import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_claude import transcript_archive as archive
from loop_claude.project import checkout, model_choice, records
from loop_claude.effects import Effects
from loop_claude.claude_code import entries, session, transcript, trust
from claude_code import entries, session
from failure import Failure
from loop_claude.cycle.judge_reply import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from
from loop_claude.cycle import interrupt, judge, retry, run, states, worker
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
from loop_claude.cycle.retry import Limited
from loop_claude.loop import main, reload
from loop_claude import paths
from transcript_archive.location import project_archive
from loop_claude.stop import Stop
CWD = pathlib.Path("/c")
@@ -40,10 +39,6 @@ def human(content):
return {"type": "user", "message": {"content": content}}
def queued(prompt, kind):
return {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": kind}, "prompt": prompt}}
class FakeEffects:
"""Effects that record each call and answer from a script, one answer per call."""
@@ -161,12 +156,7 @@ class Transitions(unittest.TestCase):
class QuestionFor(unittest.TestCase):
def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self):
self.assertEqual(run.question_for(Interrupt("e", "Which one?")), "Which one?")
self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
class Quoted(unittest.TestCase):
def test_quotes_every_line_of_a_passage_blank_ones_included(self):
self.assertEqual(run.quoted("merged\n\nPR #1"), "> merged\n> \n> PR #1")
self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
class Cycles(unittest.TestCase):
@@ -174,14 +164,15 @@ class Cycles(unittest.TestCase):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.home = pathlib.Path(temp.name)
self.paths = paths.paths_from(self.home, {})
self.session = session.session_for("proj", self.paths)
self.paths = paths.paths_from(self.home)
self.session = session.session_named("A proj loop-claude", self.paths.claude_code_transcripts)
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", remaining=""):
return run.Cycle(effects=fake.effects(), models=model_choice.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_key="proj", records=records, remaining=remaining, root=str(self.home), session=self.session, task="Do it.")
def cycle(self, fake, records="", unfinished_evidence=""):
return run.Cycle(effects=fake.effects(), models=model_choice.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in (self.paths.transcript_archive / "proj").glob("*/*.outcomes.md"))
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
@@ -193,7 +184,7 @@ class Cycles(unittest.TestCase):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
self.assertTrue(session.transcript_file(self.session))
self.assertEqual(run.run_cycle(self.cycle(fake, remaining="working")), Unfinished("working"))
self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")), Unfinished("working"))
workers = fake.made("stream_claude")
self.assertIn("--session-id", workers[0])
self.assertIn("--resume", workers[1])
@@ -216,7 +207,7 @@ class Cycles(unittest.TestCase):
(folder.parent / f"{self.session.id}.orphaned-1.jsonl").write_text("o\n")
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 3, claude=[judged("unfinished"), judged("finished"), judged("unfinished")])
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
[chunk] = (self.paths.transcript_archive / "proj").iterdir()
[chunk] = self.archive.iterdir()
kept = chunk / "session" / str(self.session.id)
self.assertEqual((chunk / "session" / f"{self.session.id}.orphaned-1.jsonl").read_text(), "o\n")
os.utime(kept / "subagents" / "workflows" / "journal.jsonl", (0, 0))
@@ -232,7 +223,7 @@ class Cycles(unittest.TestCase):
folder.mkdir()
(folder / "custom-title.json").write_text("third")
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
[next_chunk] = set((self.paths.transcript_archive / "proj").iterdir()) - {chunk}
[next_chunk] = set(self.archive.iterdir()) - {chunk}
self.assertEqual(sorted(path.read_text() for path in (next_chunk / "session" / str(self.session.id)).glob("custom-title.json*")), ["third"])
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable folder")
@@ -253,10 +244,10 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n"])
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
prompts = [stdin for args, stdin in fake.made("claude")]
self.assertEqual(len(prompts), 2)
self.assertNotIn("the second", prompts[0])
self.assertIn("[human] the second", prompts[1])
judge_prompts = [stdin for args, stdin in fake.made("claude")]
self.assertEqual(len(judge_prompts), 2)
self.assertNotIn("the second", judge_prompts[0])
self.assertIn("[human] the second", judge_prompts[1])
def test_a_question_the_records_answer_resumes_the_worker_with_the_answer_three_times_a_cycle(self):
answered = judged("quoted", answer="Use *A*.")
@@ -264,19 +255,20 @@ class Cycles(unittest.TestCase):
with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed:
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
resumed = fake.made("stream_claude")[1]
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md answers it:\n\nUse *A*.\n\nContinue the task.")
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answers it:\n\nUse *A*.\n\nContinue the task.")
self.assertEqual(len(fake.made("stream_claude")), 4)
self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md answered: Which one? ===\nUse *A*."), 3)
self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
quoted = "2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md says:\n> Use *A*.\n\nEvidence:\n> working\n"
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answered: Which one? ===\nUse *A*."), 3)
self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
quoted = "2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n"
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
def test_stops_when_a_quoted_answer_cannot_be_archived(self):
self.paths.transcript_archive.parent.mkdir(parents=True)
self.paths.transcript_archive.write_text("")
self.archive.parent.mkdir(parents=True)
self.archive.write_text("")
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use A.")])
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(1, f"could not archive the transcript: {self.paths.transcript_archive / 'proj'}: Not a directory"))
stop = run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A."))
self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$")
self.assertEqual(len(fake.made("stream_claude")), 1)
def test_an_answer_the_records_do_not_hold_is_dropped_and_the_question_goes_to_the_human(self):
@@ -357,7 +349,7 @@ class Limits(unittest.TestCase):
class Interrupts(unittest.TestCase):
def test_stops_off_a_terminal_before_starting_claude(self):
fake = FakeEffects(on_terminal=False)
stop = interrupt.interrupt("/r", uuid7(), "m", "/t", "Which one?", paths.paths_from(pathlib.Path("/h"), {}), fake.effects())
stop = interrupt.interrupt("/r", uuid7(), "m", "/t", "Which one?", paths.paths_from(pathlib.Path("/h")), fake.effects())
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"))
self.assertEqual(fake.calls, [])
@@ -366,7 +358,7 @@ class Interrupts(unittest.TestCase):
path = pathlib.Path(home, "t.jsonl")
path.write_text(json.dumps(human("a")) + "\n")
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
stop = interrupt.interrupt(home, uuid7(), "m", str(path), "Which one?", paths.paths_from(pathlib.Path(home), {}), fake.effects())
stop = interrupt.interrupt(home, uuid7(), "m", str(path), "Which one?", paths.paths_from(pathlib.Path(home)), fake.effects())
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
@@ -391,13 +383,13 @@ class ModelPrompt(unittest.TestCase):
class WorkerArgs(unittest.TestCase):
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
opened = session.session_for("proj", paths.paths_from(pathlib.Path("/h"), {}))
fresh = worker.worker_args("Do it.", opened, "m", False)
opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects"))
fresh = worker.worker_args(opened, "m", prompts.fresh("Do it."), resume=False)
self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id))
self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude")
resumed = worker.worker_args("Do it.", opened, "m", True)
resumed = worker.worker_args(opened, "m", prompts.resumed(""), resume=True)
self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id))
self.assertNotIn("Do it.", " ".join(resumed))
self.assertNotIn("--session-id", resumed)
self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once"))
@@ -405,120 +397,40 @@ class Records(unittest.TestCase):
def test_heads_each_record_by_its_name_the_humans_rules_last(self):
with tempfile.TemporaryDirectory() as root:
claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md")
self.assertEqual(records.read_records(root, claude_md), "")
self.assertEqual(records.read_records(root, claude_md.parent), "")
claude_md.parent.mkdir(parents=True)
claude_md.write_text("# Global\n")
self.assertEqual(records.read_records(root, claude_md), "From ~/.claude/CLAUDE.md:\n# Global")
self.assertEqual(records.read_records(root, claude_md.parent), "From ~/.claude/CLAUDE.md:\n# Global")
pathlib.Path(root, "docs").mkdir()
pathlib.Path(root, "docs", "decisions.md").write_text("# Decisions\n")
pathlib.Path(root, "AGENTS.md").write_text("\n# Rules\n")
self.assertEqual(records.read_records(root, claude_md), "From AGENTS.md:\n# Rules\n\nFrom docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global")
self.assertEqual(records.read_records(root, claude_md.parent), "From AGENTS.md:\n# Rules\n\nFrom docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global")
pathlib.Path(claude_md.parent, "rules").mkdir()
pathlib.Path(claude_md.parent, "rules", "todo-items.md").write_text("# Todo\n")
pathlib.Path(claude_md.parent, "rules", "goals-and-audience.md").write_text("# Goals\n")
pathlib.Path(claude_md.parent, "rules", "notes.txt").write_text("not a rule\n")
pathlib.Path(claude_md.parent, "skills", "larv-review", "standards").mkdir(parents=True)
pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n")
self.assertTrue(records.read_records(root, claude_md.parent).endswith("From ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/goals-and-audience.md:\n# Goals\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments"))
def test_stops_on_a_record_it_cannot_read(self):
with tempfile.TemporaryDirectory() as root:
claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md")
claude_md.mkdir(parents=True)
self.assertEqual(records.read_records(root, claude_md), Stop(1, f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records."))
self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records."))
pathlib.Path(root, "docs", "decisions.md").mkdir(parents=True)
self.assertEqual(records.read_records(root, claude_md), Stop(1, f"docs/decisions.md in {root}: Is a directory - the judge cannot read the records."))
self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"docs/decisions.md in {root}: Is a directory - the judge cannot read the records."))
pathlib.Path(root, "AGENTS.md").write_bytes(b"# Rules\n\xff\n")
self.assertEqual(records.read_records(root, claude_md), Stop(1, f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records."))
self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records."))
class Render(unittest.TestCase):
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self):
said = transcript.render([
human("do it"),
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
assistant({"type": "text", "text": " "}),
human([{"type": "tool_result", "content": "not typed"}]),
human("<command-name>/exit</command-name>"),
human([{"type": "text", "text": "yes, "}, {"type": "text", "text": "merge it"}]),
queued("B, while you work", "human"),
queued("origin/main moved", "coordinator"),
{**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"},
])
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.')
class Archive(unittest.TestCase):
def test_writes_afresh_a_copy_whose_outcomes_file_is_missing(self):
def test_stops_on_a_rule_it_cannot_read(self):
with tempfile.TemporaryDirectory() as root:
kept = paths.paths_from(pathlib.Path(root), {})
transcript = pathlib.Path(root, "t.jsonl")
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(archive.archive("proj", str(transcript), "Do it.", "Verdict: unfinished", NOW, kept))
(outcomes,) = kept.transcript_archive.glob("proj/*/*.outcomes.md")
outcomes.unlink()
self.assertIsNone(archive.archive("proj", str(transcript), "Do it.", "Stopped: Ctrl-C", NOW, kept))
self.assertEqual(outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n")
class CopyFor(unittest.TestCase):
def test_skips_a_version_already_kept_beside_its_copy(self):
with tempfile.TemporaryDirectory() as temp:
copy = pathlib.Path(temp, "custom-title.json")
copy.write_bytes(b"first")
beside = archive.copy_for(copy, b"second")
self.assertEqual(beside, copy.with_name(f"custom-title.json.{hashlib.sha256(b'second').hexdigest()}"))
beside.write_bytes(b"second")
self.assertIsNone(archive.copy_for(copy, b"second"))
self.assertEqual(archive.copy_for(copy, b"first, grown"), copy)
class FirstTimestampedLine(unittest.TestCase):
def test_skips_the_lines_every_chunk_shares_and_else_takes_the_first(self):
self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\nnot JSON\n{"timestamp": "t"}\n{"timestamp": "u"}\n'), b'{"timestamp": "t"}')
self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\n[1]\n'), b'{"type": "custom-title"}')
self.assertEqual(transcript.first_timestamped_line(b""), b"")
class HumanTurns(unittest.TestCase):
def test_counts_typed_turns_and_not_tool_results(self):
self.assertEqual(transcript.human_turns([
human("typed"),
human([{"type": "text", "text": "typed as a block"}]),
human([{"type": "tool_result", "content": "not typed"}]),
human("<command-name>/model</command-name>"),
{**human("<3 merge it"), "promptSource": "typed"},
{**human("<task-notification>done</task-notification>"), "promptSource": "system"},
{**human([{"type": "text", "text": "<task-notification>done</task-notification>"}]), "promptSource": "system"},
{**human("peer message"), "isMeta": True},
{**human("the loop's own prompt"), "promptSource": "sdk"},
human([{"type": "text", "text": "[Request interrupted by user]"}]),
human([]),
queued("typed while claude worked", "human"),
queued("<task-notification>done</task-notification>", "task-notification"),
{"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "task-notification", "prompt": "<task-notification>done</task-notification>"}},
assistant({"type": "text", "text": "said"}),
]), 4)
class PartLine(unittest.TestCase):
def test_renders_text_and_tool_calls_and_nothing_else(self):
self.assertEqual(transcript.part_line({"type": "text", "text": "hi"}, 20), "hi")
self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}, 20), "")
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
self.assertEqual(transcript.part_line("not a part", 20), "")
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Write", "input": {"content": "Hälsa på"}}, 40), '[tool Write] {"content": "Hälsa på"}')
class Parse(unittest.TestCase):
def test_yields_only_json_objects(self):
self.assertEqual(entries.parse_entry('{"type": "user"}'), {"type": "user"})
self.assertIsNone(entries.parse_entry("not json"))
self.assertIsNone(entries.parse_entry("[1, 2]"))
class MarkTrusted(unittest.TestCase):
def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self):
config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}}
handed = json.dumps(config)
self.assertEqual(trust.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"]))
self.assertEqual(json.dumps(config), handed)
self.assertEqual(trust.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"]))
claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md")
rules = pathlib.Path(claude_md.parent, "rules")
rules.mkdir(parents=True)
pathlib.Path(rules, "todo-items.md").write_bytes(b"\xff\n")
self.assertEqual(records.read_records(root, claude_md.parent), Stop(1, f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records."))
class JudgePrompt(unittest.TestCase):
def test_shows_the_transcripts_tail_and_returns_what_it_showed(self):
@@ -569,7 +481,7 @@ class Verdict(unittest.TestCase):
class LoopRuns(unittest.TestCase):
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "remaining": "", "root": "/r"})], [json.dumps({"cycle_number": 3, "remaining": "", "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "remaining": "", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "remaining": "", "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "remaining": "", "root": "/r", "task": "do it", "turns": 1})], [json.dumps({"cycle_number": 3, "failures": 0, "remaining": "", "root": "/r", "task": "do it"})]):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "", "unfinished_evidence": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1, "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "unfinished_evidence": ""})]):
with self.subTest(handed=handed):
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(handed)}"))
@@ -586,7 +498,7 @@ class LoopRuns(unittest.TestCase):
launcher = pathlib.Path(root, "loop-claude")
launcher.write_text("")
fake = FakeEffects(python=[ran()])
self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(1, "", "/r", "do it"), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence=""), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
class HelpLimits(unittest.TestCase):
@@ -603,7 +515,8 @@ class ExitContract(unittest.TestCase):
def test_every_exit_1_stop_has_its_clause_in_help(self):
read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "README.md holds no premises"
models_ = "the models file cannot be read or written"
unreadable = f"README.md, or {', '.join(records.RECORD_FILES)} or {records.HUMAN_RULES} where they exist, cannot be read or is not UTF-8"
names = (*records.RECORD_FILES, records.HUMAN_RULE_NAMES[0], *(f"{folder}*.md" for folder in records.HUMAN_RULE_NAMES[1:]))
unreadable = f"README.md, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
clauses = [
("cycle/interrupt.py", "interrupt", "1", "entries.reason", read),
@@ -622,18 +535,18 @@ class ExitContract(unittest.TestCase):
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
("project/checkout.py", "checkout_root", "1", "f'could not start git:", git),
("project/checkout.py", "checkout_root", "1", "found.stderr.strip()", git),
("project/checkout.py", "read_utf8", "1", "f'{name} in {folder}:", unreadable),
("project/checkout.py", "read_utf8", "1", "f'{name} in {folder} is not UTF-8", unreadable),
("project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_),
("project/model_choice.py", "read_models_file", "1", 'f"could not read {saved}: {getattr(', models_),
("project/model_choice.py", "read_models_file", "1", "f'could not read {saved}: not an object", models_),
("project/premises.py", "read_premises", "1", "f'README.md has no ##", premises_),
("project/premises.py", "read_premises", "1", "f'README.md has ## {name} more than once", premises_),
("project/premises.py", "read_premises", "1", "f'README.md has nothing under", premises_),
("project/text_file.py", "read_utf8", "1", "f'{name} in {folder}:", unreadable),
("project/text_file.py", "read_utf8", "1", "f'{name} in {folder} is not UTF-8", unreadable),
]
root = pathlib.Path(main.__file__).parents[1]
found = []
for path in sorted(root.rglob("*.py")):
for path in sorted(path for path in root.rglob("*.py") if not path.name.startswith("test_")):
functions = [node for node in ast.walk(ast.parse(path.read_text())) if isinstance(node, ast.FunctionDef)]
stops = [(call.lineno, function.name, ast.unparse(call.args[0]), ast.unparse(call.args[1])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Stop" and not (isinstance(call.args[0], ast.Constant) and call.args[0].value in (0, 2, 130))]
found += [(str(path.relative_to(root)), function, code, reason) for _, function, code, reason in sorted(stops)]
@@ -650,25 +563,21 @@ class JudgeFailures(unittest.TestCase):
started, field, unasked = "claude cannot start or exits non-zero", "its reply misses or mistypes a field", "interrupts or quotes an answer without a question"
# Every Failure the judge's run returns, in source order: path, function, start of reason, its --help clause.
clauses = [
("cycle/judge.py", "run_judge", "f'could not start claude:", started),
("cycle/judge.py", "run_judge", "proc.stderr.strip() or f'the judge exited", started),
("cycle/judge.py", "run_judge", 'f"{verdict.reason}; it replied:', field),
("cycle/judge.py", "run_judge", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"),
("cycle/judge_reply.py", "verdict_from", "'the judge returned no reply'", field),
("cycle/judge_reply.py", "verdict_from", 'f"the judge\'s reply has no {name}', field),
("cycle/judge_reply.py", "verdict_from", "'the judge interrupted without a question'", unasked),
("cycle/judge_reply.py", "verdict_from", "'the judge quoted an answer without a question'", unasked),
("verdict_from", "'the judge returned no reply'", field),
("verdict_from", 'f"the judge\'s reply has no {name}', field),
("verdict_from", "'the judge interrupted without a question'", unasked),
("verdict_from", "'the judge quoted an answer without a question'", unasked),
("run_judge", "f'could not start claude:", started),
("run_judge", "proc.stderr.strip() or f'the judge exited", started),
("run_judge", 'f"{verdict.reason}; it replied:', field),
("run_judge", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"),
]
root = pathlib.Path(main.__file__).parents[1]
found = []
for path in ("cycle/judge.py", "cycle/judge_reply.py"):
functions = [node for node in ast.walk(ast.parse((root / path).read_text())) if isinstance(node, ast.FunctionDef)]
failures = sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Failure")
found += [(path, function, reason) for _, function, reason in failures]
functions = [node for node in ast.walk(ast.parse(pathlib.Path(judge.__file__).read_text())) if isinstance(node, ast.FunctionDef)]
found = sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Failure")
self.assertEqual(len(found), len(clauses), found)
for (path, function, reason), (want_path, want_function, reason_start, _) in zip(found, clauses):
self.assertEqual((path, function), (want_path, want_function))
self.assertTrue(reason.startswith(reason_start), f"{path} {function}: {reason}")
for (_, function, reason), (want_function, reason_start, _) in zip(found, clauses):
self.assertEqual(function, want_function)
self.assertTrue(reason.startswith(reason_start), f"{function}: {reason}")
judge_clause = " ".join(main.__doc__[main.__doc__.index("a judge when"):main.__doc__.index("A usage limit")].split())
self.assertEqual([clause for *_, clause in clauses if clause not in judge_clause], [])
@@ -25,3 +25,8 @@ def sections(text: str) -> dict[str, list[str]]:
if name is not None:
found.setdefault(name, []).append("\n".join(body))
return found
# Blockquoted, so a passage holding blank lines still ends visibly where the text after it starts.
def quoted(passage: str) -> str:
return "\n".join(f"> {line}" for line in passage.splitlines())
+2 -2
View File
@@ -4,7 +4,7 @@ import dataclasses
import os
import statistics
from larv_review.history import Place
from comprehension_history import Place
from metric_bench.python_units import Unit
METRICS: dict[str, Callable[[Unit, dict[str, int]], int]] = {
@@ -84,7 +84,7 @@ def medians(runs: list[RunScores]) -> dict[str, Score]:
return {metric: Score(statistics.median(run.scores[metric].auc for run in runs), statistics.median(run.scores[metric].top_k for run in runs), all(run.scores[metric].constant for run in runs)) for metric in METRICS}
def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]:
def tracked_places(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]:
"""Entries written before paths were written from the repository's root shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones."""
found = []
dropped = []
+14 -7
View File
@@ -3,9 +3,10 @@
usage: metric-bench [history]
history defaults to docs/comprehension-history.md in the checkout it runs in, and the bench reads
the checkout that holds the history. For each scoring run in it, at the commit the panel read, it
measures each module-level function and each method of a module-level class in the Python files git
tracks, leaving out test_*.py, *_test.py and anything under a tests/ folder:
the checkout that holds the history. For each scoring run in it, those a fall called inside a paired
ruling included, at the commit the panel read, it measures each module-level function and each
method of a module-level class in the Python files git tracks, leaving out test_*.py, *_test.py and
anything under a tests/ folder:
- cognitive complexity: SonarSource's white paper, read for Python;
- length: lines;
@@ -34,8 +35,8 @@ import statistics
import subprocess
import sys
from metric_bench.bench import bench, co_changed, medians, METRICS, resolved, RunScores, Score
from larv_review.history import entries, Entry
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score, tracked_places
from comprehension_history import entries, Entry
from failure import Failure
from metric_bench.python_units import measured, python_units, Unit
@@ -77,11 +78,17 @@ def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] |
return Failure(f"could not read {history}: {failure}")
def scored_runs(found: list[Entry]) -> list[Entry]:
"""Each scoring run, and each paired ruling holding the scores a fall called unless a scoring run on its commit records them too."""
runs = {entry.commit for entry in found if not entry.paired}
return [entry for entry in found if not entry.paired or entry.scored_places and entry.commit not in runs]
def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[str]] | Failure:
"""Each scored run's heading and scores, and a note for each run skipped or not scored and each file left out."""
rows = []
notes = []
for run in [entry for entry in entries(text) if not entry.paired]:
for run in scored_runs(entries(text)):
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
notes.append(f"Skipped, its commit is not in {top}: {run.heading} ({missing.reason})")
continue
@@ -121,7 +128,7 @@ def run_scores(run: Entry, top: str) -> tuple[RunScores | None, list[str]] | Fai
log = git(["-c", "core.quotePath=false", "log", "--no-merges", "--format=tformat:@@", "--name-only", run.commit], top)
if isinstance(log, Failure):
return log
places, dropped = resolved(run.places, tracked)
places, dropped = tracked_places(run.scored_places, tracked)
return bench(units, places, len(set(dropped)), co_changed(log)), unparsed
@@ -7,15 +7,16 @@ import tempfile
import textwrap
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from metric_bench.bench import auc, bench, co_changed, resolved, top_k
from metric_bench.bench import auc, bench, co_changed, top_k, tracked_places
from metric_bench.python_units import cognitive, measured, python_units, Unit
from larv_review.history import entries, Place
from comprehension_history import entries, Place
from failure import Failure
from test_loop_claude_black_box import host_env
from test_env import isolated_env
from metric_bench.main import scored_runs
TOOL = pathlib.Path(__file__).resolve().parent / "metric-bench"
TOOL = pathlib.Path(__file__).resolve().parents[1] / "metric-bench"
def scored(source: str) -> int:
@@ -141,26 +142,29 @@ class Places(unittest.TestCase):
- `bin/tool/cycle/run.py:1` `step`
""")
def test_reads_each_scoring_runs_places_and_leaves_paired_rulings_out(self):
runs = [entry for entry in entries(self.HISTORY) if not entry.paired]
def test_reads_each_scoring_runs_places_and_leaves_rulings_out_unless_they_hold_a_falls_scores(self):
runs = scored_runs(entries(self.HISTORY))
self.assertEqual([(run.heading, run.commit) for run in runs], [("2026-10-08T12:50:49Z, PR #224 at a58a0a8", "a58a0a8")])
self.assertEqual(runs[0].places, [Place("skills/x/SKILL.md", None), Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("cycle/run.py", "close"), Place("bin/tool/cycle/judge.py", "run_judge")])
fall = "\n## 2026-10-09T09:00:00Z, PR #232 at {commit}, against 12d6d75\n\nRuling: worse\n\nJunior A, hardest first:\n\n- `bin/a.py:3` `f`\n"
self.assertEqual([run.commit for run in scored_runs(entries(self.HISTORY + fall.format(commit="bbbbbbb")))], ["a58a0a8", "bbbbbbb"])
self.assertEqual([run.commit for run in scored_runs(entries(self.HISTORY + fall.format(commit="a58a0a8")))], ["a58a0a8"])
self.assertEqual(runs[0].scored_places, [Place("skills/x/SKILL.md", None), Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("cycle/run.py", "close"), Place("bin/tool/cycle/judge.py", "run_judge")])
def test_resolves_a_shortened_path_to_the_file_nearest_the_one_before_it(self):
tracked = ["bin/tool/cycle/states.py", "bin/tool/cycle/run.py", "bin/other/cycle/run.py"]
places = [Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("gone.py", "x")]
self.assertEqual(resolved(places, tracked), ([Place("bin/tool/cycle/states.py", "transition"), Place("bin/tool/cycle/run.py", "step")], [Place("gone.py", "x")]))
self.assertEqual(tracked_places(places, tracked), ([Place("bin/tool/cycle/states.py", "transition"), Place("bin/tool/cycle/run.py", "step")], [Place("gone.py", "x")]))
def test_a_full_path_wins_over_a_file_in_the_folder_before_it(self):
self.assertEqual(resolved([Place("pkg/x.py", "a"), Place("main.py", "f")], ["pkg/x.py", "main.py", "pkg/main.py"])[0][-1], Place("main.py", "f"))
self.assertEqual(tracked_places([Place("pkg/x.py", "a"), Place("main.py", "f")], ["pkg/x.py", "main.py", "pkg/main.py"])[0][-1], Place("main.py", "f"))
def test_resolves_a_shortened_path_after_a_repeated_place_by_the_repeat(self):
tracked = ["bin/a/main.py", "bin/b/main.py", "bin/b/bench.py"]
places = [Place("bin/a/main.py", "main"), Place("bin/b/bench.py", "bench"), Place("bin/a/main.py", "main"), Place("main.py", "figures")]
self.assertEqual(resolved(places, tracked)[0][-1], Place("bin/a/main.py", "figures"))
self.assertEqual(tracked_places(places, tracked)[0][-1], Place("bin/a/main.py", "figures"))
def test_drops_a_shortened_path_two_files_match_with_no_place_before_it(self):
self.assertEqual(resolved([Place("cycle/run.py", "step")], ["bin/tool/cycle/run.py", "bin/other/cycle/run.py"]), ([], [Place("cycle/run.py", "step")]))
self.assertEqual(tracked_places([Place("cycle/run.py", "step")], ["bin/tool/cycle/run.py", "bin/other/cycle/run.py"]), ([], [Place("cycle/run.py", "step")]))
class Bench(unittest.TestCase):
@@ -194,7 +198,7 @@ class BlackBox(unittest.TestCase):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
top = directory.name
env = host_env()
env = isolated_env()
for args in (["init", "-q"], ["config", "user.email", "t@t"], ["config", "user.name", "t"]):
subprocess.run(["git", *args], cwd=top, check=True, env=env)
pathlib.Path(top, "a.py").write_text("def hard(a):\n\tif a:\n\t\tfor x in a:\n\t\t\tif x:\n\t\t\t\treturn x\n\n\ndef easy():\n\treturn 1\n")
@@ -207,7 +211,7 @@ class BlackBox(unittest.TestCase):
return top
def run_tool(self, top: str, *args: str) -> subprocess.CompletedProcess:
return subprocess.run([sys.executable, str(TOOL), *args], cwd=top, capture_output=True, text=True, env=host_env())
return subprocess.run([sys.executable, str(TOOL), *args], cwd=top, capture_output=True, text=True, env=isolated_env())
def test_prints_each_metrics_score_on_each_run_and_the_medians(self):
top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n")
+6
View File
@@ -0,0 +1,6 @@
import pathlib
def project_key(checkout_root: str, home: pathlib.Path) -> str:
"""The checkout's path relative to ~/code, or to / outside it: what names a project's loop-claude session, its entry in the models file and its archive folder."""
return checkout_root.removeprefix(f"{home / 'code'}/").lstrip("/")
+20 -62
View File
@@ -57,12 +57,11 @@ import pathlib
import re
import sys
from todo_table import cells, Item, ITEMS_HEADER, parse_row, table_rows
from failure import Failure
from markdown_sections import FENCE, sections
from markdown_text import FENCE, sections
from file_writes import replace_file
EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
LARGEST_FORMULA = 200
LONGEST_FORMULA = 4 * LARGEST_FORMULA
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
@@ -70,16 +69,6 @@ VARIABLES = ("A", "G", "R", "S", "W")
WEIGHTS_HEADER = "| Goal | W |"
@dataclasses.dataclass(frozen=True)
class Item:
id: int
release: tuple[int, int, int]
exempt: str
tagline: str
scores: dict[str, int]
goals: tuple[str, ...]
@dataclasses.dataclass(frozen=True)
class Scoring:
formula: ast.Expression
@@ -88,13 +77,6 @@ class Scoring:
weights: dict[str, float]
@dataclasses.dataclass(frozen=True)
class Table:
"""Body rows of a markdown table, and the index of the first row in the file's lines."""
start: int
rows: list[str]
@dataclasses.dataclass(frozen=True)
class Ranked:
text: str
@@ -109,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)
@@ -116,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:
@@ -124,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
@@ -357,23 +356,6 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail
return weights
def table_rows(lines: list[str], header: str) -> Table | Failure:
if lines.count(header) != 1:
return Failure(f"todo.md needs the table header {header} once")
start = lines.index(header) + 2
if start > len(lines) or not re.fullmatch(r"\|(-+\|)+", lines[start - 1].replace(" ", "")):
return Failure(f"the table under {header} has no |---| divider line")
end = start
while end < len(lines) and lines[end].startswith("|"):
end += 1
return Table(start, lines[start:end])
def cells(row: str, count: int) -> list[str] | Failure:
found = [cell.strip() for cell in re.split(r"(?<!\\)\|", row.strip())[1:-1]]
return found if len(found) == count else Failure(f"this row needs {count} cells: {row}")
def parse_item(row: str, weights: dict[str, float]) -> Item | Failure:
item = parse_row(row)
if isinstance(item, Failure):
@@ -383,30 +365,6 @@ def parse_item(row: str, weights: dict[str, float]) -> Item | Failure:
return item
def parse_row(row: str) -> Item | Failure:
"""An item row, every cell checked but the goals it cites."""
found = cells(row, 10)
if isinstance(found, Failure):
return found
id_, release, exempt, tagline, r, s, a, g, goals, _ = found
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release):
return Failure(f"item {id_}'s release {release!r} is not a semver version")
if exempt not in EXEMPTIONS:
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
scores = {}
for name, value in zip("RSAG", (r, s, a, g)):
if not re.fullmatch(r"[0-9]+", value) or not 1 <= int(value) <= 10:
return Failure(f"item {id_}'s {name} {value!r} is not a whole number from 1 to 10")
scores[name] = int(value)
cited = tuple(goal.strip() for goal in goals.split(","))
major, minor, patch = (int(part) for part in release.split("."))
return Item(int(id_), (major, minor, patch), exempt, tagline, scores, cited)
def render_item(item: Item, value: float) -> str:
release = ".".join(str(part) for part in item.release)
scores = " | ".join(str(item.scores[name]) for name in "RSAG")
-20
View File
@@ -1,20 +0,0 @@
import pathlib
import typing
from failure import Failure
from loop_claude.transcript_archive import FinishedChunk
from loop_claude.paths import paths_from
from loop_claude.project.checkout import project_key
def project_archive(checkout_root: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> pathlib.Path:
paths = paths_from(home, env)
return paths.transcript_archive / project_key(checkout_root, paths.code)
def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure:
"""The worker's transcript, then each subagent's."""
try:
return [path.read_bytes() for path in (chunk.transcript, *chunk.subagents)]
except OSError as failure:
return Failure(f"could not read {failure.filename}: {failure.strerror}")
+5 -4
View File
@@ -3,12 +3,13 @@ import re
import statistics
from failure import Failure
from loop_claude.transcript_archive import FinishedChunk, STAMPED
from transcript_archive.read import FinishedChunk
from reading_cost.measure import Reading
from markdown_sections import sections
from markdown_text import sections
from utc_stamp import STAMPED
FIGURE = re.compile(rf"^Reading cost, chunk (\w+), finished ({STAMPED})$")
PLACE = re.compile(r"^- `(.+)` (\d+)$")
FIGURE_PLACE = re.compile(r"^- `(.+)` (\d+)$")
PLACES_KEPT = 10
RESET = "Reading cost reset, "
RESET_AT = re.compile(rf"^{RESET}({STAMPED})$")
@@ -42,7 +43,7 @@ def readings_of(record: str) -> list[Reading] | Failure:
tokens = [int(match.group(1)) for line in lines if (match := TOKENS.match(line))]
if len(tokens) != 1:
return Failure(f"the figure under \"## {heading}\" holds no single tokens line; restore it from git history")
dated.append((named.group(2), heading, Reading(tokens[0], collections.Counter({match.group(1): int(match.group(2)) for line in lines if (match := PLACE.match(line))}))))
dated.append((named.group(2), heading, Reading(tokens[0], collections.Counter({match.group(1): int(match.group(2)) for line in lines if (match := FIGURE_PLACE.match(line))}))))
elif heading.startswith("Reading cost"):
return Failure(f"\"## {heading}\" names no chunk and UTC time, or no reset time; restore it from git history")
return [reading for finished, _, reading in sorted(dated, key=lambda item: item[:2]) if finished > max(resets)]
+7 -6
View File
@@ -32,9 +32,10 @@ import time
from reading_cost.measure import Checkout, measure, Reading
from failure import Failure
from reading_cost.figures import figure, merged, readings_of, RESET, trend, unheld
from loop_claude.transcript_archive import finished_chunks, utc
from reading_cost.archive import project_archive, read_threads
from transcript_archive.read import finished_chunks, read_threads
from transcript_archive.location import project_archive
from file_writes import replace_file
from utc_stamp import utc
@dataclasses.dataclass(frozen=True)
class Updated:
@@ -55,8 +56,8 @@ def main(argv: list[str]) -> int:
if isinstance(checkout, Failure):
return failed(checkout)
home = pathlib.Path.home()
archive = project_archive(checkout.root, home, os.environ)
record = pathlib.Path(given[0]) if given else pathlib.Path(checkout.top, "docs", "reading-cost.md")
archive = project_archive(checkout.main_root, home, os.environ)
record = pathlib.Path(given[0]) if given else pathlib.Path(checkout.current_root, "docs", "reading-cost.md")
updated = update(record, archive, checkout, str(home), utc(time.time()) if reset else None)
if isinstance(updated, Failure):
return failed(updated)
@@ -121,8 +122,8 @@ def located() -> Checkout | Failure:
return Failure(f"could not find the checkout: {failure}")
if listed.returncode != 0:
return Failure(listed.stderr.strip())
# The common dir is the checkout's .git, whichever worktree runs this.
return Checkout(str(pathlib.Path(common).parent), top, frozenset(filter(None, listed.stdout.split("\0"))))
# The common dir is the main checkout's .git, whichever worktree runs this.
return Checkout(top, str(pathlib.Path(common).parent), frozenset(filter(None, listed.stdout.split("\0"))))
def read_record(record: pathlib.Path) -> str | Failure:
+11 -11
View File
@@ -1,11 +1,11 @@
import collections
import dataclasses
import re
from loop_claude.claude_code.entries import assistant_parts, parse_entry, tool_call
from reading_cost.shell_reads import Reads, resolved, shell_reads
from claude_code.entries import assistant_parts, parse_entry, tool_call
from git_command import commits
from reading_cost.shell_reads import Reads, shell_reads
from shell_command import resolved, simple_commands
COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b")
@@ -16,22 +16,22 @@ class Reading:
places: collections.Counter[str]
@dataclasses.dataclass(frozen=True)
class Checkout:
root: str
top: str
"""main_root is the main checkout, whose path keys the archive; current_root is the checkout or worktree this runs in."""
current_root: str
main_root: str
tracked: frozenset[str]
def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | None:
worker, *subagents = [entries_of(thread) for thread in threads]
commit = commit_time(worker)
commit = commit_time(worker, home)
if commit is None:
return None
before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)]
reads = [reads_of(part, str(entry.get("cwd") or "/"), home) for thread in before for entry in thread for part in assistant_parts(entry)]
roots = [checkout.root, *(added for found in reads for added in found.added)]
roots = [checkout.main_root, *(added for found in reads for added in found.added)]
places = collections.Counter(place for found in reads for path in found.read if (place := relative(path, roots)) in checkout.tracked)
return Reading(sum(map(tokens_in, before)), places)
@@ -40,11 +40,11 @@ def entries_of(raw: bytes) -> list[dict]:
return [entry for line in raw.splitlines() if (entry := parse_entry(line))]
def commit_time(worker: list[dict]) -> str | None:
def commit_time(worker: list[dict], home: str) -> str | None:
for entry in worker:
for part in assistant_parts(entry):
name, arguments = call_of(part)
if name == "Bash" and COMMIT.search(str(arguments.get("command", ""))):
if name == "Bash" and commits(simple_commands(str(arguments.get("command", "")), str(entry.get("cwd") or "/"), home), home):
return str(entry.get("timestamp", ""))
return None
+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))
@@ -10,17 +10,19 @@ import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_claude.transcript_archive import archive, FINISHED, FINISHED_AT, finished_chunks, FinishedChunk, UNFINISHED, utc
from transcript_archive.write import archive
from reading_cost.measure import Checkout, Reading
from failure import Failure
from reading_cost import figures, measure
from test_loop_claude_black_box import host_env
from loop_claude.paths import paths_from
from transcript_archive.read import finished_chunks, FinishedChunk
from test_env import isolated_env
from transcript_archive import outcomes
from transcript_archive.location import project_archive
from reading_cost.shell_reads import Reads, shell_reads
TOOL = pathlib.Path(__file__).resolve().parent / "reading-cost"
TOOL = pathlib.Path(__file__).resolve().parents[1] / "reading-cost"
def said(timestamp, message_id, command=None, tokens=0, cwd="/c/p", **call):
@@ -59,11 +61,15 @@ class Measure(unittest.TestCase):
said("6", "m5", tokens=100, name="Read", input={"file_path": "/c/p/late.py"}),
]
subagent = [said("2", "s1", tokens=1, name="Grep", input={"path": "/c/w/src/a.py"}), said("7", "s2", tokens=100, name="Read", input={"file_path": "/c/p/late.py"})]
checkout = Checkout("/c/p", "/c/w", frozenset({"README.md", "late.py", "src/a.py", "src/b.py", "x.py"}))
checkout = Checkout("/c/w", "/c/p", frozenset({"README.md", "late.py", "src/a.py", "src/b.py", "x.py"}))
self.assertEqual(measure.measure([jsonl(worker), jsonl(subagent)], checkout, "/h"), Reading(33, collections.Counter({"src/a.py": 2, "README.md": 1, "src/b.py": 1})))
def test_measures_nothing_for_a_worker_that_never_committed(self):
self.assertIsNone(measure.measure([jsonl([said("1", "m1", command="git log --grep commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h"))
self.assertIsNone(measure.measure([jsonl([said("1", "m1", command="echo git commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h"))
def test_finds_a_commit_behind_git_options(self):
self.assertIsNotNone(measure.measure([jsonl([said("1", "m1", command="git -c user.name=t commit -m x")])], Checkout("/c/p", "/c/p", frozenset()), "/h"))
def test_skips_a_usage_that_is_not_a_count(self):
self.assertEqual(measure.tokens_in([{"message": {"id": "m", "usage": {"input_tokens": "7", "cache_creation_input_tokens": 2}}}]), 2)
@@ -94,35 +100,32 @@ class Figures(unittest.TestCase):
history = "\n".join([written("a", "2026-10-01T00:00:00Z", 1), written("c", "2026-10-03T00:00:00Z", 3), "## Reading cost reset, 2026-10-02T00:00:00Z\n", written("b", "2026-10-04T00:00:00Z", 2)])
self.assertEqual(figures.readings_of(history), [Reading(3, collections.Counter()), Reading(2, collections.Counter())])
def test_the_archive_stamps_what_it_reads_back(self):
self.assertRegex(f"{utc(1790000000)} {FINISHED}", FINISHED_AT)
class ReadingCostTool(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.home = pathlib.Path(os.path.realpath(temp.name))
self.env = {**host_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.home)}
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.home)}
self.checkout = self.home / "code" / "proj"
self.checkout.mkdir(parents=True)
(self.checkout / "a.py").write_text("")
self.git("init", "-q")
self.git("add", "a.py")
self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x")
self.paths = paths_from(self.home, {})
self.archive = project_archive(str(self.checkout), self.home, {})
def git(self, *args):
subprocess.run(["git", *args], cwd=self.checkout, check=True, env=self.env)
def archive_chunk(self, at, outcome=FINISHED):
def archive_chunk(self, at, outcome=outcomes.finished):
transcript = self.home / ".claude" / "projects" / "-proj" / f"{folder_name()}.jsonl"
(transcript.with_suffix("") / "subagents").mkdir(parents=True)
worker = [said("1", "m1", tokens=10, cwd=str(self.checkout), name="Read", input={"file_path": str(self.checkout / "a.py")}), said("2", "m2", command="git commit -m x")]
transcript.write_bytes(jsonl([{"timestamp": str(at)}, *worker]))
(transcript.with_suffix("") / "subagents" / "agent-a.jsonl").write_bytes(jsonl([said("1", "s1", tokens=1)]))
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(archive("proj", str(transcript), "Do it.", f"{outcome}\n\nEvidence:\n> merged", at, self.paths))
self.assertIsNone(archive(self.archive, str(transcript), "Do it.", outcome("merged"), at))
def run_tool(self, cwd, *args):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd, env=self.env, text=True)
@@ -130,8 +133,8 @@ class ReadingCostTool(unittest.TestCase):
def test_appends_each_finished_chunk_once_in_the_order_they_finished_from_a_worktree(self):
self.archive_chunk(1790000200)
self.archive_chunk(1790000100)
self.archive_chunk(1790000000, UNFINISHED)
chunks = finished_chunks(self.paths.transcript_archive / "proj")
self.archive_chunk(1790000000, outcomes.unfinished)
chunks = finished_chunks(self.archive)
self.assertEqual([chunk.finished for chunk in chunks], ["2026-09-21T14:15:00Z", "2026-09-21T14:16:40Z"])
worktree = self.home / "code" / "proj-wt"
self.git("worktree", "add", "-q", str(worktree))
View File
+48
View File
@@ -0,0 +1,48 @@
import pathlib
import re
import subprocess
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_claude.project.records import HUMAN_RULE_DIRS
from repo_checks.test_python_floor import ROOT
RULE_PATH = rf"(?:{'|'.join(map(re.escape, HUMAN_RULE_DIRS))})/[\w-]+\.md"
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE)
LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| —)", re.MULTILINE)
NAME = re.compile(r'"([^"]+)"')
RULE_FILE = re.compile(rf"(?<![\w/.-])(?:~/\.claude/)?({RULE_PATH})")
STRAY = re.compile(rf'(?:CLAUDE\.md|{RULE_PATH})(?!`? → "|:\d)[^\n"]{{1,5}}"')
class Citations(unittest.TestCase):
def test_every_citation_names_a_heading_then_headings_or_bold_leads_of_the_file_it_cites(self):
tracked = subprocess.run(["git", "ls-files", "-z"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split("\0")
texts = [(path, (ROOT / path).read_text()) for path in filter(None, tracked)]
self.assertEqual([f"{path}: {stray}" for path, text in texts for stray in STRAY.findall(text)], [], 'spell a citation `CLAUDE.md` → "Vocabulary"')
cited = [(path, file, NAME.findall(run)) for path, text in texts for file, run in CITATION.findall(text)]
self.assertTrue(cited)
unresolved = []
for path, file, names in cited:
if not (ROOT / file).exists():
unresolved.append(f"{path}: {file}")
continue
text = (ROOT / file).read_text()
headings = set(HEADING.findall(text))
leads = headings | set(LEAD.findall(text))
unresolved += [f"{path}: {file} → {name}" for i, name in enumerate(names) if name not in (headings if i == 0 else leads)]
self.assertEqual(unresolved, [], "the first name is a heading of the cited file, each later one a heading or a bold lead")
def test_every_rule_file_named_exists_and_topic_rules_lists_each(self):
tracked = subprocess.run(["git", "ls-files", "-z"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split("\0")
named = {(path, rule) for path in filter(None, tracked) if not pathlib.Path(path).name.startswith("test_") for rule in RULE_FILE.findall((ROOT / path).read_text())}
self.assertTrue(named)
self.assertEqual(sorted(f"{path}: {rule}" for path, rule in named if not (ROOT / rule).exists()), [])
topic_rules = (ROOT / "CLAUDE.md").read_text().split("## Topic rules\n")[1].split("\n## ")[0]
self.assertEqual(sorted(set(RULE_FILE.findall(topic_rules))), sorted(f"rules/{rule.name}" for rule in (ROOT / "rules").glob("*.md")))
def test_every_folder_the_judge_reads_rules_from_exists(self):
self.assertEqual([folder for folder in HUMAN_RULE_DIRS if not (ROOT / folder).is_dir()], [])
@@ -1,7 +1,11 @@
import pathlib
import subprocess
import sys
import unittest
from test_python_floor import ROOT
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import ROOT
PRIVATE = [
".claude/settings.local.json",
@@ -1,8 +1,12 @@
import ast
import pathlib
import subprocess
import sys
import unittest
from test_python_floor import ROOT
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import ROOT
def bound(node: ast.Import | ast.ImportFrom) -> list[str]:
@@ -1,7 +1,11 @@
import json
import pathlib
import sys
import unittest
from test_python_floor import ROOT
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import ROOT
class Install(unittest.TestCase):
@@ -5,7 +5,7 @@ import subprocess
import sys
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[1]
ROOT = pathlib.Path(__file__).resolve().parents[2]
FLOOR = re.compile(r"Python 3\.(\d+) or newer")
+19
View File
@@ -0,0 +1,19 @@
import pathlib
import shutil
import subprocess
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import readme_floor, ROOT
class Types(unittest.TestCase):
def test_mypy_passes_on_the_tools_at_the_floor(self):
floor = readme_floor()
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", "-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)
+109
View File
@@ -0,0 +1,109 @@
"""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, file_breaches, Outcome, rules_help, verdict
from git_command import commits
from failure import Failure
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
from shell_command import simple_commands
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: Outcome, 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 ""
+123
View File
@@ -0,0 +1,123 @@
import dataclasses
import os
import pathlib
import stat
import sys
import typing
from rule_hook.rules import Breach
from rule_hook.git import existing, git
from failure import Failure
from utc_stamp import utc
LOG = "rule-overrides.tsv"
@dataclasses.dataclass(frozen=True)
class LogLine:
"""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) -> LogLine | None:
fields = line.rstrip("\n").split("\t")
return LogLine(*fields) if len(fields) == len(dataclasses.fields(LogLine)) else None
def this_chunks(entry: LogLine, reflog: set[str], branch: str, on_default: typing.Callable[[str], bool]) -> bool:
"""Whether the override is the current branch's: its commit is in the branch's reflog, which keeps a commit an amend or a rebase replaced, follows `git branch -m`, and holds no other branch's commit."""
if entry.commit == "":
return True
# 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: LogLine) -> Failure | None:
try:
# No symlink, and no FIFO to hang on: the checkout, and so its git directory, may come from anyone.
descriptor = os.open(log.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
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) -> LogLine:
return LogLine(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")
unread = unread_reflog(reflog, head)
if unread:
print(f"rule-hook overrides cannot read the branch's reflog, so it cannot tell which overrides are this chunk's: {unread.reason}", file=sys.stderr)
return 1
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 unread_reflog(reflog: str | Failure, head: str | Failure) -> Failure | None:
if isinstance(reflog, Failure):
return reflog
if isinstance(head, Failure):
return head
# A reflog missing HEAD is off or expired, and would hide this chunk's overrides.
return None if head in reflog.split() else Failure("it does not hold HEAD")
def default_branch(directory: str) -> str | None:
return next((name for name in ("origin/HEAD", "main", "master") if not isinstance(git(directory, "rev-parse", "--verify", "--quiet", name), Failure)), None)
def holds(directory: str, descendant: str, ancestor: str) -> bool:
return bool(ancestor) and not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)
+165
View File
@@ -0,0 +1,165 @@
import dataclasses
import posixpath
import re
import typing
from git_command import commits
from shell_command import Simple
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]
@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)
@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 Outcome:
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) -> Outcome:
granted, malformed = overrides(written)
blocking = [breach for breach in breaches if breach.rule not in granted]
messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else []
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 Outcome(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]:
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())
+279
View File
@@ -0,0 +1,279 @@
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, file_breaches, overrides, verdict
from git_command import Commit, commit_message, commits
from test_rank_todo import DECISIONS, README, TODO
from test_env import isolated_env
from rule_hook.override_log import LogLine, parsed_entry, this_chunks
from shell_command import simple_commands
HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook"
# 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 = LogLine("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor\ttags no patch", "Dockerfile")
self.assertEqual(parsed_entry(entry.line()), LogLine("2026-10-13T00:00:00Z", "chunk", "c1", "image-pin", "the vendor tags no patch", "Dockerfile"))
self.assertIsNone(parsed_entry("a\tb"))
def test_an_override_is_the_chunk_s_by_its_reflog_and_name(self):
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(LogLine("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))
-25
View File
@@ -1,25 +0,0 @@
import pathlib
import re
import subprocess
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[1]
CITATION = re.compile(r'`?CLAUDE\.md`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE)
LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| —)", re.MULTILINE)
NAME = re.compile(r'"([^"]+)"')
STRAY = re.compile(r'CLAUDE\.md(?!`? → "|:\d)[^\n"]{1,5}"')
class Citations(unittest.TestCase):
def test_every_citation_names_a_heading_then_headings_or_bold_leads_of_claude_md(self):
text = (ROOT / "CLAUDE.md").read_text()
headings = set(HEADING.findall(text))
leads = headings | set(LEAD.findall(text))
tracked = subprocess.run(["git", "ls-files", "-z"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split("\0")
texts = [(path, (ROOT / path).read_text()) for path in filter(None, tracked)]
self.assertEqual([f"{path}: {stray}" for path, text in texts for stray in STRAY.findall(text)], [], 'spell a citation `CLAUDE.md` → "Vocabulary"')
cited = [(path, NAME.findall(run)) for path, text in texts for run in CITATION.findall(text)]
self.assertTrue(cited)
unresolved = [(path, name) for path, names in cited for i, name in enumerate(names) if name not in (headings if i == 0 else leads)]
self.assertEqual([f"{path}: {name}" for path, name in unresolved], [], "the first name is a heading of CLAUDE.md, each later one a heading or a bold lead")
+6
View File
@@ -0,0 +1,6 @@
import os
# A git hook's GIT_DIR, the host's LOOP_CLAUDE_* or PYTHONPATH would point the program under test at the host's own state.
def isolated_env() -> dict[str, str]:
return {name: value for name, value in os.environ.items() if not name.startswith(("GIT_", "LOOP_CLAUDE_", "PYTHON"))}
@@ -4,18 +4,21 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import markdown_sections
import markdown_text
class Sections(unittest.TestCase):
def test_keeps_every_headed_section_with_its_bodies(self):
text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n"
self.assertEqual(markdown_sections.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]})
self.assertEqual(markdown_text.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]})
def test_closes_a_fence_only_on_its_own_marker(self):
text = "## Goals\n````md\n~~~\n## Quoted\n```\n````\n ~~~\n## Also quoted\n ~~~\n1. one\n## Audience\nme\n"
self.assertEqual(list(markdown_sections.sections(text)), ["Goals", "Audience"])
self.assertEqual(list(markdown_sections.sections("```\nquoted:\n```python\n## Inside\n```\n## Goals\n1. one\n")), ["Goals"])
self.assertEqual(list(markdown_text.sections(text)), ["Goals", "Audience"])
self.assertEqual(list(markdown_text.sections("```\nquoted:\n```python\n## Inside\n```\n## Goals\n1. one\n")), ["Goals"])
def test_quotes_every_line_of_a_passage_blank_ones_included(self):
self.assertEqual(markdown_text.quoted("merged\n\nPR #1"), "> merged\n> \n> PR #1")
if __name__ == "__main__":
+1 -1
View File
@@ -9,7 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from failure import Failure
import rank_todo
from test_python_floor import ROOT
from repo_checks.test_python_floor import ROOT
README = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n\n## Audience\n\nMe.\n"
-15
View File
@@ -1,15 +0,0 @@
import shutil
import subprocess
import unittest
from test_python_floor import readme_floor, ROOT
class Types(unittest.TestCase):
def test_mypy_passes_on_the_tools_at_the_floor(self):
floor = readme_floor()
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", "-p", "larv_review", "-p", "loop_claude", "-p", "metric_bench", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline"], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+79
View File
@@ -0,0 +1,79 @@
import dataclasses
import re
from failure import Failure
EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
@dataclasses.dataclass(frozen=True)
class Item:
id: int
release: tuple[int, int, int]
exempt: str
tagline: str
scores: dict[str, int]
goals: tuple[str, ...]
@dataclasses.dataclass(frozen=True)
class Table:
"""Body rows of a markdown table, and the index of the first row in the file's lines."""
start: int
rows: list[str]
def items(todo: str) -> list[Item] | Failure:
"""Each row of a todo.md's items table."""
table = table_rows(todo.splitlines(), ITEMS_HEADER)
if isinstance(table, Failure):
return table
items = []
for row in table.rows:
item = parse_row(row)
if isinstance(item, Failure):
return item
items.append(item)
return items
def table_rows(lines: list[str], header: str) -> Table | Failure:
if lines.count(header) != 1:
return Failure(f"todo.md needs the table header {header} once")
start = lines.index(header) + 2
if start > len(lines) or not re.fullmatch(r"\|(-+\|)+", lines[start - 1].replace(" ", "")):
return Failure(f"the table under {header} has no |---| divider line")
end = start
while end < len(lines) and lines[end].startswith("|"):
end += 1
return Table(start, lines[start:end])
def cells(row: str, count: int) -> list[str] | Failure:
found = [cell.strip() for cell in re.split(r"(?<!\\)\|", row.strip())[1:-1]]
return found if len(found) == count else Failure(f"this row needs {count} cells: {row}")
def parse_row(row: str) -> Item | Failure:
"""An item row, every cell checked but the goals it cites."""
found = cells(row, 10)
if isinstance(found, Failure):
return found
id_, release, exempt, tagline, r, s, a, g, goals, _ = found
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release):
return Failure(f"item {id_}'s release {release!r} is not a semver version")
if exempt not in EXEMPTIONS:
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
scores = {}
for name, value in zip("RSAG", (r, s, a, g)):
if not re.fullmatch(r"[0-9]+", value) or not 1 <= int(value) <= 10:
return Failure(f"item {id_}'s {name} {value!r} is not a whole number from 1 to 10")
scores[name] = int(value)
cited = tuple(goal.strip() for goal in goals.split(","))
major, minor, patch = (int(part) for part in release.split("."))
return Item(int(id_), (major, minor, patch), exempt, tagline, scores, cited)
View File
+9
View File
@@ -0,0 +1,9 @@
import pathlib
import typing
from project_key import project_key
def project_archive(checkout_root: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> pathlib.Path:
archive = pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else home / ".claude" / "loop-claude-transcripts"
return archive / project_key(checkout_root, home)
+27
View File
@@ -0,0 +1,27 @@
import re
from markdown_text import quoted
from utc_stamp import STAMPED
FINISHED = "Verdict: finished"
FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE)
def finished(evidence: str) -> str:
return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}"
def unfinished(evidence: str) -> str:
return f"Verdict: unfinished\n\nEvidence:\n{quoted(evidence)}"
def interrupted(question: str, evidence: str) -> str:
return f"Verdict: interrupt\n\n{question}\n\nEvidence:\n{quoted(evidence)}"
def answered(question: str, sources: str, answer: str, evidence: str) -> str:
return f"Verdict: quoted answer\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}"
def stopped(why: str) -> str:
return f"Stopped: {why}"
+35
View File
@@ -0,0 +1,35 @@
import dataclasses
import pathlib
from failure import Failure
from transcript_archive.outcomes import FINISHED_AT
@dataclasses.dataclass(frozen=True)
class FinishedChunk:
folder: str
finished: str
transcript: pathlib.Path
subagents: list[pathlib.Path]
# One per chunk folder, its latest finished copy, in the order they finished.
def finished_chunks(project_archive: pathlib.Path) -> list[FinishedChunk] | Failure:
found = []
try:
for folder in sorted(path for path in project_archive.glob("*") if path.is_dir()):
copies = sorted((stamps[-1], outcomes) for outcomes in folder.glob("*.outcomes.md") if (stamps := FINISHED_AT.findall(outcomes.read_text(encoding="utf-8"))))
if copies:
finished, outcomes = copies[-1]
found.append(FinishedChunk(folder.name, finished, outcomes.with_name(outcomes.name.removesuffix(".outcomes.md") + ".jsonl"), sorted(folder.glob("session/*/subagents/*.jsonl"))))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the archive {project_archive}: {failure}")
return sorted(found, key=lambda chunk: (chunk.finished, chunk.folder))
def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure:
"""The worker's transcript, then each subagent's."""
try:
return [path.read_bytes() for path in (chunk.transcript, *chunk.subagents)]
except OSError as failure:
return Failure(f"could not read {failure.filename}: {failure.strerror}")
@@ -0,0 +1,61 @@
import contextlib
import hashlib
import io
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from transcript_archive import outcomes, write
from transcript_archive.location import project_archive
from project_key import project_key
from utc_stamp import utc
NOW = 1790000000
class Archive(unittest.TestCase):
def test_writes_afresh_a_copy_whose_outcomes_file_is_missing(self):
with tempfile.TemporaryDirectory() as root:
kept = pathlib.Path(root, "archive")
transcript = pathlib.Path(root, "t.jsonl")
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("working"), NOW))
(kept_outcomes,) = kept.glob("*/*.outcomes.md")
kept_outcomes.unlink()
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("Ctrl-C"), NOW))
self.assertEqual(kept_outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n")
class CopyFor(unittest.TestCase):
def test_skips_a_version_already_kept_beside_its_copy(self):
with tempfile.TemporaryDirectory() as temp:
copy = pathlib.Path(temp, "custom-title.json")
copy.write_bytes(b"first")
beside = write.copy_for(copy, b"second")
self.assertEqual(beside, copy.with_name(f"custom-title.json.{hashlib.sha256(b'second').hexdigest()}"))
beside.write_bytes(b"second")
self.assertIsNone(write.copy_for(copy, b"second"))
self.assertEqual(write.copy_for(copy, b"first, grown"), copy)
class Outcomes(unittest.TestCase):
def test_the_archive_stamps_what_it_reads_back(self):
self.assertRegex(f"{utc(NOW)} {outcomes.finished('merged')}", outcomes.FINISHED_AT)
class Location(unittest.TestCase):
def test_keys_a_project_by_its_path_under_code_or_else_under_the_root(self):
home = pathlib.Path("/h")
self.assertEqual(project_key("/h/code/log", home), "log")
self.assertEqual(project_key("/h/code", home), "h/code")
self.assertEqual(project_key("/srv/log", home), "srv/log")
self.assertEqual(project_archive("/h/code/log", home, {}), pathlib.Path("/h/.claude/loop-claude-transcripts/log"))
self.assertEqual(project_archive("/h/code/log", home, {"LOOP_CLAUDE_TRANSCRIPTS": "/a"}), pathlib.Path("/a/log"))
if __name__ == "__main__":
unittest.main()
@@ -1,38 +1,21 @@
import dataclasses
import hashlib
import os
import pathlib
import re
import sys
import time
from failure import Failure
from loop_claude.claude_code.transcript import first_timestamped_line
from claude_code.transcript import first_timestamped_line
from file_writes import make_private, replace_file
from loop_claude.paths import Paths
from loop_claude.claude_code.session import session_files
FINISHED = "Verdict: finished"
UNFINISHED = "Verdict: unfinished"
STAMP = "%Y-%m-%dT%H:%M:%SZ"
STAMPED = r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ"
FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE)
from claude_code.session import session_files
from utc_stamp import utc
@dataclasses.dataclass(frozen=True)
class FinishedChunk:
folder: str
finished: str
transcript: pathlib.Path
subagents: list[pathlib.Path]
def archive(project_key: str, path: str, task: str, outcome: str, at: float, paths: Paths) -> Failure | None:
def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, at: float) -> Failure | None:
try:
with open(path, "rb") as handle:
raw = handle.read()
# Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh.
folder = paths.transcript_archive / project_key / hashlib.sha256(first_timestamped_line(raw)).hexdigest()
folder = project_archive / hashlib.sha256(first_timestamped_line(raw)).hexdigest()
make_private(folder)
except OSError as failure:
return unarchived(failure.filename, failure.strerror)
@@ -101,21 +84,3 @@ def copy_for(copy: pathlib.Path, data: bytes) -> pathlib.Path | None:
return copy if data != kept else None
beside = copy.with_name(f"{copy.name}.{hashlib.sha256(data).hexdigest()}")
return None if beside.exists() else beside
def utc(at: float) -> str:
return time.strftime(STAMP, time.gmtime(at))
# One per chunk folder, its latest finished copy, in the order they finished.
def finished_chunks(project_archive: pathlib.Path) -> list[FinishedChunk] | Failure:
found = []
try:
for folder in sorted(path for path in project_archive.glob("*") if path.is_dir()):
copies = sorted((stamps[-1], outcomes) for outcomes in folder.glob("*.outcomes.md") if (stamps := FINISHED_AT.findall(outcomes.read_text(encoding="utf-8"))))
if copies:
finished, outcomes = copies[-1]
found.append(FinishedChunk(folder.name, finished, outcomes.with_name(outcomes.name.removesuffix(".outcomes.md") + ".jsonl"), sorted(folder.glob("session/*/subagents/*.jsonl"))))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the archive {project_archive}: {failure}")
return sorted(found, key=lambda chunk: (chunk.finished, chunk.folder))
+8
View File
@@ -0,0 +1,8 @@
import time
STAMP = "%Y-%m-%dT%H:%M:%SZ"
STAMPED = r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ"
def utc(at: float) -> str:
return time.strftime(STAMP, time.gmtime(at))
+908
View File
@@ -528,3 +528,911 @@ Junior A, decided by:
- `bin/larv_review/git.py:5` and `bin/metric_bench/main.py:38`: the git layer depends on the history type, and metric-bench on larv-review's package
- `bin/larv_review/main.py:1` the module docstring: one home, but a wall of rules leaning on terms defined elsewhere
- `bin/larv_review/rules.py:16` `votes`: a seat protocol reconstructed only from `skills/larv-review/SKILL.md:97`
## 2026-10-09T08:54:36Z, PR #232 at 2c6e063, against 12d6d75
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | same | same | better | better |
| Inherited architect | better | worse | same | better | better |
Mid A, decided by:
- `bin/larv_review/main.py:146` `round_count`: Navigation, better: the fourth-round symptom leads to a named unit, where the base had only `skills/larv-review/SKILL.md:58` "Count"
- `bin/larv_review/rules.py:42` `ruling`, `:52` `fallen` and `:128` `scoring_run_due`: Self-sufficiency, better: vote arithmetic and the scoring trigger are pure functions with docstrings, where the base had prose alone
- `README.md:68` "Tools": Navigation, better: the README names larv-review and metric-bench
- `bin/larv_review/main.py:1` the module docstring: Self-sufficiency, better, with a cost: Split, Fell, Ratchet and the moved Mean line arrive in long sentences
- `bin/larv_review/history.py:96` `heading`: Locality, against: two flags with DATED and HEADING, traced through `bin/larv_review/seats.py:38` `report` and `bin/larv_review/main.py:207` `record_scoring`
- `bin/larv_review/history.py:18` `SEAT_PLACES`, `:114` `ruling_entry` and `:125` `scoring_entry`: Locality, against: writers and parser must agree on label strings
- `bin/larv_review/rules.py:1` the module: Shape, against: one vague name over five concerns
- `bin/metric_bench/bench.py:87` `resolved` and `bin/metric_bench/main.py:38`: Shape and Locality, against: metric-bench depends on larv-review's history parser
Inherited architect, decided by:
- `bin/larv_review/main.py:146` `round_count`: Navigation: the 3am question lands on a function, where the base had `skills/larv-review/SKILL.md:58` "Count"
- `bin/larv_review/rules.py:89` `measured_commit` and `:105` `base`: Self-sufficiency: the ratchet's base is executable, where the base had `skills/larv-review/SKILL.md:100`
- `bin/larv_review/history.py:60` `entries`, `:114` `ruling_entry` and `:125` `scoring_entry`: Self-sufficiency and Navigation: the history's format is a regex plus writers, where the base had `skills/larv-review/SKILL.md:92`
- `bin/larv_review/main.py:207` `record_scoring`, with `bin/larv_review/seats.py:45` `report` and `bin/larv_review/history.py:96` `heading`: Locality: the moved Mean case threads through three modules
- `bin/larv_review/rules.py:57` `pending_fall`, called from `bin/larv_review/main.py:179` and `:224`: Locality: commands depend on state an earlier command appended to the history; `history[1]` hides it at the call site
- `bin/metric_bench/main.py:38` and `bin/metric_bench/bench.py:7`: Locality: metric-bench parses the history with larv-review's `entries`, and keeps its own `git()` at `bin/metric_bench/main.py:143`
- `bin/larv_review/rules.py:1` the module: Shape: a grab-bag name
- `bin/larv_review/git.py:56` `file_at` and `bin/larv_review/main.py:247` `history_text`: Locality: two histories, the default branch's and the checkout's
- `skills/larv-review/SKILL.md:97` "Seats": Self-sufficiency, against the skill: it needs the tool's help open beside it
- `bin/rank_todo.py:386` `parse_row`: Shape, a small gain
## 2026-10-09T09:35:29Z, PR #232 at 6a8bbcf, against 12d6d75
Ruling: same
Fell: Locality, Shape
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | worse | same | better | better |
| Inherited architect | better | worse | worse | same | worse |
| Maintainability senior | better | worse | worse | better | same |
| Junior A | better | worse | worse | better | worse |
Mid A, decided by:
- Navigation, Self-sufficiency, Overall: `bin/larv_review/rules.py:118` `round_counts`, with `bin/larv_review/main.py:155` `round_count`: the fourth-round symptom leads from the README's Tools list to a named, tested function, where the base had `skills/larv-review/SKILL.md:58` "Count"
- Self-sufficiency, Overall: `bin/larv_review/history.py:117` `ruling_entry` and `:130` `scoring_entry`: the history format is produced by code and checked by a regex, where the base had `skills/larv-review/SKILL.md:92` "History"
- Locality: `bin/larv_review/main.py:234` `record_scoring`: five conditionals on `given.moved_mean` weave a one-off migration into the main scoring path
- Locality: `bin/metric_bench/main.py:38` and `bin/larv_review/history.py:31` `Entry`: places are parsed in larv_review but used only by metric_bench; `bin/metric_bench/bench.py:87` `resolved` copes with old paths
- Locality: `bin/larv_review/main.py:1` the module docstring: rules compressed into one dense block; the fall, Ratchet and Still standing chain reaches across `bin/larv_review/rules.py:95` `fall_outcome`, `:76` `standing_ratchet` and `bin/larv_review/main.py:164` `needs_scoring_run`
- Navigation: `README.md:66` "Tools": lists larv-review and metric-bench; `skills/larv-review/SKILL.md:46` points at `--help`
- Shape: `bin/larv_review/rules.py:155` `plan_items` and `:169` `scoring_run_due`: a catch-all module, offset by the clean package split and the truthful `skills/comprehension-panel/seat-prompts.md:1` name
Inherited architect, decided by:
- Locality: `bin/larv_review/main.py:234` `record_scoring`: whether a run is allowed and whether the floor blocks depend on the plan diff, a pending fall read from the history, and `moved_mean`, checked five times in 25 lines
- Locality: `bin/larv_review/rules.py:71` `pending_fall` and `:76` `standing_ratchet`: commands talk only through the history file, so the outcome depends on the order they ran in
- Locality, Shape: `bin/larv_review/rules.py:127` `measured_commit`: re-parses the history around every merged change and applies a two-clause rule; where it rots first
- Shape: `bin/larv_review/rules.py:1` the module: vote counting, round counting, base search, plan parsing and release emptying under a name that says as little as utils; `HistoryChange` defined in history but built in `bin/larv_review/git.py:66` `history_changes`
- Shape: `bin/metric_bench/main.py:38`: a second tool no review runs, depending on larv_review's history parser; `bin/` gains two packages
- Shape: `bin/metric_bench/bench.py:87` `resolved`: a shim for old path formats
- Navigation: `bin/larv_review/rules.py:118` `round_counts` and `bin/larv_review/main.py:155` `round_count`: the 3am symptom lands on a named command, where the base had `skills/larv-review/SKILL.md:58` "Count"
- Navigation: `README.md:66` "Tools": lists every tool
- Navigation: `skills/comprehension-panel/seat-prompts.md:1`: a truthful name
- Self-sufficiency: `bin/larv_review/main.py:1` the module docstring and `skills/larv-review/SKILL.md:93` "Paired ruling": the code explains itself, but the skill's ratchet text needs the docstring open beside it; ruled same
Maintainability senior, decided by:
- Locality: `bin/larv_review/main.py:234` `record_scoring`: tests `given.moved_mean` five times, each branch tied to `chunk_history`, `due_reasons` and `pending_fall`
- Locality: `bin/larv_review/rules.py:71` `pending_fall`: its docstring holds only because `bin/larv_review/history.py:62` `entries` gives scoring runs an empty `fell`; the Fell, Ratchet and Still standing chain spans four files
- Locality, Shape: `bin/metric_bench/main.py:38` `main`: metric-bench imports larv_review's history internals; `bin/metric_bench/main.py:143` `git` repeats `bin/larv_review/git.py:10` `git`
- Shape: `bin/larv_review/rules.py:35` `counted`: a function and a parameter share the name; the module name says nothing of its contents
- Shape: `bin/larv_review/main.py:177` `due_reasons`: main holds commands plus I/O helpers, and the vocabulary grew to seven concepts
- Navigation: `README.md:66` "Tools": every tool listed with its `--help`
- Self-sufficiency, Navigation: `bin/larv_review/rules.py:118` `round_counts`: the round count, vote count and trigger state their rules in code, where the base had `skills/larv-review/SKILL.md:58` "Count"
- Self-sufficiency: `bin/larv_review/main.py:1` the module docstring: an 80-line block of every rule at once, partly cancelling the gain
Junior A, decided by:
- Locality, Overall: `bin/larv_review/main.py:234` `record_scoring`: the moved-Mean case is checked five times and decides four things
- Locality, Overall: `bin/larv_review/rules.py:76` `standing_ratchet` and `:71` `pending_fall`: a merge block depends on state earlier commands wrote into the history
- Locality, Shape: `bin/larv_review/rules.py:127` `measured_commit`: walks every merged change's history; restated at `bin/larv_review/main.py:11`, the hardest sentence in the repo
- Shape: `bin/larv_review/rules.py:1` the module: a grab-bag name beside truthfully named siblings
- Shape: `bin/larv_review/seats.py:31` `Report`: the field `read` looks like a verb; `said`, `counted`, `given` and `found` at `bin/larv_review/main.py:217` `record_ruling` need tracing
- Shape: `bin/metric_bench/main.py:38`: the history format is a contract between two tool packages
- Navigation, Self-sufficiency: `bin/larv_review/rules.py:118` `round_counts`: the 3am question lands on one named function, where the base had `skills/larv-review/SKILL.md:58` "Count"
- Navigation: `README.md:66` "Tools": the README lists larv-review and metric-bench
- Self-sufficiency: `bin/larv_review/history.py:62` `entries` and `:117` `ruling_entry`: the history format is enforced in code; the skill needs `--help` open beside it
## 2026-10-09T09:46:21Z, PR #232 at 324d650, against 12d6d75
Ruling: same
Fell: Locality
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | worse | worse | better | same |
| Inherited architect | better | worse | worse | better | better |
| Maintainability senior | better | worse | same | better | better |
| Junior A | better | worse | same | same | same |
Mid A, decided by:
- Navigation, Self-sufficiency: `bin/larv_review/rules.py:125` `round_counts`: the fourth-round symptom leads to a named function and `CAP`, where the base had prose at `skills/larv-review/SKILL.md:58` "Count"
- Navigation: `README.md:70` "Tools": names larv-review and metric-bench and the rules each holds
- Locality: `bin/larv_review/main.py:238` `record_scoring`: its result depends on which entry is newest in the history; the whole fall, scoring run, Ratchet, Still standing sequence must be held
- Locality: `bin/larv_review/rules.py:71` `pending_fall` and `:83` `standing_ratchet`: the verdict depends on entry order in a file no single function shows
- Locality, Shape: `bin/metric_bench/bench.py:7` and `bin/metric_bench/main.py:38`: metric-bench depends on larv-review's history parser and keeps its own `git` at `bin/metric_bench/main.py:143`
- Shape: `bin/larv_review/rules.py:16` `votes` through `:176` `scoring_run_due`: one module named rules holds four concepts
- Shape: `bin/larv_review/rules.py:35` `counted` and `bin/larv_review/history.py:68` `entries`: one name over two things
- Self-sufficiency: `bin/larv_review/seats.py:38` `report` and `bin/larv_review/history.py:99` `heading`: the seats file and history entry shapes are enforced in code
Inherited architect, decided by:
- Navigation, Self-sufficiency, Overall: `bin/larv_review/rules.py:125` `round_counts`, with `bin/larv_review/main.py:159` `round_count`: the 3am question leads to one tested function, where the base had `skills/larv-review/SKILL.md:58` "Count"
- Navigation, Overall: `README.md:70` "Tools": one hop from a symptom to a file
- Locality: `bin/larv_review/main.py:238` `record_scoring`: four helpers over four sources; why `fell` is empty here and not at `bin/larv_review/main.py:168` is stated nowhere at the call
- Locality: `bin/larv_review/rules.py:83` `standing_ratchet` with `bin/larv_review/history.py:12` `RATCHET`: state passes between commands through a markdown file's wording
- Locality, Shape: `bin/larv_review/rules.py:176` `scoring_run_due` and `:192` `emptied`: the due rule packs five conditions
- Shape: `bin/larv_review/rules.py:1` the module: one name over many concepts
- Shape: `bin/metric_bench/main.py:38` and `bin/metric_bench/bench.py:7`: the history format has no home of its own; `bin/larv_review/git.py:7` `HISTORY` sits in a module named for git
- Self-sufficiency: `bin/larv_review/main.py:1` the module docstring: dense, but it ships with the code and states every rule
Maintainability senior, decided by:
- Navigation, Self-sufficiency, Overall: `bin/larv_review/rules.py:125` `round_counts`, with `bin/larv_review/main.py:159` `round_count`: the rule is one small tested function, where the base had `skills/larv-review/SKILL.md:58` "Count"
- Navigation: `README.md:66` "Tools": lists both tools with a pointer to each `--help`
- Self-sufficiency: `bin/larv_review/rules.py:35` `counted`, `:50` `ruling` and `:60` `fallen`: each rule stated in a docstring and enforced beside it, where the base had `skills/larv-review/SKILL.md:100` "Ratchet"
- Locality: `bin/larv_review/main.py:238` `record_scoring`: `due_reasons` with an empty fall, then `pending_fall` separately; four places to hold
- Locality: `bin/larv_review/rules.py:71` `pending_fall` and `:83` `standing_ratchet`: order dependence between commands through a file
- Locality, Shape: `bin/larv_review/seats.py:38` `report`, `bin/larv_review/history.py:99` `heading` and `bin/larv_review/main.py:267` `record_moved_mean`: a one-time migration threaded through three modules
- Shape: `bin/metric_bench/main.py:38` and `bin/metric_bench/bench.py:7`: a second tool depends on the first one's parser; `Entry.places` at `bin/larv_review/history.py:40` exists only for it
- Shape: `bin/larv_review/rules.py:176` `scoring_run_due`: a grab-bag module, offset by the truer `skills/comprehension-panel/seat-prompts.md:1` name
- Self-sufficiency: `bin/larv_review/main.py:11` the `ruling-base` paragraph: took three reads, resolved only by `bin/larv_review/rules.py:134` `measured_commit`
Junior A, decided by:
- Navigation: `bin/larv_review/rules.py:125` `round_counts`: the symptom leads to the `round-count` command, where the base had `skills/larv-review/SKILL.md:58` "Count"
- Navigation: `README.md:68` "Tools": names both tools; `skills/larv-review/SKILL.md:46` points at the same tool
- Locality: `bin/larv_review/main.py:238` `record_scoring`: whether the run blocks, ratchets or fails depends on three outside sources
- Locality: `bin/larv_review/rules.py:134` `measured_commit`: the base depends on what each past merged change added, by heading time
- Locality: `bin/metric_bench/main.py:38` `entries, Entry`: a second tool parses the history through larv-review's internals
- Shape: `bin/larv_review/rules.py:176` `scoring_run_due`: a catch-all module, offset by the clean split and the truer `skills/comprehension-panel/seat-prompts.md:1`
- Self-sufficiency: `skills/larv-review/SKILL.md:98` "Ruling": the skill needs `bin/larv_review/main.py:1` open beside it, offset by rules now in code
## 2026-10-09T09:47:25Z, PR #232 at 324d650
Ratchet: the paired ruling counts as worse, as Locality fell and Locality is 6.50, under the floor of 7.0.
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 6 | 6.5 | 6 | 6.5 |
| Mid A | 7 | 7 | 6.5 | 6.5 | 7 |
| Maintainability senior | 7.5 | 6.5 | 7 | 7 | 7 |
| Inherited architect | 7 | 6.5 | 6.5 | 7 | 7 |
| Mean | 7.13 | 6.50 | 6.63 | 6.63 | 6.88 |
Junior A, hardest first:
- `bin/larv_review/main.py:238` `record_scoring`: `due_reasons` with an empty fall means "reasons besides a fall", stated only at `bin/larv_review/rules.py:93` `floor_verdict`
- `bin/larv_review/main.py:1` the module docstring: 80 lines of interlocking rules that never say why
- `bin/larv_review/rules.py:134` `measured_commit`: `not (last and last.fell)` is true with no ruling at all
- `bin/larv_review/rules.py:16` `votes`, with `:35` `counted` and `:40` `names_a_place`: the counting rule spans three files
- `bin/larv_review/history.py:62` `entries` and `:75` `seat_places`: the parser and writer share a format by eye
- `bin/loop_claude/cycle/judge.py:31` `run_judge`: five outcomes, the spec a prompt string
- `bin/loop_claude/transcript_archive.py:30` `archive`: reading-cost parses its outcome text
- `bin/metric_bench/bench.py:87` `resolved`: order-dependent legacy shim
Mid A, hardest first:
- `bin/larv_review/main.py:238` `record_scoring`: six exits; `due_reasons` with an empty fall list on purpose
- `bin/larv_review/rules.py:134` `measured_commit`: states what, never why
- `bin/larv_review/rules.py:176` `scoring_run_due`: five inputs in one dense sentence
- `bin/loop_claude/cycle/judge.py:31` `run_judge`: two text checks against two texts
- `bin/loop_claude/transcript_archive.py:30` `archive`: a prose format that is a contract with another tool
- `bin/loop_claude/cycle/states.py:69` `transition`: case order decides behaviour
- `bin/larv_review/rules.py:16` `votes`: parse also enforces the ruling protocol; `counted` shadowed
- `bin/loop_claude/claude_code/entries.py:45` `string_by_human`: heuristics on who wrote an entry
Maintainability senior, hardest first:
- `bin/larv_review/main.py:238` `record_scoring`: ten lines, six ideas; `due_reasons`'s third argument means different things to its two callers
- `bin/larv_review/rules.py:134` `measured_commit`: the no-ruling case deduced only from the help
- `bin/larv_review/rules.py:176` `scoring_run_due`: a 70-word docstring and a second document open
- `bin/larv_review/rules.py:16` `votes`: Overall's rule hidden in `DIMENSIONS[-1]`; `None` means split
- `bin/larv_review/history.py:62` `entries`: eight positional arguments counted against a regex
- `bin/larv_review/history.py:99` `heading`: a one-off migration threaded through three files
- `bin/metric_bench/bench.py:87` `resolved`: depends on earlier bullets' order
- `bin/loop_claude/cycle/states.py:69` `transition`: case order, resolved by comments
Inherited architect, would restructure first:
- `bin/loop_claude/transcript_archive.py:111` `finished_chunks`, `bin/reading_cost/archive.py:10` `project_archive` and `bin/loop_claude/claude_code/entries.py:5` `parse_entry`: lift the shared formats out of loop_claude
- `bin/larv_review/rules.py:125` `round_counts` and `:176` `scoring_run_due`: split rules into rounds, ruling, base and scoring
- `bin/loop_claude/cycle/judge_reply.py:12` `JUDGE_RULES` and `bin/loop_claude/cycle/worker.py:41` `worker_args`: give the prompt text one home
- `bin/failure.py:5` `Failure`, `bin/file_writes.py:21` `replace_file` and `bin/markdown_sections.py:6` `sections`: tidy the bin root
- `bin/larv_review/git.py:10` `git`, `bin/metric_bench/main.py:143` `git` and `bin/reading_cost/main.py:113` `located`: one git runner
- `bin/loop_claude/project/checkout.py:32` `read_utf8`: a generic reader under a lying name
- `bin/larv_review/main.py:101` `main`: an if/elif dispatch where the next command lands
## 2026-10-09T12:31:47Z, PR #234 at b1913ed, against 2157f59
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | better | same | better | better |
| Inherited architect | better | better | better | better | better |
Mid A, decided by:
- Locality, Navigation: `bin/transcript_archive/outcomes.py:4` `FINISHED_AT` and `finished`: one module now writes and parses the outcome lines, which `bin/loop_claude/cycle/run.py:83` built inline and another file parsed
- Locality, Navigation: `bin/reading_cost/main.py:35` imports: reading-cost depends only on the shared `transcript_archive`, no longer on loop-claude's internals
- Locality: `bin/loop_claude/paths.py:15` `paths_from`: no longer reads the environment; `LOOP_CLAUDE_TRANSCRIPTS` has one home in `bin/transcript_archive/location.py:5` `project_archive`
- Navigation, Self-sufficiency: `README.md:77` "Tools": states the import root, the shared packages and where tests live
- Self-sufficiency: `bin/transcript_archive/write.py:13` `archive`: states the archive's layout at the write
- Shape: `bin/loop_claude/loop/main.py:86` `run_loop`: imports `project_key`, which names the session and the models entry, from the archive package; `bin/loop_claude/cycle/worker.py:7` takes `quoted` from the archive's outcomes
- Shape: `bin/loop_claude/cycle/judge.py:15` `JUDGE_RULES`: judge_reply merged in, 183 lines
Inherited architect, decided by:
- Navigation, Shape: `bin/reading_cost/main.py:35` `main`: imports one shared package named for what it holds, in place of loop-claude's private packages
- Locality, Self-sufficiency: `bin/transcript_archive/outcomes.py:10` `finished`: the outcome texts sit beside `FINISHED_AT`, the regex that reads them back
- Shape: `bin/claude_code/session.py:21` `session_named`: the Claude Code package depends on nothing in loop-claude
- Locality: `bin/loop_claude/cycle/judge.py:15` `JUDGE_RULES` and `:93` `verdict_from`: in one file with `run_judge`
- Locality: `bin/loop_claude/cycle/states.py:75` `transition`: the cap no longer depends on case order
- Navigation, Self-sufficiency: `README.md:77` "Tools": states the layout and puts each test beside its package
- Self-sufficiency: `bin/loop_claude/cycle/run.py:34` `Cycle.unfinished_evidence`: the name says what `remaining` needed a comment for
- Shape: `bin/loop_claude/loop/main.py:86` `run_loop`, `bin/loop_claude/cycle/worker.py:7` `worker_args` and `bin/host_env.py:5` `host_env`: small seams against the decoupling
## 2026-10-09T12:32:00Z, PR #234 at b1913ed
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 6 | 6.5 | 6 | 6.5 |
| Mid A | 7 | 6 | 6.5 | 6 | 6.5 |
| Maintainability senior | 7 | 6.5 | 7 | 6.5 | 7 |
| Inherited architect | 7 | 6.5 | 6 | 6.5 | 6.5 |
| Mean | 7.00 | 6.25 | 6.50 | 6.25 | 6.63 |
Junior A, hardest first:
- `skills/larv-review/SKILL.md:55` "Round cap": the counting rule spread across Round cap, Re-entry, Fresh and Suspended
- `bin/larv_review/main.py:197` `record_ruling`: split, fell, refuse and stand branches; `ruling` returns None for a split and `fallen` reuses it
- `bin/larv_review/scoring.py:54` `scoring_run_due`: why the next-release fallback holds is stated nowhere
- `bin/larv_review/base.py:14` `measured_commit`: mechanics without purpose
- `bin/loop_claude/cycle/judge.py:126` `run_judge`: the prompt assembled from `records.py` constants; two texts, two matchers
- `bin/reading_cost/measure.py:21` `Checkout`: `root` and `top` read as synonyms
Mid A, hardest first:
- `bin/larv_review/main.py:197` `record_ruling`: said and counted, None as split, three fall steps
- `bin/comprehension_history.py:74` `entries`: the history format is defined only by its writer
- `bin/loop_claude/cycle/judge.py:126` `run_judge`: elided evidence fails, a misquoted answer becomes an interrupt
- `bin/larv_review/scoring.py:54` `scoring_run_due`: one dense sentence over two plans; the module also parses the plan
- `bin/larv_review/base.py:14` `measured_commit`: the why lives in the help and the skill
- `bin/loop_claude/cycle/states.py:69` `transition`: `quoted_answers` threaded through three states and two files
Maintainability senior, hardest first:
- `bin/larv_review/main.py:197` `record_ruling`: said and count, ruled reassigned, a silent fall-through; `ruling`'s None means two things
- `bin/larv_review/base.py:14` `measured_commit`: a three-step fallback across three files, ordered by an ISO string unsaid
- `bin/comprehension_history.py:74` `entries`: the format is never stated in one place
- `bin/loop_claude/cycle/judge.py:15` `JUDGE_RULES`: the prompt interpolates four constants from another module
- `bin/larv_review/scoring.py:54` `scoring_run_due`: five inputs; `scoring` also parses the plan
- `bin/rank_todo.py:416` `rank_details`: regex surgery in a script larv-review imports as a library
Inherited architect, would restructure first:
- `bin/loop_claude/project/records.py:6` `QUOTE_SOURCES`: prompt fragments spliced into the judge, worker and interrupt texts
- `bin/transcript_archive/location.py:10` `project_key`: the project's identity filed under the archive
- `bin/host_env.py:5` `host_env`: a test helper among the production modules
- `bin/larv_review/rounds.py:8` `round_counts`: only counts; the cap lives in the skill
- `bin/larv_review/base.py:1` the module: the ruling base, named like a base class
- `bin/larv_review/scoring.py:6` imports: one tool imports another tool's internals from `bin/rank_todo.py`
- `bin/loop_claude/loop/main.py:1` the docstring: restates constants it cannot keep true
## 2026-10-09T12:46:51Z, PR #234 at dde06fc, against 2157f59
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | better | better | better | better |
| Inherited architect | better | better | better | better | better |
Mid A, decided by:
- Navigation, Locality, Shape: `bin/transcript_archive/location.py:7` `project_archive`: the archive's location lives in one shared package, where reading-cost reached into loop-claude's internals
- Locality, Shape, Self-sufficiency: `bin/loop_claude/cycle/run.py:83` `worker_start`: `worker_args` builds only flags and each prompt is a named function in `bin/loop_claude/cycle/prompts.py:41`
- Locality, Self-sufficiency: `bin/transcript_archive/outcomes.py:10` `finished`: the outcomes format's writer and reader sit in one file
- Shape: `bin/larv_review/ruling.py:42` `split`: `ruling` no longer returns None for a split
- Shape, Locality: `bin/larv_review/main.py:204` `record_ruling`: two plain checks in place of `fall_step`'s strings; plan logic in `bin/larv_review/plan.py:5`
- Navigation: `README.md:77` "Tools": states the import root and the shared packages
- Self-sufficiency: `bin/comprehension_history.py:74` `entries`: a worked example of an entry above the parser
- Self-sufficiency, Shape: `bin/metric_bench/bench.py:88` `tracked_places`: the rename garbled the docstring
- Locality: `bin/loop_claude/cycle/prompts.py:60` `quoted`: duplicates `bin/transcript_archive/outcomes.py:31` `quoted`
Inherited architect, decided by:
- Navigation, Locality: `bin/transcript_archive/outcomes.py:10` `finished`: every outcome line and `FINISHED_AT` sit in one module
- Navigation, Locality: `bin/reading_cost/main.py:35` imports: reading-cost no longer reaches into loop-claude's internals
- Navigation, Self-sufficiency: `README.md:77` "Tools": the layout is stated
- Shape, Locality: `bin/todo_table.py:27` `items`: the table format is its own module, not a CLI script used as a library
- Shape: `bin/larv_review/plan.py:5` `scoring_run_due`: the plan trigger with its why, apart from the floor arithmetic
- Locality, Shape: `bin/larv_review/ruling.py:42` `split`: split, ruling and lead are separate
- Locality, Shape: `bin/loop_claude/cycle/prompts.py:41` `fresh`: every prompt text in one module
- Shape: `bin/comprehension_history.py:67` `ScoringRun`: one name no longer covers two concepts
- Self-sufficiency: `bin/larv_review/main.py:5` the help: defines the ratchet, the paired ruling and the scoring run first
- Locality: `bin/loop_claude/cycle/states.py:75` `transition`: the past-the-cap case has its own guard
- Shape: `bin/metric_bench/bench.py:87` `tracked_places`: the docstring reads worse after the rename
## 2026-10-09T12:46:51Z, PR #234 at dde06fc
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 6.5 | 6 | 6 | 6 |
| Mid A | 7.5 | 6.5 | 7 | 6.5 | 7 |
| Maintainability senior | 7 | 6.5 | 7 | 7 | 7 |
| Inherited architect | 7 | 6.5 | 6.5 | 7 | 7 |
| Mean | 7.13 | 6.50 | 6.63 | 6.63 | 6.75 |
Junior A, hardest first:
- `bin/larv_review/main.py:204` `record_ruling`: six outcomes, said against count, `[-1]` meaning Overall
- `bin/larv_review/ruling.py:8` `votes`: a parser that also enforces the seat-count rule
- `bin/larv_review/ruling_base.py:14` `measured_commit`: the docstring explains only after the code confused
- `bin/larv_review/plan.py:5` `scoring_run_due`: four ideas at once; `emptied` traced by hand
- `bin/metric_bench/bench.py:87` `tracked_places`: a garbled docstring
- `bin/loop_claude/cycle/states.py:69` `transition`: the quoted-answer cap across three files
Mid A, hardest first:
- `skills/larv-review/SKILL.md:55` "Round cap": four subsections pointing at each other
- `bin/larv_review/main.py:204` `record_ruling`: five outcomes; the duplicate check in two places
- `bin/loop_claude/cycle/judge.py:95` `run_judge`: many endings, two quote checks
- `bin/loop_claude/cycle/states.py:69` `transition`: the cap counter rides through three states
- `bin/larv_review/ruling_base.py:14` `measured_commit`: needs the history format and first-parent semantics
- `bin/reading_cost/measure.py:27` `measure`: string-compared timestamps and approximate shell parsing
Maintainability senior, hardest first:
- `bin/larv_review/main.py:204` `record_ruling`: five outcomes, competing local names
- `skills/larv-review/SKILL.md:55` "Round cap": a chain of cross-references
- `bin/comprehension_history.py:103` `seat_places`: depends unsaid on `sections` dropping blank lines
- `bin/larv_review/plan.py:5` `scoring_run_due`: four inputs; the rule restated in the help
- `bin/larv_review/ruling_base.py:14` `measured_commit`: why same is safe needs the skill
- `bin/metric_bench/bench.py:87` `tracked_places`: a garbled docstring
Inherited architect, would restructure first:
- `bin/larv_review/rounds.py:12` `round_counts`: the round cap lives in prose; a mis-cased title escapes the count
- `bin/loop_claude/cycle/judge.py:17` `Reply`: the judge contract spread over four files
- `bin/loop_claude/project/checkout.py:28` `read_utf8`: a generic reader under the checkout's name
- `bin/test_env.py:5` `isolated_env`: test support named like a test
- `bin/larv_review/git.py:6` imports: the git adapter depends on a domain type
- `bin/loop_claude/cycle/prompts.py:60` `quoted`: two copies, with `STAMP` and the git runner also duplicated
## 2026-10-09T12:53:41Z, PR #234 at b346a35, against 2157f59
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | better | better | better | better |
| Inherited architect | better | better | better | better | better |
Mid A, decided by:
- Navigation, Locality: `bin/reading_cost/main.py:35` `main`: the archive reader and location come from a shared package, not loop-claude's internals
- Locality, Shape: `bin/loop_claude/cycle/run.py:83` `worker_start`: picks one of three named prompts for a four-argument `worker_args`
- Navigation, Shape: `bin/loop_claude/cycle/prompts.py:1` the module: the texts the worker and the human see sit together
- Locality, Shape: `bin/larv_review/main.py:204` `record_ruling`: plain checks with `split`, `lead` and `overall`
- Navigation, Shape: `bin/larv_review/ruling_base.py:4` `measured_commit`: a truthful module name; `HistoryChange` beside the format
- Navigation, Locality: `bin/todo_table.py:27` `items`: the table parser is shared, not reached into a CLI script
- Navigation, Self-sufficiency: `README.md:77` "Tools": states the layout
- Self-sufficiency: `bin/comprehension_history.py:82` `entries`: a worked example above the parser
- Shape: `bin/reading_cost/measure.py:20` `Checkout`: fields say which root keys the archive
- Locality: `bin/loop_claude/cycle/states.py:75` `transition`: the past-the-cap case has its own guard
Inherited architect, decided by:
- Locality, Shape: `bin/transcript_archive/location.py:7` `project_archive`: both tools import one shared package
- Navigation, Locality: `bin/transcript_archive/outcomes.py:10` `finished`: the outcome line sits beside the regex that reads it back
- Locality, Shape: `bin/loop_claude/cycle/run.py:83` `worker_start`: `worker_args` takes the finished prompt
- Shape: `bin/larv_review/git.py:5` imports: the git helper no longer depends on the base search
- Shape, Self-sufficiency: `bin/larv_review/plan.py:5` `scoring_run_due`: its own module, saying why each trigger exists
- Self-sufficiency, Locality: `bin/larv_review/ruling.py:27` `overall` and `:47` `split`: no None meaning split, no bare index
- Navigation: `bin/reading_cost/measure.py:20` `Checkout`: the fields name which root
- Self-sufficiency: `bin/comprehension_history.py:82` `entries`: a worked example
- Navigation: `README.md:77` "Tools": the import root and the tests' place
- Shape: `bin/larv_review/main.py:234` `recorded_ruling`: eight positional parameters, a step back
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:29` `quoted`: a second copy
## 2026-10-09T12:53:41Z, PR #234 at b346a35
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 6 | 7 | 6 | 6.5 |
| Mid A | 7.5 | 7 | 7 | 6.5 | 7 |
| Maintainability senior | 7.5 | 7 | 7 | 7 | 7 |
| Inherited architect | 7.5 | 7 | 6.5 | 7 | 7 |
| Mean | 7.38 | 6.75 | 6.88 | 6.63 | 6.88 |
Junior A, hardest first:
- `skills/larv-review/SKILL.md:55` "Round cap": rules pointing at each other; Fresh mixes five things
- `bin/larv_review/main.py:204` `record_ruling`: five exits; the counting rule in `bin/larv_review/ruling.py:32` `counted`
- `bin/larv_review/ruling_base.py:4` `measured_commit`: a set difference of headings per change
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: a prompt built from constants in three files; two quote checks
- `bin/comprehension_history.py:95` `entries`: two label regexes tied to the writer's wording
- `bin/reading_cost/shell_reads.py:52` `segments`: heuristic shell parsing
Mid A, hardest first:
- `bin/larv_review/main.py:204` `record_ruling`: five branches across four modules
- `bin/larv_review/ruling_base.py:4` `measured_commit`: reread three times to trust it
- `bin/loop_claude/cycle/judge.py:127` `run_judge`: two quote checks with opposite policies
- `bin/loop_claude/cycle/states.py:69` `transition`: the quoted-answer counter through three states
- `bin/comprehension_history.py:95` `entries`: Markdown parsed back into records
- `bin/metric_bench/bench.py:87` `tracked_places`: order-dependent legacy resolution
Maintainability senior, hardest first:
- `bin/larv_review/main.py:204` `record_ruling`: six exits; `fresh=False` hides a skipped check
- `bin/larv_review/ruling_base.py:4` `measured_commit`: why needs the skill
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: assembled across three files
- `bin/comprehension_history.py:95` `entries`: the format defined by example and regexes
- `bin/loop_claude/cycle/states.py:69` `transition`: the counter survives an interrupt
- `bin/reading_cost/shell_reads.py:52` `segments`: opaque on what it misses
Inherited architect, would restructure first:
- `bin/larv_review/rounds.py:8` `round_counts`: the cap lives in prose; the tool only reports
- `bin/larv_review/main.py:204` `record_ruling`: the record commands in a 326-line main
- `bin/larv_review/git.py:8` `git`: four git wrappers, one archive key computed two ways
- `bin/loop_claude/cycle/prompts.py:29` `quoted`: duplicated, as is `STAMP`
- `bin/larv_review/ruling_base.py:24` `base`: a name that reads as a base class
## 2026-10-09T13:04:47Z, PR #234 at b2a277b, against 2157f59
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | better | better | better | better |
| Inherited architect | better | better | better | better | better |
Mid A, decided by:
- Locality, Navigation: `bin/transcript_archive/location.py:7` `project_archive`: the archive's writer and readers share one package; outcome strings sit beside the regex that reads them
- Locality, Shape: `bin/loop_claude/cycle/run.py:83` `worker_start`: picks the prompt in three lines; `worker_args` only builds argv
- Shape, Navigation: `bin/larv_review/main.py:100` `main`: only dispatch; recording and plan reading have their own modules
- Locality, Navigation: `bin/todo_table.py:27` `items`: table parsing shared, not reached into a tool script
- Shape: `bin/larv_review/ruling.py:47` `split`: split, lead and overall each say what they compute
- Shape, Self-sufficiency: `bin/reading_cost/measure.py:20` `Checkout`: fields name which root
- Locality: `bin/claude_code/session.py:21` `session_named`: the adapter takes only a name and a folder
- Navigation: `README.md:77` "Tools": names the import root and where tests live
- Self-sufficiency: `bin/larv_review/main.py:5` the help: explains the ruling, ratchet, scoring run and floor first
Inherited architect, decided by:
- Locality, Navigation: `bin/transcript_archive/location.py:7` `project_archive`: location, writer and reader are peers both tools import
- Locality: `bin/transcript_archive/outcomes.py:6` `FINISHED`: the format and its parser in one module
- Shape, Navigation: `bin/larv_review/plan.py:8` `scoring_run_due`: the plan trigger has its own file; `scoring.py` holds only the floor
- Shape: `bin/larv_review/record.py:14` `record_ruling`: recording is one module, its guards inline
- Locality, Self-sufficiency: `bin/loop_claude/cycle/worker.py:40` `worker_args`: takes a ready prompt; the texts are named functions
- Shape: `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: the judge is one file
- Locality: `bin/loop_claude/paths.py:15` `paths_from`: the env override is read in one place
- Self-sufficiency: `bin/comprehension_history.py:81` `entries`: a worked example above the parser
- Navigation, Self-sufficiency: `README.md:77` "Tools": the layout is stated and checked
- Locality: `bin/larv_review/ruling.py:52` `ruling`: returns same for a split, so only `split` guards it
## 2026-10-09T13:04:48Z, PR #234 at b2a277b
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 6 | 7 | 6 | 6.5 |
| Mid A | 7.5 | 6.5 | 7 | 6.5 | 6.5 |
| Maintainability senior | 7.5 | 6.5 | 7 | 6.5 | 7 |
| Inherited architect | 7.5 | 7 | 6.5 | 7 | 7 |
| Mean | 7.38 | 6.50 | 6.88 | 6.50 | 6.75 |
Junior A, hardest first:
- `bin/larv_review/record.py:14` `record_ruling`: seven exits; the terms only in the help and the skill
- `bin/larv_review/ruling_base.py:4` `measured_commit`: diffs heading sets per change
- `bin/comprehension_history.py:94` `entries`: regex groups used by position
- `bin/larv_review/ruling.py:32` `counted`: the counting rule stated in the help, not here
- `bin/loop_claude/cycle/states.py:69` `transition`: the cap counter across three files
- `bin/loop_claude/cycle/judge.py:127` `run_judge`: two quote checks with different rules
Mid A, hardest first:
- `skills/larv-review/SKILL.md:82` "Architecture": conditions with exceptions; Fresh took three rereads
- `bin/larv_review/record.py:14` `record_ruling`: six outcomes across five modules
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: one sentence takes three files
- `bin/larv_review/ruling_base.py:4` `measured_commit`: the fallback chain over two files
- `bin/larv_review/plan.py:8` `scoring_run_due`: release sets held at once
- `bin/comprehension_history.py:94` `entries`: the format pinned in three places
Maintainability senior, hardest first:
- `bin/larv_review/record.py:14` `record_ruling`: five exits; the rule spread over five modules
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: instructions stitched from three modules
- `bin/larv_review/plan.py:8` `scoring_run_due`: five inputs; the docstring restates the help
- `bin/larv_review/ruling_base.py:4` `measured_commit`: opaque without its docstring
- `bin/larv_review/seats.py:17` `SeatsFile`: `read` is a noun; locals rename one pair two ways
- `bin/comprehension_history.py:110` `seat_places`: a line-state parser two tools depend on
Inherited architect, would restructure first:
- `bin/larv_review/rounds.py:4` `PASSES`: the cap is the skill's; the pass list has two homes
- `bin/comprehension_history.py:149` `ruling_entry`: reader, writer and seat registry in one root module
- `bin/larv_review/record.py:67` `read_fall_scores`: a parameter named votes holds a heading
- `bin/larv_review/git.py:8` `git`: four ways to run git; the archive key's root differs between tools
- `bin/larv_review/record.py:14` `record_ruling`: branches on worse, fell, scores file and split at once
## 2026-10-09T13:23:40Z, PR #234 at 7e13778, against 2157f59
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | better | better | better | better |
| Inherited architect | better | better | better | better | better |
Mid A, decided by:
- Navigation, Shape: `bin/larv_review/record.py:14` `record_ruling`: recording, dispatch and plan reading each in a file named for it
- Shape, Navigation: `bin/larv_review/plan.py:8` `scoring_run_due`: file names tell the truth; todo parsing in `bin/todo_table.py:27` `items`
- Navigation, Shape: `bin/transcript_archive/location.py:7` `project_archive`: both tools share top-level packages, not another tool's internals
- Locality: `bin/loop_claude/cycle/run.py:83` `worker_start`: a prompt changes without reading the argument plumbing
- Locality: `bin/loop_claude/cycle/states.py:75` `transition`: the past-the-cap case has its own guard
- Locality: `bin/transcript_archive/location.py:7` `project_archive`: the env override resolved in one place
- Self-sufficiency: `bin/larv_review/main.py:1` the help: defines seats, the ruling, the ratchet and the floor first
- Shape, Self-sufficiency: `bin/reading_cost/measure.py:20` `Checkout`: fields say which root keys the archive
Inherited architect, decided by:
- Locality, Navigation: `bin/transcript_archive/outcomes.py:6` `FINISHED`: outcome lines written and parsed in one file
- Locality, Shape: `bin/transcript_archive/location.py:7` `project_archive`: reading-cost no longer reaches into loop-claude
- Navigation, Locality: `bin/loop_claude/cycle/judge.py:94` `verdict_from`: the 3am question lands in one file
- Shape, Navigation: `bin/larv_review/main.py:102` `main`: dispatch only
- Locality, Shape: `bin/todo_table.py:27` `items`: larv-review imports no tool's internals
- Locality: `bin/larv_review/record.py:32` `record_ruling`: the fall handling reads in place
- Locality, Shape: `bin/loop_claude/cycle/run.py:83` `worker_start`: the start chosen at the call site
- Shape: `bin/reading_cost/measure.py:20` `Checkout`: names that say which root
- Self-sufficiency: `bin/comprehension_history.py:81` `entries`: a sample entry above the parser
- Locality: `bin/loop_claude/cycle/states.py:75` `transition`: no case-order dependence
## 2026-10-09T13:23:40Z, PR #234 at 7e13778
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7.5 | 7 | 7 | 6.5 | 7 |
| Mid A | 7 | 6.5 | 7 | 6.5 | 6.5 |
| Maintainability senior | 7 | 6.5 | 7 | 6 | 6.5 |
| Inherited architect | 7 | 6.5 | 6 | 7 | 6.5 |
| Mean | 7.13 | 6.63 | 6.75 | 6.50 | 6.63 |
Junior A, hardest first:
- `bin/larv_review/record.py:14` `record_ruling`: four outcomes, two parallel vote dicts
- `bin/larv_review/ruling.py:32` `counted`: an asymmetric rule; `PLACE` in another file
- `bin/metric_bench/python_units.py:86` `score`: needs a paper outside the repo
- `bin/comprehension_history.py:94` `entries`: leans on `sections` dropping blank lines
- `bin/loop_claude/cycle/judge.py:127` `run_judge`: two quote checks against two texts
- `skills/larv-review/SKILL.md:55` "Round cap": sections pointing at each other
Mid A, hardest first:
- `bin/larv_review/record.py:14` `record_ruling`: five outcomes; `read` as a noun
- `bin/comprehension_history.py:110` `seat_places`: depends unsaid on `sections` dropping blank lines
- `bin/larv_review/ruling_base.py:4` `measured_commit`: several ideas held at once
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: decision logic in English
- `bin/claude_code/entries.py:28` `written_by_human`: heuristics over the transcript shape
- `bin/loop_claude/loop/reload.py:50` `exec_if_edited`: any tool's edit reloads the loop
Maintainability senior, hardest first:
- `skills/larv-review/SKILL.md:82` "Architecture": six interlocking conditions
- `bin/larv_review/record.py:14` `record_ruling`: two checks run twice; the rule whole only in the help
- `bin/comprehension_history.py:94` `entries`: a format shared by three tools by string convention
- `bin/larv_review/plan.py:8` `scoring_run_due`: three things combined in "work has landed"
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: behaviour in prose, post-filtered three ways
- `bin/rank_todo.py:357` `rank_details`: rebuilds the file by slicing
Inherited architect, would restructure first:
- `bin/larv_review/rounds.py:8` `round_counts`: the cap is prose in the skill
- `bin/larv_review/record.py:14` `record_ruling`: an if-chain with prints interleaved
- `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
## 2026-10-12T22:43:27Z, PR #242 at 63b0759, against 4cc9953
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | same | better | better | better |
| Inherited architect | better | same | same | same | better |
Mid A, decided by:
- Shape, Navigation: `bin/shell_command.py:20` `simple_commands`: splitting a shell command and tracking each `cd` is one module named for what it holds, where `shell_reads.py` spread it over three helpers
- Shape: `bin/reading_cost/measure.py:7` `measure` imports: `resolved` comes from `shell_command`, no longer from a module named for shell reads
- Self-sufficiency, Navigation: `bin/rule_hook/main.py:1` module docstring: each rule's `holds` and `checked` build `--help`, so a blocked commit leads to one authority
- Navigation: `CLAUDE.md:50` "Topic rules": each topic's rules have their own file and the section says which loads with what, where the old charter was one 167-line wall
- Shape: `bin/rule_hook/rules.py:108` `git_subcommand`: git argument parsing sits in `rules`, while `git.py` only runs git
- Locality: `bin/loop_claude/project/records.py:14` `read_records`: the rules folder is spelled twice, as `HUMAN_RULES_DIR` and as `claude_md.parent / "rules"`
- Shape: `bin/rule_hook/todo_check.py:7` `import rank_todo`: one tool imports another tool's script, though the README states it
Inherited architect, decided by:
- Navigation, Overall: `CLAUDE.md:50` "Topic rules": each topic has a file named for it and scoped by `paths:`, indexed in four lines, so a rule is one step from its question
- Navigation: `bin/shell_command.py:20` `simple_commands`: command splitting has one obvious home, used by the hook and by reading-cost
- Locality: `bin/shell_command.py:31` `segments`: the shared parser means a change for the hook moves reading-cost's figures, and nothing at `reading_cost/` says so
- Shape: `bin/rule_hook/rules.py:108` `git_subcommand`: a module named `rules` parses git's command line, and `Breach.directory` carries the override log's concern
- Shape, Locality: `bin/rule_hook/override_log.py:96` `print_overrides`: a chained ternary of four outcomes beside `this_chunks`, whose reflog rule needs both comments held at once
- Locality: `bin/rule_hook/main.py:82` `answer`: resolve-before-write holds only by the loops' arrangement, stated in one comment
- Self-sufficiency: `bin/rule_hook/main.py:1` module docstring: the rules print from `RULES`, while `CLAUDE.md:67` now sends a charter reader to `rules.py` for the pinning rule
- Locality: `bin/rule_hook/todo_check.py:10` `todo_breaches`: a change to `rank_todo`'s output reaches a hook that can block every commit
## 2026-10-12T22:56:19Z, PR #242 at f351e14, against 4cc9953
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | same | worse | same | same |
| Inherited architect | same | same | same | same | same |
Mid A, decided by:
- Shape: `bin/rule_hook/rules.py:99` `commits`: a file named for the rule table parses git's command line, while `git.py` only runs git
- Shape: `bin/rule_hook/override_log.py:82` `logged`: builds an Entry and logs nothing; `holds` is an is-ancestor test and `this_chunks` needs two comments
- Shape: `bin/shell_command.py:20` `simple_commands`: shell lexing moved out of `shell_reads.py`, which now holds only what counts as a read
Inherited architect, decided by:
- Locality, Shape: `bin/shell_command.py:20` `simple_commands`: one shared lexer, though a fix for the hook shifts reading-cost's figures unseen
- Locality, Shape: `bin/rule_hook/rules.py:108` `git_subcommand`: a second definition of a commit beside `measure.py`'s `COMMIT` regex, in a module that also holds the rule table and verdict
- Locality: `bin/rule_hook/override_log.py:86` `print_overrides`: a four-way chained conditional beside `this_chunks`' reflog rule
- Locality: `skills/larv-review/SKILL.md:56` "Opt-out": a third skip mechanism to cross-check beside "Precedent, then ask" and "Suspended"
- Navigation, Self-sufficiency: `bin/rule_hook/main.py:46` `main`: a blocked call leads cold to the rule, its text and the override syntax
- Self-sufficiency, Navigation: `CLAUDE.md:50` "Topic rules": each topic's rules are found by file name, while `CLAUDE.md:67` sends a reader to `rules.py` for the pinning rule's full text
## 2026-10-12T23:45:13Z, PR #245 at b568522, against 4cc9953
Ruling: worse
Fell: Navigation, Locality. Under the floor of 7.0: Locality 6.88, so the same ruling counts as worse.
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | worse | same | same | same |
| Inherited architect | worse | worse | same | same | worse |
| Maintainability senior | worse | worse | same | same | worse |
| Junior A | worse | same | same | same | same |
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 6.5 | 6.5 | 6.5 | 6.5 |
| Mid A | 7.5 | 7 | 7 | 6.5 | 7 |
| Maintainability senior | 7.5 | 7 | 7 | 7 | 7 |
| Inherited architect | 7.5 | 7 | 6.5 | 7 | 7 |
| Mean | 7.38 | 6.88 | 6.75 | 6.75 | 6.88 |
Mid A, decided by:
- Locality: `agents/prose-reviewer.md:9` "The bar": the prose bar now combines CLAUDE.md → "Prose", the standards files and path-matched rules/ files, and `prose.md` splits one concept across two files
- Locality: `bin/loop_claude/project/records.py:11` `HUMAN_RULE_NAMES`: what the judge reads depends on the files in two folders, and `QUOTE_SOURCES` slices the tuple to word it
- Overall, Shape: `bin/shell_command.py:20` `simple_commands`: `shell_reads` drops its own lexer for a shared module, at the cost of denser regexes
- Shape: `bin/rule_hook/rules.py:99` `commits`: git argument parsing sits in a module named for the rule registry
- Self-sufficiency: `bin/rule_hook/main.py:1` module docstring: each rule carries its own text and --help is generated from it
- Navigation: `CLAUDE.md:36` "Topic rules": a router to rules/, and the standards are a third home for instructions, balanced by README's rule-hook entry
Inherited architect, decided by:
- Navigation, Locality: `CLAUDE.md:21` "Prose": each priority is split between CLAUDE.md and `skills/larv-review/standards/prose.md`, and nothing in CLAUDE.md points to the second
- Navigation: `agents/prose-reviewer.md:9` "The bar": the bar is a three-way split, the worst place to go from a flag to the rule that fired
- Locality: `bin/loop_claude/project/records.py:10` `HUMAN_RULE_DIRS`: the judge globs one skill's internal folder, and moving it silently empties the records
- Locality: `bin/loop_claude/cycle/prompts.py:5` `QUOTE_SOURCES`: a tuple sliced with [:-1] and [-1] to place an "or", worked out across two modules
- Locality, Shape: `bin/shell_command.py:20` `simple_commands`: lexing moved out of `shell_reads` into a shared module, the change's clearest gain
- Shape: `bin/rule_hook/rules.py:108` `git_subcommand`: git command parsing sits in rules.py while git.py only runs git
- Navigation: `README.md:75` "Tools": the new tool is easy to find cold, and --help renders each rule
- Locality: `bin/rule_hook/override_log.py:96` `print_overrides`: a three-level conditional expression, and "this chunk" needs reflog semantics
Maintainability senior, decided by:
- Navigation, Locality: `skills/larv-review/standards/prose.md:3` "Prose, in detail": it expands CLAUDE.md's priorities by number, so it reads only with CLAUDE.md open, and a change to a priority edits two files
- Navigation: `CLAUDE.md:36` "Topic rules": the router lists only rules/, so finding where comments or "A false claim is a bug" live needs README line 3 or the Vocabulary
- Locality: `skills/larv-review/standards/quality.md:7` "Quality": each standard points at two or three other files, and CLAUDE.md:50 paraphrases the README rule without pointing to it
- Locality: `bin/loop_claude/project/records.py:9` `HUMAN_RULE_NAMES`: a derived tuple sliced by position feeds three prompts, and the folder list must match hand-kept copies in CLAUDE.md and AGENTS.md
- Locality: `bin/shell_command.py:31` `segments`: reading-cost and rule-hook share one parser, so a fix for the hook moves the reading-cost figures
- Navigation: `bin/rule_hook/main.py:1` module docstring: from a blocked commit to the rule is easy through --help and `RULES`
Junior A, decided by:
- Navigation: `CLAUDE.md:36` "Topic rules": the moved rules are not routed from here, and nothing in CLAUDE.md points to `standards/quality.md`
- Navigation: `skills/larv-review/standards/prose.md:3` "Prose, in detail": one rule lives in two files, and a reader must know the second exists
- Navigation: `agents/prose-reviewer.md:9` "The bar": working out which documents bind a review takes a small search
Junior A, hardest first:
- `skills/larv-review/SKILL.md:64` "Round cap": with "Re-entry" and "Fresh", four sections held at once to count a round
- `bin/larv_review/record.py:14` `record_ruling`: four exits, its terms defined in three other files
- `bin/rule_hook/override_log.py:36` `this_chunks`: reflog semantics, and a three-way conditional at :96
- `bin/shell_command.py:31` `segments`: dense regexes and a redirect flag, output unpredictable by reading
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: the judge's prompt assembled from three files
- `bin/larv_review/plan.py:8` `scoring_run_due`: set arithmetic over four inputs
Mid A, hardest first:
- `bin/larv_review/record.py:14` `record_ruling`: four outcomes, the counting rule only in the help
- `skills/larv-review/SKILL.md:64` "Round cap": interlocking with "Re-entry" and "Fresh"
- `bin/loop_claude/cycle/judge.py:127` `run_judge`: two mismatches handled two ways; `QUOTE_SOURCES` slices a tuple
- `bin/loop_claude/cycle/states.py:69` `transition`: a counter threaded through three states
- `bin/rule_hook/override_log.py:86` `print_overrides`: three chained conditionals
- `bin/larv_review/ruling_base.py:4` `measured_commit`: rests on the docstring and the help
Maintainability senior, hardest first:
- `skills/larv-review/SKILL.md:91` "Architecture": six conditions held at once, and the no-rescore file list only in prose
- `bin/larv_review/record.py:14` `record_ruling`: five modules open at once
- `bin/larv_review/ruling_base.py:4` `measured_commit`: why same does not move the base, on a second read
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: what the judge accepts spans three files nothing checks agree
- `bin/rule_hook/override_log.py:36` `this_chunks`: reflog membership; two `default_branch` functions differ
- `bin/rank_todo.py:374` `rank_details`: regex surgery on markdown
Inherited architect, would restructure first:
- `bin/loop_claude/project/records.py:16` `read_records`: a missing rule folder is skipped silently
- `bin/rule_hook/override_log.py:110` `default_branch`: a second default-branch rule, unlike larv-review's
- `bin/loop_claude/loop/main.py:16` module docstring: --help restates the retry constants as prose
- `bin/larv_review/rounds.py:4` `PASSES`: the round cap and rescores live in the skill's prose
- `bin/comprehension_history.py:42` `Entry`: one name over five concepts across the repo
## 2026-10-13T05:52:26Z, PR #245 at f6d5ea7, against 4cc9953
Ruling: worse
Fell: Shape. Under the floor of 7.0: Shape 6.75, so the same ruling counts as worse.
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | same | worse | same | same |
| Inherited architect | same | worse | worse | same | worse |
| Maintainability senior | same | worse | same | same | same |
| Junior A | better | same | worse | same | same |
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 6.5 | 7 | 6 | 6.5 |
| Mid A | 7.5 | 6.5 | 7 | 6.5 | 7 |
| Maintainability senior | 7.5 | 7 | 6.5 | 6.5 | 7 |
| Inherited architect | 7 | 6.5 | 6.5 | 7.5 | 7 |
| Mean | 7.25 | 6.63 | 6.75 | 6.63 | 6.88 |
Mid A, decided by:
- Shape: `bin/rule_hook/rules.py:108` `git_subcommand`: a module named for the rule catalogue also parses git arguments, override markers and verdicts
- Shape: `bin/rule_hook/override_log.py:96` `print_overrides`: three chained conditional expressions decide whether the reflog is readable
- Shape: `bin/rule_hook/rules.py:73` `Verdict`: two unrelated `Verdict` types, and `logged`, `existing` and `holds` do not say what they compute
- Shape: `bin/loop_claude/project/records.py:11` `HUMAN_RULE_NAMES`: a nested comprehension where one constant stood, though `either` keeps the prompt readable
- Shape: `bin/shell_command.py:20` `simple_commands`: a flat `shell_reads` over a denser shared lexer, a small net change
Inherited architect, decided by:
- Shape: `bin/rule_hook/rules.py:108` `git_subcommand`: rules.py mixes six jobs while git.py only runs git, and `reading_cost/measure.py:9` `COMMIT` is a second commit check
- Locality: `CLAUDE.md:21` "Prose": the worker's core and `skills/larv-review/standards/prose.md` are two copies that word the contrastive tail differently
- Locality: `bin/loop_claude/project/records.py:10` `HUMAN_RULE_DIRS`: the judge hard-codes larv-review's folder, and a test imports the constant back out
- Locality, Shape: `bin/rule_hook/override_log.py:86` `print_overrides`: a three-deep conditional, reflog semantics in a docstring, and the git-dir lookup done again
- Shape: `bin/rule_hook/main.py:82` `answer`: a two-phase pass and an unnamed 3-tuple from `breaches_of`
- Locality, Shape: `skills/larv-review/SKILL.md:56` "Opt-out": a third skip mechanism, three sections held at once
Maintainability senior, decided by:
- Locality: `CLAUDE.md:21` "Prose": the prose rules exist twice, and `CLAUDE.md:30` words the contrastive tail differently from `skills/larv-review/standards/prose.md:13`
- Locality: `rules/decisions.md:9` "Decisions": the decision rule is split between a worker file and `skills/larv-review/standards/comments.md:9` "Where a choice goes"
- Locality: `bin/rule_hook/override_log.py:110` `default_branch`: a second default-branch rule and git runner, unlike larv-review's
- Locality: `bin/loop_claude/project/records.py:10` `HUMAN_RULE_DIRS`: one folder list feeds the judge, the quote sources and a test, and `loop/main.py` spells it out by hand
- Locality: `bin/rank_todo.py:114` `check_failures`: copies the read, rank and compare flow `main` still runs
- Locality: `bin/rule_hook/rules.py:99` `commits`: computed on two paths for one command
Junior A, decided by:
- Navigation: `CLAUDE.md:38` "Topic rules": a short router to one small file per topic
- Navigation: `README.md:75` "Tools": names rule-hook and what runs it
- Shape: `bin/rule_hook/rules.py:108` `git_subcommand`: the rule table's file also parses git arguments, Dockerfiles and ignore files
- Shape: `bin/rule_hook/override_log.py:96` `print_overrides`: three failure cases in one chained conditional
- Shape: `bin/rule_hook/main.py:38` imports: the entry point pulls from six modules
- Navigation: `bin/shell_command.py:20` `simple_commands`: shell tokenizing has one home
Junior A, hardest first:
- `bin/larv_review/record.py:14` `record_ruling`: five files held at once, four outcomes
- `bin/rule_hook/override_log.py:36` `this_chunks`: reflog semantics and a three-level conditional at :96
- `skills/larv-review/SKILL.md:64` "Round cap": rules pointing at each other, exceptions on exceptions
- `bin/loop_claude/cycle/judge.py:127` `run_judge`: two quote checks with different tolerance
- `bin/shell_command.py:31` `segments`: heredoc and comment regexes and a redirect flag at once
- `bin/larv_review/plan.py:8` `scoring_run_due`: plan before and after, shipped IDs and tag state
Mid A, hardest first:
- `skills/larv-review/SKILL.md:64` "Round cap": a dozen interlocking conditions simulated in the head
- `bin/larv_review/record.py:14` `record_ruling`: branch order carries meaning, terms defined only in the skills
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: the prompt assembled from three files
- `bin/comprehension_history.py:110` `seat_places`: a parser with a flag reset by any unindented line
- `bin/rule_hook/override_log.py:86` `print_overrides`: reflog semantics and a chained conditional
- `bin/shell_command.py:31` `segments`: regex-heavy, no inline samples
Maintainability senior, hardest first:
- `skills/larv-review/SKILL.md:29` "Passes": a rule engine in prose, its mechanised half unmarked
- `bin/larv_review/record.py:14` `record_ruling`: four exits over two parallel vote maps
- `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`: the judge's contract built across three files
- `bin/rule_hook/override_log.py:86` `print_overrides`: reflog membership and a three-level conditional
- `bin/shell_command.py:31` `segments`: five concerns in one pass, two tools depend on it
- `bin/transcript_archive/write.py:13` `archive`: one invariant held across three files
Inherited architect, would restructure first:
- `bin/larv_review/rounds.py:8` `round_counts`: the round cap is enforced only by prose across five places
- `bin/larv_review/git.py:21` `default_branch`: one of two default-branch rules and five git runners
- `bin/loop_claude/loop/main.py:8` module docstring: the rule-folder list hand-written in four places
- `bin/rule_hook/rules.py:73` `Verdict`: one name over three concepts, like `Entry` and `ruling`
- `bin/rule_hook/rules.py:108` `git_subcommand`: a second commit detector beside `reading_cost/measure.py:9` `COMMIT`
## 2026-10-13T06:49:43Z, PR #245 at a796bb3, against 4cc9953
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | same | same | same | same |
| Inherited architect | same | worse | better | same | same |
Mid A, decided by:
- Locality: `bin/git_command.py:16` `commits`: one shared parser replaces reading-cost's lexer and regex, at the cost of a parser shared with rule-hook
- Locality, Self-sufficiency: `skills/larv-review/standards/prose.md:3` "Prose": a full copy beside CLAUDE.md's core, against small single-topic files
- Navigation: `CLAUDE.md:38` "Topic rules": three homes for a rule, all listed in the README map
- Shape: `bin/rule_hook/git.py:11` `git`: a bounded package, but `rule_hook/git.py` beside `git_command.py` and some vague names
Inherited architect, decided by:
- Locality: `CLAUDE.md:21` "Prose": two spellings of the prose rules, already worded differently
- Locality: `agents/prose-reviewer.md:9` "The bar": the bar is assembled from three sources and path globs
- Locality: `bin/loop_claude/project/records.py:16` `read_records`: any file added to the rule folders lengthens the judge's records
- Locality: `bin/rule_hook/override_log.py:36` `this_chunks`: reflog, default branch and logged branch held at once
- Shape: `bin/reading_cost/measure.py:43` `commit_time`: reading-cost and rule-hook share one parser, one concept with one implementation
- Shape: `bin/rank_todo.py:114` `check_failures`: --check pulled out so rule-hook reuses it
+44 -6
View File
@@ -4,7 +4,7 @@
2026-09-20, lilleman. Serves goal 1. Across six projects scored with the four seats, Locality or Self-sufficiency was the lowest dimension at every seat and Navigation at none, so a layout fix would not lift a project under the floor. Valid while the scoring run keeps those four seats.
## loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md` and `~/.claude/CLAUDE.md`, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
## loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
2026-09-21, lilleman. Serves goal 1. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. Valid while the worker's self-report stays unreliable.
@@ -12,7 +12,11 @@
2026-10-03, lilleman: the judge is to read `~/.claude/CLAUDE.md` whole too. The worker follows that file, so a question it answers should not reach the human (goal 1.2). Reading the whole file is safe, because the judge may quote only words that appear in it. A list of sections would need keeping current. Implemented the same day.
2026-10-03, lilleman: the judge rules a chunk finished only once every answer the human typed in it is recorded. A finished chunk's session is deleted, and its answers with it, so an answer recorded nowhere would be asked again in a later chunk (goal 1.2). Implemented the same day by claude, which settled two choices the ruling left open. First, an answer counts as recorded where the files the judge reads hold it, `~/.claude/CLAUDE.md` included, or where the transcript shows the worker writing it into `README.md`'s premises, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. A worker's write to `~/.claude/CLAUDE.md` does not count: `CLAUDE.md` → "Maintaining this file" leaves new rules in it to the human. The judge cannot read a code comment or `todo.md`. Yet `CLAUDE.md` → "Working loop", "Ask, don't guess" puts a standing choice made in one place in a comment there. And the human's approval of a release's items, which "Working loop" requires, is the set of rows `todo.md` names for that release. The judge also reads the records once a cycle from the main checkout. That checkout may not yet hold an answer the worker wrote and merged. A judge that refused any of these would hold the chunk open every cycle. Second, only an answer a later chunk could need must be recorded, so an approval such as "merge it" holds nothing open. The worker's resume prompt states the rule, so a worker whose chunk is held open knows it.
2026-10-03, lilleman: the judge rules a chunk finished only once every answer the human typed in it is recorded. A finished chunk's session is deleted, and its answers with it, so an answer recorded nowhere would be asked again in a later chunk (goal 1.2). Implemented the same day by claude, which settled two choices the ruling left open. First, an answer counts as recorded where the files the judge reads hold it, `~/.claude/CLAUDE.md` included, or where the transcript shows the worker writing it into `README.md`'s premises, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. A worker's write to `~/.claude/CLAUDE.md` does not count: the judge reads the live `~/.claude`, which holds the write only once it merges and the checkout is pulled. The judge cannot read a code comment or `todo.md`. Yet `CLAUDE.md` → "Working loop", "Ask, don't guess" puts a standing choice made in one place in a comment there. And the human's approval of a release's items, which "Working loop" requires, is the set of rows `todo.md` names for that release. The judge also reads the records once a cycle from the main checkout. That checkout may not yet hold an answer the worker wrote and merged. A judge that refused any of these would hold the chunk open every cycle. Second, only an answer a later chunk could need must be recorded, so an approval such as "merge it" holds nothing open. The worker's resume prompt states the rule, so a worker whose chunk is held open knows it.
2026-10-13, implementing todo item 95: the judge reads each file under `~/.claude/rules/` whole too, as the `rules/:` decision moved topic rules there, for the reason it reads `CLAUDE.md` whole, and a worker's write to one does not count as recording an answer, as a write to `CLAUDE.md` does not.
2026-10-13, implementing todo item 104: the judge reads each file under `~/.claude/skills/larv-review/standards/` whole too, for the same reason, as the `worker:` decision moved rules there.
## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
@@ -34,9 +38,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):
@@ -52,6 +56,8 @@ lilleman decided to ship each of these under the floor on the day listed. Each l
- 2026-10-08, PR #225: 7.25, 6.75, 7.00, 6.88, 6.88. Above PR #224's run on every score but Shape, which held.
- 2026-10-08, PR #228: no scoring run; its last paired ruling, against 12d6d75, was worse, 2 votes to 0. lilleman shipped it below the ratchet: the seats blamed the new ratchet's own rules, since moved into the tested `bin/larv-review`.
- 2026-10-08, PR #229: no scoring run; its last paired ruling, against 12d6d75, was worse, 2 votes to 0. lilleman shipped it below the ratchet for PR #228's reason: the seats' decisive places were still PR #228's rules, since moved into `bin/larv-review`.
- 2026-10-09, PR #232: 7.13, 6.50, 6.63, 6.63, 6.88, at 324d650, whose ruling the fall made worse. Its last paired ruling, at 53014f8 against 12d6d75, split: Mid A better, the inherited architect worse, both with Locality worse. lilleman shipped it below the ratchet: after a restructure the seats still weigh PRs #229 to #231's code against the base, and their Locality places are filed under item 62; the `bin/` regrouping, item 83, shipped in PR #234.
- 2026-10-09, PR #234: 7.13, 6.63, 6.75, 6.50, 6.63, at 7e13778. Four architecture rounds and the rescore each ruled better, 2 votes to 0, while the means moved within the panel's noise between runs. lilleman shipped it below the floor: most of every seat's remaining places sit in larv-review's rules, which cannot be followed without `skills/larv-review/SKILL.md` §3 open beside the code. Fixing that is a chunk of its own, under item 62.
## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
@@ -65,14 +71,20 @@ lilleman decided to ship each of these under the floor on the day listed. Each l
2026-10-08, lilleman, replacing the 2026-09-30 rule that every fix, a nit's included, re-enters review. Serves goal 1.4. An audit of the four costliest archived chunks (2026-10-08) found nearly every finding that mattered in a pass's first round; later rounds mostly re-checked the last fix, reworded what an earlier round wrote, or contradicted another round on the same line. A round 2 caught real bugs only where a fix changed behaviour, so stability still reruns on every fix that does, and security on every fix that opens an untrusted-input boundary or touches authn/authz, secrets or crypto. Valid while round-2 reviews of nit and prose fixes keep changing nothing a user would notice.
## review: a paired ruling against the last measured commit decides the ratchet; the four-seat scoring run checks the floor when a release's items run out or an item names the floor
## 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
2026-10-08, lilleman. Serves goals 1.1 and 1.4. Two independent four-seat runs moved up to 0.4 on near-identical code, so a fall within that noise forced rounds that changed nothing (PR #224). A seat reading both versions judges the difference on the same material, so the noise the versions share cancels. No conventional significance level lets a sign test settle with four votes, so the human chose a lead of two votes over every other ruling, same included. Two seats that agree settle it, so a PR that leaves the reading as it was costs two seats. A third seat alone can never settle it, so the third and fourth launch together. The base is the default branch's newest merged change that adds a scoring run to the history, or whose last added paired ruling is better. The human chose the last measured commit on the architect's finding that with a merge base as the base, chunks without an architecture pass, and a suspended restructure's steps, could each lower comprehension unseen. A ruling of same leaves the base where it was, or a run of small falls each ruled same would add up unseen. A scoring run moves it too: otherwise a project never ruled better would compare against its first ruling forever, and a release's floor check is where the human sees the absolute level. Reading the default branch one merged change at a time keeps the rule working for merge commits and squash merges alike: a branch's own early ruling of better never counts, only the merged change's last ruling. The scoring run also runs on a chunk shipping an item that names the floor, so the chunk that lifts a project to the floor can prove it. A chunk that removes a release's last item without shipping it runs it too, so no release ends unmeasured. Valid while seats reading both versions agree more often than two absolute runs do.
2026-10-09, lilleman: each seat also rules each dimension, and a dimension falls by the same lead of two. A better or same ruling naming a fallen dimension calls the scoring run, and counts as worse when that dimension's mean is under the floor, so between releases a project cannot trade one dimension below the floor for gains in the other three. The four scoring seats' scores go into the ruling itself, which `record-ruling` decides in one call, so no command reads a fall another command recorded. Those scores block on the fallen dimensions alone, the floor's own block staying with a release's end and an item naming the floor, and they leave the base where the ruling leaves it: a run of falls each ruled same must not add up unseen. PR #232's own history holds one fall-called scoring run recorded on its own, before this rule; it moves the base like any scoring run, which is safe under it, since a later fall of a dimension under the floor is always caught. A dimension's vote counts only where one of the seat's places opens with that dimension, so a fall rests on places the seats name.
## review: a project decision may suspend the comprehension check for the plan items it names
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.
@@ -109,7 +121,7 @@ lilleman decided to ship each of these under the floor on the day listed. Each l
## 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`
2026-10-02, lilleman. Serves goal 1: findings were filed faster than chunks closed them, so the plan grew without telling what mattered. Each item is scored as `CLAUDE.md` → "Todo items" says; this repo's formula counts value highest and size least. An item under the bar is not kept; this repo's bar started at 10 and was set to 9 the same day, purging the 17 items under it. An Exempt cell keeps a row past the bar where a rule needs it kept. lilleman retired the two decisions whose plans the purge removed: the stats line in the transcript archive, and three benches before a workflow change merges. A finding under the bar is recorded nowhere, so a later review may raise it again, and the run rescores it. That costs one scoring; a ledger of dropped findings would regrow the list the bar caps. larv-review's "Round cap" → "Done" counts a finding named under the bar as settled, so one raised again holds no pass open. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale. The format is mandatory in every project, as the premises are (goal 1.3); the formula, bar and weights are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. A 🟡 against a technical principle is exempt as `principle`, because its audience value scores low and the bar would drop every one. A 🟢 against a principle is scored like any other finding. 2026-10-08, lilleman: the goal weights in `todo.md` depart from an even spread by position, which would weigh goal 4, leaking nothing, at 0.11. Valid while one human sets the bar and reads the ranking, and while the items marked `principle` stay few enough to rank.
2026-10-02, lilleman. Serves goal 1: findings were filed faster than chunks closed them, so the plan grew without telling what mattered. Each item is scored as `~/.claude/rules/todo-items.md` says; this repo's formula counts value highest and size least. An item under the bar is not kept; this repo's bar started at 10 and was set to 9 the same day, purging the 17 items under it. An Exempt cell keeps a row past the bar where a rule needs it kept. lilleman retired the two decisions whose plans the purge removed: the stats line in the transcript archive, and three benches before a workflow change merges. A finding under the bar is recorded nowhere, so a later review may raise it again, and the run rescores it. That costs one scoring; a ledger of dropped findings would regrow the list the bar caps. larv-review's "Round cap" → "Done" counts a finding named under the bar as settled, so one raised again holds no pass open. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale. The format is mandatory in every project, as the premises are (goal 1.3); the formula, bar and weights are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. A 🟡 against a technical principle is exempt as `principle`, because its audience value scores low and the bar would drop every one. A 🟢 against a principle is scored like any other finding. 2026-10-08, lilleman: the goal weights in `todo.md` depart from an even spread by position, which would weigh goal 4, leaking nothing, at 0.11. Valid while one human sets the bar and reads the ranking, and while the items marked `principle` stay few enough to rank.
## settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
@@ -126,3 +138,29 @@ 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.
## rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
2026-10-13, lilleman through todo item 95, implemented by claude. Serves goals 1.3 and 1.4. Every session loaded `CLAUDE.md` whole, about 4,200 words. Anthropic's memory docs (code.claude.com/docs/en/memory) say a longer file "reduce[s] adherence", and IFScale (arxiv.org/abs/2507.11538) measures adherence falling as the instruction count grows. A rule goes in `CLAUDE.md` when no file path marks the moment it is needed: the working loop, prose that chat follows, commits, and API spec text, which may sit in code. Every other topic gets a file under `rules/` whose `paths:` name the files that topic is about.
A session that writes a file has read one first, since Edit needs a Read, except for a new file written before any read; the "Topic rules" line says to read the rule file first there. 2026-10-13, todo item 104: the rules a reviewer applies and the worker need not load, those for comments and READMEs among them, moved out of `rules/`, per the `worker:` decision.
Claude Code's user-level rules tie this repo to Claude Code, which "Prefer the vendor-neutral option" (`principles/technical-principles.md`) allows here because this repo configures Claude Code itself. The tie buys topic rules that load without a pointer the session must follow.
Valid while Claude Code loads `~/.claude/rules/*.md` in every project, a path-scoped one when a session reads, writes or edits a matching file, or reads one with a single-file Bash command such as `cat`, and after a write only once the write is done. On 2026-10-13 a smoke test confirmed both triggers: a rule in `~/.claude/rules/` with `paths: ["**/smoke-target.txt"]` held a secret word. `claude -p` in a project under `/tmp` printed the word after reading the target with the Read tool, and after creating it with the Write tool. A control run that opened no file printed none. Per the docs, a path-scoped rule leaves the context at compaction and returns at the next matching read.
## worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
2026-10-13, lilleman through todo item 104, implemented by claude. Serves goals 1.4 and 1.5. Like red, green, refactor: the worker makes the item work, and the review passes raise it to the bar. A loop-claude worker loaded `CLAUDE.md` and every file under `rules/`, 4,247 words, and `CLAUDE.md` told it to read `technical-principles.md` too, 2,426 words more. The reviewers read the principles anyway, and a finding against one names it.
The worker keeps what it needs to write its own work. Each project's decision titles stay in its `AGENTS.md`, since a worker that misses a decision builds the wrong behaviour. A core of "Prose" stays in `CLAUDE.md`, since no reviewer reads the worker's chat. lilleman chose both on 2026-10-13. The rules for writing Goals and Audience, `todo.md` items and decisions stay in `rules/`, since writing those is the worker's job. `bin/rule-hook` stays: it blocks what a program can check, at no context cost. "Quality", the rules for comments and READMEs, and the examples behind "Prose" moved to `skills/larv-review/standards/`, which no path loads. The prose and stability reviewers read them, and so does loop-claude's judge. They sit beside larv-review, whose passes apply them; `principles/` stays where it is, since the principles auditor reads it per file.
A finding against a principle names it, so the worker reads only that one when it fixes or declines the finding. The worker still writes a failing test first wherever a test can check the change, since no reviewer can make a test come first. On 2026-10-13 lilleman widened it from code changes to anything there is to test. A chunk that changes no code, config or test, such as one that only plans, meets no principles review; the chunk that implements its items does. The prose reviewer checks that a doc sorts a list whose order carries no meaning.
The item also cut the rule that a session proposes new rules for `CLAUDE.md` and `rules/` and restructures them after each change: changes to these rules go through this repo's chunks and their reviews, like any other change.
Valid while review rounds per pass do not rise. A principle found late, such as functional core, can cost a rewrite within a pass's three rounds. `todo.md` item 105 compares rounds per pass and reading cost in loop-claude's archive for the five chunks before and after this one.
+34
View File
@@ -111,3 +111,37 @@ Read most (opens and searches):
- `skills/larv-review/SKILL.md` 1
- `skills/larv-review/review-findings.md` 1
- `todo.md` 1
## Reading cost, chunk 00ad6c532a93, finished 2026-10-12T22:15:42Z
172162 new input tokens before the first commit.
Read most (opens and searches):
- `.gitignore` 2
- `bin/loop_claude/cycle/prompts.py` 2
- `bin/rank_todo.py` 2
- `skills/larv-review/SKILL.md` 2
- `.claude/settings.json` 1
- `AGENTS.md` 1
- `CHANGELOG.md` 1
- `CLAUDE.md` 1
- `README.md` 1
- `bin/failure.py` 1
## Reading cost, chunk 8c8ffb885ec4, finished 2026-10-12T23:06:46Z
106562 new input tokens before the first commit.
Read most (opens and searches):
- `CLAUDE.md` 11
- `todo.md` 7
- `skills/larv-review/SKILL.md` 5
- `bin/loop_claude/loop/main.py` 4
- `bin/loop_claude/test_loop_claude.py` 4
- `README.md` 3
- `bin/loop_claude/project/records.py` 3
- `docs/decisions.md` 3
- `CHANGELOG.md` 2
- `bin/loop_claude/cycle/judge.py` 2
+11 -6
View File
@@ -12,6 +12,16 @@
- Functions: a function takes what it needs as arguments and returns what it produces. One that works only after another has set up shared state, or leaves state for the next to find, is entangled with it. BANNED: `validate(conf)` that fills defaults `send(conf)` relies on. GOOD: `send(withDefaults(conf))`.
- Tests and tooling: a test, script or pipeline stage that passes only because another ran first is entangled; it states what it needs and gets it.
- Proximity is not a reason. Reusing a listener, config file, table, module or service because it is already there, when the new thing has no relationship to it, is how entanglement gets in. If you cannot name the seam, there is none.
* Functional core, imperative shell — a core rule beside "Compose, do not entangle": no other principle overrides it.
- Decisions live in pure functions, data in and data out; the shell around them performs the effects and holds no branching of its own.
- Every side effect comes from outside: output, time, randomness, network and storage are injectable, so a test runs exactly the code production runs.
- BANNED: `new Date(entry.msTimestamp ?? Date.now())` in a formatter; a test swapping `globalThis.fetch`. GOOD: the clock is a parameter, defaulted to the system clock only where the program is wired together.
- Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. An entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code.
* Prefer deep modules: a small, intuitive interface in front of a lot of hidden work.
- A caller should know what a call does and what it returns, without knowing how it does it. `fs.writeFile("notes.txt", data)` hides opening the file, encoding, buffering, permissions and the disk itself. Yet anyone reading that line knows the outcome: the data is written, or the call fails and says why.
- A module hides how it works, never what it depends on: what "Functional core, imperative shell" injects stays injected.
- A shallow module costs more to learn than it saves. BANNED: a wrapper that only renames the function it calls; a module whose callers must make three calls in an order nothing but their memory enforces. GOOD: one call that does the whole job and handles the order itself.
- When this pulls against "Explicit over implicit", the deep module wins, unless hiding the work makes it harder for someone new to the project to tell what the call does.
* Make invalid states unrepresentable.
- Example: using a time-only type in the database when we actually want to store a time of day introduces risk for errors.
* Always store timestamps as full ISO datetime in UTC.
@@ -51,13 +61,8 @@
- A default earns its place where most callers want the same value, a wrong guess does no harm, and the caller can see and change it through a `--help` line or a documented option. Anything else is asked for.
- Defaults live at the program's edge: a CLI, a config file, a library's public API. A library still asks for every input that can change between runs, such as data, the clock and randomness; only the code that wires a program together, such as its CLI, defaults those, as "Functional core, imperative shell" asks.
- BANNED: a CLI that refuses to run until given `--data-path` and `--seed`, when nearly every run wants the shipped data and fresh randomness. GOOD: it uses the shipped data and fresh randomness unless a flag overrides them, and `--help` names those flags.
* Functional core, imperative shell.
- Decisions live in pure functions, data in and data out; the shell around them performs the effects and holds no branching of its own.
- Every side effect comes from outside: output, time, randomness, network and storage are injectable, so a test runs exactly the code production runs.
- BANNED: `new Date(entry.msTimestamp ?? Date.now())` in a formatter; a test swapping `globalThis.fetch`. GOOD: the clock is a parameter, defaulted to the system clock only where the program is wired together.
- Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. An entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code.
* Deterministic order wherever order carries no meaning.
- Sort it, on a key that does not move: the name a line introduces, never where it came from. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to.
- Sort such a list, on a key that does not move: the name a line introduces, never where it came from. Exception: `id` goes first. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to.
- An import sorts on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group.
* Keep It Simple, Stupid (KISS): keep solutions simple, so a reader new to the project understands each part on one read.
- Keep a size or complexity limit only while the comprehension panel's readers (`~/.claude/skills/comprehension-panel/`) find the code it flags hard.
+11
View File
@@ -0,0 +1,11 @@
---
paths:
- "**/AGENTS.md"
- "**/docs/decisions.md"
---
# Decisions: one home, each linked to a goal or a technical principle
**The decision log has one home: `docs/decisions.md`**. A title states the whole decision in one line: what holds at the commit it ships in, in words a reader finds in the code or the plan. `AGENTS.md` lists every title, so a session works by the decisions without loading their background. A session reads the entry under a title only to question, revise or add a decision. The entry holds the background: its date, who made it, the reasoning, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies.
**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess" says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it.
+9
View File
@@ -0,0 +1,9 @@
---
paths:
- "**/README.md"
---
# Goals and Audience
- **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.
+17
View File
@@ -0,0 +1,17 @@
---
paths:
- "**/todo.md"
---
# Todo items (`todo.md`)
- **`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.
- **An item's release allows the bump that semver read strictly asks for.** An item that changes what exists needs a major, or before 1.0.0 a minor. One that only adds needs a minor, and a fix a patch.
- **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`.
- **G** — its value to the goals it cites in the Goals column; W is the weight of the heaviest of them.
- **An item scoring under the bar is deleted, with every item that needs it, and a finding under the bar is not filed.** The chunk's summary names each, with its score.
- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding, `question` for a question only the human can answer, `decision` for an item `docs/decisions.md` cites, and, where no other reason fits, `principle` for a 🟡 finding against a file under `~/.claude/principles/`, whose item's detail names that principle. Every item `docs/decisions.md` cites carries one of these reasons.
- **Unless the project has a reason to differ, weigh goals by position, the first heaviest.** When the weights stop listing the README's goals, `rank_todo.py` fails and prints those weights.
+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": {
+4 -4
View File
@@ -6,7 +6,7 @@ A scoring-run seat's prompt is the opening, the seat's background, the shared br
- `{main}`: the project's main checkout.
- `{forbidden}`: `todo.md, docs/decisions.md, docs/comprehension-history.md or docs/reading-cost.md (the plan, the decision log, past panels' records and past chunks' reading cost)`.
- `{git}`: `git -C {checkout} ls-files`, and for a paired seat also `git -C {base checkout} ls-files`, each in backticks.
- `{files}`: every tracked non-test file but those `{forbidden}` names, from `git -C {checkout} ls-files`, listed as one recursive glob per top-level source directory, such as `bin/loop_claude/**/*.py`.
- `{files}`: every tracked file in `git -C {checkout} ls-files`, except test files and those `{forbidden}` names. Give one recursive glob per top-level source directory, say which test files it leaves out, and list each file no glob matches. Example: `bin/**/*.py` except `test_*.py`, plus launchers such as `bin/loop-claude`.
- `{preloaded}`: the files the harness pre-loads into a seat, found per `SKILL.md` → "What makes the result trustworthy".
- `{anchors}` and `{dimensions}`: the six anchor bullets and the four dimension bullets in `SKILL.md` → "The score", verbatim, without bold and each on one line.
- `{language}`, `{kind}`, `{domain}`, `{domain docs}` and `{3am question}`: the project's `AGENTS.md` → "Scoring run".
@@ -84,11 +84,11 @@ Your harness pre-loads these files into your context before your first tool call
No running anything, no builds, no tests, no edits of any kind.
Rule whether the project as a whole reads better, the same or worse at {head} than at {base}, judged on these four dimensions:
Rule whether the project reads better, the same or worse at {head} than at {base} on each of these four dimensions, and as a whole:
{dimensions}
Same means a reader of either version would find it as easy to understand and change. Do not manufacture a difference.
Report, in this shape:
1. Your ruling: better, same or worse.
2. The places that decided it, most decisive first. Each: path:line and the unit's name, in the version the place is in, and one or two sentences on what reads easier or harder there than in the other version. A better or worse ruling with no named place is discarded.
1. Your rulings, each better, same or worse, in this shape: Navigation <ruling>, Locality <ruling>, Shape <ruling>, Self-sufficiency <ruling>, Overall <ruling>
2. The places that decided them, most decisive first. Each opens with the names from your rulings line that it moves, joined by ", " and followed by ": ", such as `Locality, Shape: `. Then `path:line` and the unit's name, each in backticks, in the version the place is in, and one or two sentences on what reads easier or harder there than in the other version. A dimension's ruling that no place opens with counts as same, and the overall ruling does unless you name a place.
```
+26 -15
View File
@@ -9,7 +9,7 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchr
**Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. Resolve the tooling from the remote per `~/.claude/CLAUDE.md` → "Git, commits, and PRs"; on any other forge, achieve the same intents through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary.
Words: `~/.claude/CLAUDE.md` → "Vocabulary". What a reviewer reports: ~/.claude/skills/larv-review/review-findings.md; how you resolve it: §3 → "Findings".
The bar a chunk is reviewed to: ~/.claude/skills/larv-review/standards/quality.md. Words: `~/.claude/CLAUDE.md` → "Vocabulary". What a reviewer reports: ~/.claude/skills/larv-review/review-findings.md; how you resolve it: §3 → "Findings".
**An ask** holds only what it asks about; the rest runs on while it waits. No user reachable (a headless run) → finish the rest, then leave the PR unmerged with the question and your recommendation in the summary, unless the ask's rule names another branch.
@@ -24,7 +24,7 @@ Words: `~/.claude/CLAUDE.md` → "Vocabulary". What a reviewer reports: ~/.claud
Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the default branch. Commit, push with upstream set, and open a **draft** PR so CI cycles while the review runs. No remote → review locally and say so in the summary.
**Reading cost.** Run `~/.claude/bin/reading-cost` in the chunk's worktree and commit what it appends to `docs/reading-cost.md`; the commit re-enters no pass. Resolve a merge conflict in that file by putting the default branch's figures first and dropping a figure for a chunk the default branch already holds. On `Rising:`, file a plan item titled `**Lower the reading cost of the files chunks read most before their first commit.**`, scored per `~/.claude/CLAUDE.md` → "Todo items" with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. Leave the plan as it is on any other output. The chunk that ships that item runs the tool with `--reset` instead, so the next rise is measured on chunks that finished after it.
**Reading cost.** Run `~/.claude/bin/reading-cost` in the chunk's worktree and commit what it appends to `docs/reading-cost.md`; the commit re-enters no pass. Resolve a merge conflict in that file by putting the default branch's figures first and dropping a figure for a chunk the default branch already holds. On `Rising:`, file a plan item titled `**Lower the reading cost of the files a chunk reads most before its first commit.**`, scored per `~/.claude/rules/todo-items.md` with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. Leave the plan as it is on any other output. The chunk that ships that item runs the tool with `--reset` instead, so the next rise is measured on chunks that finished after it.
## 3. Passes
@@ -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.
@@ -71,9 +80,9 @@ Give a reviewer without Bash the branch diff and `git ls-files`'s output in its
**Findings.** A reviewer rates each finding 🔴 must fix, 🟡 should fix, 🟢 nit, ❓ question, or 🔀 escalation naming the reviewer whose concern it is.
- **Outside the chunk.** A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". A 🔴 is marked `defect`. A 🟡 against a file under `~/.claude/principles/` is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security".
- **Outside the chunk.** A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/rules/todo-items.md`. A 🔴 is marked `defect`. A 🟡 against a file under `~/.claude/principles/` is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security".
- **Goal or decision.** A fix that would change a goal, or a `docs/decisions.md` entry the repo held before the chunk began, is asked; no user reachable → filed, marked `question`, the goal or decision left as is.
- **🔴.** A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/CLAUDE.md` → "Decisions: one home, each linked to a goal or a technical principle": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined.
- **🔴.** A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/skills/larv-review/standards/comments.md` → "Where a choice goes": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined.
- **🟡.** A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix.
- **🟢 and ❓.** A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test, a goal or a decision the repo held before the chunk began settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed, marked `question`.
- **🔀.** A 🔀 runs the named reviewer's pass once the current pass is done.
@@ -94,30 +103,28 @@ Then the comprehension check: simulated readers, launched per `~/.claude/skills/
- **Base.** The last measured commit, which `~/.claude/bin/larv-review ruling-base` prints.
- **Head.** Before each ruling, merge `origin/<default branch>` into this branch unless the head already holds it, so the seats see only this branch's change on top of the base.
- **Seats.** Mid A and the inherited architect. Write what they read and their replies into a seats file in your scratchpad, in the shape `~/.claude/bin/larv-review --help` shows, and run `~/.claude/bin/larv-review record-ruling <file>`. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again.
- **Seats.** Mid A and the inherited architect. Write what they read and their replies into a votes file in your scratchpad, in the shape `~/.claude/bin/larv-review --help` shows, and run `~/.claude/bin/larv-review record-ruling <votes file>`. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again. On `Fell:`, launch the four scoring seats, below, on the same commit, write their lines into a scores file, and run `record-ruling <votes file> <scores file>`.
- **Ruling.** The `Ruling:` line `record-ruling` prints and appends to the history.
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Write their lines into a seats file and run `~/.claude/bin/larv-review record-scoring <file>`, which appends the run to the history and prints the four seats' means.
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Write their lines into a scores file and run `~/.claude/bin/larv-review record-scoring <scores file> <the same item IDs>`, which appends the run to the history and prints the four seats' means. Where a fall's scores file already read the head, run `record-scoring` on that file.
The chunk does not merge while either holds:
- **Ratchet.** The paired ruling is worse.
- **Floor.** `record-scoring` names a mean under the floor of 7.0.
- **Floor.** `record-scoring` prints `Floor:`, naming means under the floor of 7.0.
Each is a 🔴 of the comprehension check. It is never filed, and stands until a later run clears it or, for the floor, a decision to ship answers it.
Fix a worse ruling at the places the seats voting worse name, and the floor at the places the seats name under the lowest dimension. Under the floor alone, the user may decide to ship instead. A decision that lets every chunk ship under the floor, held in the project's `docs/decisions.md` before the chunk began, counts as theirs while it stands. A decision to ship listed in the `comprehension floor:` entry covers only the chunk it names. No user reachable → fix. A worse ruling never ships: after three rounds, "Round cap" → "Cap" asks the user for another round.
Fix a worse ruling at the places the seats voting worse name, or, where a fallen dimension made it worse, at the places that open with that dimension, and the floor at the places the seats name under the lowest dimension. When only the Floor bullet holds, the user may decide to ship instead. A decision that lets every chunk ship under the floor, held in the project's `docs/decisions.md` before the chunk began, counts as theirs while it stands. A decision to ship listed in the `comprehension floor:` entry covers only the chunk it names. No user reachable → fix. A worse ruling never ships: after three rounds, "Round cap" → "Cap" asks the user for another round.
Two files of the project keep the records:
- **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, which `larv-review` appends; never edit one. Appending re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first.
- **Entry.** `docs/decisions.md` keeps one entry whose title opens `comprehension floor:`. It holds each decision to ship under the floor, with its scores.
A `comprehension floor:` entry written before the history may still hold a scoring run's five scores. The next scoring run moves them, and only them, into the history as its first run. Write a seats file of two lines and run `~/.claude/bin/larv-review record-scoring` on it. The first line is `<the date or time the entry gives>, <what the entry names the run by> at <commit>`, the commit being the one the entry names, or else the one that wrote those scores into it. The second is `Mean:` and the five scores, in the shape `--help` shows. The rest of the entry stays.
Put each ruling with its base and votes, and each run's five scores, in the summary. List in the entry each decision to ship under the floor, and file its places in `todo.md` per `~/.claude/rules/todo-items.md`. A project without the entry gets it at its first scoring run, titled `comprehension floor: every dimension and the overall at 7.0 or above` and applying KISS (`~/.claude/principles/technical-principles.md`).
Put each ruling with its base and votes, and each run's five scores, in the summary. List in the entry each decision to ship under the floor, and file its places in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". A project without the entry gets it at its first scoring run, titled `comprehension floor: every dimension and the overall at 7.0 or above` and applying KISS (`~/.claude/principles/technical-principles.md`).
**Fresh.** Where the chunk ran a comprehension check, the architecture pass is done only once its last paired ruling, and its last scoring run where it ran one, read the commit to merge. They may predate commits that change only `docs/decisions.md`, `docs/comprehension-history.md`, `docs/reading-cost.md`, `todo.md` or `CHANGELOG.md`. Any other commit after them, a prose fix included, because the seats read the docs, calls for a rescore: the comprehension check again, once every other pass is done, the auto-reviewer included. A rescore reporting a 🔴 that no decision to ship answers is an architecture round. Any other rescore is not a round: append only its results to the history, in a commit titled `Rescore: …`. A `Rescore:` commit re-enters no pass: push it and wait for the forge's checks (§4 step 3), not for an auto-review.
**Fresh.** Where the chunk ran a comprehension check, the architecture pass is done only once its last paired ruling, and its last scoring run where one is due, read the commit to merge. They may predate commits that change only `docs/decisions.md`, `docs/comprehension-history.md`, `docs/reading-cost.md`, `todo.md` or `CHANGELOG.md`. Any other commit after them, a prose fix included, because the seats read the docs, calls for a rescore: the comprehension check again, once every other pass is done, the auto-reviewer included. A rescore reporting a 🔴 that no decision to ship answers is an architecture round. Any other rescore is not a round: append only its results to the history, in a commit titled `Rescore: …`. A `Rescore:` commit re-enters no pass: push it and wait for the forge's checks (§4 step 3), not for an auto-review.
**Suspended.** A decision in the project's `docs/decisions.md`, held before the chunk began, may name plan items to ship without a comprehension check. A named item counts as `todo.md` worded it before the chunk began. The decision must name the later plan item whose chunk ends the suspension with a comprehension check. A chunk may ship named items only with each other. Such a chunk skips the comprehension check, so neither the ratchet nor the floor can block it, and its summary cites the decision. A chunk due a scoring run runs it, even when every item it ships is named.
@@ -131,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.
@@ -157,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.

Some files were not shown because too many files have changed in this diff Show More