Compare commits

...

266 Commits

Author SHA1 Message Date
lilleman fc5e463594 Record the comprehension check: paired ruling same against cde7720; file item 250 for the repeat-read seam the seats found hard 2026-10-28 17:24:54 +01:00
lilleman 0447f2e07a Record lilleman's no to a fourth principles round in item 246 2026-10-28 17:14:41 +01:00
lilleman 155dedcf5c Merge remote-tracking branch 'origin/main' into item-239
# Conflicts:
#	todo.md
2026-10-28 14:58:17 +01:00
lilleman 312a8b590d Answer product-owner round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-28 14:57:47 +01:00
lilleman e9e130cb77 Answer stability round 3: 0 🔴, 0 🟡 (0 misread); keep the Edit-refusal comment above the tests it explains 2026-10-28 14:57:43 +01:00
lilleman f4a2ea823d Answer stability round 2: 0 🔴, 2 🟡 (0 misread); test calls that neither read nor write, a change in the read's millisecond, and the change stamp's format 2026-10-28 14:55:19 +01:00
lilleman dd90d109fd Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); say that a Read goes through until the agent read the file with Read 2026-10-28 14:41:52 +01:00
lilleman e68100b35e Answer principles round 3: 0 🔴, 0 🟡 (0 misread); drop the test's pin on the block's wording 2026-10-28 14:17:59 +01:00
lilleman 53459014a4 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); reword repeat-read's docstrings, changelog and test names 2026-10-28 14:14:55 +01:00
lilleman 5ea156a67b Answer product-owner round 1: 1 🔴, 1 🟡 (0 misread); let a Read through once the file changed after the last Read or write, and reword the changelog 2026-10-28 14:14:54 +01:00
lilleman b1a90abff4 Answer stability round 1: 1 🔴, 8 🟡 (0 misread); read only a regular file, only as far as the shown lines, skip cut-short output, and test the surviving mutants 2026-10-28 14:14:53 +01:00
lilleman e41f4e0979 Answer principles round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-28 13:06:52 +01:00
lilleman 71e2e0f893 Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-28 13:05:01 +01:00
lilleman 488d9b0eee Answer principles round 1: 0 🔴, 2 🟡 (0 misread); kill the surviving mutants and split repeat-read's tests to one behaviour each 2026-10-28 13:05:00 +01:00
lilleman 8602b8a7ee Answer architecture round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:53:26 +01:00
lilleman 248e46f616 Answer architecture round 1: 2 🔴, 2 🟡 (0 misread); move transcript parsing into claude_code and keep repeat_read pure 2026-10-28 12:52:34 +01:00
lilleman d583f8d48c Merge pull request 'Reword the note that prose findings stay' (#389) from item-246-prose into main 2026-10-28 12:47:46 +01:00
lilleman f5afc7f6d3 Reword the note that prose findings stay 2026-10-28 12:47:43 +01:00
lilleman 058804bb13 Merge pull request 'File items 246 and 247: cap review at two rounds, count escaped defects; record that prose findings stay' (#388) from item-246 into main 2026-10-28 12:47:36 +01:00
lilleman 592a6052fe File items 246 and 247: cap review at two rounds, count escaped defects; record that prose findings stay 2026-10-28 12:47:33 +01:00
lilleman 1d2f3d14d2 Sort repeat_read's imports and keep its sed range's names apart 2026-10-28 12:44:18 +01:00
lilleman 2d3ec3a636 Block a read of file lines already in the agent's context, unless a compaction dropped them or the file changed 2026-10-28 12:43:46 +01:00
lilleman 37df9b7805 Append the reading-cost figure 2026-10-28 12:43:46 +01:00
lilleman cde7720750 Merge pull request 'Run the tests once, on the latest stable Python, in one heavy slot's four workers' (#386) from item-245 into main 2026-10-28 12:36:56 +01:00
lilleman b2aa02eb22 Record the comprehension check: paired ruling same 2026-10-28 12:36:47 +01:00
lilleman 722dd5e451 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:33:34 +01:00
lilleman d371869f4a Answer stability round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:33:34 +01:00
lilleman 4193165c5d Answer prose round 1: 0 🔴, 2 🟡 (0 misread); put the Test command first, rewrite the changelog entry 2026-10-28 12:33:34 +01:00
lilleman 17fb0ac247 Answer principles round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:29:32 +01:00
lilleman 6ca9b4a2e7 Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:28:57 +01:00
lilleman dd4bcbd1c4 Answer principles round 1: 0 🔴, 3 🟡 (0 misread); type-check every tool for README's Python, check the worker count, pin pytest 2026-10-28 12:28:57 +01:00
lilleman 084d763412 Answer architecture round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:21:34 +01:00
lilleman d57727ec39 Answer architecture round 1: 0 🔴, 2 🟡 (0 misread); run the tests in one heavy slot's four workers, pin pytest 2026-10-28 12:21:08 +01:00
lilleman 53e663c8f8 Run the tests once, on the latest stable Python, across the CPUs 2026-10-28 12:17:05 +01:00
lilleman d7806d0b16 Merge pull request 'Report the routing figures in dollars, cache reads included, from the cost each archived run records' (#382) from item-234 into main 2026-10-28 12:10:30 +01:00
lilleman b086e7bf2a Say the routing figures now count the compaction dollars in item 235's detail 2026-10-28 12:07:03 +01:00
lilleman b6548d32e6 Merge remote-tracking branch 'origin/main' into item-234
# Conflicts:
#	todo.md
2026-10-28 12:06:47 +01:00
lilleman 6c059e0545 Answer principles round 4: 0 🔴, 0 🟡 (0 misread); drop a no-op slice in a test, keep the local defaultdicts 2026-10-28 12:06:23 +01:00
lilleman f6f21fc38c Merge pull request 'File item 245: run the tests once, on the latest stable Python, across the CPUs' (#385) from item-245 into main 2026-10-28 12:05:08 +01:00
lilleman b7cadb328e File item 245: run the tests once, on the latest stable Python, across the CPUs 2026-10-28 12:05:06 +01:00
lilleman 14ed4f9cdc Type the dollars as floats so mypy passes 2026-10-28 12:01:30 +01:00
lilleman 7daa3268da Merge pull request 'File item 244: stamp each line loop-claude prints with local time' (#384) from item-244 into main 2026-10-28 11:47:50 +01:00
lilleman 83171df2ce File item 244: stamp each line loop-claude prints with local time 2026-10-28 11:47:45 +01:00
lilleman 9b089d3c30 Merge remote-tracking branch 'origin/main' into item-234 2026-10-28 11:44:37 +01:00
lilleman 9d888c9e47 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 11:44:37 +01:00
lilleman 12e3d4ffa6 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 11:44:37 +01:00
lilleman 67e4b36dfd Answer prose round 1: 0 🔴, 7 🟡 (0 misread); reworded the comments, the intro and the changelog entry, fixed in the stability answer 2026-10-28 11:43:46 +01:00
lilleman c37c80297e Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); the intro says where a missing transcript's cost lands, fixed in the stability answer 2026-10-28 11:43:46 +01:00
lilleman 69f05a8c3c Answer stability round 1: 1 🔴, 2 🟡 (0 misread); keep f-strings 3.11-valid, count Agent calls without a transcript across subagents, pin the undated message's rung 2026-10-28 11:43:46 +01:00
lilleman bb3eb4fac6 Answer principles round 3: 0 🔴, 2 🟡 (0 misread); count lacking subagents by launches less transcripts and say the cost lands mostly on the worker 2026-10-28 11:29:01 +01:00
lilleman 7c5af45aaf Answer principles round 2: 0 🔴, 1 🟡 (0 misread); count the launched subagents the archive has no transcript of 2026-10-28 11:27:58 +01:00
lilleman 0c1e92943a Answer principles round 1: 0 🔴, 3 🟡 (0 misread); name Spent, derive cache-write prices, say a missing subagent's cost lands on the held messages 2026-10-28 11:26:12 +01:00
lilleman 6917092fd7 Merge pull request 'File item 243: answer every waiting loop-claude from one terminal app' (#383) from item-243 into main 2026-10-28 11:24:52 +01:00
lilleman 499b111071 File item 243: answer every waiting loop-claude from one terminal app 2026-10-28 11:24:40 +01:00
lilleman e83ed096c4 Report the routing figures in dollars, cache reads included, from the cost each archived run records 2026-10-28 11:21:15 +01:00
lilleman dac60ccf7b Merge pull request 'Record lilleman's choice to try one principles auditor despite the trial's two misses' (#381) from item-233 into main 2026-10-28 11:14:28 +01:00
lilleman d6ff9e26b5 Answer prose round 2: 0 🔴, 2 🟡 (0 misread); split the sentence and stop implying code health had its own auditor 2026-10-28 11:14:24 +01:00
lilleman 64a7242139 Record lilleman's choice to try one principles auditor despite the trial's two misses 2026-10-28 11:13:07 +01:00
lilleman 22265be7fd Merge pull request 'Run one principles-auditor per round for the goals and every principles file that applies' (#380) from item-233 into main 2026-10-28 10:16:32 +01:00
lilleman 31edfe0c37 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 10:16:25 +01:00
lilleman efa98dae4a Answer stability round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 10:16:25 +01:00
lilleman c31f367771 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); define a yardstick in the auditor, name the one auditor plainly in the decision's title, split and correct the trial paragraph, explain the old pass in the changelog, and name the split in item 242's tagline 2026-10-28 10:16:21 +01:00
lilleman 3af346ef75 Answer principles round 2: 0 🔴, 0 🟡 (0 misread); have item 242 also split the tests that check several behaviours 2026-10-28 10:10:10 +01:00
lilleman 9bb27ce493 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 10:08:57 +01:00
lilleman 3833c91bc0 Answer principles round 1: 0 🔴, 2 🟡 (0 misread); make the decision's validity checkable by a replay, name one auditor in its title, file item 242 for loops without subTest 2026-10-28 10:08:57 +01:00
lilleman d9b4939b99 Refresh item 155 with the latest reading-cost figures 2026-10-28 10:04:04 +01:00
lilleman 27e61c4c9d Run one principles-auditor per round for the goals and every principles file that applies 2026-10-28 10:03:54 +01:00
lilleman ba5fc55539 Record the reading cost of the last chunk 2026-10-28 10:03:53 +01:00
lilleman 31e363a469 Merge pull request 'Have the worker enter the chunk's worktree before the security pass, so the skill scans the branch's diff' (#379) from item-238 into main 2026-10-28 09:48:01 +01:00
lilleman debabc40fd Answer prose round 1: 0 🔴, 1 🟡 (0 misread); enter the worktree in §2, before the first pass 2026-10-28 09:46:06 +01:00
lilleman 44974bcd02 Have the worker enter the chunk's worktree before the security pass, so the skill scans the branch's diff 2026-10-28 09:43:39 +01:00
lilleman ecff799cb6 Merge pull request 'Record in the comment at UNFINISHED_LIMIT that the human confirmed 6' (#378) from item-59 into main 2026-10-28 09:42:21 +01:00
lilleman 15e22a79f3 Answer prose round 1: 0 🔴, 1 🟡 (0 misread); end the comment with what the human confirmed 2026-10-28 09:42:07 +01:00
lilleman 48f795b1a3 Record in the comment at UNFINISHED_LIMIT that the human confirmed 6, counting every unfinished verdict 2026-10-28 09:40:31 +01:00
lilleman 243a9d872d Merge pull request 'Stop loop-claude and ask the human after six unfinished verdicts running' (#371) from item-59 into main 2026-10-28 02:48:42 +01:00
lilleman 946815a495 Record the comprehension check: PR #371 ruled the same 2026-10-28 02:47:14 +01:00
lilleman 51faf71ecc Answer stability round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 02:45:15 +01:00
lilleman c64b3f362d Answer principles round 2: 0 🔴, 1 🟡 (0 misread); record at LoopRun why its three fields stay apart 2026-10-28 02:45:15 +01:00
lilleman 7a7528fba8 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); reword the exit-2 heading and bullet, drop the false claim of six runs, say the stop needs the human, and record at LoopRun why its fields stay apart 2026-10-28 02:45:15 +01:00
lilleman 8caf92dfbe Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); say in the comment at UNFINISHED_LIMIT that it counts every unfinished verdict 2026-10-28 02:40:46 +01:00
lilleman 4bcead0b89 Answer principles round 1: 1 🔴, 3 🟡 (0 misread); the stability round's commit fixes the import order and the untested stepped route, and folds the help test into HelpLimits; LoopRun keeps three fields since renaming one stops a running loop at its next reload 2026-10-28 02:40:46 +01:00
lilleman 2815b89589 Answer stability round 1: 1 🔴, 4 🟡 (1 misread); sort the imports, test the stop's stepped route on the ladder, fix the false archive claim, and assert the stop's facts, not its sentence 2026-10-28 02:40:46 +01:00
lilleman f41b549ff7 Merge origin/main into item-59 2026-10-28 02:24:52 +01:00
lilleman ca6bce76ce Say in the comment at UNFINISHED_LIMIT that it counts every unfinished verdict 2026-10-28 02:24:41 +01:00
lilleman 0d706c7240 Merge pull request 'Launch a round's reviewers in up to three waves, each in one message' (#377) from item-232 into main 2026-10-28 02:22:56 +01:00
lilleman 83cf3897a7 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); state the waves in the imperative, cite Done, skip a wave none of whose passes runs, narrow the claim to Agent calls, and fix the changelog's timing 2026-10-28 02:19:40 +01:00
lilleman 9accc68ec3 Launch a round's reviewers in up to three waves, each in one message, in place of one at a time 2026-10-28 02:17:15 +01:00
lilleman b23bf4f9c3 Merge pull request 'Give the worker's claude a 200k auto-compact window, from item 231's evaluation of context cost, and file items 235 to 241' (#376) from item-231 into main 2026-10-27 09:16:09 +01:00
lilleman c36d7a2f9c Answer prose round 3: 0 🔴, 8 🟡 (0 misread); put the reading rule in the worker's prompt, quote it, mark the items the decision cites, name the whole-project reading in the audit decision's title, and state each answer once 2026-10-27 09:13:00 +01:00
lilleman b46d5374ff Record lilleman's answers: merge the window, trial the reading rule as item 240, no scout for reviewers, and the audit keeps reading the project whole 2026-10-27 09:08:18 +01:00
lilleman 172e72ae07 Answer prose round 2: 0 🔴, 12 🟡 (0 misread); pair each option with its trial and put the conclusion first, tell the two read measures apart, move the security workaround into the skill, and restate items 238 to 241 2026-10-27 02:17:30 +01:00
lilleman d96e5c35ef Record the read pricing, precision and tool trials in item 231's decision, and file questions 240 and 241 2026-10-27 02:11:05 +01:00
lilleman 34a623e261 File item 239, lilleman's call: block a re-read of a file range already in context while the file is unchanged 2026-10-27 01:30:34 +01:00
lilleman b569f638ac Answer prose round 1: 0 🔴, 12 🟡 (0 misread); put the decision first in its entry, list the compact instructions, write the changelog for the public, and restate items 52, 102, 233, 235, 236 and 238 2026-10-27 01:06:24 +01:00
lilleman 34c13f97cd Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); say subagents inherit the window and how many compact, keep a reviewer's drafted findings through a compaction, move item 238 into 0.4.0 2026-10-27 00:57:56 +01:00
lilleman 2b2e18ec6d Answer stability round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-27 00:51:39 +01:00
lilleman 9abc5f4781 Answer principles round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-27 00:46:53 +01:00
lilleman 56b9077e4c Answer stability round 1: 0 🔴, 2 🟡 (0 misread); cut the help paragraph to one sentence and tie its 200k to COMPACT_WINDOW 2026-10-27 00:45:38 +01:00
lilleman 78837aabc6 Answer security round 1: 0 🔴, 0 🟡 (0 misread); file item 238, since the skill scans nothing when a subagent runs it outside the worktree 2026-10-27 00:38:12 +01:00
lilleman 23fbf853d8 Answer principles round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-27 00:35:37 +01:00
lilleman 14736e8e6e Answer principles round 1: 0 🔴, 9 🟡 (0 misread); name the 200k window's compaction point, read a compaction summary as Claude Code's, remove item 231, refresh items 234, 235, 52 and 102, file item 237 2026-10-27 00:32:10 +01:00
lilleman f2e239d111 Compact the worker's context above 200k tokens, from item 231's evaluation of context cost, and file items 235 and 236 2026-10-27 00:13:08 +01:00
lilleman aa020f15f7 Merge pull request 'Move each release forward one, and file items 231 to 234 into 0.4.0' (#375) from item-231 into main 2026-10-26 23:35:19 +01:00
lilleman a0458e0a2c Answer prose round 1: 0 🔴, 5 🟡 (0 misread); restate items 231 to 233's taglines and details 2026-10-26 23:35:12 +01:00
lilleman ea6300a432 Move each release forward one, and file items 231 to 234 into 0.4.0: context cost, parallel reviews, one principles auditor, dollar figures 2026-10-26 23:32:03 +01:00
lilleman 5a0c3f47b9 Merge pull request 'File item 230: an ambitious refactor whenever a scoring run is under 7.0' (#374) from item-230 into main 2026-10-26 22:01:34 +01:00
lilleman d66c0bb317 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); restate item 230's tagline and detail 2026-10-26 21:57:45 +01:00
lilleman cd76c1f511 Wrap item 230's detail 2026-10-26 21:55:31 +01:00
lilleman 4aa8eb9467 File item 230: an ambitious refactor whenever a scoring run is under 7.0 2026-10-26 21:47:22 +01:00
lilleman 3bde9cd6dd Merge pull request 'Cap the memory of each container a heavy command makes under run-heavy at its slot's share' (#373) from item-227 into main 2026-10-24 11:54:30 +02:00
lilleman cf961b55f0 Record the comprehension check: paired ruling same against eb7b506 2026-10-24 11:54:21 +02:00
lilleman 3ac8c79694 Answer stability round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-24 11:46:56 +02:00
lilleman 3617498f33 Answer principles round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-24 11:46:56 +02:00
lilleman ed22a48a61 Answer product-owner round 3: 0 🔴, 1 🟡 (0 misread); a call with a --memory of 0 anywhere passes through unchanged, so neither docker's -m 0 nor a container's grep -m 0 is dropped or overridden 2026-10-24 11:46:56 +02:00
lilleman 6a2f29635e Answer stability round 2: 1 🔴, 2 🟡 (0 misread); drop a --memory of 0 so the added limit stands, pin the 6m floor's edge, test env --unset, env --ignore-environment and doas, and say on Linux in the rule text 2026-10-24 11:42:53 +02:00
lilleman 594b28ff68 Answer principles round 2: 0 🔴, 1 🟡 (0 misread); the -m 1.2.3 crash was answered in the product-owner round 2 commit, which also refuses the exemption to env -i and env -u 2026-10-24 11:39:12 +02:00
lilleman 055c2d2df0 Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); a size has at most one point, so -m 1.2.3 in a container's command is no size and crashes nothing 2026-10-24 11:39:12 +02:00
lilleman c87e9f19d6 Answer stability round 1: 1 🔴, 5 🟡 (0 misread); the 🔴, the rule text and the PATH half of the exemption were answered in the principles round 1 commit; exempt no docker under sudo or doas, test unknown memory and the shim without a share, keep helped beside unlimited, drop a dead fallback 2026-10-24 11:37:08 +02:00
lilleman e551a2b5a9 Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-24 11:31:10 +02:00
lilleman 487adc2091 Answer prose round 1: 0 🔴, 10 🟡 (0 misread); answered in the principles round 1 commit: the decision title says where the rule passes, the help lists the cap's cases, the rule text names the run-heavy exemption, and the docstrings, CLAUDE.md, reviewer step, README and changelog say what a reader does 2026-10-24 11:31:10 +02:00
lilleman a12e68fa61 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); answered in the principles round 1 commit: a memory option below docker's 6m floor, such as grep -m 1, belongs to the container's command, and run-heavy adds its docker only where PATH finds a real one 2026-10-24 11:31:10 +02:00
lilleman 2fa328a406 Answer principles round 1: 0 🔴, 4 🟡 (0 misread); exempt only a bare docker under run-heavy with no PATH of its own, drop the stale item citation, unit-test the slot share in MiB, place the limits by the subcommand's index; also a named Option, exit 126, clearer names and the launcher's import order 2026-10-24 11:31:10 +02:00
lilleman 2eb6fc828f Answer architecture round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-24 11:26:42 +02:00
lilleman 5649331a5e Answer architecture round 2: 0 🔴, 1 🟡 (0 misread); capped adds only the limit a container lacks and removes only an unset or unlimited swap, so a size in the container's own command stays 2026-10-24 11:25:58 +02:00
lilleman 52641079b7 Answer architecture round 1: 0 🔴, 3 🟡 (0 misread); keep the slot's share beside ROOM_SHARE in machine_load, move the rule's predicate into rule_hook, and have capped set both limits itself instead of leaning on docker taking the last option 2026-10-24 11:24:21 +02:00
lilleman 4c1ab3f185 Cap the memory of each container a heavy command makes under run-heavy at its slot's share, and have stability-reviewer size a mutation run's concurrency to fit it 2026-10-24 01:06:56 +02:00
lilleman eb7b50698c Merge pull request 'Block a docker run or docker create that sets no memory limit, and read docker's TLS and buildx --builder options as taking a value' (#372) from item-228 into main 2026-10-24 01:00:41 +02:00
lilleman 7fb8c61c5e Say in README why docker_command.py sits at bin's root 2026-10-24 01:00:35 +02:00
lilleman f4d25691d6 Record the comprehension check: paired ruling better against d1733a2 2026-10-24 01:00:31 +02:00
lilleman 899e8ed55c Answer principles round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-24 00:47:57 +02:00
lilleman a622d19280 Answer stability round 3: 0 🔴, 1 🟡 (0 misread); test that a size after the image's command is no limit; name given's regex parameter pattern 2026-10-24 00:47:57 +02:00
lilleman e17ed74fc2 Answer stability round 2: 0 🔴, 2 🟡 (0 misread); --memory-swap -1 was answered in the principles round 2 commit, and requiring a swap limit stays, as the decision says docker's default swaps as much again as the limit; test a --help past the image 2026-10-24 00:45:13 +02:00
lilleman e1a67eff2a Answer principles round 2: 0 🔴, 1 🟡 (0 misread); a swap limit is a size other than 0, so --memory-swap -1 is no limit, read like the memory limit and not from any word; the docstrings and changelog name both limits 2026-10-24 00:44:13 +02:00
lilleman 1ae4018101 Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-24 00:42:39 +02:00
lilleman 951f166c79 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); answered in the product-owner round 1 commit: -m and --memory count only with a size 2026-10-24 00:42:39 +02:00
lilleman e2606b8dab Answer prose round 1: 0 🔴, 6 🟡 (0 misread); answered in the principles round 1 commit: the shipped items leave the plan, the decision names Bash commands, compose and its scripts, splits the cgroup-parent sentence, item 227 names each machine load decision in full, and the docstrings say what -m and --help do 2026-10-24 00:42:39 +02:00
lilleman 196abe18a9 Answer principles round 1: 0 🔴, 5 🟡 (0 misread); require a swap limit beside the memory limit, ask in CLAUDE.md for both where rule-hook can't see the container, remove items 225 and 228 with a changelog entry; the -m finding was answered in the product-owner round 1 commit 2026-10-24 00:42:39 +02:00
lilleman 2d219ff6c8 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); read -m and --memory as a limit only with a size, so python -m pytest in the container is no limit, and read timeout as a launcher; also take the technical principles' nits: --help counts only beside docker's subcommand, sort STARTS_CONTAINER, print the example limit once, and name item 227 in the decision 2026-10-24 00:36:19 +02:00
lilleman 500e2c2947 Answer architecture round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-24 00:32:30 +02:00
lilleman f7ad418b20 Name the launcher reading in shell_command's docstring 2026-10-24 00:32:30 +02:00
lilleman a292ec4cae Answer architecture round 1: 0 🔴, 3 🟡 (0 misread); move docker's parsing to bin/ for item 227's shim, read launchers once in shell_command.launched, and give the memory limit its own decision, sized to what the work needs 2026-10-24 00:31:41 +02:00
lilleman 7b61fd5b4b Sort rule_hook's imports by their first binding 2026-10-24 00:18:50 +02:00
lilleman b6d8fe48af Record the reading cost of the chunks before item 228, and refresh item 155 with its rise 2026-10-24 00:16:05 +02:00
lilleman fbaa3075c4 Block a docker run or docker create that sets no memory limit, and read docker's TLS and buildx --builder options as taking a value 2026-10-24 00:15:44 +02:00
lilleman b6954e5aa7 File items 227 and 228: cap a heavy command's containers at its slot's memory share, and block a docker run without a memory limit 2026-10-24 00:13:26 +02:00
lilleman 2135afe8d7 Answer architecture round 1: 1 🔴, 4 🟡 (0 misread); share the stop archiving, fix the limit at 6, reword the exit-2 contract, close the cycle in one step 2026-10-23 15:09:46 +02:00
lilleman 008c187192 Stop loop-claude and ask the human after six unfinished verdicts running 2026-10-23 15:06:10 +02:00
lilleman 4fa114905a Record reading cost for PR #370 2026-10-23 15:06:10 +02:00
lilleman d1733a2d8d Merge pull request 'Move the run-heavy rule's command parsing into its own module' (#370) from item-223 into main 2026-10-23 14:50:23 +02:00
lilleman 2249655796 Record the comprehension check: PR #370 ruled better 2026-10-23 14:49:23 +02:00
lilleman 686c1dc7a4 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:46:30 +02:00
lilleman c70dda6bd9 Answer principles round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:46:30 +02:00
lilleman bd00eee3ca Answer prose round 1: 0 🔴, 1 🟡 (0 misread); reword two comments, rename docker_at, file the DOCKER_VALUED gap as item 225 2026-10-23 14:45:45 +02:00
lilleman fc38e80591 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:45:45 +02:00
lilleman f94f23a3d7 Answer stability round 1: 1 🔴, 0 🟡 (0 misread); the import sort of the principles round answers it 2026-10-23 14:45:45 +02:00
lilleman 6ea148bdf4 Answer principles round 1: 1 🔴, 0 🟡 (0 misread); sort the heavy_command import before review_folder 2026-10-23 14:45:45 +02:00
lilleman ff3babef74 Answer architecture round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:36:16 +02:00
lilleman 578de9231f Move the run-heavy rule's command parsing into its own module and pick docker's position without a nested conditional 2026-10-23 14:35:06 +02:00
lilleman 2558a6ad7e Record the last chunk's reading cost 2026-10-23 14:35:06 +02:00
lilleman eb1c302553 Merge pull request 'Renumber the decision-paragraph split from item 222 to 224, which item-222's chunk had also used' (#369) from item-224 into main 2026-10-23 14:33:32 +02:00
lilleman 1895bbbad5 Answer prose round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:33:25 +02:00
lilleman 620590cf24 Renumber the decision-paragraph split from item 222 to 224, which item-222's chunk had also used 2026-10-23 14:32:54 +02:00
lilleman 64d438681e Merge pull request 'Hold each heavy command for one of a heavy slot per 4 CPUs, and each worker until a quarter of memory is available' (#366) from item-222 into main 2026-10-23 11:56:55 +02:00
lilleman 5f54116696 Merge remote-tracking branch 'origin/main' into item-222
# Conflicts:
#	CHANGELOG.md
#	README.md
#	docs/comprehension-history.md
#	todo.md
2026-10-23 11:53:36 +02:00
lilleman 065a0d2d3f File item 223: move the run-heavy rule's command parsing into its own module 2026-10-23 11:52:41 +02:00
lilleman 83c0f268d4 Record the comprehension check: paired ruling same against 4a0ba59 2026-10-23 11:52:41 +02:00
lilleman fd60b6da97 Merge pull request 'Count, per finished chunk, the findings that arose from misreading code that had already shipped' (#368) from item-198 into main 2026-10-23 11:51:22 +02:00
lilleman 91f328e8de Record the comprehension check: paired ruling better against 4a0ba59 2026-10-23 11:51:12 +02:00
lilleman 5e7e3649c6 Answer overrides round 3: 0 🔴, 0 🟡 (0 misread); all four overrides accepted, later round 3 commits ruled on ahead 2026-10-23 11:49:30 +02:00
lilleman 2bbfb90936 Answer product-owner round 3: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 11:49:30 +02:00
lilleman 29715fcd2a Answer stability round 3: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 11:49:30 +02:00
lilleman ff08f496cb Answer principles round 3: 0 🔴, 0 🟡 (0 misread); rename two tests to what they check 2026-10-23 11:49:30 +02:00
lilleman e05c54aad0 Merge remote-tracking branch 'origin/main' into item-222 2026-10-23 11:45:57 +02:00
lilleman 203049f4c3 Answer prose round 1: 0 🔴, 9 🟡; reword the decision, the rule's help, run-heavy's help and the reviewer's step 4, and drop -h from the light flags 2026-10-23 11:45:53 +02:00
lilleman ef392502ba Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); all six overrides accepted 2026-10-23 11:45:40 +02:00
lilleman 222ee12e09 Answer stability round 2: 0 🔴, 2 🟡 (0 misread); both answered in the principles and product-owner answers 2026-10-23 11:45:40 +02:00
lilleman 73b9eec07c Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); head the list as findings with their misread count 2026-10-23 11:45:40 +02:00
lilleman 9aa174d511 Answer principles round 2: 0 🔴, 1 🟡 (0 misread); say in rule-hook's refusal that the misread count is at most the findings, and move a stray assertion back 2026-10-23 11:45:40 +02:00
lilleman 2d2371766d Answer product-owner round 1: 0 🔴, 0 🟡; name the slot folder and fuser in the wait message, keep help calls light, and give the reviewer's suite the long timeout 2026-10-23 11:43:10 +02:00
lilleman 477772d7a5 Answer prose round 1: 0 🔴, 12 🟡 (0 misread); reword the decision, the Misread section and the comments, mark item 110 decision, file item 222 2026-10-23 11:40:38 +02:00
lilleman 9d4d6ee401 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); spell each chunk's line as round titles do, and say where the list sits 2026-10-23 11:40:38 +02:00
lilleman bac9dd54bc Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); both overrides accepted 2026-10-23 11:40:38 +02:00
lilleman 13447388a2 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 11:40:38 +02:00
lilleman 779d05886b Answer stability round 1: 0 🔴, 1 🟡 (0 misread); the three repeated tests went in the principles answer 2026-10-23 11:40:38 +02:00
lilleman 1e225c4397 Answer principles round 1: 0 🔴, 3 🟡 (0 misread); refuse a misread count above the findings, share the lower-bound rule, name score-outcomes' new list in the README 2026-10-23 11:40:38 +02:00
lilleman a68f6a781d Answer overrides round 1: 0 🔴, 0 🟡 2026-10-23 11:39:51 +02:00
lilleman ef33efd2e4 Answer stability round 3: 0 🔴, 0 🟡 2026-10-23 11:39:14 +02:00
lilleman 44305e6f8d Answer principles round 4: 0 🔴, 0 🟡 2026-10-23 11:38:24 +02:00
lilleman 1d3b928bdb Answer architecture round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 11:30:54 +02:00
lilleman 80cc36e904 Answer architecture round 1: 0 🔴, 2 🟡 (0 misread); read a round title's counts once, into one Counts value 2026-10-23 11:30:17 +02:00
lilleman 4d18b8e125 Count, per finished chunk, the findings that arose from misreading code that had already shipped 2026-10-23 11:23:44 +02:00
lilleman e00eb558c2 Append the reading-cost figure 2026-10-23 11:23:44 +02:00
lilleman 4a0ba59210 Merge pull request 'Give "record", "outcome" and "places" one meaning each across bin/, and rename larv_review/git.py by what it holds' (#367) from item-125 into main 2026-10-23 11:16:34 +02:00
lilleman 447668865d Record the comprehension check: paired ruling better against dcbdc97 2026-10-23 11:16:21 +02:00
lilleman 27d778ed81 Answer stability round 2: 0 🔴, 2 🟡; the docker fix and the echo and bare env cases landed with principles round 3 2026-10-23 11:14:03 +02:00
lilleman 1d00bfd1ef Answer principles round 3: 0 🔴, 2 🟡; find docker past a launcher's own options, as for a mutation tool 2026-10-23 11:14:03 +02:00
lilleman 5a56fff040 Answer principles round 2: 0 🔴, 0 🟡; call the loop index index, clear of the imported position 2026-10-23 11:10:51 +02:00
lilleman bd64bd59c2 Answer stability round 1: 0 🔴, 2 🟡; the two hard places it touches change by one word, settled in the PR summary 2026-10-23 11:09:51 +02:00
lilleman dd9dda8f69 Answer security round 1: 0 🔴, 0 🟡; nothing to change 2026-10-23 11:09:51 +02:00
lilleman e3566f694a Answer prose round 1: 0 🔴, 4 🟡; correct the decision's counts and wording, and call the archived route a worker line in item 218 2026-10-23 11:09:51 +02:00
lilleman 21d507f0c5 Answer principles round 1: 0 🔴, 1 🟡; give the true reason score-outcomes keeps its name, name archived_kind and three locals by what they hold 2026-10-23 11:09:51 +02:00
lilleman 792fa2b8b0 Answer stability round 1: 0 🔴, 5 🟡; test the lock-error and slot-folder exits and the default folder, and return a Failure from held_slot 2026-10-23 11:06:55 +02:00
lilleman dde9caa172 Answer principles round 2: 0 🔴, 2 🟡; have rule-hook read docker's subcommand and the tool inside docker run or exec, and pass a run-heavy behind a launcher 2026-10-23 11:06:55 +02:00
lilleman c7dbd56f39 Answer principles round 1: 0 🔴, 5 🟡; enforce run-heavy in rule-hook, take slots through one tested function, exit 125 on lock errors, fake meminfo in black-box tests 2026-10-23 10:55:55 +02:00
lilleman 504aa31bdb Answer architecture round 2: 0 🔴, 0 🟡; nothing to change 2026-10-23 10:55:05 +02:00
lilleman 387a5ce506 Answer architecture round 1: 0 🔴, 2 🟡; finish "record", record the three meanings as a decision, name rule-hook's check once 2026-10-23 10:54:24 +02:00
lilleman 6725ee4c9d Answer security round 1: 0 🔴, 0 🟡 2026-10-23 10:48:39 +02:00
lilleman 6ff77f7049 Answer architecture round 2: 0 🔴, 0 🟡 2026-10-23 10:47:49 +02:00
lilleman 66af309e71 Answer architecture round 1: 0 🔴, 3 🟡; keep the slots and the memory share in machine_load, exit 125/126/127 as GNU wrappers do, point --help at the module 2026-10-23 10:47:01 +02:00
lilleman 8d2a1cf9fd Give "record", "outcome" and "places" one meaning each across bin/, and rename larv_review/git.py by what it holds 2026-10-23 10:42:06 +02:00
lilleman 7c05bf414c Append the reading-cost figure 2026-10-23 10:41:12 +02:00
lilleman 6c823de29c Hold each heavy command for one of a heavy slot per 4 CPUs, and each worker until a quarter of memory is available 2026-10-23 10:40:57 +02:00
lilleman 9df08bd41e Merge pull request 'Keep item 218 blocked on item 170 whether or not 170 changes the routing steps' (#365) from item-218 into main 2026-10-23 10:28:39 +02:00
lilleman f20d1799c3 Answer prose round 1: 0 🔴, 1 🟡; say item 218 waits for item 170 whether or not 170 changes the steps 2026-10-23 10:28:35 +02:00
lilleman 1b7d5244b1 Keep item 218 blocked on item 170 whether or not 170 changes the routing steps 2026-10-23 10:27:09 +02:00
lilleman e923534fc9 Merge pull request 'Keep the routing steps as they are, and re-tune them once 50 chunks have shipped under them' (#364) from item-170 into main 2026-10-23 10:25:15 +02:00
lilleman c8d97fb516 Answer prose round 1: 0 🔴, 4 🟡; state the 15 chunks and the 50-chunk threshold once, and drop the worker's move of the item 2026-10-23 10:24:44 +02:00
lilleman e92bde2bd3 Keep the routing steps as they are, and re-tune them once 50 chunks have shipped under them 2026-10-23 10:22:12 +02:00
lilleman 7a4ac91597 Merge pull request 'Say in larv-review's skill that the auto-reviewer's round commit takes no round title' (#363) from item-216 into main 2026-10-23 05:39:16 +02:00
lilleman b68b1b60ac Answer prose round 1: 0 🔴, 2 🟡; move the auto-reviewer's commit rule into its bullet and say what title it takes 2026-10-23 05:36:05 +02:00
lilleman 2317ed4c90 Say in larv-review's skill that the auto-reviewer's round commit takes no round title 2026-10-23 05:34:08 +02:00
lilleman 65a0433deb Record the reading cost of the last finished chunk 2026-10-23 05:34:08 +02:00
lilleman ad6e6898c2 Merge pull request 'Sort the decision log by title, and rewrite its six amendment-log entries as the current state' (#362) from item-82 into main 2026-10-23 05:33:11 +02:00
lilleman 22e2c22b8f Answer prose round 1: 1 🔴, 6 🟡; restore the lost reasons, mark the unbuilt scoring parts, and name who ruled 2026-10-23 05:33:02 +02:00
lilleman e452b0c55e Sort the decision log by title, and rewrite its six amendment-log entries as the current state 2026-10-23 05:29:51 +02:00
lilleman dcbdc970a6 Merge pull request 'Hold the escalation mark in one module, and carry a ruling's step-up through the cycle's states' (#361) from item-210 into main 2026-10-23 05:24:55 +02:00
lilleman 0b1289cb33 Record the comprehension check: paired ruling better against 39dd51b 2026-10-23 05:24:46 +02:00
lilleman 6f98a1855b Answer prose round 1: 0 🔴, 5 🟡; tighten the escalation mark's comments, item 221's detail, and fold three decision entries into item 190 2026-10-23 05:22:15 +02:00
lilleman d70cbca594 Answer stability round 2: 0 🔴, 0 🟡; approved 2026-10-23 05:09:15 +02:00
lilleman 6733615e1c Answer principles round 2: 0 🔴, 0 🟡; approved, file item 221 and fix two blank-line nits 2026-10-23 05:09:15 +02:00
lilleman 92afe2ac08 Answer stability round 1: 0 🔴, 2 🟡; assert the mark-0 transcript and underscore emphasis, in f781ac6 2026-10-23 05:07:36 +02:00
lilleman fa2024c09f Answer security round 1: 0 🔴, 0 🟡; no findings 2026-10-23 05:07:30 +02:00
lilleman f781ac611b Answer principles round 1: 0 🔴, 1 🟡; rename the module escalation_mark.py so it no longer shares the escalation field's name 2026-10-23 05:07:30 +02:00
lilleman aebd92de43 Answer architecture round 2: 0 🔴, 0 🟡; approved 2026-10-23 04:55:50 +02:00
lilleman bf8b642ead Answer architecture round 1: 0 🔴, 2 🟡; rename Step to StepUp and let escalation.py own the judge's step-line sentence 2026-10-23 04:54:45 +02:00
lilleman f0e14f3fdf Hold the escalation mark in one module, and carry a ruling's step through the cycle's states 2026-10-23 04:45:03 +02:00
lilleman 4764d3d522 Merge pull request 'Have rule-hook refuse a round commit past round 3 unless an override quotes the human answer' (#360) from item-214 into main 2026-10-23 04:32:34 +02:00
lilleman ef12b17d8b Answer prose round 1: 0 🔴, 0 🟡; tighten the changelog, decision and item 220 wording 2026-10-23 04:29:37 +02:00
lilleman 9f044044ab Answer stability round 2: 0 🔴, 0 🟡; approved 2026-10-23 04:27:25 +02:00
lilleman a85b0a44d5 Answer principles round 2: 0 🔴, 0 🟡; approved 2026-10-23 04:27:25 +02:00
lilleman a99a98c504 Answer stability round 1: 0 🔴, 1 🟡; test the checkout a round-cap breach names 2026-10-23 04:23:52 +02:00
lilleman dceff3c985 Answer principles round 1: 1 🔴, 0 🟡; file the title-only count as item 220 and cite it in the decision 2026-10-23 04:23:52 +02:00
lilleman 1a83c13eb9 Have rule-hook refuse a round commit past round 3 unless an override quotes the human answer 2026-10-23 04:15:52 +02:00
lilleman 39dd51bb44 Merge pull request 'Split review_launches into model_routing's choice of each review's rung and whole prompt sentences that render it' (#359) from item-212 into main 2026-10-23 04:06:02 +02:00
lilleman 66a12bd806 Record the comprehension check: ruling better for PR #359 2026-10-23 04:05:52 +02:00
lilleman 72a63c5ade Answer product-owner round 1: 0 🔴, 0 🟡; approved 2026-10-23 04:03:31 +02:00
lilleman a0780ca0bd Answer stability round 3: 0 🔴, 0 🟡; approved 2026-10-23 04:03:31 +02:00
lilleman 5732b898a6 Answer principles round 3: 0 🔴, 0 🟡; approved 2026-10-23 04:03:31 +02:00
lilleman a225166956 Answer principles round 2: 0 🔴, 1 🟡; the 🟡 is answered by the stability round 2 fix 2026-10-23 03:53:14 +02:00
lilleman 7c42f038ac Answer prose round 1: 0 🔴, 4 🟡; reword the docstrings and comments the pass found false or hard to read, and add a changelog line 2026-10-23 03:53:14 +02:00
lilleman f58fe5a9db Answer stability round 2: 0 🔴, 1 🟡; name when a replay applies in ladder.py and have chosen find the higher E + I that end it, so a top-rung project keeps them 2026-10-23 03:53:14 +02:00
lilleman 28b64042ba Answer stability round 1: 0 🔴, 2 🟡; find the higher E + I that move the reviewers by their rung alone, and keep the choice's tests the prompt tests do not repeat 2026-10-23 03:46:01 +02:00
lilleman 061b32dd66 Answer principles round 1: 0 🔴, 2 🟡; drop the stale clause from item 174, point --help at review_choice.py, and tidy the new module's docstring, imports and comments 2026-10-23 03:45:46 +02:00
lilleman 061118be0b Answer architecture round 1: 0 🔴, 1 🟡; give a chunk no item routed the same rung sentences as its resumed prompt, and sort the new modules' imports 2026-10-23 03:37:12 +02:00
lilleman 28da11dd8d Split review_launches into model_routing's choice of each review's rung and whole prompt sentences that render it 2026-10-23 03:32:47 +02:00
lilleman a351ba8a33 Merge pull request 'State each routing rule once in the docstring of the code that enforces it, cut loop-claude --help's routing paragraph, and name the project's rung project in bin/loop_claude' (#358) from item-211 into main 2026-10-23 03:21:06 +02:00
lilleman a4071f59ce Answer prose round 1: 0 🔴, 1 🟡; state the help's step-up rule as the code holds it, and reword the docstrings and the changelog entry 2026-10-23 03:20:54 +02:00
lilleman 372cfa7535 File item 219 to name the project's rung project in the three tools outside bin/loop_claude 2026-10-23 03:12:39 +02:00
lilleman 2f03ba1a77 Answer product-owner round 2: 0 🔴, 0 🟡; approved 2026-10-23 03:11:41 +02:00
lilleman 5b615ef46e Answer stability round 2: 0 🔴, 0 🟡; approved 2026-10-23 03:11:41 +02:00
lilleman 058ec1da4f Answer principles round 2: 0 🔴, 0 🟡; approved 2026-10-23 03:11:41 +02:00
lilleman 038ef6e732 Answer stability round 1: 0 🔴, 4 🟡; test the escalation sentence on the second-highest rung, and the docstring and judge_rung fixes came in the principles round 2026-10-23 03:10:31 +02:00
lilleman a81f878f92 Answer principles round 1: 0 🔴, 5 🟡; make the routing.py and prompts.py module docstrings true and short, drop the routing_check copy of the figures, rename judge_rung's local, and keep the help's 20 2026-10-23 03:10:31 +02:00
lilleman aa9a4cb78b Answer product-owner round 1: 0 🔴, 1 🟡; keep the help's rung definition and the routing qualifier 2026-10-23 03:10:31 +02:00
lilleman 3b69ced357 State each routing rule once in the docstring of the code that enforces it, cut loop-claude --help's routing paragraph, and name the project's rung project in bin/loop_claude 2026-10-22 22:42:01 +02:00
lilleman 545ab3ab37 Merge pull request 'Archive the route as a JSON record loop-claude reads back field by field, and name the stepping functions and the judge's taken-in levels by what they do' (#357) from item-137 into main 2026-10-22 22:32:32 +02:00
91 changed files with 3493 additions and 1238 deletions
+8
View File
@@ -25,6 +25,7 @@
!bin/claude_code/
!bin/claude_code/*.py
!bin/comprehension_history.py
!bin/docker_command.py
!bin/failure.py
!bin/file_writes.py
!bin/git_command.py
@@ -39,6 +40,8 @@
!bin/loop_claude/
!bin/loop_claude/**/
!bin/loop_claude/**/*.py
!bin/machine_load/
!bin/machine_load/*.py
!bin/markdown_text.py
!bin/metric-bench
!bin/metric_bench/
@@ -65,6 +68,11 @@
!bin/rule_hook/*.py
!bin/rung_replay/
!bin/rung_replay/*.py
!bin/run-heavy
!bin/run_heavy/
!bin/run_heavy/*.py
!bin/run_heavy/path_entry/
!bin/run_heavy/path_entry/docker
!bin/score-outcomes
!bin/score_outcomes/
!bin/score_outcomes/*.py
+41 -36
View File
@@ -2,55 +2,60 @@
Decisions live in `docs/decisions.md`:
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
- 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 it opens claude on the terminal, 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/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names
- bin/: the tools and their tests run on the host's Python, with no container
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
- chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
- 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 reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge
- review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
- review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
- 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, and a project opting out of the comprehension check voids code health
- review: the principles audit runs on every chunk that changes code, config or tests, and on no other chunk
- 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
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
- loop-claude: a `claude` that cannot start is a failed worker run, retried
- review: an ask no user answers leaves the PR unmerged
- 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: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
- loop-claude: every claude it starts bypasses permissions inside its sandbox
- review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
- review: the premises chunk's whole review is the human's approval
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
- settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
- 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
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
- loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` → "Compact instructions" says what the summary keeps
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
- machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
- reading cost and `score-outcomes`: each waits for 10 finished chunks before it shows a median
- 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/`
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
- 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
- review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
- review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
- review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human
- 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
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
- review: a project decision may suspend the comprehension check for the plan items it names
- review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge
- review: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
- review: an ask no user answers leaves the PR unmerged
- review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`
- review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose
- review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
- review: the premises chunk's whole review is the human's approval
- review: the principles audit runs on every chunk that changes code, config or tests, reads the project whole with one auditor checking the goals and every principles file that applies, and runs on no other chunk
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
- routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
- routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass; the seats and the security pass always on the project's
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
- routing: loop-claude measures review rounds and unfinished verdicts per rung every 20 cycles, and calls for a routing change when, of two rungs with 5 or more chunks each, the lower took more of either than the one above, or when 5 or more subagents of one type had reports longer than the tool results they read
- routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
- routing: a worker delegates a task only where it needs just the task's conclusion, and each subagent runs on the rung its task's L picks from the project's rung, never below the project's rung when it files or scores todo.md items
- routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it
- routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, steps one rung up as the judge interrupts or quotes an answer, or next cycle, up to two rungs above the rung its item picks
- routing: loop-claude measures review rounds and unfinished verdicts per rung every 20 cycles, and calls for a routing change when, of two rungs with 5 or more chunks each, the lower took more of either than the one above, or when 5 or more subagents of one type had reports longer than the tool results they read
- routing: on a model judge-replay covered, the judge runs on the rung a review would get from the highest E + I among its chunk's items, never below the project's rung
- routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
- chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
- routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
- 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
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
- settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
- 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/`
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
## Working rules
+20
View File
@@ -2,6 +2,26 @@
## Unreleased
- rule-hook has a new rule, `repeat-read`, and now runs before each Read call too. It blocks a Read, or a Bash `cat`, `head` or `sed -n '<A>,<B>p'` of one file, when every line it asks for is already in the agent's context, and the block names those lines. The rule takes no override.
- A line is in context when an earlier read's result in the agent's own transcript showed it since the last compaction, as the file holds it now. A subagent is judged on its own transcript, not its session's.
- A read goes through when it asks for a line no earlier read showed, or one that changed since. A Bash output that Claude Code cut short shows no lines.
- A Read also goes through until the agent has read the file with Read or written it with Edit, MultiEdit or Write, and again once the file changed after that. Edit, MultiEdit and Write refuse the file until then, and a Bash read does not count.
- Where the context lacks lines the transcript shows, as after Claude Code cleared old tool results, `grep -n '' <file> | sed -n '<A>,<B>p'` reads them.
- Install the latest stable Python, today 3.14, as `python3`: the tools and their tests no longer support 3.11 to 3.13. A full test run now takes about 29 s, where it took about 3.3 minutes. It runs once, on that Python, in four pytest-xdist workers, where it used to rerun the whole suite on 3.11.
- `routing-figures.md` now reports dollars by project, subagent type, rung and tool, in place of tokens. Cache reads are included; the tokens left them out, though they were about a quarter of the cost. The dollars are what each worker transcript's last `cost-state` entry records for each model, split across the messages of the worker and its subagents in proportion to their cost at list prices. The judge's runs are not counted, since the archive doesn't hold them.
- larv-review's principles pass now launches one auditor per round, which checks the README's goals, code health and every principles file that applies, so it reads the project once per round. It used to launch one auditor for the goals with code health and one for each principles file, each reading the whole project. Its report is `principles-round-<n>.md`, like every other pass's.
- A session running larv-review now enters the chunk's worktree with `EnterWorktree` before the first review pass, so `/security-review` and the full scan read the branch's diff. Run from the checkout root, they used to find it empty.
- `loop-claude` now stops with exit 2 when the judge rules one chunk unfinished 6 cycles running, so a worker and a judge that disagree can no longer cycle unattended without end. Rerunning resumes the chunk and gives it 6 more cycles.
- larv-review now launches a round's reviewers in up to three waves, each wave's reviewers in one message, in place of one reviewer at a time: first the architect, then the principles auditor with the security and overrides passes, then the stability, product-owner and prose passes. Each wave now lasts as long as its slowest reviewer, where a round used to last as long as all its reviewers one after another.
- loop-claude's worker, and every subagent it launches, now run with a 200k auto-compact window, handed as `CLAUDE_CODE_AUTO_COMPACT_WINDOW`: Claude Code compacts their context at about 170k tokens, where it used to let it grow to about 967k. loop-claude's judge no longer reads a compaction summary as words you typed. `CLAUDE.md` has a new section, "Compact instructions", saying what a summary keeps.
- On Linux, `run-heavy` now caps the memory of a container its command makes with `docker run` or `docker create`. A container that sets no limit gets a memory limit and a swap limit, both the slot's share: three quarters of the machine's memory, split across the heavy slots. A container that sets one of the two limits keeps it, and gets the other as large. This covers containers a project's own scripts start, which rule-hook can't see. A `docker compose` service, and a docker named by its full path, get no cap. rule-hook's `docker-run-memory` now lets a `docker run` under run-heavy pass.
- rule-hook has a new rule, `docker-run-memory`. It blocks a `docker run` or `docker create` that lacks a memory limit or a swap limit, such as `--memory 4g --memory-swap 4g`, sized to what the work needs. `--memory-swap -1`, unlimited swap, counts as none. `CLAUDE.md` asks for the same limits on a container a script or a compose file starts, which rule-hook can't see. rule-hook's `run-heavy` rule also now reads docker's `--tlscacert`, `--tlscert`, `--tlskey` and buildx's `--builder` as options that take a value, and reads `docker container run` as a run: `docker --tlscacert ca.pem build .` was not blocked outside run-heavy before.
- Reviewers now mark a 🔴 or 🟡 `[misread]` where it arose because the implementer misread code that had already shipped. A round's commit title now counts the marked findings, as in `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, and rule-hook's `round-title-counts` blocks a round title without that count. `score-outcomes` shows the count on each finished item, and lists it after the medians for each chunk whose round titles carry it, newest first. A chunk whose round titles predate this change reads as unknown.
- Sessions running at once no longer starve the machine. A new tool, `run-heavy <command>`, runs a heavy command, such as a full gate, mutation tests, an e2e run or a `docker build`, once it holds one of the machine's heavy slots: one per 4 CPUs, shared by every session. `CLAUDE.md` has every session run its heavy commands under it, and rule-hook blocks a `docker build` or a mutation run outside it. loop-claude now waits to start a worker while less than a quarter of the machine's memory is available.
- larv-review's skill now says a commit answering the external auto-reviewer takes no `Answer <pass> round` title, and that `larv-review round-count` doesn't list the auto-reviewer. A worker who followed the skill used to get a "not a pass" warning.
- rule-hook now blocks a larv-review round commit titled past round 3, such as `Answer stability round 4: …`, unless a `round-cap` override quotes the human's yes.
- loop-claude's first prompt for a chunk that no plan item routed now also names the rung on which the worker launches its reviews for an item it takes in, as the prompt after a step-up or an unfinished verdict already did.
- `loop-claude --help` now describes routing in two short paragraphs for the person running the loop. The rules it used to repeat are now stated once, in the code that enforces them.
- loop-claude now archives the route on each `Worker:` line as a JSON record, such as `{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 12}`, and reads it back field by field. The line used to be a sentence, such as `claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5`, which loop-claude parsed back word for word: rewording the sentence in the code would have made every archived line unreadable, and a rerun would have routed the open chunk afresh. A rerun and the routing figures still read the sentences archived since loop-claude routed on L. A rerun that finds a `Worker:` line it can't read now says so on stderr. The judge's reply now names the levels the worker took in `highest_likelihood_taken_in` and `highest_escape_and_impact_taken_in`, in place of `bundled` and `bundled_escape_and_impact`.
- A chunk now takes every unblocked item of its release that fires the same review passes, whatever its purpose: one PR title no longer has to state what the items achieve together. An item with R above 5 ships alone. `chunk-preflight` says so for such an item, and never lists one as an item that may join another.
- A branch whose name is not UTF-8 now shows no branch in the status line, in place of a name with replacement characters.
+15
View File
@@ -65,6 +65,8 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
- Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along.
- 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 every container you start a memory limit and a swap limit, as large as its work needs: `--memory 4g --memory-swap 4g` on `docker run`, or `mem_limit` and `memswap_limit` in a compose file, scripts included. rule-hook checks only the `docker run` and `docker create` in your Bash commands.
- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run it in the background, since the wait can outlast the Bash tool's timeout.
- Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's L as for a `todo.md` item; a task that changes no file, such as a search, is L 1. `<model>` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits:
1. A reviewer, a comprehension seat or the security pass: those loop-claude's prompt gives it. Given none, pass no model or effort, so it runs on your model.
2. An escalated task, below: the rung loop-claude's prompt names for escalation, or case 3's rung where the subagent files or scores `todo.md` items and that rung is higher.
@@ -102,6 +104,19 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
- **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.
- 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.
## Compact instructions
Claude Code reads this section by its heading when it compacts a conversation. Keep in the summary:
- what remains before the chunk is finished;
- the task loop-claude gave, and each `todo.md` item the chunk takes with its L and E + I;
- the worktree, branch and PR;
- the rung loop-claude named for each review launch, rerun and escalated subagent;
- each review pass's rounds so far, each open 🔴 and 🟡, and how the answered ones were answered;
- every question the human answered, with the answer;
- each escalation trigger that fired;
- for a reviewer or comprehension seat, every finding and place it has drafted.
## Vocabulary
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
+9 -8
View File
@@ -47,7 +47,7 @@ git remote add origin ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git
Then run Update's commands, skipping `git add settings.json`: the new repository tracks no file yet.
Have Python 3.11 or newer as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
Have the latest stable Python, today 3.14, as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
```sh
claude plugin marketplace add anthropics/claude-plugins-official
@@ -103,28 +103,29 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `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.
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
- `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, Write and Agent call, and `rule-hook --help` states the rules and the override.
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; `score-outcomes --help` states the measures.
- `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 Agent, Bash, Edit, MultiEdit, Read and Write call, and `rule-hook --help` states the rules and the override.
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; then each chunk's 🔴 and 🟡 findings with how many a reviewer marked `[misread]`, code health's counter-signal; `score-outcomes --help` states the measures.
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
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'`. Test the bench's git wrapper with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
Test on the host with `uvx --python "$(command -v python3)" --with pytest-xdist==3.8.0 pytest==9.2.0 -n 4 bin`. It needs `uv` on `PATH`, which fetches pytest, pytest-xdist and mypy. pytest-xdist runs the tests in four workers, one heavy slot's CPUs (`docs/decisions.md` → `bin/: the tools support only the latest stable Python, …`). `python3 -m unittest discover -s bin -p 'test_*.py'` runs the same tests one at a time. Test the bench's git wrapper with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/outcomes.py`. Leave out each test class that starts a tool's launcher through `subprocess`: a mutated module fails to load in a process mutmut did not start.
To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/results.py`. Leave out each test class that starts a tool's launcher through `subprocess`: a mutated module fails to load in a process mutmut did not start.
```ini
[mutmut]
source_paths=score_outcomes/outcomes.py
source_paths=score_outcomes/results.py
also_copy=.
pytest_add_cli_args_test_selection=score_outcomes/
pytest_add_cli_args=-k
not ScoreOutcomesTool
```
Then, in the copy: `uvx --with pytest 'mutmut>=3,<4' run && uvx --with pytest 'mutmut>=3,<4' results`, and `uvx --with pytest 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with pytest==9.2.0 'mutmut>=3,<4' results`, and `uvx --with pytest==9.2.0 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
`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`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
## Tracking a new file
+4 -3
View File
@@ -1,13 +1,14 @@
---
name: principles-auditor
description: "Use this agent for larv-review's principles pass: one yardstick checked against the whole project."
description: "Use this agent for larv-review's principles pass: the project's goals and every principles file handed to it, checked against the whole project."
tools: Read, Grep, Glob, Write
---
You check one yardstick against the whole project: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`, with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it.
You check every yardstick you are handed against the whole project, which you read once for all of them. A yardstick is either the project's goals, every goal under its `README.md` → `## Goals` with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it, or one principles file, every principle in it.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardstick, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardsticks, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
- Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why.
- A departure a `todo.md` item plans away is named with that item, not raised.
- A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the `todo.md` item that ends it. Weigh it hard: that it was decided is no reason.
- Report under one heading per yardstick.
+2 -2
View File
@@ -12,8 +12,8 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
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 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, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it 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. **Mutation-test the changed lines.** Run the project's documented mutation command, or else a widely deployed mutation tool for the language: cargo-mutants for Rust, Infection for PHP, mutmut for Python, Stryker for JavaScript and TypeScript. Limit it to the lines the change adds or modifies, through the tool's own option where it has one (cargo-mutants `--in-diff <diff file>`, Infection `--git-diff-lines`, Stryker `--mutate <file>:<lines>`); otherwise mutate only the changed files and keep only the mutants on changed lines. Run it through the project's tooling, as in step 4, on a scratch copy: the tools write files. Report its wall time and mutant count in Coverage & Verification, or why nothing was mutated. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch.
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. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. 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. Make scratch work with Bash, since Write is for your report alone. Put it 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. **Mutation-test the changed lines.** Run the project's documented mutation command, or else a widely deployed mutation tool for the language: cargo-mutants for Rust, Infection for PHP, mutmut for Python, Stryker for JavaScript and TypeScript. Limit it to the lines the change adds or modifies, through the tool's own option where it has one (cargo-mutants `--in-diff <diff file>`, Infection `--git-diff-lines`, Stryker `--mutate <file>:<lines>`); otherwise mutate only the changed files and keep only the mutants on changed lines. Run it through the project's tooling and run-heavy, as in step 4, on a scratch copy: the tools write files. Under run-heavy, a container that sets neither memory limit gets the slot's share, in MiB in `RUN_HEAVY_MEMORY`. Set the tool's concurrency so that its parallel test runs together fit in that share. Report its wall time and mutant count in Coverage & Verification, or why nothing was mutated. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch.
6. **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).
+28 -2
View File
@@ -1,5 +1,6 @@
"""Entries of Claude Code's transcripts and of its stream-json and json output."""
import json
import typing
def parse_entry(raw: str | bytes) -> dict | None:
@@ -36,8 +37,9 @@ def written_by_human(entry: dict) -> bool:
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
# {"type": "user", "isCompactSummary": true, "message": {"content": "This session is being continued from a previous conversation that ran out of context. ..."}}
def tagged_as_injected(entry: dict) -> bool:
return bool(entry.get("isMeta")) or entry.get("promptSource") in ("sdk", "system")
return bool(entry.get("isMeta")) or bool(entry.get("isCompactSummary")) or entry.get("promptSource") in ("sdk", "system")
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
@@ -86,11 +88,35 @@ def part_text(part: object) -> str | None:
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
# {"type": "tool_use", "id": "toolu_01…", "name": "Bash", "input": {"command": "echo hi"}}
def tool_call(part: object) -> tuple[object, object] | None:
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
def tool_use_id(part: object) -> str | None:
return part["id"] if isinstance(part, dict) and part.get("type") == "tool_use" and isinstance(part.get("id"), str) else None
class ToolResult(typing.NamedTuple):
tool_use_id: str
text: str
failed: bool
# {"type": "tool_result", "tool_use_id": "toolu_01…", "content": "hi"}, its content also as [{"type": "text", "text": "hi"}], and with "is_error": true where the call failed
def tool_result(part: object) -> ToolResult | None:
if not isinstance(part, dict) or part.get("type") != "tool_result":
return None
return ToolResult(str(part.get("tool_use_id")), result_text(part.get("content")), bool(part.get("is_error")))
def result_text(content: object) -> str:
if isinstance(content, str):
return content
# Claude Code may split one text across blocks, even inside a line, so the blocks join with nothing between them.
return "".join(part_text(part) or "" for part in content) if isinstance(content, list) else ""
# stream-json's last line: {"type": "result", "subtype": "success", ...}
def ends_stream(event: dict) -> bool:
return event.get("type") == "result"
+5
View File
@@ -37,6 +37,11 @@ def session_files(transcript: str) -> list[str]:
return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*"))
# <session id>/subagents/agent-<agent id>.jsonl, beside <session id>.jsonl
def subagent_transcript(session_transcript: str, agent_id: str) -> str:
return os.path.join(session_transcript.removesuffix(".jsonl"), "subagents", f"agent-{agent_id}.jsonl")
def delete_session(session: Session) -> Failure | None:
path = transcript_file(session)
if path is None:
+23 -5
View File
@@ -39,6 +39,14 @@ class Render(unittest.TestCase):
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.\n\n[loop] Your question: A or B?\n\n[human] use B')
class Verbatim(unittest.TestCase):
def test_a_quote_holds_only_word_for_word_less_emphasis_and_whitespace(self):
self.assertTrue(transcript.verbatim("Merge **ff-only**.", "Merge ff-only.\nNever squash."))
self.assertTrue(transcript.verbatim("Merge _ff-only_.", "Merge ff-only.\nNever squash."))
self.assertFalse(transcript.verbatim("Merge ... squash.", "Merge ff-only.\nNever squash."))
self.assertFalse(transcript.verbatim("", "Merge ff-only."))
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"}')
@@ -46,6 +54,15 @@ class FirstTimestampedLine(unittest.TestCase):
self.assertEqual(transcript.first_timestamped_line(b""), b"")
class CurrentThread(unittest.TestCase):
def test_a_parent_cycle_ends_the_thread(self):
looped = [{"uuid": "a", "parentUuid": "b"}, {"uuid": "b", "parentUuid": "a"}]
self.assertEqual([entry["uuid"] for entry in transcript.current_thread(looped)], ["a", "b"])
def test_entries_without_a_uuid_make_no_thread(self):
self.assertEqual(transcript.current_thread([{"type": "summary"}]), [])
class HumanTurns(unittest.TestCase):
def test_counts_typed_turns_and_not_tool_results(self):
self.assertEqual(transcript.human_turns([
@@ -58,6 +75,7 @@ class HumanTurns(unittest.TestCase):
{**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("This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation."), "isCompactSummary": True},
human([{"type": "text", "text": "[Request interrupted by user]"}]),
human([]),
queued("typed while claude worked", "human"),
@@ -85,12 +103,12 @@ class Parse(unittest.TestCase):
class ClaudeReply(unittest.TestCase):
@staticmethod
def claude(*outcomes):
def claude(*results):
def run(args, cwd, prompt):
outcome = outcomes[0]
if isinstance(outcome, OSError):
raise outcome
return subprocess.CompletedProcess(args, *outcome)
result = results[0]
if isinstance(result, OSError):
raise result
return subprocess.CompletedProcess(args, *result)
return run
def test_runs_claude_headless_with_the_args_in_cwd_on_the_prompt(self):
+26
View File
@@ -21,6 +21,21 @@ def read_transcript(path: str) -> list[dict] | Failure:
return Failure(f"could not read the transcript {path}: {failure.strerror}")
def current_thread(entries: list[dict]) -> list[dict]:
"""The entries of the transcript's current thread since its last compaction, oldest first: the newest entry with a uuid and its ancestors by parentUuid.
That leaves out a branch the session rewound, and the results of parallel tool calls that Claude Code chains on a side branch."""
chained = [entry for entry in entries if isinstance(entry.get("uuid"), str)]
by_uuid = {entry["uuid"]: entry for entry in chained}
found: list[dict] = []
entry = chained[-1] if chained else None
# A compaction writes {"type": "system", "subtype": "compact_boundary", "parentUuid": null, ...}, so the thread starts there; the length check stops a parent cycle.
while entry is not None and len(found) < len(chained):
found.append(entry)
entry = by_uuid.get(entry.get("parentUuid"))
return found[::-1]
# The lines before it, such as the session's title, are the same for every chunk of a project.
def first_timestamped_line(raw: bytes) -> bytes:
lines = raw.splitlines()
@@ -51,3 +66,14 @@ def part_line(part: object, tool_input_chars: int) -> str:
name, arguments = call
return f"[tool {name}] {json.dumps(arguments, ensure_ascii=False)[:tool_input_chars]}"
return ""
def verbatim(quote: str, text: str) -> bool:
"""Whether text holds the judge's quote word for word, once plain strips emphasis and reflows whitespace in both."""
quoted = plain(quote)
return quoted != "" and quoted in plain(text)
def plain(text: str) -> str:
# The judge drops markdown emphasis and reflows whitespace when it quotes.
return " ".join(text.replace("*", "").replace("_", "").split())
+1 -1
View File
@@ -31,7 +31,7 @@ def trust(config: pathlib.Path, roots: list[str]) -> None:
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict):
return Failure('not an object whose "projects" is an object')
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
if (wrong := next((path for path, settings in projects.items() if not isinstance(settings, dict)), None)) is not None:
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
+122
View File
@@ -0,0 +1,122 @@
"""What a docker command asks of docker: its subcommand, and whether a container it makes has a memory limit and a swap limit. capped adds the limits such a container lacks."""
import re
import typing
# The options of docker, docker buildx and docker compose that take a value, so the value is not read as a subcommand.
DOCKER_VALUED = frozenset({"--ansi", "--builder", "--config", "--context", "--env-file", "--file", "--host", "--log-level", "--parallel", "--profile", "--progress", "--project-directory", "--project-name", "--tlscacert", "--tlscert", "--tlskey", "-c", "-f", "-H", "-l", "-p"})
# The subcommands that make a container, whose memory limits docker reads from the same options.
STARTS_CONTAINER = (["container", "create"], ["container", "run"], ["create"], ["run"])
# A size as docker reads one, such as 4g, 512M or 1.5GiB, each unit a power of 1024: go-units' RAMInBytes pattern, less a number with two points, such as 1.2.3, which its float parse refuses.
SIZE = r"(\d+(?:\.\d+)?)([kKmMgGtTpP]?)[iI]?[bB]?"
# Docker's documented floor for --memory, 6m: a smaller value, such as grep -m 1's, belongs to the container's own command.
MEMORY_FLOOR = 6 * 1024**2
MEMORY_OPTIONS = ("-m", "--memory")
SWAP_OPTIONS = ("--memory-swap",)
class Option(typing.NamedTuple):
"""An option the arguments give: where it stands, how many words it takes, and its value."""
at: int
length: int
value: str
def size(value: str) -> float | None:
"""The bytes a docker size spells; None for a value that is no size."""
spelled = re.fullmatch(SIZE, value)
return float(spelled.group(1)) * 1024 ** " kmgtp".index(spelled.group(2).lower() or " ") if spelled else None
def memory_limit(value: str) -> bool:
return (size(value) or 0) >= MEMORY_FLOOR
def swap_limit(value: str) -> bool:
"""Whether a --memory-swap value limits swap: -1 leaves it unlimited, and 0 leaves it unset, which docker reads as twice the memory limit."""
return bool(size(value))
def unset_swap(value: str) -> bool:
return value == "-1" or size(value) == 0
def zero(value: str) -> bool:
return size(value) == 0
def docker_subcommand(arguments: list[str]) -> list[str]:
"""The subcommand docker's arguments name, past its options: such as ["build"], ["compose", "run"] or ["buildx", "build"]."""
return [arguments[at] for at in subcommand_at(arguments)]
def subcommand_at(arguments: list[str]) -> list[int]:
"""Where in docker's arguments each word of its subcommand stands, so a global option's value that spells it, as in --context run, is not taken for it."""
positional: list[int] = []
skip = False
for at, word in enumerate(arguments):
if skip:
skip = False
elif word.startswith("-"):
skip = word in DOCKER_VALUED
else:
positional.append(at)
if arguments[positional[0]] not in ("buildx", "compose", "container") or len(positional) == 2:
break
return positional
def unlimited(arguments: list[str]) -> bool:
"""Whether docker's arguments make a container, with docker run or docker create, and leave its memory or its swap without a limit.
The container's own arguments, past its image, are read too: telling them apart needs every value-taking option of docker run. So a -m 4g there reads as a limit, while python -m pytest and grep -m 1 do not, since neither is a size docker takes.
"""
subcommand = docker_subcommand(arguments)
limited = option_value(arguments, MEMORY_OPTIONS, memory_limit) and option_value(arguments, SWAP_OPTIONS, swap_limit)
return subcommand in STARTS_CONTAINER and not limited and not helped(arguments)
def helped(arguments: list[str]) -> bool:
"""Whether docker only prints its help: a --help before the subcommand or as the first word after it, not one the container's own command takes."""
after = subcommand_at(arguments)[-1] + 1
return "--help" in arguments[:after + 1]
def capped(arguments: list[str], share: str) -> list[str]:
"""docker's arguments, with each limit a container they make lacks added right after the subcommand.
A container that sets neither limit gets share for both. One that sets one limit gets the other at the same size, since docker refuses less swap than memory. A --memory-swap of -1 or 0 is dropped; every other word stays. Arguments with a --memory of 0 anywhere come back unchanged.
"""
# A -m 0 asks docker for unlimited memory, and would override an added limit; it may also be the container's own, as in grep -m 0, so it is neither dropped nor capped.
if not unlimited(arguments) or option_value(arguments, MEMORY_OPTIONS, zero):
return arguments
memory = option_value(arguments, MEMORY_OPTIONS, memory_limit)
swap = option_value(arguments, SWAP_OPTIONS, swap_limit)
rest = without(arguments, SWAP_OPTIONS, unset_swap)
limits = ([] if memory else ["--memory", swap or share]) + ([] if swap else ["--memory-swap", memory or share])
after = subcommand_at(rest)[-1] + 1
return [*rest[:after], *limits, *rest[after:]]
def option_value(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> str | None:
"""The value the arguments give one of the options, where it fits, as its next word or attached, as in -m4g or --memory=4g; None where they give none."""
found = option_at(arguments, options, fits)
return found.value if found else None
def without(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> list[str]:
"""The arguments with each of the options removed, with its value, where the value fits."""
while found := option_at(arguments, options, fits):
arguments = [*arguments[:found.at], *arguments[found.at + found.length:]]
return arguments
def option_at(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> Option | None:
"""Where the arguments first give one of the options, with a value that fits."""
for at, (word, following) in enumerate(zip(arguments, [*arguments[1:], ""])):
for option in options:
attached = word.removeprefix(option if len(option) == 2 else option + "=")
if attached != word and fits(attached):
return Option(at, 1, attached)
if word == option and fits(following):
return Option(at, 2, following)
return None
+8 -8
View File
@@ -16,12 +16,12 @@ Kind = str
@dataclasses.dataclass(frozen=True)
class Case:
"""One archived verdict: on_record, judged at its UTC stamp."""
"""One archived verdict: the kind the archive gives it, judged at its UTC stamp."""
root: str
task: str
transcript: pathlib.Path
at: str
on_record: Kind
archived_kind: Kind
def case_from(root: str, outcomes: str, transcript: pathlib.Path) -> Case | None:
@@ -40,8 +40,8 @@ def sample(cases: list[Case], per_kind: int) -> list[Case]:
seen: collections.Counter[Kind] = collections.Counter()
kept = []
for found in sorted(cases, key=lambda found: (found.at, found.root, str(found.transcript)), reverse=True):
seen[found.on_record] += 1
if seen[found.on_record] <= per_kind:
seen[found.archived_kind] += 1
if seen[found.archived_kind] <= per_kind:
kept.append(found)
return kept[::-1]
@@ -63,12 +63,12 @@ def verdict_kind(verdict: Verdict | Failure) -> Kind:
def reproduced(case: Case, kind: Kind) -> list[Kind]:
"""The kind on record, where the reply returns it: a rung is held only to a verdict the reference judge reproduces."""
return [kind] if kind == case.on_record else []
"""The archived kind, where the reply returns it: a rung is held only to a verdict the reference judge reproduces."""
return [kind] if kind == case.archived_kind else []
def report(model: str, reference: Rung, cases: list[Case], replay: Replay[Case, Kind, Kind]) -> str:
kinds = collections.Counter(found.on_record for found in cases)
kinds = collections.Counter(found.archived_kind for found in cases)
unreproduced = [(found, kind) for found, kind in zip(cases, replay.on_reference) if not reproduced(found, kind)]
lines = [
f"Replayed {len(cases)} verdicts of {model} projects: {', '.join(f'{count} {kind}' for kind, count in sorted(kinds.items()))}.",
@@ -86,4 +86,4 @@ def report(model: str, reference: Rung, cases: list[Case], replay: Replay[Case,
def missed_lines(missed: list[tuple[Case, Kind]]) -> list[str]:
return [f" {found.root} {found.at}: on record {found.on_record}, replayed {kind}" for found, kind in missed]
return [f" {found.root} {found.at}: archived {found.archived_kind}, replayed {kind}" for found, kind in missed]
+7 -7
View File
@@ -25,8 +25,8 @@ MIDDLE = Rung("claude-sonnet-5-5", "high")
REFERENCE = Rung("claude-opus-5-5", "xhigh")
def case(at, on_record):
return Case("/code/p", "Do the next chunk.", TRANSCRIPT, at, on_record)
def case(at, archived_kind):
return Case("/code/p", "Do the next chunk.", TRANSCRIPT, at, archived_kind)
class CaseFrom(unittest.TestCase):
@@ -37,7 +37,7 @@ class CaseFrom(unittest.TestCase):
def test_reads_each_kind_of_verdict(self):
for verdict in (FINISHED, UNFINISHED, INTERRUPTED, ANSWERED):
found = case_from("/code/p", f"Task: t\n\n2026-10-14T10:00:00Z {verdict}\n\nmore\n", TRANSCRIPT)
self.assertEqual(found.on_record, verdict)
self.assertEqual(found.archived_kind, verdict)
def test_skips_a_copy_with_no_verdict(self):
self.assertIsNone(case_from("/code/p", "Task: t\n\n2026-10-14T10:00:00Z Stepped up\n\nWorker: y\n", TRANSCRIPT))
@@ -60,7 +60,7 @@ class VerdictKind(unittest.TestCase):
class Reproduced(unittest.TestCase):
def test_holds_a_rung_to_a_verdict_only_where_the_reference_returned_the_kind_on_record(self):
def test_holds_a_rung_to_a_verdict_only_where_the_reference_returned_the_archived_kind(self):
self.assertEqual(reproduced(case("2026-10-14T10:00:00Z", FINISHED), FINISHED), [FINISHED])
self.assertEqual(reproduced(case("2026-10-14T10:00:00Z", FINISHED), INTERRUPTED), [])
@@ -72,10 +72,10 @@ class Report(unittest.TestCase):
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, replay).splitlines(), [
"Replayed 2 verdicts of claude-opus-5-5 projects: 1 Verdict: finished, 1 Verdict: interrupt.",
"The reference judge, claude-opus-5-5 at xhigh effort, reproduced 1. It returned another kind on:",
" /code/p 2026-10-14T10:00:00Z: on record Verdict: finished, replayed Verdict: unfinished",
" /code/p 2026-10-14T10:00:00Z: archived Verdict: finished, replayed Verdict: unfinished",
"claude-sonnet-5-5 at high effort missed 0.",
"claude-haiku-5-5 at xhigh effort missed 1:",
" /code/p 2026-10-14T10:00:01Z: on record Verdict: interrupt, replayed Verdict: finished",
" /code/p 2026-10-14T10:00:01Z: archived Verdict: interrupt, replayed Verdict: finished",
"Lowest rung that, like each rung above it, returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort",
])
missed_all = report("claude-opus-5-5", REFERENCE, cases, Replay([FINISHED, INTERRUPTED], [Tried(MIDDLE, [Miss(cases[1], INTERRUPTED, FINISHED)])], None)).splitlines()
@@ -114,7 +114,7 @@ class Main(unittest.TestCase):
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
-22
View File
@@ -1,22 +0,0 @@
from failure import Failure
from git_repo import file_at, full_history, git
from comprehension_history import HISTORY, HistoryChange
def history_changes(default: str) -> list[HistoryChange] | Failure:
"""Each merged change on the default branch that touched the history, newest first; a merge commit counts as one change against its first parent."""
if partial := full_history():
return partial
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
if isinstance(commits, Failure):
return commits
changes = []
for commit in commits.split():
before = file_at(f"{commit}^1", HISTORY)
if isinstance(before, Failure):
return before
after = file_at(commit, HISTORY)
if isinstance(after, Failure):
return after
changes.append(HistoryChange(commit, before, after))
return changes
+30
View File
@@ -0,0 +1,30 @@
from failure import Failure
from git_repo import file_at, full_history, git
from comprehension_history import HISTORY, HistoryChange
def history_changes(default: str) -> list[HistoryChange] | Failure:
"""Each merged change on the default branch that touched the history, newest first."""
if partial := full_history():
return partial
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
if isinstance(commits, Failure):
return commits
changes = []
for commit in commits.split():
change = history_change(commit)
if isinstance(change, Failure):
return change
changes.append(change)
return changes
def history_change(commit: str) -> HistoryChange | Failure:
"""The history before and after commit. A merge commit counts as one change, against its first parent."""
before = file_at(f"{commit}^1", HISTORY)
if isinstance(before, Failure):
return before
after = file_at(commit, HISTORY)
if isinstance(after, Failure):
return after
return HistoryChange(commit, before, after)
@@ -77,7 +77,7 @@ def scored_seats(given: SeatsFile) -> ScoringRun | Failure:
def read_seats(path: pathlib.Path, paired: bool) -> 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 the history already holds an entry on what it reads; it runs before anything is printed."""
"""The seats file and the heading its entry goes under. Fails when the file names a commit the checkout lacks, or 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:
+3 -3
View File
@@ -86,7 +86,7 @@ and the inherited architect vote alike overall in a paired ruling more often tha
same way in a pair. It prints both counts. It opens `Unchecked:` until the history holds {pairs} such
pairs and one paired ruling, then `Assumption holds:` or `Assumption fails:`, and exits 0 each time.
Each record is appended to the history, created when missing, under a heading of the current UTC
Each entry is appended to the history, created when missing, under a heading of the current UTC
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.
@@ -105,12 +105,12 @@ from round_titles import CAP, round_counts
from git_repo import default_branch, git, top
from failure import Failure
from comprehension_history import FLOOR
from larv_review.git import history_changes
from larv_review.history_changes import history_changes
from larv_review.ruling_base import measured_commit
from larv_review.agreement import MIN_PAIRS
from review_passes import PASSES
from larv_review.plan import plan_reasons
from larv_review.record import record_ruling, record_scoring, show_agreement, show_places
from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places
from review_folder import REPORTS, review_folder
USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement"
+13 -30
View File
@@ -6,12 +6,12 @@ import typing
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typed_answer
from claude_code.reply import claude_reply, Limited
from loop_claude.effects import Effects
from loop_claude import escalation_mark
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from claude_code.entries import human_text, loop_text
from todo_table import LEVELS
from model_routing.route import on_its_scale
from claude_code.transcript import render
from claude_code.transcript import plain, verbatim
from loop_claude.cycle.retry import retried
from model_routing.ladder import Rung
from loop_claude.stop import Stop
@@ -58,8 +58,6 @@ FINISHED_RULES = (
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
)
JUDGE_RULES = "\n\n".join((INTERRUPT_RULES, QUOTE_RULES, FINISHED_RULES))
# The line judge_prompt shows the judge where an escalation last stepped the worker up, which Reply.escalation's description points at. Only the judge reads it, so it is no [loop] line.
STEP_LINE = "[step] loop-claude stepped the worker up a rung here, so the escalation triggers that fired before this line are spent."
@dataclasses.dataclass(frozen=True)
@@ -69,8 +67,8 @@ class Reply:
highest_likelihood_taken_in: int = dataclasses.field(metadata={"description": "The highest L the worker states for a todo.md item it took into this chunk; 0 when it states none."})
# Routes the next cycle's judge and reviewers, as highest_likelihood_taken_in routes the worker.
highest_escape_and_impact_taken_in: int = dataclasses.field(metadata={"description": "The highest E + I the worker states for a todo.md item it took into this chunk; 0 when it states none."})
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`.
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. Where a [step] line says loop-claude stepped the worker up a rung, quote only the worker's own words after it, and leave this empty where the trigger fired only before it. Never a later mention of the trigger, and never the request itself."})
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: loop_claude/escalation_mark.py.
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. " + escalation_mark.QUOTE_AFTER_STEP + " Never a later mention of the trigger, and never the request itself."})
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 worker'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."})
@@ -95,13 +93,11 @@ class Rejected(Failure):
reply: str
class Grounds(typing.NamedTuple):
"""What run_judge checks the judge's quotes against, word for word, since stitched fragments can say what their source does not."""
# The transcript as the judge saw it. The evidence must quote it, its fragments in order: a misquote is Rejected, which judge retries.
shown: str
# The worker's own lines after the mark, all of them before any step-up. loop-claude's prompts and the human's lines are left out, since they repeat earlier passages, such as the judge's evidence or the worker's question. An escalation must quote both this and shown: a misquote, or a quote of a passage before the mark, drops the escalation, so the worker's rung holds.
# escalation_mark.since_step's lines. An escalation must quote both these and shown: a misquote drops the escalation, as escalation_mark.checked says.
since_step: str
# README.md's premises and the records. A quoted answer must quote them: a misquote puts the question to the human.
quotable: str
@@ -135,10 +131,10 @@ def judge(root: str, task: str, premises: str, records: str, entries: list[dict]
def judge_once(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run on the transcript's entries, as judge retries it; judge-replay replays it. escalated_at is the route's mark: an escalation quote counts only from the entries after it."""
"""One judge run on the transcript's entries, as judge retries it; judge-replay replays it. escalated_at is the route's mark, as loop_claude/escalation_mark.py says."""
prompt, grounds = judge_prompt(task, premises, records, entries, escalated_at)
verdict = run_judge(root, judge_args(rung), prompt, grounds, effects)
return dataclasses.replace(verdict, entries_read=len(entries)) if isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) else verdict
return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, len(entries))
def judge_args(rung: Rung) -> list[str]:
@@ -152,7 +148,7 @@ def judge_args(rung: Rung) -> list[str]:
def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run, each quote in its verdict checked against grounds as Grounds says. quotes_checked checks the quoted answer and the escalation: neither misquote is a Failure, which would otherwise exit an unattended loop."""
"""One judge run, each quote in its verdict checked against grounds as Grounds says."""
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
if isinstance(reply, Failure | Limited):
return reply
@@ -166,18 +162,15 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict:
"""The verdict with its quoted answer and its escalation checked, as Grounds says; a quoted answer put to the human keeps the escalation it carried."""
"""The verdict with its quoted answer and its escalation checked. A quoted answer that neither README.md's premises nor the records hold goes to the human as an interrupt, which keeps the escalation the answer carried. Neither misquote is a Failure, which would otherwise exit an unattended loop."""
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable):
verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, highest_likelihood_taken_in=verdict.highest_likelihood_taken_in)
if isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) and verdict.escalation and not (verbatim(verdict.escalation, grounds.since_step) and verbatim(verdict.escalation, grounds.shown)):
return dataclasses.replace(verdict, escalation="")
return verdict
return escalation_mark.checked(verdict, since=grounds.since_step, shown=grounds.shown)
def judge_prompt(task: str, premises: str, records: str, entries: list[dict], escalated_at: int) -> tuple[str, Grounds]:
"""The prompt, and what the judge's quotes are checked against. Where escalated_at, the route's mark, is above 0, the prompt shows STEP_LINE after that many entries."""
transcript = "\n\n".join(part for part in (render(entries[:escalated_at], typed_answer), STEP_LINE if escalated_at else "", render(entries[escalated_at:], typed_answer)) if part)
workers_own = [entry for entry in entries[escalated_at:] if human_text(entry) is None and loop_text(entry) is None]
"""The prompt, and what the judge's quotes are checked against."""
transcript = escalation_mark.transcript(entries, escalated_at, typed_answer)
head = (
f"From README.md:\n{premises}\n\n"
f"The records: the project's working rules and decisions, then the human's rules for every project:\n{records or 'none'}\n\n"
@@ -187,7 +180,7 @@ def judge_prompt(task: str, premises: str, records: str, entries: list[dict], es
room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2)
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
shown = transcript[max(0, len(transcript) - room):]
return f"{head}{shown}\n\n{JUDGE_RULES}", Grounds(shown, render(workers_own, typed_answer), f"{premises}\n\n{records}")
return f"{head}{shown}\n\n{JUDGE_RULES}", Grounds(shown, escalation_mark.since_step(entries, escalated_at), f"{premises}\n\n{records}")
def grounded(evidence: str, rendered_transcript: str) -> bool:
@@ -201,13 +194,3 @@ def grounded(evidence: str, rendered_transcript: str) -> bool:
return False
at = found + len(fragment)
return fragments != []
def verbatim(quote: str, text: str) -> bool:
quoted = plain(quote)
return quoted != "" and quoted in plain(text)
def plain(text: str) -> str:
# The judge drops markdown emphasis and reflows whitespace when it quotes.
return " ".join(text.replace("*", "").replace("_", "").split())
+88 -81
View File
@@ -1,5 +1,7 @@
from model_routing.ladder import climbed, LADDER, position, review_rungs, reviewers_rung, ReviewKind, Rung
from model_routing.route import ESCALATION_MARKER, HIGHEST_ESCAPE_AND_IMPACT, Route
"""What loop-claude says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. In a chunk's first prompt, routed_by places them after its routing sentences where an item routed the chunk, and fresh places them alone otherwise. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict."""
from model_routing.review_choice import chosen, ReviewChoice
from model_routing.ladder import climbed, LADDER, position, Rung
from model_routing.route import ESCALATION_MARKER, Route
from loop_claude.routing import escalation_rungs
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
from markdown_text import listed, quoted
@@ -11,27 +13,33 @@ QUOTE_SOURCES = listed(("README.md's Goals and Audience", *RECORD_FILES, *HUMAN_
# 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"
# Each kind of review, as review_launches names those it launches: a row per pass, since a replay may lower one pass alone. "each reviewer" names every pass no replay lowered.
REVIEWS: tuple[tuple[str, ReviewKind], ...] = (*((f"each {agent}", kind) for kind, agent in REVIEWERS.items()), ("each comprehension seat", "seat"), ("the security pass's subagent", "security"))
# How review_launches names the reviews: "each reviewer" covers every pass with an agent that no replay lowered.
EACH_REVIEWER = "each reviewer"
EACH_SEAT = "each comprehension seat"
THE_SECURITY_PASS = "the security pass's subagent"
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it'
def fresh(task: str, premises: str, route: Route, anchor: Rung | None, facts: str) -> str:
def fresh(task: str, premises: str, route: Route, project: Rung | None, facts: str) -> str:
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
escalated = f"{escalation(route, anchor)}{reruns(route, anchor)}".lstrip()
routed = f"{routed_by(route, anchor)}{recount(route)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "")
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
routed = f"{routed_by(route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, project))
opening = f"{routed}\n\n" if routed else ""
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
def routed_by(route: Route, anchor: Rung | None) -> str:
return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
def routed_by(route: Route, project: Rung | None) -> str:
return " ".join((
f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.",
f"Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.",
*rung_sentences(route, project),
))
def recount(route: Route) -> str:
"""Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code."""
return f" After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
def preflight_facts(printed: str) -> str:
@@ -44,127 +52,126 @@ def preflight_failed(reason: str) -> str:
return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}"
def review_launches(route: Route, anchor: Rung | None) -> str:
"""Which reviews to launch on a rung other than the worker's, and on which, then the rung of each pass a replay lowered; below the project's rung, anchor, also where to launch a subagent that files or scores todo.md items; then taken_in_launches, the reviewers' rung each higher E + I picks. Empty off the ladder.
def review_launches(route: Route, project: Rung | None) -> list[str]:
"""The sentences naming where to launch reviews, in this order; none off the ladder:
- one for each rung, other than the worker's, that a reviewer, a seat or the security pass runs on;
- the rung of each pass a replay lowered;
- where the security pass runs on another rung than the worker's, that a full scan runs only from its subagent;
- where the worker runs below the project's rung, where to launch a subagent that files or scores todo.md items;
- the reviewers' rung each higher E + I picks.
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, it opens: ` Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks. Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Haiku 5.5 at low, and the E + I steps no review up, a sentence follows: ` Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose.`
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they open: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Haiku 5.5 at low, and the E + I steps no review up, a sentence follows: `Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose.`
"""
if anchor is None:
return ""
rungs, reviewers = review_rungs(anchor, route.rung, route.reviewed_on()), reviewers_rung(anchor, route.rung, route.reviewed_on())
lowered_launches = "".join(f" Launch {reviews} instead with the Agent tool set to {rung.agent_args()}, the rung the replay of its pass chose." for reviews, rung in lowered(rungs, reviewers))
scan = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them." if rungs["security"] != route.rung else ""
planning = f" Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {anchor.model} <L>` prints." if position(route.rung) < position(anchor) else ""
return f"{shared_launches(rungs, reviewers, route, anchor)}{lowered_launches}{scan}{planning}{taken_in_launches(route, anchor)}"
if project is None:
return []
choice = chosen(project, route)
lowered = [f"Launch each {REVIEWERS[kind]} instead with the Agent tool set to {rung.agent_args()}, the rung the replay of its pass chose." for kind, rung in choice.lowered.items()]
scan = ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else []
planning = [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if position(route.rung) < position(project) else []
return [*shared_launches(choice, route, project), *lowered, *scan, *planning, *taken_in_launches(choice)]
def shared_launches(rungs: dict[ReviewKind, Rung], reviewers: Rung, route: Route, anchor: Rung) -> str:
"""A sentence for each rung other than the worker's that a review runs on. "each reviewer" names every pass no replay lowered; those run on reviewers."""
together = {"each reviewer": reviewers} | {reviews: rungs[kind] for reviews, kind in REVIEWS if kind not in REVIEWERS}
def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[str]:
"""A sentence for each rung, other than the worker's, that the reviewers no replay lowered, the seats or the security pass run on."""
together = {EACH_REVIEWER: choice.reviewers, EACH_SEAT: choice.seat, THE_SECURITY_PASS: choice.security}
launched: dict[Rung, list[str]] = {}
for reviews, rung in together.items():
if rung != route.rung:
launched.setdefault(rung, []).append(reviews)
return "".join(f" Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, anchor)}." for rung, reviews in launched.items())
return [f"Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, project)}." for rung, reviews in launched.items()]
def lowered(rungs: dict[ReviewKind, Rung], reviewers: Rung) -> list[tuple[str, Rung]]:
"""Each pass a replay put below reviewers, the rung of every other pass, as REVIEWS names it, with the rung the replay chose."""
return [(reviews, rungs[kind]) for reviews, kind in REVIEWS if kind in REVIEWERS and rungs[kind] != reviewers]
def taken_in_launches(choice: ReviewChoice) -> list[str]:
"""The sentence naming the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run, since the judge reports a taken-in item's E + I only as the cycle ends, and loop-claude routes on it from the next cycle. None where no higher E + I picks a higher rung.
def taken_in_launches(route: Route, anchor: Rung) -> str:
"""The rung each higher E + I picks for the reviewers, so the worker reviews an item it takes in on that rung in the same run; the judge reports it as the cycle ends, so loop-claude routes on it only from the next cycle. Empty where no higher E + I picks a higher rung.
For a worker on Opus 5.5 at medium, routed by an item of E + I 6, it reads: ` Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.`
For a worker on Opus 5.5 at medium, on an Opus 5.5 project, routed by an item of E + I 6, it reads: `Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.`
"""
now = review_rungs(anchor, route.rung, route.reviewed_on())
higher: dict[Rung, int] = {}
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
# An E + I that lifts any pass puts every pass on reviewers_rung, since a replay lowers a pass only where the E + I steps no review up.
if review_rungs(anchor, route.rung, escape_and_impact) != now:
higher.setdefault(reviewers_rung(anchor, route.rung, escape_and_impact), escape_and_impact)
if not higher:
return ""
picks = [f"`{rung.agent_args()}` from {escape_and_impact}" for rung, escape_and_impact in higher.items()]
return f" Where an item you take into the chunk has an E + I of {min(higher.values())} or more, launch each reviewer with the Agent tool set to {listed(picks, 'and')}."
if not choice.higher:
return []
picks = [f"`{rung.agent_args()}` from {escape_and_impact}" for rung, escape_and_impact in choice.higher.items()]
return [f"Where an item you take into the chunk has an E + I of {min(choice.higher.values())} or more, launch {EACH_REVIEWER} with the Agent tool set to {listed(picks, 'and')}."]
def rung_named(rung: Rung, route: Route, anchor: Rung) -> str:
"""Why a review runs on rung: it is the project's, anchor, or the one the route's reviewed_on E + I picks, the item's or one taken in."""
if rung == anchor:
def rung_named(rung: Rung, route: Route, project: Rung) -> str:
"""Why a review runs on rung: it is the project's, or the one the route's reviewed_on E + I picks, the item's or one taken in."""
if rung == project:
return "the project's rung"
if route.escape_and_impact_taken_in:
return f"the rung picked by an item of E + I {route.escape_and_impact_taken_in} taken into the chunk"
return f"the rung item {route.item}'s E + I of {route.escape_and_impact} picks"
def escalation(route: Route, anchor: Rung | None) -> str:
"""The prompt's escalation sentences, the marker's among them, each led by a space. Empty off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
def escalation(route: Route, project: Rung | None) -> list[str]:
"""The prompt's escalation sentences, the marker's among them. None off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs.
For a worker on Opus 5.5 at high, on an Opus 5.5 project, routed by item 3 of L 4, they read: ` When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort max`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort max`.`
For a worker on Opus 5.5 at high, on an Opus 5.5 project, routed by item 3 of L 4, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort max`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort max`.`
"""
if anchor is None or route.rung not in LADDER[:-1]:
return ""
if project is None or route.rung not in LADDER[:-1]:
return []
marked = f"Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(anchor, route)]
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(project, route)]
if not rungs:
return " " + " ".join((
return [
f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.",
marked,
))
]
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
return " " + " ".join((
return [
f"When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to {rungs[0]}, one rung above yours{further}; above that, ask the human first.",
marked,
f"Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to {rungs[-1]}.",
))
]
def reruns(route: Route, anchor: Rung | None) -> str:
"""The prompt's sentences naming the rung one above a review's, on which it reruns when it asks: shared_reruns' for a reviewer and a seat, then one for each pass a replay lowered. Empty off the ladder.
def reruns(route: Route, project: Rung | None) -> list[str]:
"""The sentences naming the rung one above a review's, on which it reruns when it asks: shared_reruns' for a reviewer and a seat, then one for each pass a replay lowered. None off the ladder.
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Haiku 5.5 at low, routed by an item of E + I 4, they read: ` A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`. Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead.`
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Haiku 5.5 at low, routed by an item of E + I 4, they read: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.` and `Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead.`
"""
if anchor is None or route.rung not in LADDER:
return ""
rungs, reviewers = review_rungs(anchor, route.rung, route.reviewed_on()), reviewers_rung(anchor, route.rung, route.reviewed_on())
lowered_reruns = "".join(f" Rerun {reviews} that asks with the Agent tool set to `{climbed(rung, 1).agent_args()}` instead." for reviews, rung in lowered(rungs, reviewers))
return f"{shared_reruns(reviewers, rungs['seat'])}{lowered_reruns}"
if project is None or route.rung not in LADDER:
return []
choice = chosen(project, route)
lowered = [f"Rerun each {REVIEWERS[kind]} that asks with the Agent tool set to `{climbed(rung, 1).agent_args()}` instead." for kind, rung in choice.lowered.items()]
return [*shared_reruns(choice), *lowered]
def shared_reruns(reviewers: Rung, seats: Rung) -> str:
"""The sentence naming the rung one above reviewers, the rung of each pass no replay lowered, and one above seats, leaving out one already on the top rung."""
launched = (("reviewer", reviewers), ("comprehension seat", seats))
def shared_reruns(choice: ReviewChoice) -> list[str]:
"""The sentence naming the rung one above choice.reviewers and the one above choice.seat, leaving out either that is already on the top rung."""
launched = (("reviewer", choice.reviewers), ("comprehension seat", choice.seat))
rerun = {name: climbed(rung, 1) for name, rung in launched if rung != LADDER[-1]}
if not rerun:
return ""
return []
if len(set(rerun.values())) == 1:
return f" A {listed(list(rerun), 'or')} that asks for a rerun one rung up reruns with the Agent tool set to `{next(iter(rerun.values())).agent_args()}`."
return f" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."
return [f"A {listed(list(rerun), 'or')} that asks for a rerun one rung up reruns with the Agent tool set to `{next(iter(rerun.values())).agent_args()}`."]
return [f"A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."]
def resumed(unfinished_evidence: str, route: Route, anchor: Rung | None) -> str:
def resumed(unfinished_evidence: str, route: Route, project: Rung | None) -> str:
"""Names the worker's rung, so it learns whether its request for a higher rung went through, and the project's again, since a step-up between cycles may have taken the worker above it."""
on = f" loop-claude runs you on {route.rung}." if anchor else ""
on = f" loop-claude runs you on {route.rung}." if project else ""
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}.{on}{rungs_held(route, anchor)}"
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}.{on}{rungs_held(route, project)}"
def rungs_held(route: Route, anchor: Rung | None) -> str:
def rung_sentences(route: Route, project: Rung | None) -> list[str]:
"""The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run."""
return f"{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
return [*review_launches(route, project), *escalation(route, project), *reruns(route, project)]
def answered(question: str, answer: str, route: Route, anchor: Rung | None, stepped: bool) -> str:
def rungs_held(route: Route, project: Rung | None) -> str:
"""rung_sentences, each after a space, to follow the sentence a prompt ends on."""
return "".join(f" {sentence}" for sentence in rung_sentences(route, project))
def answered(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
"""stepped is whether the answer's ruling stepped the worker up."""
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, anchor, stepped)}"
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, project, stepped)}"
def typed(question: str, answer: str, route: Route, anchor: Rung | None, stepped: bool) -> str:
def typed(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
"""The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it."""
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, anchor, stepped)}"
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, project, stepped)}"
# Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds.
@@ -180,9 +187,9 @@ def typed_answer(prompt: str) -> Typed | None:
return Typed(rest, answer)
def stepped_to(route: Route, anchor: Rung | None, stepped: bool) -> str:
def stepped_to(route: Route, project: Rung | None, stepped: bool) -> str:
"""The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise."""
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, anchor)}" if stepped else ""
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, project)}" if stepped else ""
def past_the_cap(question: str, answer: str, cap: int) -> str:
+50 -44
View File
@@ -5,10 +5,11 @@ import typing
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
from loop_claude.routing import after_ruling, judge_rung
from transcript_archive.write import archive
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
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.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.cycle.judge import judge, Rejected
from transcript_archive import outcomes
from loop_claude.paths import Paths
@@ -17,8 +18,8 @@ from loop_claude.cycle.interrupt import put_question, talk, Talk
from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried
from model_routing.route import Route
from loop_claude.cycle.worker import run_worker, worker_args
from model_routing.ladder import Rung
from loop_claude.escalation_mark import StepUp
from loop_claude.stop import Stop
from model_routing import worker_rungs
@@ -38,12 +39,9 @@ class Cycle:
task: str
route: Route
# The project's rung; None for a model off the ladder.
anchor: Rung | None
project: Rung | None
# Empty when the previous cycle's verdict was not Unfinished.
unfinished_evidence: str
# Only an interrupt's or a quoted answer's escalation changes the route within a cycle. No transition reads the route or the fields below, so they stay out of the states.
# The route before that ruling stepped it up, for ask and keep_answer to archive and for worker_start to tell the worker; None unless the latest event is that ruling, or the answer the human typed to it.
stepped_from: Route | None = None
@dataclasses.dataclass(frozen=True)
@@ -60,28 +58,31 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
event = step(cycle, state)
if isinstance(event, Stop):
return stopped(cycle, event, event.reason)
cycle = escalated(cycle, event)
# Only a ruling's step-up changes the route within a cycle. No transition reads the current route, so Cycle holds it, not the states.
if isinstance(event, Ruled) and event.step_up:
cycle = dataclasses.replace(cycle, route=event.step_up.after)
state = transition(state, event)
except KeyboardInterrupt:
return stopped(cycle, Stop(130, ""), "Ctrl-C")
return Concluded(state.verdict, cycle.route)
def escalated(cycle: Cycle, event: Event) -> Cycle:
"""The cycle after event. Where the judge interrupted or quoted an answer with an escalation, its route steps up before the human is asked or the worker resumes, so the work after the answer runs on it. stepped_from holds through the answer the human types, so the worker resuming with it is told of the step; a copy on TypedAnswer would give the step a second owner."""
if isinstance(event, HumanTyped):
return cycle
cycle = dataclasses.replace(cycle, stepped_from=None)
if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and cycle.anchor):
return cycle
route = after_ruling(cycle.anchor, cycle.route, event.verdict)
return dataclasses.replace(cycle, route=route, stepped_from=cycle.route if route != cycle.route else None)
def ruling_step_up(cycle: Cycle, verdict: Verdict) -> StepUp | None:
"""The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds."""
if not (isinstance(verdict, Interrupt | QuotedAnswer) and cycle.project):
return None
after = after_ruling(cycle.project, cycle.route, verdict)
return StepUp(cycle.route, after) if after != cycle.route else None
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
path = transcript_file(cycle.session)
failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(cycle.route.record(), 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 archived_stop(cycle.project_archive, cycle.session, cycle.task, cycle.route, stop, why, cycle.effects)
def archived_stop(project_archive: pathlib.Path, session: Session, task: str, route: Route, stop: Stop, why: str, effects: Effects) -> Stop:
"""stop, once archived with the route the worker holds. A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once."""
path = transcript_file(session)
failure = archive(project_archive, path, task, outcomes.stopped(route.worker_line(), why), effects.now()) if path else None
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
@@ -92,12 +93,12 @@ def judge_of(cycle: Cycle) -> Rung:
def step(cycle: Cycle, state: Active) -> Event | Stop:
match state:
case Working(answered, _):
return work(cycle, answered)
case Working(answered, _, step_up):
return work(cycle, answered, step_up)
case Judging(transcript_path, _):
return rule(cycle, transcript_path)
case Interrupting(transcript_path, ruling, _):
return ask(cycle, transcript_path, ruling)
case Interrupting(transcript_path, ruling, _, step_up):
return ask(cycle, transcript_path, ruling, step_up)
case Talking(transcript_path, _):
return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked()
case Closing(transcript_path, verdict):
@@ -106,40 +107,40 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
typing.assert_never(state)
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> WorkerRan | Stop:
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> WorkerRan | Stop:
if isinstance(answered, QuotedAnswer):
print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
if stop := keep_answer(cycle, answered):
if stop := keep_answer(cycle, answered, step_up):
return stop
# 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), worker_environment(cycle), cycle.effects), cycle.effects):
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, step_up), worker_environment(cycle), 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_environment(cycle: Cycle) -> dict[str, str]:
"""The rungs the worker's claude is handed, which rule-hook holds its review launches to."""
return worker_rungs.environment(cycle.anchor, cycle.route)
"""The rungs the worker's claude is handed, which rule-hook holds its review launches to, and the auto-compact window of its context."""
return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW)}
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> list[str]:
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> list[str]:
if isinstance(answered, QuotedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
if isinstance(answered, TypedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
if session_open(cycle.session):
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, cycle.facts), resume=False)
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False)
def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None:
def keep_answer(cycle: Cycle, answered: QuotedAnswer, step_up: StepUp | None) -> Stop | None:
path = transcript_file(cycle.session)
if not path:
return None
# As in ask: the answer names the rung the worker ran on until then, and a step-up archived after it names the rung it runs on from then.
quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), (cycle.stepped_from or cycle.route).record())
if failure := archive_stepped(cycle, path, quoted):
quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), ran_on(cycle, step_up).worker_line())
if failure := archive_stepped(cycle, path, quoted, step_up):
return Stop(1, failure.reason)
return None
@@ -149,7 +150,7 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
if isinstance(entries, Failure):
return Stop(1, entries.reason)
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, entries, cycle.route.escalated_at, judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
return verdict if isinstance(verdict, Stop) else Ruled(verdict)
return verdict if isinstance(verdict, Stop) else Ruled(verdict, ruling_step_up(cycle, verdict))
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
@@ -159,12 +160,12 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
return None
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | TalkChosen | Stop:
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | 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.
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, (cycle.stepped_from or cycle.route).record())
if failure := archive_stepped(cycle, transcript_path, interrupted):
interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, ran_on(cycle, step_up).worker_line())
if failure := archive_stepped(cycle, transcript_path, interrupted, step_up):
return Stop(1, failure.reason)
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects)
@@ -174,9 +175,14 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer))
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str) -> Failure | None:
"""Archives the outcome of a ruling, then the step-up it caused when it stepped the route. The first failure is returned."""
for kept in (outcome, outcomes.stepped_up(cycle.route.record())) if cycle.stepped_from else (outcome,):
def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route:
"""The route the worker ran on until the ruling: the one before its step-up, if it made one."""
return step_up.before if step_up else cycle.route
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None) -> Failure | None:
"""Archives the outcome of a ruling, then the step-up it made, if it made one. The first failure is returned."""
for kept in (outcome, outcomes.stepped_up(step_up.after.worker_line())) if step_up else (outcome,):
if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now()):
return failure
return None
@@ -189,7 +195,7 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
outcome = outcomes.finished(cycle.route.record(), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.record(), verdict.evidence, str(judge_of(cycle)), verdict.escalation)
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation)
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now()):
return Stop(1, failure.reason)
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
+15 -8
View File
@@ -1,6 +1,7 @@
import dataclasses
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.escalation_mark import StepUp
# 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
@@ -18,6 +19,8 @@ class Working:
"""The worker runs, resumed with an answer quoted from README.md or the records, or typed by the human, when there is one."""
answered: QuotedAnswer | TypedAnswer | None = None
quoted_answers: int = 0
# The step-up made by the ruling that brought the answer, so the worker is told of it; None for none.
step_up: StepUp | None = None
@dataclasses.dataclass(frozen=True)
@@ -33,6 +36,8 @@ class Interrupting:
transcript_path: str
ruling: Interrupt | QuotedAnswer
quoted_answers: int = 0
# The step-up the ruling made. It holds through the answer the human types, and drops on /talk.
step_up: StepUp | None = None
@dataclasses.dataclass(frozen=True)
@@ -65,6 +70,8 @@ class WorkerRan:
@dataclasses.dataclass(frozen=True)
class Ruled:
verdict: Verdict
# None unless an interrupt's or a quoted answer's escalation stepped the route; always None for a finished or unfinished verdict.
step_up: StepUp | None = None
@dataclasses.dataclass(frozen=True)
@@ -94,16 +101,16 @@ def transition(state: State, event: Event) -> State:
match state, event:
case Working(_, quoted_answers), WorkerRan(transcript_path):
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(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(_, quoted_answers), Ruled(QuotedAnswer() as answered, step_up) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE:
return Working(answered, quoted_answers + 1, step_up)
case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer() as ruling, step_up) if quoted_answers >= QUOTED_ANSWERS_PER_CYCLE:
return Interrupting(transcript_path, ruling, quoted_answers, step_up)
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() as ruling, step_up):
return Interrupting(transcript_path, ruling, quoted_answers, step_up)
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
return Closing(transcript_path, verdict)
case Interrupting(_, _, quoted_answers), HumanTyped(typed):
return Working(typed, quoted_answers)
case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed):
return Working(typed, quoted_answers, step_up)
case Interrupting(transcript_path, _, quoted_answers), TalkChosen():
return Talking(transcript_path, quoted_answers)
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
+19
View File
@@ -1,15 +1,24 @@
import sys
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 claude_code.reply import Limited
from claude_code.transcript import part_line
from machine_load.memory import ROOM_SHARE
from model_routing.ladder import Rung
from claude_code.session import Session
PRINTED_TOOL_INPUT = 160
# Seconds between reads of the machine's memory while too little of it is available to start a worker.
MEMORY_POLL = 60
# The auto-compact window, in tokens, handed to the worker's claude in the environment variable AUTO_COMPACT_WINDOW names. Claude Code compacts before the window fills, at about 170k: docs/decisions.md → `loop-claude: the worker's claude compacts its context before it fills a 200k window`.
AUTO_COMPACT_WINDOW = "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
COMPACT_WINDOW = 200_000
def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects) -> Failure | Limited | None:
wait_for_memory(effects)
try:
proc = effects.stream_claude(args, root, env)
except OSError as failure:
@@ -28,6 +37,16 @@ def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects
return worker_outcome(proc.wait(), result, resets)
def wait_for_memory(effects: Effects) -> None:
"""Returns once the machine has room for a worker, or its memory cannot be read, so loops running at once do not push it into swap. While it waits, it says so once on stderr and reads the memory again each MEMORY_POLL seconds."""
said = False
while (memory := effects.memory()) is not None and not memory.has_room():
if not said:
print(f"waiting to start the worker until at least {ROOM_SHARE:.0%} of the machine's memory is available; {memory.available // 1024} MiB of {memory.total // 1024} MiB is available now", file=sys.stderr, flush=True)
said = True
effects.sleep(MEMORY_POLL)
def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure | Limited | None:
if result is not None and hit_limit(result):
return Limited(max(resets, default=None), limit_said(result))
+4
View File
@@ -8,6 +8,7 @@ import typing
from failure import Failure
import git_repo
from machine_load.memory import Memory, read_memory
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
PYTHON_TIMEOUT = 600
@@ -37,6 +38,8 @@ class Effects:
git: Git
input: typing.Callable[[str], str]
local_time: typing.Callable[[float], str]
# The machine's memory; None where it cannot be read.
memory: typing.Callable[[], Memory | None]
now: typing.Callable[[], float]
on_terminal: typing.Callable[[], bool]
# Runs a Python script in a directory, as run_python does.
@@ -66,6 +69,7 @@ def system_effects() -> Effects:
git=git_repo.git,
input=input,
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)),
memory=read_memory,
now=time.time,
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
+57
View File
@@ -0,0 +1,57 @@
"""The escalation mark makes one escalation trigger step the worker up one rung, never two (docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`).
A worker whose run ends asking loop-claude for a higher rung cites the trigger that fired, and the judge quotes the passage where it fired as the verdict's escalation. The mark, Route.escalated_at, is how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. The session's transcript only grows, so the mark holds across cycles, and the archive's Worker: lines keep it for a rerun.
- Stamp. stamped() writes on the judge's verdict how many entries the judge read.
- Step. routing.after_unfinished() and routing.after_ruling() step the worker up on an escalation and move the mark to moved_to(verdict). A ruling's StepUp travels through the cycle's states, so the archive and the worker's next prompt name it.
- Show. transcript() puts STEP_LINE after the mark, telling the judge that the triggers before that line are spent. QUOTE_AFTER_STEP, in the judge's schema, tells the judge to quote only the worker's words after that line.
- Check. checked() keeps an escalation only where it quotes both the transcript the judge was shown and the worker's own lines after the mark, which since_step() renders, so a passage that bought one step cannot buy another.
"""
import dataclasses
import typing
from loop_claude.verdicts import Escalating, Verdict
from claude_code.entries import human_text, loop_text
from claude_code.transcript import render, Typed, verbatim
from model_routing.route import Route
# Only the judge reads the step line, so it is not a [loop] line.
STEP_TAG = "[step]"
STEP_LINE = f"{STEP_TAG} loop-claude stepped the worker up a rung here, so the escalation triggers that fired before this line are spent."
# Reply.escalation's description in cycle/judge.py carries this sentence, so the judge reads STEP_LINE as the mark.
QUOTE_AFTER_STEP = f"Where a {STEP_TAG} line says loop-claude stepped the worker up a rung, quote only the worker's own words after it, and leave this empty where the trigger fired only before it."
@dataclasses.dataclass(frozen=True)
class StepUp:
"""An interrupt's or a quoted answer's escalation stepping the route within a cycle: the route the worker ran on until the ruling, and the one it runs on after."""
before: Route
after: Route
def stamped(verdict: Verdict, entries_read: int) -> Verdict:
"""The verdict with how many transcript entries the judge read, where it may carry an escalation."""
return dataclasses.replace(verdict, entries_read=entries_read) if isinstance(verdict, Escalating) else verdict
def moved_to(verdict: Escalating) -> int | None:
"""Where the verdict's escalation would move the mark, if the escalation steps the worker; None for a verdict without one."""
return verdict.entries_read if verdict.escalation else None
def transcript(entries: list[dict], at: int, typed_answer: typing.Callable[[str], Typed | None]) -> str:
"""The transcript as the judge sees it. Where the mark, at, is above 0, STEP_LINE comes after that many entries."""
return "\n\n".join(part for part in (render(entries[:at], typed_answer), STEP_LINE if at else "", render(entries[at:], typed_answer)) if part)
def since_step(entries: list[dict], at: int) -> str:
"""The worker's own lines after the mark, all of them, however much of the transcript the judge is shown. loop-claude's prompts and the human's lines are left out, since they repeat earlier passages, such as the judge's evidence or the worker's question."""
# No loop-claude prompt is left to carry an answer the human typed.
return render([entry for entry in entries[at:] if human_text(entry) is None and loop_text(entry) is None], lambda prompt: None)
def checked(verdict: Verdict, *, since: str, shown: str) -> Verdict:
"""The verdict without its escalation unless the escalation quotes both texts: since, the worker's lines after the mark as since_step renders them, and shown, the transcript the judge was shown. A misquote, or a quote of a passage before the mark, drops the escalation, so the worker's rung holds."""
if isinstance(verdict, Escalating) and verdict.escalation and not (verbatim(verdict.escalation, since) and verbatim(verdict.escalation, shown)):
return dataclasses.replace(verdict, escalation="")
return verdict
+80 -117
View File
@@ -44,104 +44,40 @@ copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default roo
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
Before each worker starts, loop-claude waits until at least a quarter of the machine's memory is available
(bin/machine_load/memory.py).
Each worker's claude, the session /talk opens and the subagents either launches run with a 200k
auto-compact window (CLAUDE_CODE_AUTO_COMPACT_WINDOW, bin/loop_claude/cycle/worker.py), so each
compacts its context at about 170k tokens.
Every claude loop-claude starts runs the project's model, saved per <key> in
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
the session /talk opens and the judge on another rung; a project without an entry, as on its first
run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL
for the worker and the session /talk opens; with both set, nothing is asked.
Routing: the worker's rung
the session /talk opens and the judge on another rung, a model at an effort. A project without an
entry, as on its first run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the
judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with both set, nothing
is asked.
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
session /talk opens run on one of the ladder's rungs: a model at an effort. As a chunk starts, it is
routed on the item chunk-preflight names, read from todo.md on the default branch as the preflight
just fetched it (chunk_pick.chunk_item). That item is the earliest release's top item that does not
wait, but only where that release is the next one: the earliest after the newest vX.Y.Z tag that
todo.md has named at that tag or since, skipping a release its ## Renamed section marks renamed, or,
where no tag names a version, the earliest release. Otherwise no item routes the chunk. An item
waits while it is marked question, or while an item that blocks it is still in the table. The item's
L picks the worker's rung, stepping from the model's cheapest rung by WORKER_STEPS in
bin/model_routing/ladder.py, below it for a low L; without such an item, or with its L, E or I
unscored, the chunk runs on the model's cheapest rung.
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when
the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher
rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
without it.
Routing: the reviewers' rung
The routed item's E + I picks the reviewers' rung, stepping up from the cheapest rung by
REVIEW_STEPS in bin/model_routing/ladder.py, never below the worker's rung. Where it steps none and
the worker runs no higher than the cheapest rung, a pass REPLAYED in that file names runs on the
rung it names, the lowest a review-replay run found finding what the cheapest rung finds, even below
the worker's.
Routing: what the worker's prompts say
The worker's first prompt names the rung and the item, and asks the worker to name each item the
chunk takes, with its L and E + I, and to count the item's size again once it has read the code
(prompts.recount). The prompt names the rung of each review that runs on a rung other than the
worker's: the reviewers' rung or the replay's for each pass's reviewer, and the cheapest rung for
each comprehension seat and the security pass. It also names the reviewers' rung each higher E + I
picks, so the worker reviews an item it takes in on that rung in the same run. When the worker runs
below the cheapest rung, the prompt has it launch each subagent that files or scores todo.md items
on the rung subagent-rung --plan prints. The prompt after each unfinished verdict says this again,
since a step-up may have moved the worker. A reviewer or seat that rules the work below standard may
ask to rerun one rung up; each prompt names that rung. loop-claude hands the worker's claude its own
rung, the project's and the reviews' E + I, in LOOP_CLAUDE_WORKER_RUNG, LOOP_CLAUDE_PROJECT_RUNG and
LOOP_CLAUDE_ESCAPE_AND_IMPACT, and rule-hook refuses a review launched below the rung those pick for
it.
Routing: step-ups
The judge reports the highest L and the highest E + I the worker states for an item it takes in. The
next cycle steps the worker up to the rung that L picks, never down, and the reviewers to the rung
picked by the higher of two: that E + I, or the routed item's (Route.reviewed_on in
bin/model_routing/route.py). A level off its scale counts as none. Every second unfinished verdict
on a chunk steps it up one rung (routing.after_unfinished). So does an unfinished verdict on a
worker that ended its run asking for a higher rung, once the judge quotes the transcript showing
that the escalation trigger it named fired (~/.claude/CLAUDE.md → "Working with the codebase" lists
them). An interrupt or a quoted answer with such a quote steps the rung as it comes in, before the
human is asked or the worker resumes (routing.after_ruling). Each such step marks how many
transcript entries the session held, and from then on the judge must quote the worker's own lines
after that mark, where it reads a [step] line. Each step on an escalation stops two rungs above the
rung the chunk's item picks, and the worker's prompts offer it only while the worker is below that
limit.
Routing: the archive and reruns
Each finished or unfinished verdict, interrupt, quoted answer, stop and step-up in the archive ends
with a Worker: line, the route's JSON record (Route.record in bin/model_routing/route.py). A rerun
resumes an open chunk on the latest route named there, and counts its unfinished verdicts afresh.
It also reads a Worker: line an older loop-claude wrote as a sentence, such as "claude-opus-5-5 at
high effort, routed by item 3's L of 4 and E + I of 5". A rung no longer on the ladder, or below the
one its item's L picks, is dropped, and the chunk is routed afresh from todo.md. So is a chunk whose
archived line names an R + C, as loop-claude wrote before it routed on L. A todo.md or an archive
that cannot be read or parsed is said on stderr, and the chunk is routed without it.
Routing: the judge's rung
The judge of a model listed in JUDGE_REPLAYED (bin/loop_claude/routing.py) runs on the rung that the
reviewers' E + I (Route.reviewed_on) picks for a review from that model. It never runs below the
model's cheapest rung, and runs on it when no item routed the chunk or was taken in. Its rung stays
put when the worker steps up. A model is listed once judge-replay found its cheapest rung returning
every verdict the reference judge reproduced. Any other model's judge runs at the effort its
settings give.
Routing: the figures
Counting the cycles a verdict closed across all projects in the archive, the first loop to close one
20 or more cycles after the last measurement measures every finished chunk there, with no model run:
tokens by project, subagent type, rung and the tool whose results they took in, and, for each chunk
a todo.md item routed, grouped by the rung it started on: its review rounds past each pass's first,
its unfinished verdicts and its subagents' rungs. It writes them to routing-figures.md at the
archive's root. They call for a routing change when chunks routed onto a rung took more review
rounds or unfinished verdicts than chunks routed onto the next rung up, each rung with 5 chunks or
more, or when the reports of 5 or more subagents of one type were longer than the tool results they
read. Each call not raised before is an interrupt: claude, on the project's model, on the terminal
in ~/.claude, asked to put the calls to the human. Once that claude ends, the calls are listed in
routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the calls are said
on stderr, the loop goes on, and they are raised again at the next measurement. A line
`- <UTC time> Reset` in routing-calls-raised.md restarts both: the figures count only chunks that
finished after it, and a call raised before it may be raised again. A chunk that cannot be read is skipped and
named in the figures; figures that cannot be measured or written are said on stderr, and the loop
goes on.
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
loop to close one measures every finished chunk there, with no model run, and writes
routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures
make for a routing change, unless raised before, is an interrupt: claude, on the project's model,
on the terminal in ~/.claude, asked to put the calls to the human. Once that claude ends, the calls
are listed in routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the
calls are said on stderr, the loop goes on, and they are raised again at the next measurement.
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
loop-claude --help succeeds: the loop reloads into the edited script.
@@ -170,11 +106,12 @@ Exit 1, saying why, when:
more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is
always retried every 10 minutes. stderr says when the next try is due.
Exit 2, when the human is needed and cannot answer:
Exit 2, when the human is needed to go on:
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
- the input ends while a model is picked
- an interrupt's answer is empty, or the input ends before one is typed
- the claude opened for /talk, or for a release ready to cut, ends with nothing typed
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
Rerunning resumes any open session.
"""
@@ -186,18 +123,19 @@ import typing
from loop_claude.routing import after_unfinished, first_route, kept, routed_item
from transcript_archive.write import archive
from transcript_archive.location import archive_root, project_archive
from loop_claude.cycle.run import archived_stop, Concluded, Cycle, run_cycle
from loop_claude.loop.routing_check import check_routing
from loop_claude.project.checkout import checkout_root
from loop_claude.cycle.run import Concluded, Cycle, run_cycle
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
from chunk_pick import default_plan, DefaultPlan
from git_repo import default_ref
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.verdicts import Finished
from loop_claude.verdicts import Finished, Unfinished
from loop_claude.project.model_choice import get_or_ask_models
from todo_table import Item
from transcript_archive.read import latest_worker
from loop_claude.stop import needs_human, Stop
from transcript_archive import outcomes
from loop_claude.paths import Paths
from project_key import project_key
@@ -207,10 +145,11 @@ from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from model_routing.route import Route, route_from
from claude_code.session import Session, session_named, session_open, transcript_file
from loop_claude.stop import Stop
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
ORIGIN_TIMEOUT = 60
# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts.
UNFINISHED_LIMIT = 6
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
@@ -247,45 +186,69 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
return models
# After the reads above, so a loop that stops on one makes no worktree.
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
anchor = project_rung(models.worker)
route = routed(loop_run.route, anchor, models.worker, lambda: archived_route(archive_folder, session), item)
project = project_rung(models.worker)
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session), item)
print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True)
concluded = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
if isinstance(concluded, Stop):
return concluded
loop_run = after_verdict(loop_run, anchor, concluded)
if stop := archive_step(archive_folder, session, loop_run.task, concluded.route, loop_run.route, effects):
return stop
if stop := check_routing(archive_root(paths.home, env), anchor or Rung(models.worker), paths, effects):
closed = closed_cycle(loop_run, project, concluded, archive_folder, session, effects)
if isinstance(closed, Stop):
return closed
loop_run = closed
if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects):
return stop
def routed(route: Route | None, anchor: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
"""The route the cycle runs on. anchor is the project's rung, and model the project's model.
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
"""The route the cycle runs on. project is the project's rung, and model the project's model.
Where anchor is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, while that route's rung is at or above the one its item's L picks from anchor. Else the plan item routes the chunk afresh.
Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh.
"""
if anchor is None:
if project is None:
return Route(Rung(model))
route = route or archived()
return route if route and kept(route, anchor) else first_route(anchor, item())
return route if route and kept(route, project) else first_route(project, item())
def after_verdict(loop_run: LoopRun, anchor: Rung | None, concluded: Concluded) -> LoopRun:
"""The loop run the next cycle starts from. A finished chunk drops its route. An unfinished one takes the route after_unfinished makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised; off the ladder, it keeps that route."""
def closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, session: Session, effects: Effects) -> LoopRun | Stop:
"""The loop run after a cycle concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
after = after_verdict(loop_run, project, concluded)
if stop := archive_step(archive_folder, session, after.task, concluded.route, after.route, effects):
return stop
if limit := reached_limit(after):
# An unfinished verdict always leaves a route; the `or` only satisfies LoopRun.route's optional type. The stop is archived with that route, the one the next cycle would run on, so a rerun resumes there.
return archived_stop(archive_folder, session, after.task, after.route or concluded.route, limit, limit.reason, effects)
return after
def reached_limit(loop_run: LoopRun) -> Stop | None:
"""The stop that needs the human once the loop run holds UNFINISHED_LIMIT unfinished verdicts running."""
if loop_run.unfinished_run < UNFINISHED_LIMIT:
return None
return needs_human("go on with the chunk", f"the judge ruled it unfinished {loop_run.unfinished_run} cycles running; finish the chunk yourself, or rerun loop-claude to give it {UNFINISHED_LIMIT} more cycles")
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
"""The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route stepped_route makes, the evidence the judge gave for the verdict, and counts the verdict."""
verdict = concluded.verdict
if isinstance(verdict, Finished):
return dataclasses.replace(loop_run, route=None, unfinished_evidence="")
route = after_unfinished(anchor, concluded.route, verdict) if anchor else concluded.route
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence)
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0)
route = stepped_route(project, concluded.route, verdict)
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1)
def stepped_route(project: Rung | None, ended_on: Route, verdict: Unfinished) -> Route:
"""The route an unfinished chunk's next cycle starts on: the route after_unfinished makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised. Off the ladder there is no rung to step, and it keeps that route."""
return after_unfinished(project, ended_on, verdict) if project else ended_on
def archive_step(archive_folder: pathlib.Path, session: Session, task: str, before: Route, after: Route | None, effects: Effects) -> Stop | None:
"""Archives the route after an unfinished verdict as a step-up, where its record differs from the route before it: a higher rung, or a higher E + I taken in. The verdict itself names the route before, which its cycle ran on."""
if after is None or after.record() == before.record():
"""Archives the route after an unfinished verdict as a step-up, where its worker line differs from the one before it: a higher rung, or a higher E + I taken in. The verdict itself names the route before, which its cycle ran on."""
if after is None or after.worker_line() == before.worker_line():
return None
path = transcript_file(session)
failure = archive(archive_folder, path, task, outcomes.stepped_up(after.record()), effects.now()) if path else None
failure = archive(archive_folder, path, task, outcomes.stepped_up(after.worker_line()), effects.now()) if path else None
return Stop(1, failure.reason) if failure else None
+2
View File
@@ -24,6 +24,8 @@ class LoopRun:
unfinished_evidence: str
# Set by each unfinished verdict; None before the chunk's first one, and once it finishes.
route: Route | None = None
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
unfinished_run: int = 0
def decode_handed(handed: str, kind: type[T]) -> T | None:
+43 -34
View File
@@ -1,10 +1,19 @@
"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`."""
"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`.
The worker, and the session /talk opens, run on a Route (model_routing/route.py). A model off the ladder gets a route without an item, and it is never stepped.
- Start. routed_item finds the plan item that routes a fresh chunk, if there is one with L, E and I scored; first_route picks the worker's rung from its L, or the project's rung without an item.
- Rerun. kept decides whether a rerun resumes the route its archive last names.
- Step-up. after_unfinished raises the route after an unfinished verdict, after_ruling after an interrupt or a quoted answer that carries an escalation; escalation_cap bounds an escalation, and loop_claude/escalation_mark.py states the escalation mark's rule.
- Judge. judge_rung picks the rung of the judge of a JUDGE_REPLAYED model.
"""
import dataclasses
from chunk_pick import chunk_item, LastCut, Next
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung
from loop_claude.verdicts import escalation_mark, Interrupt, QuotedAnswer, Unfinished
from loop_claude import escalation_mark
from failure import Failure
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
from todo_table import Item, items, NoItemsTable
from model_routing.route import Route
@@ -27,64 +36,64 @@ def routed_item(todo: str, cut: LastCut) -> Item | Failure | None:
return takes if takes and takes.likelihood and takes.escape_and_impact else None
def first_route(anchor: Rung, item: Item | None) -> Route:
"""The route a chunk starts on: the rung its item's L picks from anchor, the project's rung."""
def first_route(project: Rung, item: Item | None) -> Route:
"""The route a chunk starts on: the rung its item's L picks from the project's rung, or the project's rung without an item."""
if item is None:
return Route(anchor)
return Route(worker_rung(anchor, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
return Route(project)
return Route(worker_rung(project, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
def kept(route: Route, anchor: Rung) -> bool:
def kept(route: Route, project: Rung) -> bool:
"""Whether a chunk keeps route: its rung is on the ladder and at or above item_rung."""
return kept_rung(anchor, route) == route.rung
return kept_rung(project, route) == route.rung
def kept_rung(anchor: Rung, route: Route) -> Rung:
def kept_rung(project: Rung, route: Route) -> Rung:
"""The route's rung, raised to item_rung where it is lower or off the ladder."""
return highest(route.rung, item_rung(anchor, route))
return highest(route.rung, item_rung(project, route))
def item_rung(anchor: Rung, route: Route) -> Rung:
"""The rung the route's item's L picks from anchor, the project's rung, or anchor itself when no item routed it. The worker may run on a rung below anchor."""
return worker_rung(anchor, route.likelihood) if route.item else anchor
def item_rung(project: Rung, route: Route) -> Rung:
"""The rung the route's item's L picks from the project's rung, or the project's rung itself when no item routed it. The worker may run on a rung below the project's."""
return worker_rung(project, route.likelihood) if route.item else project
def escalation_rungs(anchor: Rung, route: Route) -> tuple[Rung, ...]:
def escalation_rungs(project: Rung, route: Route) -> tuple[Rung, ...]:
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder."""
if route.rung not in LADDER:
return ()
return LADDER[position(route.rung) + 1:position(escalation_cap(anchor, route)) + 1]
return LADDER[position(route.rung) + 1:position(escalation_cap(project, route)) + 1]
def escalation_cap(anchor: Rung, route: Route) -> Rung:
def escalation_cap(project: Rung, route: Route) -> Rung:
"""The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
It counts from item_rung, the rung the chunk started on, so a step-up between cycles narrows what the worker may climb without a yes, and never widens it.
"""
return climbed(item_rung(anchor, route), ESCALATION_CAP)
return climbed(item_rung(project, route), ESCALATION_CAP)
def after_unfinished(anchor: Rung, route: Route, verdict: Unfinished) -> Route:
def after_unfinished(project: Rung, route: Route, verdict: Unfinished) -> Route:
"""The route the next cycle runs on after an unfinished verdict.
Its rung never falls. It first rises to the rung that the verdict's highest L taken in picks, where that is higher. From there it steps one rung up on every second unfinished verdict, or on an escalation while below escalation_cap; where both fall on one verdict, it steps once. A step on an escalation moves the route's mark, Route.escalated_at, to where the judge stopped reading, so the trigger it quoted buys no second step; a step on the count of unfinished verdicts alone keeps the mark. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
Its rung never falls. It first rises to the rung that the verdict's highest L taken in picks, where that is higher. From there it steps one rung up on every second unfinished verdict, or on an escalation while below escalation_cap; where both fall on one verdict, it steps once. A step on an escalation moves the mark, as loop_claude/escalation_mark.py says; a step on the count of unfinished verdicts alone keeps it. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
"""
rung = raised(anchor, route, verdict.highest_likelihood_taken_in)
mark = escalation_mark(verdict)
if route.unfinished + 1 >= UNFINISHED_PER_STEP or (mark is not None and below_cap(anchor, route, rung)):
rung = raised(project, route, verdict.highest_likelihood_taken_in)
mark = escalation_mark.moved_to(verdict)
if route.unfinished + 1 >= UNFINISHED_PER_STEP or (mark is not None and below_cap(project, route, rung)):
after = one_rung_up(route, rung, route.escalated_at if mark is None else mark)
else:
after = dataclasses.replace(route, rung=rung, unfinished=route.unfinished + 1)
return after.taking_in(verdict.highest_escape_and_impact_taken_in)
def after_ruling(anchor: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
def after_ruling(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
"""The route after the judge's interrupt or quoted answer: unchanged without an escalation. With one, raised to the rung the highest L taken in picks, and one rung up from there while below escalation_cap, moving the mark as after_unfinished does. Neither is an unfinished verdict, so the count of those restarts only with a step."""
mark = escalation_mark(verdict)
mark = escalation_mark.moved_to(verdict)
if mark is None:
return route
rung = raised(anchor, route, verdict.highest_likelihood_taken_in)
return one_rung_up(route, rung, mark) if below_cap(anchor, route, rung) else dataclasses.replace(route, rung=rung)
rung = raised(project, route, verdict.highest_likelihood_taken_in)
return one_rung_up(route, rung, mark) if below_cap(project, route, rung) else dataclasses.replace(route, rung=rung)
def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
@@ -92,14 +101,14 @@ def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0, escalated_at=escalated_at)
def below_cap(anchor: Rung, route: Route, rung: Rung) -> bool:
def below_cap(project: Rung, route: Route, rung: Rung) -> bool:
"""Whether an escalation trigger may take the worker one rung up from rung without the human's yes: rung is below escalation_cap, two rungs above item_rung."""
return position(rung) < position(escalation_cap(anchor, route))
return position(rung) < position(escalation_cap(project, route))
def raised(anchor: Rung, route: Route, likelihood_taken_in: int) -> Rung:
"""kept_rung, raised to the rung that likelihood_taken_in picks from anchor. likelihood_taken_in is the highest L the worker took into the chunk, or 0 for none."""
return highest(kept_rung(anchor, route), worker_rung(anchor, likelihood_taken_in)) if likelihood_taken_in else kept_rung(anchor, route)
def raised(project: Rung, route: Route, likelihood_taken_in: int) -> Rung:
"""kept_rung, raised to the rung that likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, or 0 for none."""
return highest(kept_rung(project, route), worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else kept_rung(project, route)
def judge_rung(judge_model: str, route: Route) -> Rung:
@@ -107,7 +116,7 @@ def judge_rung(judge_model: str, route: Route) -> Rung:
A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give.
"""
anchor = project_rung(judge_model)
if anchor is None or judge_model not in JUDGE_REPLAYED:
cheapest = project_rung(judge_model)
if cheapest is None or judge_model not in JUDGE_REPLAYED:
return Rung(judge_model)
return review_floor(anchor, route.reviewed_on())
return review_floor(cheapest, route.reviewed_on())
+39 -2
View File
@@ -116,6 +116,11 @@ if os.path.basename(sys.argv[0]) == "loop-claude":
record({"argv": sys.argv[1:]})
pause = time.sleep
time.sleep = lambda seconds: record({"sleep": seconds}) if seconds >= 1 else pause(seconds)
# The host's own memory doesn't matter: every read finds all of it available.
sys.path.insert(0, os.path.dirname(os.path.realpath(sys.argv[0])))
import pathlib
from machine_load import memory
memory.MEMINFO = pathlib.Path(os.environ["FAKE_MEMINFO"])
"""
PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n"
@@ -181,8 +186,10 @@ class Checkout:
site = self.temp / "site"
site.mkdir()
(site / "sitecustomize.py").write_text(SITECUSTOMIZE)
(self.temp / "meminfo").write_text("MemTotal: 16 kB\nMemAvailable: 16 kB\n")
self.env.update({
"FAKE_CLAUDE_LOG": str(self.temp / "calls.jsonl"),
"FAKE_MEMINFO": str(self.temp / "meminfo"),
"FAKE_CLAUDE_SCENARIO": str(self.temp / "scenario.json"),
"GIT_CONFIG_GLOBAL": os.devnull,
"GIT_CONFIG_NOSYSTEM": "1",
@@ -240,7 +247,7 @@ class Checkout:
os.write(controller, typed.encode())
output, deadline = b"", time.monotonic() + 60
while time.monotonic() < deadline:
if select.select([controller], [], [], 1)[0]:
if select.select([controller], [], [], 0.05)[0]:
try:
chunk = os.read(controller, 4096)
except OSError:
@@ -640,6 +647,36 @@ class Cycles(unittest.TestCase):
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
self.assertIn("claude left no transcript for session", run.stderr)
def test_exits_2_after_six_unfinished_verdicts_running_and_a_rerun_gets_six_more(self):
checkout = Checkout(self)
six = [step for _ in range(6) for step in (worker(), judge())]
run = checkout.run(six + [worker()])
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"] * 6))
self.assertIn("the judge ruled it unfinished 6 cycles running", run.stderr.strip().splitlines()[-1])
self.assertIn("rerun loop-claude to give it 6 more cycles", run.stderr.strip().splitlines()[-1])
stops = [outcome for outcome in checkout.archived().values() if "Stopped: " in outcome]
self.assertEqual(len(stops), 1)
self.assertIn(f"\n\nWorker: {OFF_LADDER}\n", stops[0])
run = checkout.run(six[:-2] + [worker()])
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 6))
def test_archives_the_stop_on_the_route_the_sixth_verdict_stepped_to_and_a_rerun_resumes_there(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
checkout.commit_plan(CHEAP)
run = checkout.run([step for _ in range(6) for step in (worker(), judge())] + [worker()])
self.assertEqual(run.code, 2)
stepped = '<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stopped: '
self.assertEqual(len([outcome for outcome in checkout.archived().values() if stepped in outcome]), 1)
run = checkout.run([worker()])
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-opus-5-5", "xhigh")])
def test_five_unfinished_verdicts_and_a_finished_one_do_not_add_up_to_six(self):
checkout = Checkout(self)
five = [step for _ in range(5) for step in (worker(), judge())]
run = checkout.run(five + [worker(), judge(finished=True)] + five + [worker()])
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 12))
class Interrupt(unittest.TestCase):
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
@@ -861,7 +898,7 @@ 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, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE} for cycle in (2, 3, 4)])
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5,", run.stdout)
outside = checkout.temp / "outside"
+84 -53
View File
@@ -10,18 +10,18 @@ import stat
import subprocess
import sys
import tempfile
import time
import unittest
import unittest.mock
import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from routing_figures import archive
from routing_figures import archive, measure
from loop_claude.project import checkout, model_choice, records
from chunk_pick import DefaultPlan, LastCut
from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python
from claude_code import entries, reply, session
from loop_claude import escalation_mark, paths, routing
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
@@ -29,10 +29,10 @@ from model_routing import ladder
from model_routing.ladder import LADDER, Rung
from claude_code.reply import Limited
from loop_claude.loop import main, reload, routing_check
from machine_load import memory
from transcript_archive import outcomes, write
from loop_claude import paths, routing
from transcript_archive.location import project_archive
from model_routing.route import Record, Route, route_from
from model_routing.route import Route, route_from, WorkerLine
from loop_claude.stop import Stop
from utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
@@ -59,9 +59,11 @@ def human(content):
class FakeEffects:
"""Effects that record each call and answer from a script, one answer per call."""
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True):
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()):
self.calls = []
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
# Without a script, every read finds all memory available.
self.free_memory = list(free_memory)
self.terminal = on_terminal
self.worker_environments = []
self.terminal_environments = []
@@ -75,6 +77,7 @@ class FakeEffects:
git=lambda *args, cwd: self.answer("git", list(args)),
input=lambda prompt: self.answer("input", prompt),
local_time=lambda seconds: f"<{seconds}>",
memory=self.memory,
now=lambda: NOW,
on_terminal=lambda: self.terminal,
python=lambda args, cwd: self.answer("python", (args, cwd)),
@@ -82,6 +85,10 @@ class FakeEffects:
stream_claude=self.stream,
)
def memory(self):
self.calls.append(("memory", None))
return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16)
def on_terminal_claude(self, args, cwd, env):
self.terminal_environments.append(env)
return self.answer("claude_on_terminal", args)
@@ -105,12 +112,6 @@ class FakeEffects:
return [what for called, what in self.calls if called == seam]
def uuid7():
# Python 3.11, the floor, has no uuid.uuid7.
random = int.from_bytes(os.urandom(10))
return uuid.UUID(int=int(time.time() * 1000) << 80 | 7 << 76 | (random >> 62 & 0xFFF) << 64 | 2 << 62 | random & (1 << 62) - 1)
def ran(stdout="", code=0, stderr=""):
return subprocess.CompletedProcess([], code, stdout, stderr)
@@ -135,7 +136,7 @@ class Worker:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "a") as handle:
if flag == "--session-id":
handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid7())}) + "\n")
handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid.uuid7())}) + "\n")
if self.prompted:
handle.write(json.dumps({**human(args[args.index("-p") + 1]), "promptSource": "sdk"}) + "\n")
handle.write(json.dumps(assistant({"type": "text", "text": self.text})) + "\n")
@@ -193,6 +194,20 @@ class Transitions(unittest.TestCase):
with self.subTest(state=state, event=event), self.assertRaises(ValueError):
states.transition(state, event)
def test_a_rulings_step_up_reaches_the_worker_it_resumes_through_the_answer_the_human_types_and_no_further(self):
step_up = escalation_mark.StepUp(Route(Rung("claude-opus-5-5", "medium")), Route(Rung("claude-opus-5-5", "high"), escalated_at=3))
interrupt, quoted = Interrupt("e", "q", "round 2: 🔴"), QuotedAnswer("e", "q", "A.", "round 2: 🔴")
for state, event, after in (
(states.Judging("/t"), states.Ruled(quoted, step_up), states.Working(quoted, 1, step_up)),
(states.Judging("/t", 3), states.Ruled(quoted, step_up), states.Interrupting("/t", quoted, 3, step_up)),
(states.Judging("/t"), states.Ruled(interrupt, step_up), states.Interrupting("/t", interrupt, 0, step_up)),
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTyped(TYPED), states.Working(TYPED, 0, step_up)),
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen(), states.Talking("/t")),
(states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")),
):
with self.subTest(state=state, event=event):
self.assertEqual(states.transition(state, event), after)
class QuestionFor(unittest.TestCase):
def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self):
@@ -210,7 +225,7 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
return run.Cycle(anchor=None, effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence)
return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -230,11 +245,11 @@ class Cycles(unittest.TestCase):
self.assertIn("- A preflight fact.", fresh)
self.assertNotIn("- A preflight fact.", resumed)
def test_a_worker_is_handed_the_projects_rung_its_own_and_its_reviews_e_plus_i_in_its_environment(self):
def test_a_worker_is_handed_the_projects_rung_its_own_its_reviews_e_plus_i_and_its_compaction_window_in_its_environment(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
cycle = dataclasses.replace(self.cycle(fake), project=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
self.assertEqual(run.run_cycle(cycle).verdict, Finished("working"))
self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}])
self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5", "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "200000"}])
def test_the_claude_an_interrupt_resumes_is_handed_the_same_rungs_as_the_worker(self):
def answer(args):
@@ -242,7 +257,7 @@ class Cycles(unittest.TestCase):
handle.write(json.dumps(human("the second")) + "\n")
return 0
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], inputs=["/talk"], on_terminal_claude=[answer], git=[""])
cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
cycle = dataclasses.replace(self.cycle(fake), project=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(cycle).verdict, Finished("working"))
self.assertEqual(fake.terminal_environments, fake.worker_environments)
@@ -364,7 +379,7 @@ class Cycles(unittest.TestCase):
def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")])
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
@@ -381,7 +396,7 @@ class Cycles(unittest.TestCase):
def test_a_quoted_answer_past_the_cap_archives_the_escalation_it_carried_with_the_interrupt_and_steps_up(self):
steps = [judged("quoted", answer="Use A.")] * 3 + [judged("quoted", answer="Use A.", escalation="working")]
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, inputs=[""])
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
kept = "".join(self.archived_outcomes())
@@ -389,18 +404,17 @@ class Cycles(unittest.TestCase):
self.assertIn(f"Stepped up\n\nWorker: {OPUS_179_AT_6}\n", kept)
def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_taken_in_l_picks(self):
cycle = dataclasses.replace(self.cycle(FakeEffects()), anchor=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4))
cycle = dataclasses.replace(self.cycle(FakeEffects()), project=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4))
for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)):
with self.subTest(ruling=ruling):
self.assertEqual(run.escalated(cycle, states.Ruled(ruling)), cycle)
stepped = run.escalated(cycle, states.Ruled(Interrupt("e", "q", "round 2: 🔴", 4, entries_read=3)))
self.assertEqual((stepped.route, stepped.stepped_from), (Route(Routing.XHIGH, 3, 3, 4, escalated_at=3), cycle.route))
self.assertIsNone(run.ruling_step_up(cycle, ruling))
self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", 4, entries_read=3)), escalation_mark.StepUp(cycle.route, Route(Routing.XHIGH, 3, 3, 4, escalated_at=3)))
def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self):
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)]
rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("quoted", answer="Use A.", escalation="working"), judged("finished")]
fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."])
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.HIGH, 179, 2, 5, escalated_at=4))
@@ -413,7 +427,7 @@ class Cycles(unittest.TestCase):
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent)]
rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("unfinished", escalation=escalation)]
fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."])
cycle = dataclasses.replace(self.cycle(fake), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
cycle = dataclasses.replace(self.cycle(fake), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded, run.Concluded(verdict, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)))
@@ -437,7 +451,7 @@ class Cycles(unittest.TestCase):
def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."])
cycle = dataclasses.replace(self.cycle(fake), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
cycle = dataclasses.replace(self.cycle(fake), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
@@ -570,6 +584,21 @@ class Limits(unittest.TestCase):
self.assertEqual(entries.rejected_until({"type": "rate_limit_event", "rate_limit_info": info}), want, info)
class MemoryWait(unittest.TestCase):
def test_a_worker_starts_only_once_a_quarter_of_memory_is_available(self):
fake = FakeEffects(free_memory=[memory.Memory(available=3, total=16), memory.Memory(available=3, total=16), memory.Memory(available=4, total=16)], streams=[Streamed(0)])
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertIsNone(worker.run_worker("/r", [], {}, fake.effects()))
self.assertEqual([seam for seam, _ in fake.calls], ["memory", "sleep", "memory", "sleep", "memory", "stream_claude"])
self.assertEqual(fake.made("sleep"), [worker.MEMORY_POLL] * 2)
self.assertEqual(said.getvalue().count("waiting"), 1, said.getvalue())
def test_a_worker_starts_at_once_where_memory_cannot_be_read(self):
fake = FakeEffects(free_memory=[None], streams=[Streamed(0)])
self.assertIsNone(worker.run_worker("/r", [], {}, fake.effects()))
self.assertEqual([seam for seam, _ in fake.calls], ["memory", "stream_claude"])
class Interrupts(unittest.TestCase):
def put(self, fake, answer_here=True):
with contextlib.redirect_stderr(io.StringIO()) as said:
@@ -604,7 +633,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=[""])
stop = interrupt.talk(home, uuid7(), Rung("m", "high"), str(path), paths.paths_from(pathlib.Path(home)), {}, fake.effects())
stop = interrupt.talk(home, uuid.uuid7(), Rung("m", "high"), str(path), paths.paths_from(pathlib.Path(home)), {}, fake.effects())
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
@@ -614,7 +643,7 @@ class Interrupts(unittest.TestCase):
path.write_text(json.dumps(human("a")) + "\n")
fake = FakeEffects(on_terminal_claude=[0], git=[""])
handed = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort"}
interrupt.talk(home, uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects())
interrupt.talk(home, uuid.uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects())
self.assertEqual(fake.terminal_environments, [handed])
@@ -882,24 +911,24 @@ class Routing(unittest.TestCase):
without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |")
self.assertIsNone(routing.routed_item(without_i, NO_CUT))
def test_archives_the_route_as_a_json_record_it_reads_back_field_by_field(self):
def test_archives_the_route_as_a_json_worker_line_it_reads_back_field_by_field(self):
route = Route(self.HIGH, 3, 4, 5)
self.assertEqual(route.record(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5}')
self.assertEqual(route_from(route.record()), route)
self.assertEqual(Route(Rung("worker-model")).record(), '{"model": "worker-model"}')
self.assertEqual(route.worker_line(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5}')
self.assertEqual(route_from(route.worker_line()), route)
self.assertEqual(Route(Rung("worker-model")).worker_line(), '{"model": "worker-model"}')
self.assertEqual(route_from('{"model": "worker-model"}'), Route(Rung("worker-model")))
marked = Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12)
self.assertEqual(marked.record(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}')
self.assertEqual(route_from(marked.record()), marked)
self.assertEqual(route_from(Route(self.HIGH, escalated_at=3).record()), Route(self.HIGH, escalated_at=3))
self.assertEqual(marked.worker_line(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}')
self.assertEqual(route_from(marked.worker_line()), marked)
self.assertEqual(route_from(Route(self.HIGH, escalated_at=3).worker_line()), Route(self.HIGH, escalated_at=3))
def test_leaves_the_count_of_unfinished_verdicts_out_of_the_record_so_a_rerun_restarts_it(self):
self.assertEqual(route_from(Route(self.HIGH, 3, 4, 5, unfinished=1).record()), Route(self.HIGH, 3, 4, 5))
def test_leaves_the_count_of_unfinished_verdicts_out_of_the_worker_line_so_a_rerun_restarts_it(self):
self.assertEqual(route_from(Route(self.HIGH, 3, 4, 5, unfinished=1).worker_line()), Route(self.HIGH, 3, 4, 5))
def test_reads_no_route_from_a_record_of_unknown_or_mistyped_fields_or_levels_off_their_scales(self):
for record in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": '):
with self.subTest(record=record):
self.assertIsNone(route_from(record))
def test_reads_no_route_from_a_worker_line_of_unknown_or_mistyped_fields_or_levels_off_their_scales(self):
for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": '):
with self.subTest(line=line):
self.assertIsNone(route_from(line))
def test_reads_the_route_from_a_line_loop_claude_wrote_before_it_archived_json(self):
self.assertEqual(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5"), Route(self.HIGH, 3, 4, 5))
@@ -949,12 +978,12 @@ class RouteSources(unittest.TestCase):
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
self.assertIsNone(main.archived_route(archive, opened))
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.record(), "working", "j", ""), NOW))
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW))
with contextlib.redirect_stderr(stderr):
self.assertEqual(main.archived_route(archive, opened), route)
self.assertEqual(stderr.getvalue(), "")
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(Record('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1))
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIsNone(main.archived_route(archive, opened))
self.assertEqual(stderr.getvalue(), 'routing the chunk afresh: the archive\'s latest Worker: line names no route loop-claude can read: {"model": "claude-opus-5-5", "rung": 3}\n')
@@ -974,7 +1003,8 @@ class Steps(unittest.TestCase):
def test_a_finished_verdict_clears_the_route_and_the_evidence(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS))
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", 4), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new"))
self.assertEqual(main.after_verdict(dataclasses.replace(run_with, unfinished_run=3), self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", 4), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4))
@@ -1000,7 +1030,7 @@ class Steps(unittest.TestCase):
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
before = Route(self.OPUS, 3, 3, 4)
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.record(), "working", "j", ""), NOW))
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", 4), before))
self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects()))
self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
@@ -1022,7 +1052,7 @@ class Steps(unittest.TestCase):
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
before = Route(self.OPUS, 3, 3, 4)
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.record(), "working", "j", ""), NOW))
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", highest_escape_and_impact_taken_in=6), before))
self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects()))
self.assertEqual(main.archived_route(archive, opened), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6))
@@ -1169,10 +1199,11 @@ class WorkerArgs(unittest.TestCase):
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus))
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 4, 8), opus))
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "max"), 3, 4, 5), opus))
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus))
self.assertIn("before creating a new one.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
self.assertIn("before creating a new one.\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self):
opus = Rung("claude-opus-5-5", "medium")
@@ -1292,6 +1323,7 @@ class JudgePrompt(unittest.TestCase):
self.assertEqual(grounds.since_step, "round 3: 🔴")
prompt, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 0)
self.assertNotIn("stepped the worker up", prompt)
self.assertEqual(grounds.shown, "round 2: 🔴\n\nround 3: 🔴")
self.assertEqual(grounds.since_step, "round 2: 🔴\n\nround 3: 🔴")
def test_drops_an_escalation_quote_from_after_the_step_up_that_the_tail_it_shows_cuts_off(self):
@@ -1325,11 +1357,6 @@ class Grounded(unittest.TestCase):
self.assertFalse(judge.grounded("Decision for you ... invented", transcript))
self.assertFalse(judge.grounded("... …", transcript))
def test_an_answer_holds_only_word_for_word(self):
self.assertTrue(judge.verbatim("Merge **ff-only**.", "Merge ff-only.\nNever squash."))
self.assertFalse(judge.verbatim("Merge ... squash.", "Merge ff-only.\nNever squash."))
self.assertFalse(judge.verbatim("", "Merge ff-only."))
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
@@ -1482,6 +1509,10 @@ class HelpLimits(unittest.TestCase):
self.assertIn("fails three times running, retried a minute apart", said)
self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said)
self.assertIn(f"still running after {PYTHON_TIMEOUT} s", said)
self.assertIn(f"Once {measure.CYCLES_PER_CHECK} cycles have closed across all projects", said)
self.assertIn(f"run with a {worker.COMPACT_WINDOW // 1000}k auto-compact window", said)
self.assertIn(f"unfinished {main.UNFINISHED_LIMIT} cycles running", said)
self.assertIn(f"rerun to give it {main.UNFINISHED_LIMIT} more", said)
class ExitContract(unittest.TestCase):
@@ -1496,7 +1527,7 @@ class ExitContract(unittest.TestCase):
("cycle/interrupt.py", "talk", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
("cycle/interrupt.py", "talk", "1", "f'could not tell whether you typed anything:", read),
("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
("cycle/run.py", "stopped", "1", "f'{failure.reason}", read),
("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
("cycle/run.py", "keep_answer", "1", "failure.reason", read),
("cycle/run.py", "rule", "1", "entries.reason", read),
+3 -6
View File
@@ -11,7 +11,7 @@ class Interrupt:
# The highest L the judge saw the worker take into the chunk, 0 for none: an escalation steps up from the rung that L picks.
highest_likelihood_taken_in: int = 0
release_ready: bool = False
# How many transcript entries the judge read, which judge_once stamps. An escalation the verdict carries moves the route's mark there. None means judge_once never stamped it, and then its escalation doesn't step the worker.
# How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
entries_read: int | None = None
@@ -46,8 +46,5 @@ class Unfinished:
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
def escalation_mark(verdict: Interrupt | QuotedAnswer | Unfinished) -> int | None:
"""Where the verdict's escalation would move the route's mark, if it steps the worker; None where it carries none."""
return verdict.entries_read if verdict.escalation else None
# The verdicts that may carry an escalation.
Escalating = Interrupt | QuotedAnswer | Unfinished
View File
+38
View File
@@ -0,0 +1,38 @@
"""How much of the machine's memory is available, as /proc/meminfo's MemAvailable and MemTotal state it. A worker starts while at least ROOM_SHARE of it is available. The rest is split across the heavy slots, as the memory limit run-heavy gives each container."""
import dataclasses
import pathlib
import re
MEMINFO = pathlib.Path("/proc/meminfo")
# A worker starts only while at least this share of the machine's memory is available; the human chose it, as no standard sets one. The rest is the heavy slots' share, so changing it also changes the memory limit run-heavy gives a container.
ROOM_SHARE = 0.25
@dataclasses.dataclass(frozen=True)
class Memory:
"""The machine's memory, in kB as /proc/meminfo counts it: what a new process can have without swapping, and all of it."""
available: int
total: int
def has_room(self) -> bool:
return self.available >= ROOM_SHARE * self.total
def slot_share(self, slots: int) -> int:
"""The memory limit, in MiB, that run-heavy gives each container a slot's command makes: what ROOM_SHARE leaves, split evenly across the slots."""
return int(self.total * (1 - ROOM_SHARE)) // slots // 1024
def parsed(meminfo: str) -> Memory | None:
"""The memory a /proc/meminfo text states; None where it lacks MemAvailable or MemTotal."""
fields = dict(re.findall(r"^(MemAvailable|MemTotal):\s+(\d+) kB$", meminfo, re.MULTILINE))
if len(fields) != 2:
return None
return Memory(available=int(fields["MemAvailable"]), total=int(fields["MemTotal"]))
def read_memory(meminfo: pathlib.Path | None = None) -> Memory | None:
"""The machine's memory, read from meminfo or else MEMINFO; None where it cannot be read, as off Linux."""
try:
return parsed((meminfo or MEMINFO).read_text())
except OSError:
return None
+51
View File
@@ -0,0 +1,51 @@
"""The machine's heavy slots: one per 4 CPUs, and at least one, each a file locked with flock that every session on the machine shares."""
import fcntl
import os
import pathlib
import time
import typing
CPUS_PER_SLOT = 4
# Seconds between tries while every slot is held; a slot frees as its command exits.
POLL_SECONDS = 1
def usable_cpus() -> int | None:
"""The CPUs this process may run on, which an affinity mask can make fewer than the machine's; None where the count is unknown."""
return len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count()
def slot_count(cpus: int | None) -> int:
return max(1, (cpus or 0) // CPUS_PER_SLOT)
def slot_folder(env: typing.Mapping[str, str]) -> pathlib.Path:
state = env.get("XDG_STATE_HOME") or str(pathlib.Path.home() / ".local" / "state")
return pathlib.Path(state) / "run-heavy"
def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None:
"""The number and open file of a slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
for slot in range(slots):
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
os.close(fd)
continue
except OSError:
os.close(fd)
raise
return slot, fd
return None
def waited_slot(folder: pathlib.Path, slots: int, say: typing.Callable[[], None], sleep: typing.Callable[[float], None] = time.sleep) -> tuple[int, int]:
"""The number and open file of a slot this call locked, once one frees. While every slot is held, it calls say once and tries again each POLL_SECONDS."""
said = False
while (taken := taken_slot(folder, slots)) is None:
if not said:
say()
said = True
sleep(POLL_SECONDS)
return taken
+91
View File
@@ -0,0 +1,91 @@
import errno
import fcntl
import os
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from machine_load import memory
from machine_load.slots import slot_count
from machine_load import slots
class SlotCount(unittest.TestCase):
def test_one_slot_per_four_cpus_and_never_none(self):
for cpus, slots in ((16, 4), (8, 2), (7, 1), (4, 1), (1, 1), (None, 1)):
self.assertEqual(slot_count(cpus), slots, cpus)
class MemoryShare(unittest.TestCase):
def test_has_room_from_a_quarter_of_memory_available(self):
self.assertFalse(memory.Memory(available=3, total=16).has_room())
self.assertTrue(memory.Memory(available=4, total=16).has_room())
def test_reads_available_and_total_memory_from_meminfo(self):
meminfo = "MemTotal: 16387072 kB\nMemFree: 981236 kB\nMemAvailable: 4096000 kB\n"
self.assertEqual(memory.parsed(meminfo), memory.Memory(available=4096000, total=16387072))
for unread in ("MemTotal: 16 kB\n", "MemTotal: x kB\nMemAvailable: 1 kB\n", ""):
self.assertIsNone(memory.parsed(unread), unread)
def test_reads_a_meminfo_file_and_none_where_it_cannot(self):
with tempfile.TemporaryDirectory() as temp:
meminfo = pathlib.Path(temp, "meminfo")
meminfo.write_text("MemTotal: 8 kB\nMemAvailable: 2 kB\n")
self.assertEqual(memory.read_memory(meminfo), memory.Memory(available=2, total=8))
self.assertIsNone(memory.read_memory(pathlib.Path(temp, "gone")))
class SlotShare(unittest.TestCase):
def test_splits_the_three_quarters_a_worker_leaves_evenly_across_the_slots_in_mib(self):
self.assertEqual(memory.Memory(available=0, total=32 * 1024 * 1024).slot_share(4), 6144)
self.assertEqual(memory.Memory(available=0, total=8000000).slot_share(2), 2929)
class SlotFolder(unittest.TestCase):
def test_every_session_shares_the_slots_under_the_users_state_folder(self):
self.assertEqual(slots.slot_folder({}), pathlib.Path.home() / ".local" / "state" / "run-heavy")
self.assertEqual(slots.slot_folder({"XDG_STATE_HOME": "/s"}), pathlib.Path("/s/run-heavy"))
class TakenSlot(unittest.TestCase):
def test_a_lock_that_fails_for_another_reason_than_a_holder_closes_its_file_and_raises(self):
closed = []
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch("fcntl.flock", side_effect=OSError(errno.ENOLCK, "No locks available")), unittest.mock.patch("os.close", side_effect=closed.append):
with self.assertRaises(OSError):
slots.taken_slot(pathlib.Path(folder), 2)
self.assertEqual(len(closed), 1)
self.assertIsInstance(closed[0], int)
os.close(closed[0])
class WaitedSlot(unittest.TestCase):
def test_waits_while_every_slot_is_held_saying_so_once_then_takes_the_freed_one(self):
with tempfile.TemporaryDirectory() as folder:
held = [open(pathlib.Path(folder, f"slot-{slot}"), "a") for slot in range(2)]
for file in held:
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
said, slept = [], []
def sleep(seconds):
slept.append(seconds)
if len(slept) == 2:
held[1].close()
slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: said.append(True), sleep)
os.close(fd)
held[0].close()
self.assertEqual((slot, said, slept), (1, [True], [slots.POLL_SECONDS] * 2))
def test_takes_a_free_slot_at_once(self):
with tempfile.TemporaryDirectory() as folder:
slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: self.fail("said it waits"), lambda seconds: self.fail("slept"))
os.close(fd)
self.assertEqual(slot, 0)
if __name__ == "__main__":
unittest.main()
+7 -2
View File
@@ -36,7 +36,7 @@ class Rung:
return Rung(model, effort)
return Rung(family.model, effort) if effort else family
# The one spelling of a rung. loop-claude hands it to rule-hook in environment variables, and archive lines written before route.Route.record hold it, so parse must keep reading it.
# The one spelling of a rung. loop-claude hands it to rule-hook in environment variables, and archive lines written before route.Route.worker_line hold it, so parse must keep reading it.
def __str__(self) -> str:
return f"{self.model} at {self.effort} effort" if self.effort else self.model
@@ -105,11 +105,16 @@ def review_rungs(project: Rung, worker: Rung, escape_and_impact: int) -> dict[Re
A pass's reviewer runs on reviewers_rung. Where the E + I steps no review up and the worker runs no higher than the project's rung, a pass whose replay chose a rung for the project's model runs on that rung instead, even below the worker's: the replay compared reviews on the project's rung only, never on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
"""
rungs: dict[ReviewKind, Rung] = {**dict.fromkeys(REVIEWERS, reviewers_rung(project, worker, escape_and_impact)), "seat": project, "security": project}
if escape_and_impact not in REVIEW_STEPS and position(worker) <= position(project):
if replay_applies(project, worker, escape_and_impact):
rungs |= {kind: rung for (kind, model), rung in REPLAYED.items() if model == project.model}
return rungs
def replay_applies(project: Rung, worker: Rung, escape_and_impact: int) -> bool:
"""Whether a pass's replay chose its rung for a chunk like this: only where the E + I steps no review up and the worker runs no higher than the project's rung."""
return escape_and_impact not in REVIEW_STEPS and position(worker) <= position(project)
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int) -> Rung:
"""The rung of each pass's reviewer that no replay lowered: the higher of the worker's rung and review_floor's."""
return highest(worker, review_floor(project, escape_and_impact))
+32
View File
@@ -0,0 +1,32 @@
"""Where a chunk's reviews run, chosen from its route and the project's rung."""
import dataclasses
from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route
from model_routing.ladder import replay_applies, review_rungs, reviewers_rung, Rung
from review_passes import ReviewedPass, REVIEWERS
@dataclasses.dataclass(frozen=True)
class ReviewChoice:
# The rung of each pass's reviewer that no replay lowered.
reviewers: Rung
# The passes whose replay chose another rung, with that rung.
lowered: dict[ReviewedPass, Rung]
seat: Rung
security: Rung
# Each rung a higher E + I than the route's picks for the reviewers, with the lowest E + I that picks it, in rising order.
higher: dict[Rung, int]
def chosen(project: Rung, route: Route) -> ReviewChoice:
"""The rung each kind of review runs on for a chunk whose route is route, on a project whose rung is project."""
rungs = review_rungs(project, route.rung, route.reviewed_on())
reviewers = reviewers_rung(project, route.rung, route.reviewed_on())
lowered = {kind: rungs[kind] for kind in REVIEWERS if rungs[kind] != reviewers}
higher: dict[Rung, int] = {}
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
# A higher E + I changes a review by moving the reviewers' rung, or by ending the replay that lowered a pass.
rung = reviewers_rung(project, route.rung, escape_and_impact)
if rung != reviewers or (lowered and not replay_applies(project, route.rung, escape_and_impact)):
higher.setdefault(rung, escape_and_impact)
return ReviewChoice(reviewers, lowered, rungs["seat"], rungs["security"], higher)
+21 -21
View File
@@ -1,4 +1,4 @@
"""A chunk's route: its worker's rung and the plan item that picked it. The archive keeps the route as a record beside each verdict."""
"""A chunk's route: its worker's rung and the plan item that picked it. The archive keeps the route as JSON on the Worker: line that ends each outcome."""
import dataclasses
import json
import re
@@ -9,9 +9,9 @@ from model_routing.ladder import REVIEW_STEPS, Rung
# How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`.
ESCALATION_MARKER = "Escalation trigger"
# What Route.record writes. The outcome writers take only this as the worker, so mypy refuses a str(route) there.
Record = typing.NewType("Record", str)
# A worker line loop-claude wrote before it archived the route as a record. Nothing writes this format any more, so its wording never changes. route_from reads it for the chunks the routing figures still count, and for a chunk a rerun resumes across the change.
# What Route.worker_line writes. The outcome writers take only this as the worker, so mypy refuses a str(route) there.
WorkerLine = typing.NewType("WorkerLine", str)
# A worker line loop-claude wrote before it archived the route as JSON. Nothing writes this format any more, so its wording never changes. route_from reads it for the chunks the routing figures still count, and for a chunk a rerun resumes across the change.
LEGACY_WORKER = re.compile(r"(?P<rung>.+?)(?:, routed by item (?P<item>[0-9]+)'s L of (?P<likelihood>[0-9]+) and E \+ I of (?P<escape_and_impact>[0-9]+))?(?:, taking in an E \+ I of (?P<escape_and_impact_taken_in>[0-9]+))?(?:, escalated at transcript entry (?P<escalated_at>[0-9]+))?")
@@ -40,7 +40,7 @@ class Route:
unfinished counts the unfinished verdicts towards the next one-rung step; a reload hands it over with the rung.
"""
# Each field below but rung and unfinished is a key of the archive's records, so renaming one makes the records already archived unreadable, and their chunks route afresh.
# Each field below but rung and unfinished is a key of the archive's worker lines, so renaming one makes the lines already archived unreadable, and their chunks route afresh.
# The fields a loop-claude from before L and E + I replaced R + C hands on reload; the reloaded script drops such a route, and the chunk routes afresh.
RETIRED: typing.ClassVar[frozenset[str]] = frozenset({"risk_and_complexity"})
rung: Rung
@@ -50,7 +50,7 @@ class Route:
unfinished: int = 0
# The highest E + I the judge saw the worker take in, kept only where it picks a higher review step than the item's; 0 otherwise.
escape_and_impact_taken_in: int = 0
# The mark: how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. The judge's escalation quote counts only from the entries after it, so a passage that already bought a step cannot buy another; the session's transcript only grows, so the mark holds across cycles.
# The escalation mark, as loop_claude/escalation_mark.py says: how many transcript entries the session held when an escalation last stepped the worker up, 0 before any.
escalated_at: int = 0
def __post_init__(self) -> None:
@@ -71,38 +71,38 @@ class Route:
"""The E + I that picks the reviewers' and the judge's rung: the routed item's or the highest taken in, whichever is higher; 0 for neither."""
return max(self.escape_and_impact, self.escape_and_impact_taken_in)
def record(self) -> Record:
"""What the archive records as each verdict's worker: a JSON object of the rung's model and effort and the RECORD_FIELDS, leaving out each that is 0 or empty; route_from reads it back."""
fields = {"model": self.rung.model, "effort": self.rung.effort, **{name: getattr(self, name) for name in RECORD_FIELDS}}
return Record(json.dumps({name: value for name, value in fields.items() if value}))
def worker_line(self) -> WorkerLine:
"""What the archive records as each verdict's worker: a JSON object of the rung's model and effort and the WORKER_LINE_FIELDS, leaving out each that is 0 or empty; route_from reads it back."""
fields = {"model": self.rung.model, "effort": self.rung.effort, **{name: getattr(self, name) for name in WORKER_LINE_FIELDS}}
return WorkerLine(json.dumps({name: value for name, value in fields.items() if value}))
# The Route fields a record holds beside the rung's model and effort. A human reads the record in the archive, so it is flatter than the JSON a reload hands over (loop_claude/loop/reload.py) and leaves out zeros. It leaves out unfinished, so a rerun restarts that count.
RECORD_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if field.name not in ("rung", "unfinished"))
# The Route fields a worker line holds beside the rung's model and effort. A human reads the line in the archive, so it is flatter than the JSON a reload hands over (loop_claude/loop/reload.py) and leaves out zeros. It leaves out unfinished, so a rerun restarts that count.
WORKER_LINE_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if field.name not in ("rung", "unfinished"))
def route_from(worker: str) -> Route | None:
"""The route an archived worker line names, whether a record or a line written before records. None where it names no model, holds fields Route.record never writes, or holds levels off their scales; and for an older line, where it names a model without an effort."""
fields = record_fields(worker) if worker.startswith("{") else legacy_fields(worker)
"""The route an archived worker line names, whether JSON or a line written before JSON. None where it names no model, holds fields Route.worker_line never writes, or holds levels off their scales; and for an older line, where it names a model without an effort."""
fields = json_fields(worker) if worker.startswith("{") else legacy_fields(worker)
if fields is None or not Route.fits(fields):
return None
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in RECORD_FIELDS})
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})
def record_fields(record: str) -> dict[str, typing.Any] | None:
"""The fields of a record Route.record wrote; None for any other text."""
def json_fields(line: str) -> dict[str, typing.Any] | None:
"""The fields of a line Route.worker_line wrote; None for any other text."""
try:
fields = json.loads(record)
fields = json.loads(line)
except ValueError:
return None
if not (isinstance(fields, dict) and isinstance(fields.get("model"), str) and isinstance(fields.get("effort", ""), str) and fields.keys() <= {"model", "effort", *RECORD_FIELDS}):
if not (isinstance(fields, dict) and isinstance(fields.get("model"), str) and isinstance(fields.get("effort", ""), str) and fields.keys() <= {"model", "effort", *WORKER_LINE_FIELDS}):
return None
# type(), not isinstance(): JSON true is no integer.
return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in RECORD_FIELDS) else None
return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) else None
def legacy_fields(line: str) -> dict[str, typing.Any] | None:
"""The fields of a LEGACY_WORKER line, as record_fields gives them; None for any other text."""
"""The fields of a LEGACY_WORKER line, as json_fields gives them; None for any other text."""
found = LEGACY_WORKER.fullmatch(line)
rung = Rung.parse(found["rung"]) if found else None
if not (found and rung):
+26
View File
@@ -0,0 +1,26 @@
import unittest
import unittest.mock
from model_routing.review_choice import chosen, ReviewChoice
from model_routing import ladder
from model_routing.route import Route
from model_routing.ladder import Rung
HAIKU = Rung("claude-haiku-5-5", "low")
OPUS = Rung("claude-opus-5-5", "medium")
OPUS_MAX = Rung("claude-opus-5-5", "max")
FABLE = Rung("claude-fable-5-1", "max")
SONNET = Rung("claude-sonnet-5-5", "high")
class Chosen(unittest.TestCase):
def test_names_no_higher_rung_on_the_top_one(self):
self.assertEqual(chosen(OPUS, Route(FABLE, 3, 4, 5)).higher, {})
def test_names_the_e_plus_i_that_ends_a_replay_even_where_the_reviewers_are_on_the_top_rung(self):
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-fable-5-1"): HAIKU}):
self.assertEqual(chosen(FABLE, Route(OPUS_MAX, 3, 4, 4)), ReviewChoice(FABLE, {"prose": HAIKU}, FABLE, FABLE, {FABLE: 5}))
def test_puts_every_pass_on_the_reviewers_rung_once_an_e_plus_i_steps_a_review_up(self):
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): HAIKU}):
self.assertEqual(chosen(OPUS, Route(SONNET, 3, 2, 5)).lowered, {})
+8 -8
View File
@@ -9,8 +9,8 @@ from markdown_text import sections
from utc_stamp import STAMPED
FIGURE = re.compile(rf"^Reading cost, chunk (\w+), finished ({STAMPED})$")
FIGURE_PLACE = re.compile(r"^- `(.+)` (\d+)$")
PLACES_KEPT = 10
FIGURE_FILE = re.compile(r"^- `(.+)` (\d+)$")
FILES_KEPT = 10
RECORD = "docs/reading-cost.md"
RESET = "Reading cost reset, "
RESET_AT = re.compile(rf"^{RESET}({STAMPED})$")
@@ -28,8 +28,8 @@ def chunk_id(chunk: FinishedChunk) -> str:
def figure(chunk: FinishedChunk, reading: Reading) -> str:
places = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.places))
return f"## Reading cost, chunk {chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\n\n{places}" if places else "")
files = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.files))
return f"## Reading cost, chunk {chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\n\n{files}" if files else "")
# The figures after the last reset, in the order their chunks finished: each machine appends its own archive's chunks.
@@ -44,14 +44,14 @@ 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 := FIGURE_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_FILE.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)]
def ranked(places: collections.Counter[str]) -> list[tuple[str, int]]:
return sorted(places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT]
def ranked(files: collections.Counter[str]) -> list[tuple[str, int]]:
return sorted(files.items(), key=lambda item: (-item[1], item[0]))[:FILES_KEPT]
def merged(record: str, figures: list[str]) -> str:
@@ -65,7 +65,7 @@ def trend(readings: list[Reading]) -> str:
medians = f"the last {WINDOW} chunks' median is {last} new input tokens before their first commit, the {WINDOW} before them {earlier}."
if last <= earlier:
return f"Not rising: {medians}"
read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in readings[-WINDOW:]), collections.Counter())))
read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.files for reading in readings[-WINDOW:]), collections.Counter())))
return f"Rising: {medians}\n\nRead most over the last {WINDOW} (opens and searches):\n{read_most}"
+4 -4
View File
@@ -11,9 +11,9 @@ from shell_command import resolved, simple_commands
@dataclasses.dataclass(frozen=True)
class Reading:
"""What the worker and its subagents took in before the worker's first commit."""
"""What the worker and its subagents took in before the worker's first commit: tokens counts the new input tokens, and files counts how often each tracked file was opened or searched, by its path in the checkout."""
tokens: int
places: collections.Counter[str]
files: collections.Counter[str]
@dataclasses.dataclass(frozen=True)
@@ -32,8 +32,8 @@ def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | No
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.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)
files = collections.Counter(file for found in reads for path in found.read if (file := relative(path, roots)) in checkout.tracked)
return Reading(sum(map(tokens_in, before)), files)
def entries_of(raw: bytes) -> list[dict]:
+4
View File
@@ -0,0 +1,4 @@
import pathlib
# The checkout root.
ROOT = pathlib.Path(__file__).resolve().parents[2]
+1 -1
View File
@@ -7,7 +7,7 @@ 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
from repo_checks import ROOT
RULE_PATH = rf"(?:{'|'.join(map(re.escape, HUMAN_RULE_DIRS))})/[\w-]+\.md"
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
+1 -1
View File
@@ -5,7 +5,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
PRIVATE = [
".claude/settings.local.json",
+1 -1
View File
@@ -6,7 +6,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
def bound(node: ast.Import | ast.ImportFrom) -> list[str]:
+1 -1
View File
@@ -5,7 +5,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
class Install(unittest.TestCase):
-27
View File
@@ -1,27 +0,0 @@
import pathlib
import re
import shutil
import subprocess
import sys
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
FLOOR = re.compile(r"Python 3\.(\d+) or newer")
def readme_floor() -> tuple[int, int] | None:
named = FLOOR.search((ROOT / "README.md").read_text(encoding="utf-8"))
return (3, int(named.group(1))) if named else None
class PythonFloor(unittest.TestCase):
def test_the_suite_passes_on_the_python_the_readme_names_as_floor(self):
floor = readme_floor()
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if sys.version_info[:2] == floor:
self.skipTest("this run is on the floor")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches the floor interpreter; see README.md's Test line")
suite = ["python", "-m", "unittest", "discover", "-s", "bin", "-p", "test_*.py"]
ran = subprocess.run(["uv", "run", "--no-project", "--python", "%d.%d" % floor, *suite], capture_output=True, cwd=ROOT, text=True)
self.assertEqual(ran.returncode, 0, ran.stderr)
+16
View File
@@ -0,0 +1,16 @@
import pathlib
import re
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from machine_load.slots import CPUS_PER_SLOT
from repo_checks import ROOT
class TestLine(unittest.TestCase):
def test_the_readme_runs_the_tests_in_one_heavy_slots_cpus(self):
workers = re.search(r"pytest==\S+ -n (\d+) bin`", (ROOT / "README.md").read_text(encoding="utf-8"))
self.assertIsNotNone(workers, "README.md's Test line runs `pytest==X -n N bin`")
self.assertEqual(int(workers.group(1)), CPUS_PER_SLOT)
+1 -1
View File
@@ -6,7 +6,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from review_passes import PASS_AGENTS, PASSES
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
from rule_hook.reviewer_rung import SEAT, SECURITY_OPENER
OPENING = re.compile(r"^## Opening\n+```\n([^\n]+?\.)(?: |\n)", re.MULTILINE)
+1 -1
View File
@@ -7,7 +7,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from settings_filter import cleaned
from git_repo import git
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
INSTALL = "git config filter.settings.clean bin/settings_filter.py"
+20 -5
View File
@@ -1,4 +1,5 @@
import pathlib
import re
import shutil
import subprocess
import sys
@@ -6,14 +7,28 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import readme_floor, ROOT
from repo_checks import ROOT
SUPPORTED = re.compile(r"the latest stable Python, today (3\.\d+)")
def tools() -> list[str]:
"""mypy's arguments naming every package and module under bin/ except `repo_checks`, so a new tool is checked without being listed."""
bin_folder = ROOT / "bin"
packages = sorted(init.parent.name for init in bin_folder.glob("*/__init__.py") if init.parent.name != "repo_checks")
modules = sorted(path.stem for path in bin_folder.glob("*.py") if not path.name.startswith("test_"))
return [*(word for package in packages for word in ("-p", package)), *(word for module in modules for word in ("-m", module))]
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`")
def test_mypy_passes_on_the_tools_for_the_python_readme_install_names(self):
supported = SUPPORTED.search((ROOT / "README.md").read_text(encoding="utf-8"))
self.assertIsNotNone(supported, "README.md's Install names `the latest stable Python, today 3.N`")
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", "chunk_preflight", "-p", "claude_code", "-m", "comprehension_history", "-m", "git_repo", "-p", "judge_replay", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-m", "review_passes", "-p", "review_replay", "-m", "round_titles", "-p", "rule_hook", "-p", "rung_replay", "-p", "score_outcomes", "-m", "settings_filter", "-m", "shell_command", "-m", "statusline", "-p", "subagent_rung", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", sys.executable, "mypy==2.3.1", "--python-version", supported.group(1), "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", *tools()], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
def test_mypy_checks_run_heavy_and_each_root_module(self):
self.assertLessEqual({("-p", "run_heavy"), ("-p", "machine_load"), ("-m", "chunk_pick"), ("-m", "docker_command")}, set(zip(tools()[::2], tools()[1::2])))
self.assertNotIn("repo_checks", tools())
+3 -3
View File
@@ -16,11 +16,11 @@ folder, holding only the reports written after the chunk began and before the ro
finds nothing where its prompt still names the review folder, or names a file there, other than a
round's report, that the folder did not hold from the chunk's start until the round's.
It first replays every round on the project's rung, the reference reviewer. Findings on record
It first replays every round on the project's rung, the reference reviewer. Archived findings
that the reference reviewer does not raise again may rest on code or rules that have changed
since; no rung is held to them. It then replays the rounds where the reference raised any, on each
rung below, highest first, down to the ladder's lowest, and stops at the first rung that misses
one. For each replay, claude on the project's rung matches the report to the findings on record,
one. For each replay, claude on the project's rung matches the report to the archived findings,
and counts a finding only where the report raises it as 🔴 or 🟡. The tool prints each finding a
rung missed and the lowest rung that, like each rung above it, missed none. That rung is the
evidence for running the pass's reviewer on it; the decision above records each run.
@@ -150,7 +150,7 @@ def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Roun
def code_of(found: Round, effects: Effects) -> Code | Failure:
"""Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the folder rounds.reviewed_path guesses from the prompt, and the commits authored by then.
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess costs no rung: the reference reviewer, replayed on that code, finds fewer findings on record, and no rung is held to those.
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess costs no rung: the reference reviewer, replayed on that code, finds fewer of the archived findings, and no rung is held to those.
"""
if not os.path.isdir(found.root):
return Failure("the project has no checkout")
+1 -1
View File
@@ -14,7 +14,7 @@ FINDING = re.compile(r"^[\s#>*+|-]*(?:\d+[.)]\s*)?[*_]*\s*(?:🔴|🟡)")
# An absolute path in a prompt, up to the quote, bracket or punctuation that ends it.
PATH = re.compile(r"/[^\s`'\"()<>\[\],;]+")
LINE_OR_STOP = re.compile(r"(?::\d+(?:-\d+)?)?[.:]?$")
# A round's report, as skills/larv-review/SKILL.md → "Reports" names it, such as stability-round-2.md or principles-goals-round-1-rerun.md.
# A round's report, as skills/larv-review/SKILL.md → "Reports" names it, such as stability-round-2.md or principles-round-1-rerun.md.
ROUND_REPORT = re.compile(r"-round-\d+(?:-rerun)?\.md$")
+2 -2
View File
@@ -82,7 +82,7 @@ class ReviewedPath(unittest.TestCase):
class LostInputs(unittest.TestCase):
def test_names_each_file_the_prompt_names_in_the_copy_that_it_lacks_other_than_a_round_report(self):
prompt = "Read /c/branch.diff and /c/ls-files.txt:3. Earlier: /c/prose-round-1.md. Write /c/principles-goals-round-2-rerun.md; see /elsewhere/x.diff."
prompt = "Read /c/branch.diff and /c/ls-files.txt:3. Earlier: /c/prose-round-1.md. Write /c/principles-round-2-rerun.md; see /elsewhere/x.diff."
self.assertEqual(lost_inputs(prompt, "/c", {"ls-files.txt"}.__contains__), ["branch.diff"])
self.assertEqual(lost_inputs(prompt, "/c", {"branch.diff", "ls-files.txt"}.__contains__), [])
@@ -215,7 +215,7 @@ class Main(unittest.TestCase):
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
+39 -12
View File
@@ -1,12 +1,22 @@
"""The titles of larv-review's round commits, `Answer <pass> round <n>: <k> 🔴, <m> 🟡; <summary>`: each pass's round count, and the findings the rounds reported."""
"""The titles of larv-review's round commits, `Answer <pass> round <n>: <k> 🔴, <m> 🟡 (<j> misread); <summary>`: each pass's round count, and the findings the rounds reported. <j> counts the 🔴 and 🟡 findings a reviewer marked `[misread]`."""
import dataclasses
import re
from review_passes import PASSES
# The most rounds a pass takes before the run asks the human, per `docs/decisions.md` → `review: a pass gets at most three rounds per chunk; …`. rule-hook's `round-cap` refuses a round title past it, and `larv-review round-count` marks a pass at or past it.
CAP = 3
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
# What follows a round title's colon: the round's 🔴 and 🟡 counts, then `;` and its summary, if any.
FINDINGS = re.compile(r" ([0-9]+) 🔴, ([0-9]+) 🟡(?:;|$)")
# What follows a round title's colon: the round's 🔴 and 🟡 counts, then how many of them a reviewer marked `[misread]`, a count that titles from before it lack, then `;` and its summary, if any.
FINDINGS = re.compile(r" ([0-9]+) 🔴, ([0-9]+) 🟡(?: \(([0-9]+) misread\))?(?:;|$)")
@dataclasses.dataclass(frozen=True)
class Findings:
"""A round title's findings: its 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None for a title from before that count."""
red: int
yellow: int
misread: int | None
def round_counts(titles: list[str]) -> dict[str, int]:
@@ -22,18 +32,35 @@ def round_counts(titles: list[str]) -> dict[str, int]:
def lacks_counts(title: str) -> bool:
"""Whether title is a round title without the counts after its colon."""
"""Whether title is a round title without all three counts after its colon, or with more misread findings than 🔴 and 🟡 findings."""
return ROUND.match(title) is not None and ((counts := title_counts(title)) is None or counts.misread is None)
def past_cap(title: str) -> bool:
"""Whether title is a round title numbered past CAP."""
named = ROUND.match(title)
return named is not None and not FINDINGS.match(title, named.end())
return named is not None and int(named.group(2)) > CAP
def round_findings(titles: list[str]) -> tuple[int, int] | None:
"""The 🔴 and 🟡 counts summed over the round titles among titles; None where a round title lacks them, or no title is a round."""
def title_counts(title: str) -> Findings | None:
"""The counts after a round title's colon; None where title is no round title, lacks the 🔴 and 🟡 counts, or counts more misread findings than both."""
named = ROUND.match(title)
found = FINDINGS.match(title, named.end()) if named else None
if not found:
return None
counts = Findings(int(found.group(1)), int(found.group(2)), None if found.group(3) is None else int(found.group(3)))
return None if counts.misread is not None and counts.misread > counts.red + counts.yellow else counts
def round_findings(titles: list[str]) -> Findings | None:
"""The counts summed over the round titles among titles; None where a round title lacks the 🔴 and 🟡 counts, or no title is a round. Its misread is None where a round title lacks that count."""
counts = []
for title in titles:
if named := ROUND.match(title):
found = FINDINGS.match(title, named.end())
if not found:
if ROUND.match(title):
if (found := title_counts(title)) is None:
return None
counts.append((int(found.group(1)), int(found.group(2))))
return (sum(red for red, _ in counts), sum(yellow for _, yellow in counts)) if counts else None
counts.append(found)
if not counts:
return None
misreads = [found.misread for found in counts if found.misread is not None]
return Findings(sum(found.red for found in counts), sum(found.yellow for found in counts), sum(misreads) if len(misreads) == len(counts) else None)
+1 -1
View File
@@ -19,7 +19,7 @@ FIGURES = "routing-figures.md"
LOCK = "routing-figures.lock"
RAISED = "routing-calls-raised.md"
RAISED_HEADING = "# Routing calls raised\n"
# Each line is a call and when it was raised, or a reset: `- <UTC time> <call>` or `- <UTC time> Reset`.
# Each line is a call and when it was raised, or a reset: `- <UTC time> <call>` or `- <UTC time> Reset`. After a reset the figures count only chunks that finished after it, and a call raised before it may be raised again.
RAISED_LINE = re.compile(rf"^- ({STAMPED}) (.+)$", re.MULTILINE)
RESET = "Reset"
+92 -46
View File
@@ -1,13 +1,14 @@
"""Token spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`."""
"""Dollar spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`. A chunk that cannot be read is skipped and named in the figures."""
import collections
import dataclasses
import re
import statistics
import typing
from claude_code.entries import assistant_parts, parts, tool_call, usage_count
from claude_code.entries import assistant_parts, parts, tool_call, tool_result
from git_command import commits
from model_routing.route import ESCALATION_MARKER, route_from
from routing_figures.prices import listed
from model_routing.ladder import position, Rung
from round_titles import round_counts
from shell_command import simple_commands
@@ -18,6 +19,8 @@ MEASURED_AT = re.compile(r"^Measured .+, at cycle ([0-9]+) across", re.MULTILINE
# A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change.
MEASURED_AT_LEAST = 5
DIMENSIONS = ("project", "subagent type", "rung", "tool")
# Each of DIMENSIONS to its labels' dollars.
Dollars = dict[str, collections.defaultdict[str, float]]
# The tool label of a message that follows no tool call, such as the first message after a prompt.
PROMPT = "prompt"
ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):")
@@ -53,32 +56,50 @@ class Reports:
@dataclasses.dataclass(frozen=True)
class ChunkFigures:
"""tokens maps each of DIMENSIONS to its labels' tokens; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger."""
tokens: dict[str, collections.Counter[str]]
"""dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive."""
dollars: Dollars
start: Rung | None
rounds_past_first: int
unfinished: int
delegated: collections.Counter[str]
reports: dict[str, Reports]
escalated: collections.Counter[int]
unattributed: float
lacking: int = 0
@dataclasses.dataclass(frozen=True)
class Figures:
"""escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole."""
chunks: int
tokens: dict[str, collections.Counter[str]]
dollars: Dollars
routed: dict[Rung, list[ChunkFigures]]
reports: dict[str, Reports]
escalated: collections.Counter[int]
skipped: tuple[str, ...] = ()
unattributed: float = 0.0
lacking: int = 0
@dataclasses.dataclass(frozen=True)
class Message:
"""An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices."""
at: str
tools: list[str]
model: str
list_price: float
class Spent(typing.NamedTuple):
"""A message with the subagent type that wrote it, or `worker`, and the rung it ran on."""
kind: str
rung: str
message: Message
def measured(chunk: Chunk, home: str) -> ChunkFigures:
cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0])
tokens: dict[str, collections.Counter[str]] = {dimension: collections.Counter() for dimension in DIMENSIONS}
for at, tools, spent in spend(chunk.worker):
add(tokens, chunk.project, "worker", str(rung_at(cycles, at)), tools, spent)
spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)]
launches = agent_calls(chunk.worker)
reported = results(chunk.worker)
delegated: collections.Counter[str] = collections.Counter()
@@ -89,17 +110,19 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
rung = str(subagent_rung(subagent.entries, arguments, rung_at(cycles, launched_at)))
delegated[rung] += 1
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values())))
for _, tools, spent in spend(subagent.entries):
add(tokens, chunk.project, kind, rung, tools, spent)
spent += [Spent(kind, rung, message) for message in messages(subagent.entries)]
dollars, unattributed = costed(spent, chunk.project, recorded_costs(chunk.worker))
start = route_from(cycles[0][1]) if cycles else None
return ChunkFigures(
tokens=tokens,
dollars=dollars,
start=start.rung if start and start.item else None,
rounds_past_first=rounds_past_first(chunk.worker, home),
unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes),
delegated=delegated,
reports=reports,
escalated=escalations(launches),
unattributed=unattributed,
lacking=max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in chunk.subagents) - len(chunk.subagents)),
)
@@ -120,13 +143,30 @@ def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]:
return found
def add(tokens: dict[str, collections.Counter[str]], project: str, kind: str, rung: str, tools: list[str], spent: int) -> None:
tokens["project"][project] += spent
tokens["subagent type"][kind] += spent
tokens["rung"][rung] += spent
# Split whole, the first tools taking the remainder, so the tool table adds up to the others.
for place, tool in enumerate(tools):
tokens["tool"][tool] += spent // len(tools) + (place < spent % len(tools))
# {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...}
def recorded_costs(worker: list[dict]) -> dict[str, float]:
"""The cost the worker transcript's last cost-state entry records for each model. Claude Code counts every call of the session in it, the subagents' and the compactions' too."""
for entry in reversed(worker):
if entry.get("type") == "cost-state" and isinstance(by_model := entry.get("modelUsage"), dict):
return {model: cost for model, usage in by_model.items() if isinstance(usage, dict) and isinstance(cost := usage.get("costUSD"), (int, float))}
return {}
def costed(spent: list[Spent], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]:
"""Each message's dollars by DIMENSIONS, and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices."""
listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float)
for _, _, message in spent:
listed_by_model[message.model] += message.list_price
scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded}
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
for kind, rung, message in spent:
cost = message.list_price * scale.get(message.model, 1.0)
dollars["project"][project] += cost
dollars["subagent type"][kind] += cost
dollars["rung"][rung] += cost
for tool in message.tools:
dollars["tool"][tool] += cost / len(message.tools)
return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model])
def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str:
@@ -144,39 +184,27 @@ def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> R
return Rung(model, str(effort))
def spend(entries: list[dict]) -> list[tuple[str, list[str], int]]:
"""Each message's timestamp, the tools whose results it took in, and its input, cache-written and output tokens, counted once per message, as reading_cost's tokens_in dedupes them, though tokens_in leaves output tokens out."""
messages: dict[str, tuple[str, object, list[str]]] = {}
def messages(entries: list[dict]) -> list[Message]:
"""The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in."""
# Claude Code writes one entry per content block of a message, each with the message's usage. The usage is the same in every entry (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last.
kept: dict[str, tuple[str, dict, list[str]]] = {}
for entry in entries:
if entry.get("type") != "assistant" or not isinstance(message := entry.get("message"), dict):
continue
key = str(message.get("id") or entry.get("uuid"))
kept = messages.setdefault(key, (str(entry.get("timestamp", "")), message.get("usage"), []))
kept[2].extend(name for part in assistant_parts(entry) if (found := tool_call(part)) and isinstance(name := found[0], str))
spent = []
found = kept.setdefault(str(message.get("id") or entry.get("uuid")), (str(entry.get("timestamp", "")), message, []))
found[2].extend(name for part in assistant_parts(entry) if (call := tool_call(part)) and isinstance(name := call[0], str))
counted = []
before = [PROMPT]
for at, usage, called in messages.values():
tokens = sum(usage_count(usage, field) for field in ("input_tokens", "cache_creation_input_tokens", "output_tokens")) if isinstance(usage, dict) else 0
spent.append((at, before, tokens))
for at, message, called in kept.values():
model = str(message.get("model") or "")
counted.append(Message(at, before, model, listed(model, message.get("usage"))))
before = called or [PROMPT]
return spent
return counted
def results(entries: list[dict]) -> dict[str, str]:
"""Each tool result's text by the id of the call it answers."""
found = {}
for entry in entries:
for part in parts(entry):
if isinstance(part, dict) and part.get("type") == "tool_result":
found[str(part.get("tool_use_id"))] = result_text(part.get("content"))
return found
# {"type": "tool_result", "content": "hi"} or {"type": "tool_result", "content": [{"type": "text", "text": "hi"}]}
def result_text(body: object) -> str:
if isinstance(body, str):
return body
return "".join(block["text"] for block in body if isinstance(block, dict) and isinstance(block.get("text"), str)) if isinstance(body, list) else ""
return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))}
def rounds_past_first(worker: list[dict], home: str) -> int:
@@ -196,7 +224,11 @@ def due(cycle: int, last_measured: int) -> bool:
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures:
tokens = {dimension: sum((chunk.tokens.get(dimension, collections.Counter()) for chunk in chunks), collections.Counter()) for dimension in DIMENSIONS}
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
for chunk in chunks:
for dimension in DIMENSIONS:
for label, amount in chunk.dollars.get(dimension, {}).items():
dollars[dimension][label] += amount
routed: dict[Rung, list[ChunkFigures]] = {}
reports: dict[str, Reports] = {}
for chunk in chunks:
@@ -204,7 +236,7 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures
routed.setdefault(chunk.start, []).append(chunk)
for kind, found in chunk.reports.items():
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found
return Figures(len(chunks), tokens, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped)
return Figures(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks))
def calls(figures: Figures) -> list[str]:
@@ -224,14 +256,24 @@ def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -
return statistics.mean(map(of, chunks))
def basis(figures: Figures) -> str:
"""What the dollars are, what they leave out, and where the archive falls short of the recorded cost."""
text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's runs are not archived, so their cost is not counted."
if figures.unattributed:
text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive."
if figures.lacking:
text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls."
return text
def render(figures: Figures, found: list[str], at: str, cycle: int, since: str) -> str:
"""The figures as markdown; MEASURED_AT reads the cycle back. since is the latest reset's stamp, empty for none."""
sections = [
"# Routing figures",
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. Tokens are input, cache-written and output tokens; cache reads are left out. A message's tokens count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`.",
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
"## Calls for a routing change",
"".join(f"- {call}\n" for call in found).rstrip("\n") or "None.",
*[part for dimension in DIMENSIONS for part in (f"## Tokens by {dimension}", table((dimension.capitalize(), "Tokens"), [(label, str(tokens)) for label, tokens in figures.tokens[dimension].most_common()]))],
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])]))],
"## Routed chunks by the rung they started on",
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Subagent rungs", "Escalations by trigger"), [
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated)))
@@ -260,6 +302,10 @@ def triggers(escalated: collections.Counter[int]) -> str:
return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items()))
def money(dollars: float) -> str:
return f"${dollars:,.2f}"
def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str:
if not rows:
return "None."
+44
View File
@@ -0,0 +1,44 @@
"""What a message costs at list prices: the weights that split a chunk's recorded cost between its messages."""
import dataclasses
from claude_code.entries import usage_count
@dataclasses.dataclass(frozen=True)
class Price:
"""Dollars per million tokens. A cache write costs 1.25 times the input for a five-minute cache and 2 times for an hour's, as Opus 5.5's $5 and $8 show."""
input: float
read: float
output: float
@property
def write_5m(self) -> float:
return self.input * 1.25
@property
def write_1h(self) -> float:
return self.input * 2
# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Where a chunk records its cost, only the proportions between one model's messages matter, so these may be a little off.
PRICES = {
"claude-fable-5-1": Price(10, 0.25, 50),
"claude-haiku-5-5": Price(0.1, 0.01, 0.5),
"claude-opus-5-5": Price(4, 0.2, 20),
"claude-sonnet-5-5": Price(2, 0.2, 10),
}
# {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 25919}, "cache_read_input_tokens": 10365, "output_tokens": 193, ...}
def listed(model: str, usage: object) -> float:
"""The cost of one message's usage at the model's list price; 0 for a model without one."""
price = PRICES.get(model)
if not price or not isinstance(usage, dict):
return 0.0
written = usage.get("cache_creation")
# A write without the split by lifetime counts as a five-minute one.
five, hour = (usage_count(written, "ephemeral_5m_input_tokens"), usage_count(written, "ephemeral_1h_input_tokens")) if isinstance(written, dict) else (usage_count(usage, "cache_creation_input_tokens"), 0)
return (
usage_count(usage, "input_tokens") * price.input + five * price.write_5m + hour * price.write_1h
+ usage_count(usage, "cache_read_input_tokens") * price.read + usage_count(usage, "output_tokens") * price.output
) / 1_000_000
+91 -30
View File
@@ -1,5 +1,6 @@
import collections
import contextlib
import dataclasses
import io
import json
import pathlib
@@ -19,11 +20,16 @@ from model_routing.route import Route
LOW = Rung("claude-opus-5-5", "medium")
HIGH = Rung("claude-opus-5-5", "high")
LOW_ROUTE = Route(LOW, 7, 3, 4).record()
LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line()
def message(id_, at, *parts, model="claude-opus-5-5", tokens=(1, 10, 100)):
return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": {"input_tokens": tokens[0], "cache_creation_input_tokens": tokens[1], "output_tokens": tokens[2], "cache_read_input_tokens": 5000}}}
def message(id_, at, *parts, model="claude-opus-5-5", usage=None):
"""Costs $2 on Opus 5.5, whose output is $20 per million tokens, and $1 on Sonnet 5.5, whose output is $10."""
return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": usage or {"output_tokens": 100_000}}}
def cost_state(**costs):
return {"type": "cost-state", "totalCostUSD": sum(costs.values()), "modelUsage": {model.replace("_", "-"): {"costUSD": cost} for model, cost in costs.items()}}
def call(name, id_="t1", **arguments):
@@ -39,23 +45,23 @@ def stamped(at, outcome):
def figures(start=LOW, rounds=0, unfinished=0, reports=None, escalated=None):
return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {}))
return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {}), 0.0)
class Measured(unittest.TestCase):
def test_counts_each_messages_tokens_once_by_project_type_rung_and_the_tool_it_followed(self):
def test_prices_each_message_once_by_project_type_rung_and_the_tool_it_followed(self):
worker = [
message("m1", "2026-10-14T10:00:00.100Z", {"type": "text", "text": "reading"}),
message("m1", "2026-10-14T10:00:00.200Z", call("Read", file_path="/c/a")),
message("m2", "2026-10-14T10:05:00.000Z", {"type": "text", "text": "done"}),
message("m3", "2026-10-14T11:00:00.000Z", {"type": "text", "text": "on"}),
]
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(Route(HIGH).record())) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).record(), "merged", "j"))
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(Route(HIGH).worker_line())) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j"))
found = measured(Chunk("log", [kept], worker, []), "/h")
self.assertEqual(found.tokens["project"], {"log": 333})
self.assertEqual(found.tokens["subagent type"], {"worker": 333})
self.assertEqual(found.tokens["rung"], {str(LOW): 222, str(HIGH): 111})
self.assertEqual(found.tokens["tool"], {"prompt": 222, "Read": 111})
self.assertEqual(found.dollars["project"], {"log": 6.0})
self.assertEqual(found.dollars["subagent type"], {"worker": 6.0})
self.assertEqual(found.dollars["rung"], {str(LOW): 4.0, str(HIGH): 2.0})
self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 2.0})
self.assertEqual((found.start, found.unfinished), (LOW, 1))
def test_reads_a_subagents_rung_from_its_model_and_the_effort_its_call_set_or_else_the_workers(self):
@@ -70,7 +76,7 @@ class Measured(unittest.TestCase):
]
found = measured(Chunk("log", [stamped("2026-10-14T11:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j"))], worker, subagents), "/h")
self.assertEqual(found.delegated, {"claude-sonnet-5-5 at high effort": 1, str(LOW): 1})
self.assertEqual(found.tokens["subagent type"], {"worker": 111, "Explore": 222})
self.assertEqual(found.dollars["subagent type"], {"worker": 2.0, "Explore": 3.0})
self.assertEqual(found.reports, {"Explore": Reports(2, 35, 20)})
def test_counts_the_workers_escalations_by_the_trigger_each_subagents_prompt_opens_with(self):
@@ -90,17 +96,16 @@ class Measured(unittest.TestCase):
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(older, "m", "j"))
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
self.assertEqual(found.start, LOW)
self.assertEqual(found.tokens["rung"], {str(LOW): 111})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0})
def test_starts_no_route_for_a_chunk_no_item_routed(self):
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).record(), "m", "j"))
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).worker_line(), "m", "j"))
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
self.assertIsNone(found.start)
self.assertEqual(found.tokens["rung"], {str(LOW): 111})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0})
def test_puts_a_subagent_on_the_model_it_ran_at_the_effort_of_the_cycle_that_launched_it(self):
kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(Route(HIGH).record(), "m", "j"))
kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "m", "j"))
worker = [
message("m1", "2026-10-14T10:00:00.900Z"),
message("m2", "2026-10-14T10:30:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet")),
@@ -109,23 +114,72 @@ class Measured(unittest.TestCase):
subagents = [Subagent("Explore", "a1", [result("r", "x")]), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-opus-5-5")])]
found = measured(Chunk("log", [kept], worker, subagents), "/h")
self.assertEqual(found.delegated, {"sonnet at high effort": 1, str(HIGH): 1})
self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 333})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 6.0})
def test_names_a_subagent_by_its_meta_or_else_its_call_or_else_unknown(self):
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Plan"))]
subagents = [Subagent("stability-reviewer", "a1", []), Subagent("", "a2", []), Subagent("", "", [])]
self.assertEqual(measured(Chunk("log", [], worker, subagents), "/h").reports, {"stability-reviewer": Reports(1, 0, 0), "Plan": Reports(1, 0, 0), "unknown": Reports(1, 0, 0)})
def test_counts_a_message_without_usage_as_nothing_and_splits_tokens_whole_across_tools(self):
def test_counts_a_message_without_usage_or_a_priced_model_as_nothing_and_splits_a_cost_evenly_across_tools(self):
worker = [
{"type": "assistant", "uuid": "u1", "message": {"content": [call("Read"), call("Grep")], "usage": {"input_tokens": 3, "output_tokens": "many"}}},
{"type": "assistant", "uuid": "u1", "message": {"model": "claude-opus-5-5", "content": [call("Read"), call("Grep")], "usage": {"input_tokens": 1_000_000, "output_tokens": "many"}}},
{"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "t1", "content": "plain"}, "odd"]}},
{"type": "assistant", "uuid": "u2", "message": {"content": [], "usage": {"input_tokens": 5}}},
{"type": "assistant", "uuid": "u3", "message": {"content": []}},
{"type": "assistant", "uuid": "u2", "message": {"model": "claude-opus-5-5", "content": [], "usage": {"input_tokens": 2_000_000}}},
{"type": "assistant", "uuid": "u3", "message": {"model": "claude-opus-5-5", "content": []}},
{"type": "assistant", "uuid": "u4", "message": {"model": "claude-unheard-of", "content": [], "usage": {"input_tokens": 9_000_000}}},
]
found = measured(Chunk("log", [], worker, []), "/h")
self.assertEqual(found.tokens["tool"], {"prompt": 3, "Read": 3, "Grep": 2})
self.assertEqual(found.tokens["project"], {"log": 8})
self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 4.0, "Grep": 4.0})
self.assertEqual(found.dollars["project"], {"log": 12.0})
def test_prices_input_cache_writes_by_their_lifetime_cache_reads_and_output_at_the_models_list_prices(self):
usage = {"input_tokens": 1_000_000, "cache_creation_input_tokens": 2_000_000, "cache_creation": {"ephemeral_5m_input_tokens": 1_000_000, "ephemeral_1h_input_tokens": 1_000_000}, "cache_read_input_tokens": 1_000_000, "output_tokens": 1_000_000}
opus = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
self.assertAlmostEqual(opus.dollars["project"]["log"], 4 + 5 + 8 + 0.2 + 20)
sonnet = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", model="claude-sonnet-5-5", usage=usage)], []), "/h")
self.assertAlmostEqual(sonnet.dollars["project"]["log"], 2 + 2.5 + 4 + 0.2 + 10)
def test_counts_a_cache_write_without_a_lifetime_as_a_five_minute_one(self):
usage = {"cache_creation_input_tokens": 1_000_000}
found = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
self.assertAlmostEqual(found.dollars["project"]["log"], 5)
def test_splits_the_cost_a_chunks_last_cost_state_records_for_each_model_across_its_messages_by_list_price(self):
worker = [
message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore")),
message("m2", "2026-10-14T10:01:00Z"),
cost_state(claude_opus_5_5=1.0),
cost_state(claude_opus_5_5=9.0, claude_haiku_5_5=0.5),
]
subagents = [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]
found = measured(Chunk("log", [], worker, subagents), "/h")
self.assertEqual(found.dollars["subagent type"], {"worker": 6.0, "Explore": 3.0})
self.assertEqual(found.dollars["project"], {"log": 9.0})
self.assertEqual(found.unattributed, 0.5)
def test_counts_the_subagents_the_worker_launched_that_have_no_transcript(self):
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Explore"), call("Read", "r1", file_path="/c/a"))]
found = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]), "/h")
self.assertEqual(found.lacking, 1)
unnamed = measured(Chunk("log", [], worker, [Subagent("", "", [message("s1", "2026-10-14T10:00:01Z")]), Subagent("", "", [message("s2", "2026-10-14T10:00:02Z")])]), "/h")
self.assertEqual(unnamed.lacking, 0)
nested = [message("s1", "2026-10-14T10:00:01Z", call("Agent", "n1", subagent_type="Explore"))]
launched = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:00:02Z")]), Subagent("Explore", "n1", [message("s3", "2026-10-14T10:00:03Z")])]), "/h")
self.assertEqual(launched.lacking, 0)
self.assertEqual(measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [])]), "/h").lacking, 1)
def test_charges_a_message_without_a_timestamp_to_the_rung_of_the_last_outcome(self):
undated = message("m1", "")
del undated["timestamp"]
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j"))
self.assertEqual(measured(Chunk("log", [kept], [undated], []), "/h").dollars["rung"], {str(HIGH): 2.0})
def test_keeps_list_prices_for_a_model_the_cost_state_does_not_name(self):
worker = [message("m1", "2026-10-14T10:00:00Z"), message("m2", "2026-10-14T10:01:00Z", model="claude-sonnet-5-5"), cost_state(claude_opus_5_5=3.0)]
found = measured(Chunk("log", [], worker, []), "/h")
self.assertEqual(found.dollars["project"], {"log": 4.0})
self.assertEqual(found.unattributed, 0.0)
class Calls(unittest.TestCase):
@@ -154,13 +208,20 @@ class Calls(unittest.TestCase):
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), [])
def test_renders_each_dimension_largest_first_and_the_calls(self):
chunk = ChunkFigures({"project": collections.Counter({"a": 2, "b": 20})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter())
chunk = ChunkFigures({"project": collections.Counter({"a": 2.5, "b": 1234.5})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter(), 0.0)
text = render(totals([chunk]), ["Call."], "2026-10-15T00:00:00Z", 40, "")
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text)
self.assertIn("## Calls for a routing change\n\n- Call.\n", text)
self.assertIn("| b | 20 |\n| a | 2 |", text)
self.assertIn("## Dollars by project", text)
self.assertIn("| b | $1,234.50 |\n| a | $2.50 |", text)
self.assertIn("cache reads included", text)
self.assertIn("The judge's runs are not archived, so their cost is not counted.", text)
self.assertNotIn("left out", text)
self.assertNotIn("no transcript", text)
self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("$0.50 of the recorded cost is left out", render(totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |", text)
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter())
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter(), 0.0)
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("| Explore | 2 | 3 | 4 |", text)
escalated = render(totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "")
@@ -200,8 +261,8 @@ class Archive(unittest.TestCase):
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")]))
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")), [message("m1", "2026-10-14T09:00:00Z")])
found = archive.measure_archive(self.root, "/h", "")
self.assertEqual([chunk.tokens["project"] for chunk in found.chunks], [{"home/x": 222}])
self.assertEqual(found.chunks[0].tokens["subagent type"], {"worker": 111, "Explore": 111})
self.assertEqual([chunk.dollars["project"] for chunk in found.chunks], [{"home/x": 4.0}])
self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0})
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z"), archive.Measured([], ()))
def test_reads_each_cycles_route_from_its_own_outcomes_file(self):
@@ -212,10 +273,10 @@ class Archive(unittest.TestCase):
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000))
transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n")
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).record(), "m", "j"), 4070908800))
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).worker_line(), "m", "j"), 4070908800))
(found,) = archive.measure_archive(kept, "/h", "").chunks
self.assertEqual((found.start, found.unfinished), (LOW, 1))
self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 111})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 2.0})
def test_skips_a_chunk_it_cannot_read_and_names_it(self):
self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [])
+9 -2
View File
@@ -2,6 +2,7 @@ import dataclasses
import typing
from failure import Failure
from claude_code.session import subagent_transcript
FILE_TOOLS = ("Edit", "MultiEdit", "Write")
@@ -13,6 +14,8 @@ class Call:
cwd: str
# The subagent the call comes from, such as prose-reviewer; empty for the session's own agent.
agent: str = ""
# The transcript of the agent that makes the call: a subagent's own, not its session's.
transcript: str = ""
def parsed_call(hook_input: object) -> Call | Failure:
@@ -21,8 +24,12 @@ def parsed_call(hook_input: object) -> Call | Failure:
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")
agent = hook_input.get("agent_type")
return Call(tool, given, cwd, agent if isinstance(agent, str) else "")
agent, agent_id, transcript = hook_input.get("agent_type"), hook_input.get("agent_id"), hook_input.get("transcript_path")
transcript = transcript if isinstance(transcript, str) else ""
if isinstance(agent_id, str) and transcript:
# Inside a subagent, transcript_path still names the session's transcript.
transcript = subagent_transcript(transcript, agent_id)
return Call(tool, given, cwd, agent if isinstance(agent, str) else "", transcript)
def text(given: dict[str, typing.Any], key: str) -> str:
+24
View File
@@ -0,0 +1,24 @@
"""Whether a simple command is a heavy one, for the `run-heavy` rule: a docker build, or a run of a mutation tool."""
from docker_command import docker_subcommand
from shell_command import launched, tool_name
# Each mutation tool, and the words that make its call a mutation run when one of them follows it within two words; where the set is empty, every call is one.
MUTATORS = {"cargo": {"mutants"}, "infection": set(), "mutmut": {"run"}, "stryker": {"run"}}
# Flags with which a tool only prints its help, version or list, so a call that carries one is light. Not -h, which docker run reads as the container's hostname.
LIGHT_FLAGS = frozenset({"--help", "--list", "--version"})
BUILDS = (["build"], ["buildx", "build"], ["compose", "build"])
def heavy(words: list[str]) -> bool:
"""Whether the simple command, run directly or through a launcher, is a docker build or a mutation run, or runs one in a container, and is not under run-heavy."""
launch = launched(words, {"docker", *MUTATORS})
if launch is None or "run-heavy" in launch.launchers or LIGHT_FLAGS & set(words):
return False
if launch.tool == "docker":
subcommand = docker_subcommand(launch.arguments)
return subcommand in BUILDS or (subcommand[-1:] in (["run"], ["exec"]) and mutation_run([tool_name(word) for word in launch.arguments]))
return mutation_run([launch.tool, *(tool_name(word) for word in launch.arguments)])
def mutation_run(names: list[str]) -> bool:
return any(name in MUTATORS and (not MUTATORS[name] or MUTATORS[name] & set(names[i + 1:i + 3])) for i, name in enumerate(names))
+45 -8
View File
@@ -3,7 +3,7 @@
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, Write and Agent call, in every session and
settings.json runs it before each Agent, Bash, Edit, MultiEdit, Read and Write call, in every session and
subagent. The rules:
{rules}
@@ -29,16 +29,21 @@ override cannot be logged; 0 otherwise. `rule-hook overrides` exits 1 when git c
checkout or the branch's reflog. Exit 1, a non-blocking error to Claude Code, on input it
cannot read.
"""
import datetime
import itertools
import json
import os
import pathlib
import stat
import sys
import time
import typing
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 rule_hook.repeat_read import asked_lines, repeat_breaches, shown_lines
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
from git_command import commits
from claude_code.transcript import current_thread, read_transcript
from failure import Failure
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
from rule_hook.reviewer_report import report_breaches
@@ -67,7 +72,7 @@ def main(argv: list[str], stdin: str) -> int:
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())
return answer(check(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), what, time.time())
def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tuple[str, str, list[Breach]] | None:
@@ -76,7 +81,9 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
return text(call.given, "prompt"), text(call.given, "subagent_type"), reviewer_breaches(call, environ)
if call.tool == "Bash":
command = text(call.given, "command")
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home)
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home)
if call.tool == "Read":
return "", text(call.given, "file_path"), read_breaches(call, home)
path = text(call.given, "file_path")
if call.tool not in FILE_TOOLS or not path:
return None
@@ -85,12 +92,12 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
return added, path, report_breaches(call, path, home) + file_breaches(path, before, added, after)
def answer(judged: Outcome, what: str, now: float) -> int:
for message in judged.messages:
def answer(checked: Checked, what: str, now: float) -> int:
for message in checked.messages:
print(message, file=sys.stderr)
if judged.blocked:
if checked.blocked:
return 2
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in judged.overridden]
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in checked.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:
@@ -107,6 +114,36 @@ def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in todo_breaches(commit.directory)]
def read_breaches(call: Call, home: str) -> list[Breach]:
"""The repeat-read breaches of a call, read from the calling agent's transcript and the asked file; none where either cannot be read, or the file is not a regular file."""
asked = asked_lines(call.tool, call.given, call.cwd, home)
changed = modified(asked.path) if asked else None
entries = read_transcript(call.transcript) if changed and call.transcript else []
if asked is None or changed is None or isinstance(entries, Failure):
return []
shown = shown_lines(current_thread(entries), call.tool, asked.path, changed, home)
# No line past the last one shown is in context, so the file's lines through one past it tell as much as all of them, and a long file is not read whole.
return repeat_breaches(asked, first_lines(asked.path, max(shown) + 1), shown, call.cwd) if shown else []
def modified(path: str) -> str | None:
"""When a regular file last changed, stamped as a transcript entry is; None for any other path, such as a FIFO, whose read could hang."""
try:
status = os.stat(path)
except (OSError, ValueError):
return None
return datetime.datetime.fromtimestamp(status.st_mtime, datetime.UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z") if stat.S_ISREG(status.st_mode) else None
def first_lines(path: str, count: int) -> list[str]:
"""The file's first count lines, without their line ends; none where it cannot be read as UTF-8."""
try:
with open(path, encoding="utf-8") as file:
return [line.removesuffix("\n") for line in itertools.islice(file, count)]
except (OSError, UnicodeDecodeError):
return []
def read(path: str) -> str:
try:
return pathlib.Path(path).read_text(encoding="utf-8")
+115
View File
@@ -0,0 +1,115 @@
"""Whether a read asks for lines of a file already in the agent's context, for the `repeat-read` rule.
A line is in context when a read since the transcript thread's last compaction showed it at its line number, as the file holds it now.
Against a Read, no line is in context when the file changed after the agent last read it with Read or wrote it with Edit, MultiEdit or Write, or when it never did."""
import dataclasses
import re
from rule_hook.rules import Breach
from rule_hook.call import FILE_TOOLS, text
from claude_code.entries import parts, tool_call, tool_result, tool_use_id
from shell_command import resolved, simple_commands
# The lines a Read without a limit returns.
READ_LIMIT = 2000
# A line of a Read result: its number, then a tab, or an arrow in older Claude Code versions.
NUMBERED = re.compile(r" *(\d+)[\t→](.*)", re.DOTALL)
HEAD_COUNT = re.compile(r"-(?:n ?)?(\d+)")
SED_RANGE = re.compile(r"(\d+)(?:,(\d+|\$))?p")
@dataclasses.dataclass(frozen=True)
class Asked:
path: str
first: int
# None: to the file's end.
last: int | None
def repeat_breaches(asked: Asked, lines: list[str], shown: dict[int, str], cwd: str) -> list[Breach]:
"""shown is what shown_lines found, and lines the asked file's lines now, read at least through one past the last shown line."""
last = len(lines) if asked.last is None else min(asked.last, len(lines))
if not in_context(asked.first, last, lines, shown):
return []
named = f"line {last} of {asked.path} is" if asked.first == last else f"lines {asked.first}-{last} of {asked.path} are"
return [Breach("repeat-read", f"{named} in your context, unchanged since your last read of it", cwd)]
def in_context(first: int, last: int, lines: list[str], shown: dict[int, str]) -> bool:
return first <= last and all(shown.get(number) == lines[number - 1] for number in range(first, last + 1))
def asked_lines(tool: object, given: object, cwd: str, home: str) -> Asked | None:
"""The lines a tool call reads; None for any call but a Read and the Bash reads the rule names, such as one whose output goes elsewhere."""
if not isinstance(given, dict):
return None
return read_asked(given, cwd, home) if tool == "Read" else shell_asked(text(given, "command"), cwd, home) if tool == "Bash" else None
def read_asked(given: dict, cwd: str, home: str) -> Asked | None:
path, offset, limit = text(given, "file_path"), given.get("offset"), given.get("limit")
first = offset if isinstance(offset, int) and offset > 0 else 1
return Asked(resolved(cwd, path, home), first, first + (limit if isinstance(limit, int) and limit > 0 else READ_LIMIT) - 1) if path else None
# reading_cost/shell_reads.py parses a shell read too, loosely: a measure of reading counts any file a reader names, while a rule that blocks must match only a read whose lines it knows exactly.
def shell_asked(command: str, cwd: str, home: str) -> Asked | None:
simples = simple_commands(command, cwd, home) if not set("|<>") & set(command) else []
if len(simples) != 1 or len(simples[0].words) < 2 or simples[0].words[-1].startswith("-"):
return None
(name, *options, path), directory = simples[0].words, simples[0].directory
path = resolved(directory, path, home)
if name == "cat" and not options:
return Asked(path, 1, None)
if name == "head" and (counted := HEAD_COUNT.fullmatch(" ".join(options) or "-10")):
return Asked(path, 1, int(counted.group(1)))
if name == "sed" and len(options) == 2 and options[0] == "-n" and (ranged := SED_RANGE.fullmatch(options[1])):
start, end = ranged.groups()
return Asked(path, int(start), None if end == "$" else int(end or start))
return None
def shown_lines(thread: list[dict], asker: str, path: str, changed: str, home: str) -> dict[int, str]:
"""Each line number of path that a successful read in the thread showed, with the line its latest read showed; none against a Read when the file changed after the agent last read it with Read or wrote it with Edit, MultiEdit or Write, or when it never did.
changed is when the file last changed, stamped as the transcript stamps its entries, so the two compare as text."""
used = results_on(thread, path, home)
# Claude Code's Edit and Write refuse such a file until a Read, and a Bash read does not count as one.
touched = max((stamp for tool, _, _, stamp in used if tool == "Read" or tool in FILE_TOOLS), default="")
if asker == "Read" and changed > touched:
return {}
shown: dict[int, str] = {}
for tool, asked, result, _ in used:
shown |= result_lines(tool, asked, result) if asked else {}
return shown
def results_on(thread: list[dict], path: str, home: str) -> list[tuple[object, Asked | None, str, str]]:
"""Each successful result in the thread of a call that read lines of path or wrote it: the call's tool, the lines it read (None for a write), the result's text and its entry's timestamp."""
calls: dict[str, tuple[object, Asked | None]] = {}
found: list[tuple[object, Asked | None, str, str]] = []
for entry in thread:
cwd = str(entry.get("cwd", ""))
for part in parts(entry):
if (call := tool_call(part)) and (called := tool_use_id(part)):
asked = asked_lines(*call, cwd, home)
if (asked.path if asked else written(*call, cwd, home)) == path:
calls[called] = (call[0], asked)
elif (result := tool_result(part)) and not result.failed and (use := calls.get(result.tool_use_id)):
found.append((use[0], use[1], result.text, text(entry, "timestamp")))
return found
def written(tool: object, given: object, cwd: str, home: str) -> str:
"""The file an Edit, MultiEdit or Write call writes; empty for any other call."""
return resolved(cwd, path, home) if tool in FILE_TOOLS and isinstance(given, dict) and (path := text(given, "file_path")) else ""
def result_lines(tool: object, asked: Asked, result: str) -> dict[int, str]:
if tool == "Read":
return {int(numbered.group(1)): numbered.group(2) for line in result.split("\n") if (numbered := NUMBERED.fullmatch(line))}
# Claude Code cuts a long Bash output short with a note: before the output, "<persisted-output>\n" or "<truncated-output>\n" and a few more lines, or after it, "\n\n... [N lines truncated] ...".
# The note's lines would take the numbers of the file's, so such an output shows no lines.
if result.startswith(("<persisted-output>\n", "<truncated-output>\n")) or result.endswith(" lines truncated] ..."):
return {}
return {number: line for number, line in enumerate(result.split("\n"), asked.first) if asked.last is None or number <= asked.last}
+54 -10
View File
@@ -3,12 +3,14 @@ import posixpath
import re
import typing
from round_titles import CAP, lacks_counts, past_cap
from git_command import commits
from round_titles import lacks_counts
from rule_hook.heavy_command import heavy
from shell_command import launched, Simple, tool_name
from review_folder import REPORTS
from shell_command import Simple
from docker_command import unlimited
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-title-counts", "todo-rank-check"]
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
@dataclasses.dataclass(frozen=True)
@@ -28,6 +30,10 @@ RULES: dict[RuleName, 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",
),
"docker-run-memory": Rule(
"a container made with docker run or docker create has a memory limit and a swap limit, as large as its work needs, such as `--memory 4g --memory-swap 4g`, so a runaway container fails alone instead of starving the machine; a swap limit equal to the memory limit keeps it out of swap",
"docker run, docker create, docker container run and docker container create, whether direct or through a launcher such as nice or timeout. One under run-heavy passes, as run-heavy's docker adds the limits on Linux, unless it names docker by its path, or changes or clears PATH, as env -i, sudo or doas do. A container a script or docker compose starts is not checked",
),
"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",
@@ -40,6 +46,12 @@ RULES: dict[RuleName, 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",
),
# A Read carries no text for a marker, and a misjudged read has a way through that the message names, so no marker waives it.
"repeat-read": Rule(
"an agent reads no lines of a file that its context already holds unchanged, since each read pays for them again; where the context lacks them although the transcript shows them, as after Claude Code cleared old tool results, read them with another command, such as `grep -n '' <file> | sed -n '<A>,<B>p'`; a Read goes through until the agent has read the file with Read or written it with Edit, MultiEdit or Write, and again once the file changed after that, since those refuse a file until then",
"a Read call, and a Bash command that is one `cat <file>`, `head [-n <N> | -<N>] <file>` or `sed -n '<A>[,<B>]p' <file>`, with no pipe or redirect, against the reads in the calling agent's own transcript since its last compaction",
overridable=False,
),
# A reviewer only reports, so no marker waives it.
"reviewer-report": Rule(
f"a reviewer writes nothing but its report, with Write, into a file under ~/{REPORTS}/",
@@ -52,10 +64,18 @@ RULES: dict[RuleName, Rule] = {
"an Agent call, in a claude loop-claude started, whose subagent type is an agent under agents/, or whose prompt opens with seat-prompts.md's opening sentence or the one larv-review's Security section sets",
overridable=False,
),
"round-title-counts": Rule(
"a larv-review round's commit title gives the counts of 🔴 and 🟡 findings the round reported, such as `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`, since score-outcomes counts them",
"round-cap": Rule(
f"a larv-review pass takes at most {CAP} rounds per chunk, so a commit titled `Answer <pass> round <n>:` with <n> past {CAP} waits for the human's yes, which the override reason quotes",
"a git commit whose message opens `Answer <pass> round <n>:`",
),
"round-title-counts": Rule(
"a larv-review round's commit title gives the counts of 🔴 and 🟡 findings the round reported, and how many of them a reviewer marked `[misread]`, at most the two together, such as `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); flag a deleted test`, since score-outcomes counts them",
"a git commit whose message opens `Answer <pass> round <n>:`",
),
"run-heavy": Rule(
"a heavy command, which loads the machine for minutes, runs under ~/.claude/bin/run-heavy, so sessions running at once cannot starve the machine",
"a docker build, docker buildx build or docker compose build, and a run of cargo mutants, Infection, mutmut or Stryker, the mutation tools stability-reviewer names, whether direct, through a launcher such as uvx, or inside docker run, docker exec or docker compose run or exec. A gate script is not checked, since no program can tell it from a light one",
),
"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",
@@ -84,7 +104,8 @@ class Breach:
@dataclasses.dataclass(frozen=True)
class Outcome:
class Checked:
"""What rule-hook found in one tool call: the messages to show, whether it blocks the call, and the overrides to log."""
messages: list[str]
blocked: bool
# Each breach an override let through, with its reason; logged only when the call goes through.
@@ -98,7 +119,7 @@ def overrides(written: str) -> tuple[dict[str, str], list[str]]:
return granted, [f"rule-override {rule}: {reason}" for rule, reason in given if rule not in RULES or not reason]
def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Outcome:
def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Checked:
granted, malformed = overrides(written)
blocking = [breach for breach in breaches if breach.rule not in granted]
messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else []
@@ -106,11 +127,11 @@ def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) ->
for rule in sorted({breach.rule for breach in blocking}):
details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
if not RULES[rule].overridable:
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}.")
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. No marker overrides it.")
continue
marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.")
return Outcome(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
return Checked(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]:
@@ -119,16 +140,39 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre
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 simple in simples:
if heavy(simple.words):
breaches.append(Breach("run-heavy", f"run `{' '.join(simple.words)[:80]}` under `~/.claude/bin/run-heavy`, in the background", simple.directory))
if unlimited_container(simple.words):
breaches.append(Breach("docker-run-memory", f"give `{' '.join(simple.words)[:80]}` a memory limit and a swap limit as large as its work needs", simple.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))
if any(past_cap(message) for message in commit.messages):
breaches.append(Breach("round-cap", f"the pass has had its {CAP} rounds; ask the human, and quote the yes in the override", commit.directory))
if any(lacks_counts(message) for message in commit.messages):
breaches.append(Breach("round-title-counts", "open the summary after the round's colon with `<k> 🔴, <m> 🟡;`", commit.directory))
breaches.append(Breach("round-title-counts", "open the summary after the round's colon with `<k> 🔴, <m> 🟡 (<j> misread);`, where <j> is at most <k> + <m>", commit.directory))
return breaches
def unlimited_container(words: list[str]) -> bool:
"""Whether the simple command, directly or through a launcher, starts a container that lacks a memory limit or a swap limit."""
docker = launched(words, {"docker"})
if docker is None or not unlimited(docker.arguments):
return False
# On Linux, run-heavy's docker adds the limits a container lacks, where PATH finds it: docker named bare, with PATH left as run-heavy set it.
before = words[:len(words) - len(docker.arguments) - 1]
capped = "run-heavy" in docker.launchers and words[len(before)] == "docker" and not any(resets_path(word) for word in before)
return not capped
def resets_path(word: str) -> bool:
"""Whether a word before docker drops the PATH run-heavy set: a PATH= of its own, env's -i or -u, or sudo or doas, which reset it."""
return word.startswith(("PATH=", "--unset")) or word in ("-i", "--ignore-environment", "-u") or tool_name(word) in ("doas", "sudo")
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 []
+282 -11
View File
@@ -1,3 +1,4 @@
import datetime
import json
import os
import pathlib
@@ -9,9 +10,10 @@ import unittest.mock
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 rule_hook.main import breaches_of
from rule_hook.call import Call
from rule_hook.repeat_read import Asked, result_lines
from rule_hook.rules import blocks, Breach, check, command_breaches, file_breaches, overrides
from rule_hook.main import breaches_of, modified, read_breaches
from rule_hook.call import Call, parsed_call
from git_command import Commit, commit_message, commits
from test_rank_todo import DECISIONS, README, TODO
from test_env import isolated_env
@@ -40,7 +42,7 @@ def checked(command: str) -> list[str]:
def hook(call: dict, cwd: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env() | (env or {}), input=json.dumps(call), text=True)
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env() | (env or {}), input=json.dumps(call), text=True, timeout=10)
def git(cwd: str, *args: str) -> str:
@@ -101,10 +103,43 @@ class CommandBreaches(unittest.TestCase):
def test_a_round_title_without_its_counts_breaks_round_title_counts(self):
self.assertEqual(checked("git commit -m 'Answer stability round 1: fix the parser'"), ["round-title-counts"])
self.assertEqual(checked("git commit --allow-empty -m 'Answer prose round 2: 0 🔴, 0 🟡'"), [])
self.assertEqual(checked("git commit -m 'Answer stability round 1: 1 🔴, 2 🟡; fix the parser'"), [])
self.assertEqual(checked("git commit -m 'Answer stability round 1: 1 🔴, 2 🟡; fix the parser'"), ["round-title-counts"])
self.assertEqual(checked("git commit --allow-empty -m 'Answer prose round 2: 0 🔴, 0 🟡 (0 misread)'"), [])
self.assertEqual(checked("git commit -m 'Answer stability round 1: 1 🔴, 2 🟡 (1 misread); fix the parser'"), [])
self.assertEqual(checked("git commit -m 'Answer the question in the README'"), [])
def test_a_docker_build_or_a_mutation_run_outside_run_heavy_breaks_run_heavy(self):
for command in ["docker build -t x .", "cd /w && docker buildx build .", "docker compose build", "docker compose -f x.yml --verbose build app", "uvx --with pytest 'mutmut>=3,<4' run", "cargo mutants --in-diff d", "npx stryker run", "vendor/bin/infection --git-diff-lines", "docker compose run --rm app mutmut run", "docker run --rm -m 4g --memory-swap 4g -v /w:/w rust:1.90.0 cargo mutants", "docker compose exec app npx stryker run", "docker run -h box -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "nice -n 19 docker build .", "env DOCKER_BUILDKIT=1 docker build .", "time -p docker compose build", "docker --tlscacert ca.pem build .", "docker --tlscert c.pem --tlskey k.pem build .", "docker buildx --builder b build .", "docker container run -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "uvx mutmut --verbose run"]:
with self.subTest(command):
self.assertEqual(checked(command), ["run-heavy"])
def test_a_heavy_command_under_run_heavy_or_a_light_docker_or_mutmut_call_passes(self):
for command in ["~/.claude/bin/run-heavy docker build -t x .", "/home/me/.claude/bin/run-heavy uvx mutmut run", "nice -n 19 ~/.claude/bin/run-heavy docker build .", "env X=1 run-heavy docker compose run app mutmut run", "docker images", "docker compose run --rm app go vet", "docker compose run app make build", "uvx 'mutmut>=3,<4' results", "echo docker build", "npx prettier --check infection.json5", "echo mutmut run", "env", "docker build --help", "cargo mutants --list", "infection --version", "uvx mutmut a b run"]:
with self.subTest(command):
self.assertEqual(checked(command), [])
def test_a_docker_run_or_create_without_a_memory_limit_breaks_docker_run_memory(self):
for command in ["docker run --rm node:24.22.1-alpine3.24 node x.js", "cd /w && docker run -v /w:/w alpine:3.22.2 true", "docker create alpine:3.22.2", "docker container run alpine:3.22.2 true", "docker container create alpine:3.22.2", "nice -n 19 docker run alpine:3.22.2 true", "docker -H unix:///d.sock run alpine:3.22.2 true", "docker run --memory-swap 4g alpine:3.22.2 true", "docker run -m 4g alpine:3.22.2 true", "docker run --memory=4g alpine:3.22.2 sh -c 'x --memory-swap 4g'", "docker run -m 4g alpine:3.22.2 tool --memory-swap", "docker run -m 4g --memory-swap -1 alpine:3.22.2 true", "docker run -m 4g --memory-swap=0 alpine:3.22.2 true", "docker run --rm python:3.13.1 python -m pytest", "docker run alpine:3.22.2 git commit -m x", "timeout 60 docker run alpine:3.22.2 true", "docker run node:24.22.1-alpine3.24 node --help", "docker run alpine:3.22.2 --help", "docker run -m 4g alpine:3.22.2 sleep 60", "~/.claude/bin/run-heavy /usr/bin/docker run alpine:3.22.2 true", "docker run --memory-swap 4g alpine:3.22.2 grep -m 1 x", "run-heavy env PATH=/usr/bin docker run alpine:3.22.2 true", "run-heavy sudo docker run alpine:3.22.2 true", "docker run alpine:3.22.2 git tag -m 1.2.3", "run-heavy env -i docker run alpine:3.22.2 true", "run-heavy env -u PATH docker run alpine:3.22.2 true", "run-heavy env --unset=PATH docker run alpine:3.22.2 true", "run-heavy env --ignore-environment docker run alpine:3.22.2 true", "run-heavy doas docker run alpine:3.22.2 true"]:
with self.subTest(command):
self.assertEqual(checked(command), ["docker-run-memory"])
def test_a_docker_run_with_a_memory_limit_or_another_docker_call_passes_docker_run_memory(self):
for command in ["docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run -m4g --memory-swap=4g alpine:3.22.2 true", "docker run --memory 512M --memory-swap 1g alpine:3.22.2 true", "docker run -m 1073741824 --memory-swap 2g alpine:3.22.2 true", "timeout 60 docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run --rm --memory=1.5GiB --memory-swap=1.5GiB alpine:3.22.2 true", "docker container create -m 1g --memory-swap 1g alpine:3.22.2", "docker run --help", "docker container run --help", "docker --context run run --help", "docker --help", "docker ps", "docker images", "docker container ls", "docker compose run --rm app go vet", "docker exec box true", "echo docker run alpine:3.22.2", "~/.claude/bin/run-heavy docker run alpine:3.22.2 true"]:
with self.subTest(command):
self.assertEqual(checked(command), [])
def test_a_round_title_past_round_3_breaks_round_cap(self):
self.assertEqual(checked("git commit -m 'Answer stability round 4: 0 🔴, 1 🟡 (0 misread); fix the parser'"), ["round-cap"])
self.assertEqual(checked("git commit -m 'Answer stability round 3: 0 🔴, 1 🟡 (0 misread); fix the parser'"), [])
def test_a_round_cap_breach_names_the_commit_s_checkout(self):
command = "git -C /x commit -m 'Answer stability round 4: 0 🔴, 1 🟡 (0 misread); fix'"
self.assertEqual([(breach.rule, breach.directory) for breach in command_breaches(command, simple_commands(command, "/r", "/h"), "/h")], [("round-cap", "/x")])
def test_an_override_quoting_the_human_s_yes_lets_a_round_past_the_cap_through(self):
command = "git commit -m 'Answer stability round 4: 0 🔴, 1 🟡 (0 misread); fix' # rule-override round-cap: the human answered 'yes, one more'"
self.assertFalse(check(command_breaches(command, simple_commands(command, "/r", "/h"), "/h"), command, False, True).blocked)
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}' ."), [])
@@ -160,13 +195,13 @@ class Overrides(unittest.TestCase):
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)
blocked_call = check(breaches, "# rule-override image-pin: a", False, False)
self.assertTrue(blocked_call.blocked)
passed = check(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])
self.assertIn("`<!-- rule-override no-ai-attribution: <reason> -->`", check([Breach("no-ai-attribution", "x", "/r")], "", True, False).messages[0])
class OverrideLog(unittest.TestCase):
@@ -295,6 +330,242 @@ class ReviewerReport(unittest.TestCase):
self.assertEqual(self.breached("Write", "/r/README.md", "general-purpose"), [])
class RepeatRead(unittest.TestCase):
LINES = [f"line {n}" for n in range(1, 31)]
# The file is written at WRITTEN and each entry stamped READ_AT, unless a test changes the file at CHANGED and stamps a later entry AFTER_THE_CHANGE.
WRITTEN = datetime.datetime(2026, 5, 1, tzinfo=datetime.UTC).timestamp()
READ_AT = "2026-06-01T00:00:00.000Z"
CHANGED = datetime.datetime(2026, 7, 1, tzinfo=datetime.UTC).timestamp()
AFTER_THE_CHANGE = "2026-07-01T00:00:01.000Z"
def setUp(self):
self.folder = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", self.folder])
self.file = f"{self.folder}/f.txt"
self.write(self.LINES, self.WRITTEN)
self.transcript = f"{self.folder}/s.jsonl"
self.entries: list[dict] = []
def write(self, lines: list[str], at: float) -> None:
pathlib.Path(self.file).write_text("\n".join(lines) + "\n")
os.utime(self.file, (at, at))
def change(self, number: int) -> None:
self.write([("changed" if n == number else line) for n, line in enumerate(self.LINES, 1)], self.CHANGED)
def add(self, entry: dict, parent: str | None = "last") -> str:
uuid = f"u{len(self.entries)}"
parent = (self.entries[-1]["uuid"] if self.entries else None) if parent == "last" else parent
self.entries.append({"uuid": uuid, "parentUuid": parent, "cwd": self.folder, "timestamp": self.READ_AT} | entry)
pathlib.Path(self.transcript).write_text("\n".join(json.dumps(entry) for entry in self.entries) + "\n")
return uuid
def used(self, tool: str, given: dict, result: str, error: bool = False, at: str = READ_AT) -> None:
tool_id = f"toolu_{len(self.entries)}"
self.add({"type": "assistant", "timestamp": at, "message": {"content": [{"type": "tool_use", "id": tool_id, "name": tool, "input": given}]}})
self.add({"type": "user", "timestamp": at, "message": {"content": [{"type": "tool_result", "tool_use_id": tool_id, "content": result, "is_error": error}]}})
def numbered(self, start: int, end: int) -> str:
return "\n".join(f"{n}\t{self.LINES[n - 1]}" for n in range(start, end + 1))
def read(self, start: int, end: int) -> None:
self.used("Read", {"file_path": self.file, "offset": start, "limit": end - start + 1}, self.numbered(start, end))
def shown(self, start: int, end: int) -> str:
return "\n".join(self.LINES[start - 1:end])
def found(self, tool: str, given: dict, agent: str = "") -> list[Breach]:
return read_breaches(Call(tool, given, self.folder, agent, self.transcript), "/h")
def test_a_read_of_lines_already_read_is_blocked_with_a_note(self):
self.read(1, 10)
found = self.found("Read", {"file_path": self.file, "offset": 2, "limit": 5})
self.assertEqual(rules(found), ["repeat-read"])
self.assertIn(f"lines 2-6 of {self.file} are in your context", found[0].detail)
def test_the_note_names_a_single_line_as_one(self):
self.read(1, 10)
self.assertIn(f"line 7 of {self.file} is in your context", self.found("Bash", {"command": "sed -n 7p f.txt"})[0].detail)
def test_lines_read_in_two_reads_are_in_context(self):
self.read(1, 10)
self.read(11, 20)
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 5, "limit": 10})), ["repeat-read"])
def test_a_read_past_what_was_read_goes_through(self):
self.read(1, 10)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 5, "limit": 10}), [])
def test_a_read_without_a_limit_asks_for_the_whole_file(self):
self.read(1, 10)
self.assertEqual(self.found("Read", {"file_path": self.file}), [])
def test_a_read_result_in_the_older_arrow_format_counts(self):
self.used("Read", {"file_path": self.file, "offset": 1, "limit": 10}, "\n".join(f"{n:6}→{self.LINES[n - 1]}" for n in range(1, 11)))
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10})), ["repeat-read"])
def test_a_compaction_lets_the_read_through(self):
self.read(1, 10)
self.add({"type": "system", "subtype": "compact_boundary"}, parent=None)
self.add({"type": "user", "message": {"content": "This session is being continued"}})
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_a_changed_line_lets_the_read_through(self):
self.read(1, 10)
self.change(1)
self.assertEqual(self.found("Bash", {"command": f"head {self.file}"}), [])
def test_a_change_in_the_last_asked_line_lets_the_read_through(self):
self.read(1, 10)
self.change(10)
self.assertEqual(self.found("Bash", {"command": "sed -n 1,10p f.txt"}), [])
def test_lines_that_did_not_change_stay_in_context(self):
self.read(1, 10)
self.change(1)
self.assertEqual(rules(self.found("Bash", {"command": "sed -n 2,10p f.txt"})), ["repeat-read"])
def test_a_read_without_an_offset_starts_at_line_1(self):
self.read(2, 11)
self.assertEqual(self.found("Read", {"file_path": self.file, "limit": 10}), [])
def test_calls_that_neither_read_nor_write_the_file_are_passed_over(self):
self.used("Grep", {"pattern": "line", "path": self.folder}, "f.txt")
self.used("Bash", {"command": "ls"}, "f.txt")
self.read(1, 10)
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10})), ["repeat-read"])
# Claude Code's Edit refuses a file changed since the agent last read it with Read, or wrote it with Edit or Write, until it reads it again.
def test_a_change_in_the_millisecond_of_the_last_read_counts_as_before_it(self):
self.read(1, 10)
at = datetime.datetime(2026, 6, 1, tzinfo=datetime.UTC).timestamp()
os.utime(self.file, (at, at))
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10})), ["repeat-read"])
def test_a_file_s_change_is_stamped_as_the_transcript_stamps_its_entries(self):
at = datetime.datetime(2026, 6, 1, 12, 30, 5, 250000, tzinfo=datetime.UTC).timestamp()
os.utime(self.file, (at, at))
self.assertEqual(modified(self.file), "2026-06-01T12:30:05.250Z")
def test_a_read_goes_through_once_the_file_changed_after_the_last_read(self):
self.read(1, 10)
self.change(30)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_a_refused_edit_does_not_count_as_reading_the_file(self):
self.read(1, 10)
self.change(30)
self.used("Edit", {"file_path": self.file, "old_string": "line 5", "new_string": "five"}, "<tool_use_error>File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.</tool_use_error>", error=True, at=self.AFTER_THE_CHANGE)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_an_edit_keeps_the_lines_it_left_unchanged_in_context(self):
self.read(1, 10)
self.change(30)
self.used("Edit", {"file_path": self.file, "old_string": "line 30", "new_string": "changed"}, f"The file {self.file} has been updated successfully.", at=self.AFTER_THE_CHANGE)
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10})), ["repeat-read"])
def test_a_failed_read_holds_no_lines(self):
self.used("Read", {"file_path": self.file, "offset": 1, "limit": 10}, self.numbered(1, 10), error=True)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_a_read_on_a_branch_the_session_rewound_holds_no_lines(self):
start = self.add({"type": "user", "message": {"content": "go"}})
self.read(1, 10)
self.add({"type": "user", "message": {"content": "go again"}}, parent=start)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_head_and_sed_of_lines_read_are_blocked(self):
self.read(1, 20)
for command in [f"head -n 5 {self.file}", f"head -n5 {self.file}", f"head -5 {self.file}", f"head {self.file}", "sed -n '3,8p' f.txt", "sed -n 7p f.txt"]:
with self.subTest(command):
self.assertEqual(rules(self.found("Bash", {"command": command})), ["repeat-read"])
def test_a_head_starts_at_line_1(self):
self.read(2, 11)
self.assertEqual(self.found("Bash", {"command": f"head {self.file}"}), [])
def test_a_cat_asks_for_the_whole_file(self):
self.read(1, 20)
self.assertEqual(self.found("Bash", {"command": f"cat {self.file}"}), [])
# Claude Code's Edit and Write take only a Read as having read the file.
def test_a_read_goes_through_until_the_agent_read_the_file_with_read(self):
self.used("Bash", {"command": f"sed -n '1,20p' {self.file}"}, self.shown(1, 20))
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 4, "limit": 3}), [])
def test_a_bash_output_counts_against_a_read_once_the_agent_read_the_file_with_read(self):
self.read(21, 30)
self.used("Bash", {"command": f"sed -n '1,20p' {self.file}"}, self.shown(1, 20))
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 4, "limit": 3})), ["repeat-read"])
def test_a_cat_output_puts_every_line_in_context(self):
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 30))
self.assertEqual(rules(self.found("Bash", {"command": "sed -n '25,$p' f.txt"})), ["repeat-read"])
def test_a_relative_path_in_the_transcript_is_under_its_entry_s_cwd(self):
self.used("Bash", {"command": "cat f.txt"}, self.shown(1, 30))
self.assertEqual(rules(read_breaches(Call("Bash", {"command": f"head -n 5 {self.file}"}, "/", "", self.transcript), "/h")), ["repeat-read"])
def test_a_tilde_path_is_under_the_home_folder(self):
self.used("Read", {"file_path": "~/f.txt", "offset": 1, "limit": 10}, self.numbered(1, 10))
self.used("Bash", {"command": "cat ~/f.txt"}, self.shown(1, 30))
for tool, given in [("Read", {"file_path": "~/f.txt", "offset": 1, "limit": 10}), ("Bash", {"command": "sed -n 1,30p ~/f.txt"})]:
with self.subTest(tool):
self.assertEqual(rules(read_breaches(Call(tool, given, "/", "", self.transcript), self.folder)), ["repeat-read"])
def test_other_commands_on_the_file_are_not_checked(self):
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 30))
for command in [f"cat {self.file} > copy", f"cat {self.file} | wc -l", f"cat {self.file} {self.file}", f"head -c 5 {self.file}", f"sed 's/a/b/' {self.file}"]:
with self.subTest(command):
self.assertEqual(self.found("Bash", {"command": command}), [])
# As Claude Code 2.1.312 writes a Bash output it cut short.
def test_an_output_cut_short_shows_no_lines(self):
for cut in [
f"<persisted-output>\nOutput too large (37.9KB). Full output saved to: {self.folder}/tool-results/b2hymdt7w.txt\n\nPreview (first 2KB):\n{self.shown(1, 30)}\n...\n</persisted-output>",
f"<truncated-output>\nOutput too large (37.9KB). It could not be saved, so only the first 2KB are shown; the rest was dropped. If the tool can page or filter its results, call it again for the part you need.\n\n{self.shown(1, 30)}\n</truncated-output>",
self.shown(1, 5) + "\n\n... [25 lines truncated] ...",
]:
with self.subTest(cut[:20]):
self.assertEqual(result_lines("Bash", Asked(self.file, 1, None), cut), {})
def test_a_fifo_is_never_opened(self):
fifo = f"{self.folder}/fifo"
os.mkfifo(fifo)
self.used("Bash", {"command": f"cat {fifo}"}, "line 1")
# Opened, the FIFO would block the hook, since it has no writer.
ran = hook({"cwd": self.folder, "tool_name": "Bash", "tool_input": {"command": f"head -n 1 {fifo}"}, "transcript_path": self.transcript}, self.folder)
self.assertEqual((ran.returncode, ran.stderr), (0, ""))
def called(self, agent_id: str = "") -> Call:
given = {"cwd": self.folder, "tool_name": "Read", "tool_input": {"file_path": self.file, "offset": 1, "limit": 10}, "transcript_path": self.transcript}
return parsed_call(given | ({"agent_id": agent_id, "agent_type": "Explore"} if agent_id else {}))
def test_a_subagent_s_transcript_is_beside_the_session_s(self):
self.assertEqual(self.called("a1").transcript, f"{self.folder}/s/subagents/agent-a1.jsonl")
def test_the_session_s_reads_are_not_in_a_subagent_s_context(self):
self.read(1, 10)
self.assertEqual(read_breaches(self.called("a1"), "/h"), [])
def test_the_session_is_judged_on_its_own_transcript(self):
self.read(1, 10)
self.assertEqual(rules(read_breaches(self.called(), "/h")), ["repeat-read"])
def test_a_missing_transcript_lets_the_read_through(self):
self.assertEqual(read_breaches(Call("Read", {"file_path": self.file}, self.folder, "", f"{self.folder}/none.jsonl"), "/h"), [])
def test_the_hook_blocks_a_repeated_read_without_offering_an_override(self):
self.read(1, 10)
self.used("Bash", {"command": f"head -n 5 {self.file}"}, self.shown(1, 5))
for tool, given in [("Read", {"file_path": self.file, "offset": 1, "limit": 10}), ("Bash", {"command": f"head -n 5 {self.file}"})]:
with self.subTest(tool):
ran = hook({"cwd": self.folder, "tool_name": tool, "tool_input": given, "transcript_path": self.transcript}, self.folder)
self.assertEqual(ran.returncode, 2)
self.assertIn("Blocked by rule repeat-read: ", ran.stderr)
self.assertNotIn("rule-override", ran.stderr)
class Hook(unittest.TestCase):
def setUp(self):
self.repo = tempfile.mkdtemp()
@@ -444,7 +715,7 @@ class Hook(unittest.TestCase):
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", "reviewer-report", "reviewer-rung", "round-title-counts", "todo-rank-check"]:
for rule in ["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]:
self.assertIn(f" {rule}\n The rule: ", helped)
self.assertIn("reviewer-report\n The rule: a reviewer writes nothing but its report", helped)
self.assertRegex(helped, r" reviewer-report\n( .*\n){2} Takes no override\.\n")
Executable
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
import os
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from run_heavy import main
from machine_load.memory import read_memory
from machine_load.slots import usable_cpus
sys.exit(main.main(sys.argv[1:], os.environ, usable_cpus(), read_memory()))
View File
+35
View File
@@ -0,0 +1,35 @@
"""The docker that run-heavy puts first on its command's PATH. It adds the memory limits a container lacks, from the slot's share, then runs the real docker."""
import os
import pathlib
import shutil
import sys
import typing
from docker_command import capped
# The folder run-heavy puts first on its command's PATH, holding the docker that runs main.
PATH_ENTRY = pathlib.Path(__file__).resolve().parent / "path_entry"
# The environment variable that hands this docker the slot's memory share, in MiB.
SHARE_VARIABLE = "RUN_HEAVY_MEMORY"
CANNOT_RUN = 126
NOT_FOUND = 127
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
"""Replaces this process with the real docker; returns only where none is found or it cannot run."""
path = without_path_entry(env.get("PATH", ""))
docker = shutil.which("docker", path=path)
if docker is None:
print("run-heavy: docker: command not found", file=sys.stderr)
return NOT_FOUND
share = env.get(SHARE_VARIABLE)
try:
os.execve(docker, [docker, *(capped(argv, f"{share}m") if share else argv)], {**env, "PATH": path})
except OSError as failure:
print(f"run-heavy: cannot run {docker}: {failure.strerror}", file=sys.stderr)
return CANNOT_RUN
def without_path_entry(path: str) -> str:
"""path less PATH_ENTRY, so the real docker is the one found."""
return os.pathsep.join(entry for entry in path.split(os.pathsep) if pathlib.Path(entry).resolve() != PATH_ENTRY)
+93
View File
@@ -0,0 +1,93 @@
"""Run a heavy command once it holds one of the machine's heavy slots, so sessions running at once cannot starve the machine.
usage: run-heavy <command> [<arg>...]
A heavy command is one that loads the machine for minutes: a full gate, mutation tests, an e2e run,
a docker build. The machine has one heavy slot for every 4 CPUs that run-heavy may use, and at least one, shared by every
session that runs run-heavy. Each slot is a file locked with flock, under
$XDG_STATE_HOME/run-heavy (default ~/.local/state/run-heavy). While every slot is held, run-heavy
says so once on stderr and waits. It then replaces itself with the command. The slot's lock stays held
until the command, and every process that inherited the lock, exits. Its exit code is the command's.
On Linux, run-heavy also caps the memory of each container the command makes with docker run or
docker create. The cap is the slot's share: three quarters of the machine's memory, split evenly
across the slots, handed to the command in RUN_HEAVY_MEMORY, in MiB. run-heavy puts its own docker
first on the command's PATH. That docker adds the limits a container lacks, then runs the real one:
- A container that sets neither limit gets a memory limit and a swap limit, both the share.
- A container that sets one of them keeps it, and gets the other at the same size.
- A --memory-swap of -1, unlimited swap, is dropped and replaced.
- A --memory of 0, unlimited memory, leaves the call as it is.
Every other docker call goes through unchanged. A docker compose service, and a docker named by its
full path, get no cap: give those containers their own limits.
A command it runs carries the slot's number in RUN_HEAVY_SLOT, and run-heavy called with that set
runs its command at once, so a gate that wraps its own steps cannot wait on itself.
As GNU env, nice and timeout do, it exits 125, saying why, when no command is given or the slot
folder or a slot file cannot be made or locked; 126 when the command is found but cannot run; and 127 when it is not found.
"""
import os
import pathlib
import shutil
import sys
import typing
from failure import Failure
from machine_load.memory import Memory
from run_heavy.capped_docker import PATH_ENTRY, SHARE_VARIABLE, without_path_entry
from machine_load.slots import slot_count, slot_folder, waited_slot
OWN_FAILURE = 125
CANNOT_RUN = 126
NOT_FOUND = 127
HELD = "RUN_HEAVY_SLOT"
USAGE = "usage: run-heavy <command> [<arg>...]"
def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None, memory: Memory | None) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if not argv:
print(f"run-heavy: no command given; {USAGE}", file=sys.stderr)
return OWN_FAILURE
if HELD not in env:
slot = held_slot(slot_folder(env), slot_count(cpus))
if isinstance(slot, Failure):
print(f"run-heavy: {slot.reason}", file=sys.stderr)
return OWN_FAILURE
env = {**env, HELD: str(slot), **capping(memory, slot_count(cpus), env)}
return run(argv, env)
def capping(memory: Memory | None, slots: int, env: typing.Mapping[str, str]) -> dict[str, str]:
"""What the command's environment needs for its docker to cap each container it makes at the slot's share of memory; nothing where the memory is unknown, as off Linux, or where PATH finds no docker to cap."""
path = env.get("PATH", "")
if memory is None or shutil.which("docker", path=without_path_entry(path)) is None:
return {}
return {SHARE_VARIABLE: str(memory.slot_share(slots)), "PATH": os.pathsep.join([str(PATH_ENTRY), path])}
def held_slot(folder: pathlib.Path, slots: int) -> int | Failure:
"""The number of the slot this call holds, its lock left for the command to inherit, or why no slot could be taken."""
try:
folder.mkdir(parents=True, exist_ok=True)
slot, fd = waited_slot(folder, slots, lambda: print(f"run-heavy: waiting for a heavy slot, of {slots} on this machine, in {folder}; `fuser {folder}/slot-*` names the processes that hold them", file=sys.stderr, flush=True))
except OSError as failure:
return Failure(f"cannot take a heavy slot in {folder}: {failure.strerror}")
os.set_inheritable(fd, True)
return slot
def run(argv: list[str], env: typing.Mapping[str, str]) -> int:
"""Replaces this process with the command; returns only where the command cannot start."""
try:
os.execvpe(argv[0], argv, env)
except FileNotFoundError:
print(f"run-heavy: {argv[0]}: command not found", file=sys.stderr)
return NOT_FOUND
except OSError as failure:
print(f"run-heavy: cannot run {argv[0]}: {failure.strerror}", file=sys.stderr)
return CANNOT_RUN
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env python3
import os
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from run_heavy import capped_docker
sys.exit(capped_docker.main(sys.argv[1:], os.environ))
+146
View File
@@ -0,0 +1,146 @@
import contextlib
import fcntl
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from run_heavy import main
from machine_load.memory import read_memory
from machine_load.slots import slot_count, usable_cpus
TOOL = pathlib.Path(__file__).resolve().parents[1] / "run-heavy"
class RunHeavy(unittest.TestCase):
def setUp(self):
state = tempfile.TemporaryDirectory()
self.addCleanup(state.cleanup)
self.env = {**os.environ, "XDG_STATE_HOME": state.name}
self.env.pop(main.HELD, None)
self.slots = pathlib.Path(state.name) / "run-heavy"
def run_tool(self, *args: str, env=None) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, text=True, env=env or self.env, timeout=30)
def start_tool(self, *args: str, env=None) -> subprocess.Popen[str]:
tool = subprocess.Popen([sys.executable, str(TOOL), *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env or self.env)
self.addCleanup(tool.kill)
return tool
@contextlib.contextmanager
def every_slot_held(self):
self.slots.mkdir(parents=True, exist_ok=True)
with contextlib.ExitStack() as held:
for slot in range(slot_count(usable_cpus())):
file = held.enter_context(open(self.slots / f"slot-{slot}", "a"))
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
def free_slots(self) -> int:
free = 0
for slot in range(slot_count(usable_cpus())):
with open(self.slots / f"slot-{slot}", "a") as file:
try:
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
free += 1
except BlockingIOError:
pass
return free
def test_runs_the_command_and_exits_with_its_code(self):
result = self.run_tool("sh", "-c", "echo out; echo err >&2; exit 3")
self.assertEqual((result.returncode, result.stdout, result.stderr), (3, "out\n", "err\n"))
def test_holds_a_slot_while_the_command_runs_and_frees_it_after(self):
tool = self.start_tool("sh", "-c", "echo started; read line")
self.assertEqual(tool.stdout.readline(), "started\n")
self.assertEqual(self.free_slots(), slot_count(usable_cpus()) - 1)
tool.communicate("\n", timeout=30)
self.assertEqual(self.free_slots(), slot_count(usable_cpus()))
def test_a_command_inside_a_held_slot_runs_at_once(self):
with self.every_slot_held():
result = self.run_tool("echo", "nested", env={**self.env, main.HELD: "0"})
self.assertEqual((result.returncode, result.stdout), (0, "nested\n"))
def test_exits_125_saying_why_where_the_slot_folder_cannot_be_made(self):
with tempfile.NamedTemporaryFile() as state:
result = self.run_tool("echo", "ran", env={**self.env, "XDG_STATE_HOME": state.name})
self.assertEqual((result.returncode, result.stdout), (125, ""))
self.assertIn(state.name, result.stderr)
def test_a_command_not_found_exits_127_and_one_that_cannot_run_126_saying_why(self):
missing = self.run_tool("no-such-command-anywhere")
self.assertEqual((missing.returncode, missing.stdout), (127, ""))
self.assertIn("no-such-command-anywhere", missing.stderr)
with tempfile.NamedTemporaryFile(suffix=".sh") as unrunnable:
denied = self.run_tool(unrunnable.name)
self.assertEqual((denied.returncode, denied.stdout), (126, ""))
self.assertIn(unrunnable.name, denied.stderr)
def fake_docker(self) -> dict[str, str]:
"""An environment whose PATH finds, ahead of any real one, a docker that prints the arguments it was given."""
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
docker = pathlib.Path(folder.name) / "docker"
docker.write_text("#!/bin/sh\necho \"$@\"\n")
docker.chmod(0o755)
return {**self.env, "PATH": f"{folder.name}:{self.env['PATH']}"}
def test_a_docker_run_without_limits_gets_three_quarters_of_the_memory_split_across_the_slots(self):
memory = read_memory()
if memory is None:
self.skipTest("no /proc/meminfo to read the share from")
share = f"{memory.total * 3 // 4 // slot_count(usable_cpus()) // 1024}m"
result = self.run_tool("docker", "run", "--rm", "img", "true", env=self.fake_docker())
self.assertEqual((result.returncode, result.stdout), (0, f"run --memory {share} --memory-swap {share} --rm img true\n"))
def test_a_docker_call_with_its_own_limits_or_that_starts_no_container_is_passed_on_unchanged(self):
env = self.fake_docker()
for args in [["run", "-m", "40g", "--memory-swap", "40g", "img"], ["ps", "-a"], ["build", "."]]:
with self.subTest(args):
result = self.run_tool("docker", *args, env=env)
self.assertEqual((result.returncode, result.stdout), (0, " ".join(args) + "\n"))
def test_a_command_on_a_machine_without_docker_finds_none(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
(pathlib.Path(folder.name) / "python3").symlink_to(sys.executable)
(pathlib.Path(folder.name) / "sh").symlink_to("/bin/sh")
result = self.run_tool("sh", "-c", "command -v docker || echo none", env={**self.env, "PATH": folder.name})
self.assertEqual((result.returncode, result.stdout), (0, "none\n"))
def test_the_capped_docker_passes_a_call_on_unchanged_without_a_share(self):
env = self.fake_docker()
env.pop("RUN_HEAVY_MEMORY", None)
shim = pathlib.Path(TOOL).parent / "run_heavy" / "path_entry" / "docker"
result = subprocess.run([str(shim), "run", "img"], capture_output=True, text=True, env=env, timeout=30)
self.assertEqual((result.returncode, result.stdout), (0, "run img\n"))
def test_no_cap_where_the_memory_is_unknown(self):
self.assertEqual(main.capping(None, 4, self.fake_docker()), {})
def test_a_capped_docker_that_finds_no_docker_exits_127_saying_so(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
(pathlib.Path(folder.name) / "python3").symlink_to(sys.executable)
result = self.run_tool("docker", "ps", env={**self.env, "PATH": folder.name})
self.assertEqual((result.returncode, result.stdout), (127, ""))
self.assertIn("docker", result.stderr)
def test_no_command_exits_125_with_the_usage_and_help_exits_0(self):
bare = self.run_tool()
self.assertEqual((bare.returncode, bare.stdout), (125, ""))
self.assertIn("usage: run-heavy <command>", bare.stderr)
helped = self.run_tool("--help")
self.assertEqual(helped.returncode, 0)
self.assertIn("usage: run-heavy <command>", helped.stdout)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -13,7 +13,7 @@ from model_routing.ladder import Rung
AT_ONCE = 4
Case = typing.TypeVar("Case")
# What of a case's record a reply reproduces, such as a verdict's kind or a finding's index.
# What of an archived case a reply reproduces, such as a verdict's kind or a finding's index.
Item = typing.TypeVar("Item")
Reply = typing.TypeVar("Reply")
T = typing.TypeVar("T")
+3 -3
View File
@@ -2,7 +2,7 @@ import re
from todo_table import cells, LEVELS, parse_ids
from failure import Failure
from score_outcomes.outcomes import Outcome, render
from score_outcomes.results import render, Result
ANCHORS_PATH = "docs/score-anchors.md"
# A level, such as `L 1`; every scale tops out below 10.
@@ -29,13 +29,13 @@ def parse_anchors(text: str) -> Anchors | Failure:
return found
def anchor_lines(found: Anchors | Failure, outcomes: list[Outcome]) -> list[str]:
def anchor_lines(found: Anchors | Failure, results: list[Result]) -> list[str]:
"""Each level, then each of its anchors with what its chunk measured. Where the file cannot be read, one line saying why; where it names no level, one line saying how to choose anchors."""
if isinstance(found, Failure):
return [f"- None: {found.reason}"]
if not found:
return [f"- None: the project has no {ANCHORS_PATH}, or it names no level; ~/.claude/rules/todo-items.md says how to choose anchors."]
by_id = {outcome.item.id: outcome for outcome in outcomes}
by_id = {result.item.id: result for result in results}
lines = []
for level, ids in found:
lines.append(f"{level}:")
+31 -23
View File
@@ -19,8 +19,11 @@ holds R and S, and C too where its table also had A, G and Goals. The chunk meas
- review rounds past each pass's first: among the branch's `Answer <pass> round <n>:` commit
titles, each pass's rounds as `larv-review round-count` counts them, less one, summed;
- 🔴 and 🟡 findings: summed over those titles, each opening `<k> 🔴, <m> 🟡` after the colon,
such as `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`. Unknown where a round title
lacks the counts, or the branch has no round.
such as `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); flag a deleted test`. Unknown where a
round title lacks the counts, or the branch has no round;
- misread findings: how many of those 🔴 and 🟡 findings a reviewer marked `[misread]`, the
`(<j> misread)` after the 🟡 count, summed over the titles. Unknown where a round title lacks
that count, as every title written before the count does, or the branch has no round.
A chunk is marked `by rebase` where a commit in it has a committer time apart from its author time,
since a rebase replays a pull request's commits at once, and `never replayed` where none does, since
@@ -48,6 +51,10 @@ that shipped one item, since a chunk measures all its items at once. It leaves o
replayed, which may hold only part of a pull request. It reports a score only once 10 of the chunks
it counts hold it and its outcomes.
Then, newest first, each finished chunk's 🔴 and 🟡 findings with its misread findings, for every
chunk whose round titles count them: code health's counter-signal in
~/.claude/CLAUDE.md → "Shared goal".
Exit 1, saying why, on bad arguments, when git cannot start, finds no checkout or reads a shallow
clone, or the default branch cannot be read; or, after the rest of the report, when the anchors are
left out.
@@ -57,7 +64,7 @@ import re
import sys
from score_outcomes.anchors import anchor_lines, Anchors, ANCHORS_PATH, parse_anchors
from score_outcomes.outcomes import Chunk, Landing, nearest, Outcome, outcomes_of, render, report, shipped
from score_outcomes.results import Chunk, Landing, misreads, nearest, render, report, Result, results_of, shipped
from git_repo import default_branch, file_at, full_history, git, top
from failure import Failure
from todo_table import LEVELS, risk, TOP_SCORE
@@ -91,24 +98,25 @@ def main(argv: list[str]) -> int:
default, note = found
if note:
print(f"score-outcomes: {note}", file=sys.stderr)
outcomes = read_outcomes(default)
if isinstance(outcomes, Failure):
return failed(outcomes)
results = read_results(default)
if isinstance(results, Failure):
return failed(results)
anchored = read_anchors()
print(report_text(outcomes, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None))
print(report_text(results, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None))
return failed(anchored) if isinstance(anchored, Failure) else 0
def report_text(outcomes: list[Outcome], anchored: Anchors | Failure, given: dict[str, int] | None) -> str:
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians."""
def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[str, int] | None) -> str:
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians, then each chunk's misread findings."""
sections = []
if given is not None:
r = risk(given["L"], given["E"], given["I"])
near = [render(outcome) for outcome in nearest(outcomes, given | {"R": r})] or ["- None: no chunk on the default branch shipped an item from todo.md."]
near = [render(result) for result in nearest(results, given | {"R": r})] or ["- None: no chunk on the default branch shipped an item from todo.md."]
sections.append([f"Finished items nearest L {given['L']}, E {given['E']}, I {given['I']}, so R {r}, and S {given['S']}, closest first:", "", *near])
sections.append([f"Anchors in {ANCHORS_PATH}, each level's shipped items:", "", *anchor_lines(anchored, outcomes)])
sections.append(["Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:", "", *report(outcomes)])
if any(outcome.landed != "merge" for outcome in outcomes):
sections.append([f"Anchors in {ANCHORS_PATH}, each level's shipped items:", "", *anchor_lines(anchored, results)])
sections.append(["Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:", "", *report(results)])
sections.append(["🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:", "", *misreads(results)])
if any(result.landed != "merge" for result in results):
sections.append(UNMERGED)
return "\n\n".join("\n".join(section) for section in sections)
@@ -131,19 +139,19 @@ def read_anchors() -> Anchors | Failure:
return Failure(f"cannot read {ANCHORS_PATH}: {failure}")
def read_outcomes(default: str) -> list[Outcome] | Failure:
def read_results(default: str) -> list[Result] | Failure:
"""What each chunk on the default branch's first-parent line measured."""
if partial := full_history():
return partial
log = git("log", "--first-parent", "--format=%x1e%h %ct %at %p", "--name-only", default)
if isinstance(log, Failure):
return log
# Each record is a commit's line, then the files it changed against its first parent.
records = [record.splitlines() for record in log.split("\x1e")[1:]]
headers = [record[0] for record in records]
# Each commit's part of the log is its line, then the files it changed against its first parent.
commits = [part.splitlines() for part in log.split("\x1e")[1:]]
headers = [commit[0] for commit in commits]
hashes = [header.split()[0] for header in headers]
plan = {short for short, record in zip(hashes, records) if "todo.md" in record}
outcomes: list[Outcome] = []
plan = {short for short, commit in zip(hashes, commits) if "todo.md" in commit}
results: list[Result] = []
for first, last, committed, landed in chunk_log(headers):
# Only a chunk that changed todo.md can ship an item, so the others skip measure's git calls.
if not any(short in plan for short in hashes[hashes.index(last):hashes.index(first) + 1]):
@@ -153,8 +161,8 @@ def read_outcomes(default: str) -> list[Outcome] | Failure:
measured = measure(f"{first}^1", last, label, utc(committed), titled, landed)
if isinstance(measured, Failure):
return measured
outcomes += measured
return outcomes
results += measured
return results
def chunk_log(lines: list[str]) -> list[Chunk]:
@@ -175,7 +183,7 @@ def chunk_log(lines: list[str]) -> list[Chunk]:
return chunks
def measure(before: str, tip: str, label: str, merged: str, titled: str, landed: Landing) -> list[Outcome] | Failure:
def measure(before: str, tip: str, label: str, merged: str, titled: str, landed: Landing) -> list[Result] | Failure:
"""What one chunk measured for each item it shipped: its change from the commit before it to its tip, and the titles of the commits in the range titled."""
planned = file_at(before, "todo.md")
if isinstance(planned, Failure):
@@ -192,4 +200,4 @@ def measure(before: str, tip: str, label: str, merged: str, titled: str, landed:
titles = git("log", "--format=%s", titled)
if isinstance(titles, Failure):
return titles
return outcomes_of(items, label, merged, numstat, titles.splitlines(), landed)
return results_of(items, label, merged, numstat, titles.splitlines(), landed)
-132
View File
@@ -1,132 +0,0 @@
import dataclasses
import statistics
import typing
from comprehension_history import HISTORY
from todo_table import Item, items
from markdown_text import listed
from reading_cost.figures import RECORD
from round_titles import round_counts, round_findings
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
ENOUGH = 10
# The plan, and the records tools append to: none of their lines are the chunk's work.
NOT_WORK = ("todo.md", HISTORY, RECORD)
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
Landing = typing.Literal["merge", "rebase", "push"]
# A chunk's first and last commit as short hashes, its commit time, and how it reached the default branch.
Chunk = tuple[str, str, int, Landing]
@dataclasses.dataclass(frozen=True)
class Outcome:
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, None where a round title lacks them or the branch has no round. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed."""
item: Item
merge: str
merged: str
shipped_with: tuple[int, ...]
lines: int
files: int
rounds_past_first: int
findings: tuple[int, int] | None
landed: Landing
# An outcome's name and how to read it from an Outcome, None where the chunk did not record it.
Measure = tuple[str, typing.Callable[[Outcome], int | None]]
# The scores whose median outcome the report gives at each guessed value.
MEDIANS: dict[str, Measure] = {"R": ("🔴 findings", lambda outcome: outcome.findings[0] if outcome.findings else None), "S": ("lines changed", lambda outcome: outcome.lines)}
# The levels R is built from; for each, the report gives how well it orders chunks by review rounds and by 🔴 findings.
ORDERED = ("L", "E", "I")
# The scores render shows, in this order; C only on an item scored before L, E and I replaced it.
SHOWN = ("L", "E", "I", "R", "S", "C")
def shipped(before: str, after: str) -> list[Item]:
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
planned, left = items(before), items(after)
if not isinstance(planned, list) or not isinstance(left, list):
return []
kept = {item.id for item in left}
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
def outcomes_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing) -> list[Outcome]:
"""What one chunk measured for each item it shipped, from `git diff --numstat` against the commit before it and its commit titles; none where it changed nothing but the plan and the records."""
changed = [row.split("\t", 2) for row in numstat.splitlines()]
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
if not work:
return []
# Git counts a binary file's lines as "-".
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
ids = [item.id for item in shipped]
return [Outcome(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed) for item in shipped]
def nearest(outcomes: list[Outcome], given: dict[str, int], count: int = 5) -> list[Outcome]:
"""The outcomes whose guesses sit closest to the given scores: the least mean squared difference over the scores both hold, the newest first among equals."""
def distance(outcome: Outcome) -> float:
shared = [name for name in given if name in outcome.item.scores]
return sum((given[name] - outcome.item.scores[name]) ** 2 for name in shared) / len(shared)
newest_first = sorted(outcomes, key=lambda outcome: outcome.merged, reverse=True)
return sorted(newest_first, key=distance)[:count]
def report(outcomes: list[Outcome]) -> list[str]:
"""Among chunks that shipped one item, since a chunk measures all its items at once, and that were merged or replayed, since a never-replayed one may hold only part of a pull request: for each score in MEDIANS, the median outcome at each value it was guessed at; for each level in ORDERED, how well it orders chunks by review rounds and by 🔴 findings."""
single = [outcome for outcome in outcomes if not outcome.shipped_with and outcome.landed != "push"]
lines = []
for name, (what, measure) in MEDIANS.items():
held = [(outcome.item.scores[name], value) for outcome in single if name in outcome.item.scores and (value := measure(outcome)) is not None]
if len(held) < ENOUGH:
lines.append(f"- {name}, {what}: {too_few(len(held), name, 'its outcome')}")
continue
medians = [(guess, [value for at, value in held if at == guess]) for guess in sorted({guess for guess, _ in held})]
lines.append(f"- {name}, {what}: " + ", ".join(f"{guess} → {statistics.median(found):g} ({plural(len(found), 'chunk')})" for guess, found in medians))
for name in ORDERED:
# Each pass takes a first round whatever the change, so only the rounds after it measure how hard the change was to get right.
rows = [(outcome.item.scores[name], outcome.rounds_past_first, outcome.findings[0]) for outcome in single if name in outcome.item.scores and outcome.findings is not None]
opening = f"- {name}, by review rounds past each pass's first and 🔴 findings: "
if len(rows) < ENOUGH:
lines.append(opening + too_few(len(rows), name, "both outcomes"))
continue
guesses, rounds, red = ([row[column] for row in rows] for column in range(3))
found = [rank_correlation(guesses, rounds), rank_correlation(guesses, red)]
undefined = ", since every chunk held one value" if None in found else ""
lines.append(opening + f"rank correlation {listed(['none' if value is None else f'{value:+.2f}' for value in found], 'and')}{undefined} ({plural(len(rows), 'chunk')})")
return lines
def too_few(held: int, name: str, what: str) -> str:
chunks = "such chunk records" if held == 1 else "such chunks record"
return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}."
def rank_correlation(guesses: list[int], outcomes: list[int]) -> float | None:
"""Spearman's rank correlation, tied values sharing their mean rank; None where either side holds one value, which no order can rank."""
if len(set(guesses)) < 2 or len(set(outcomes)) < 2:
return None
return statistics.correlation(ranks(guesses), ranks(outcomes))
def ranks(values: list[int]) -> list[float]:
"""Each value's rank from 1, tied values sharing their mean rank."""
ordered = sorted(values)
return [ordered.index(value) + (ordered.count(value) + 1) / 2 for value in values]
def render(outcome: Outcome) -> str:
scores = ", ".join(f"{name} {outcome.item.scores[name]}" for name in SHOWN if name in outcome.item.scores)
# Rebase drops a round's commit that changed no file, so history shows such a chunk's rounds and findings short.
at_least = "" if outcome.landed == "merge" else "at least "
merged = {"merge": f"merged {outcome.merged} in {outcome.merge}", "rebase": f"merged {outcome.merged} by rebase in {outcome.merge}", "push": f"committed {outcome.merged} in {outcome.merge}, never replayed, so perhaps part of a pull request"}[outcome.landed]
findings = f"{at_least}{outcome.findings[0]} 🔴, {outcome.findings[1]} 🟡" if outcome.findings else "findings unknown"
others = outcome.shipped_with
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
return f"- Item {outcome.item.id}, {scores}: {plural(outcome.lines, 'line')} in {plural(outcome.files, 'file')}, {at_least}{plural(outcome.rounds_past_first, 'round')} past each pass's first, {findings}; {merged}{together}. {outcome.item.tagline}"
def plural(count: int, noun: str) -> str:
return f"{count} {noun}{'' if count == 1 else 's'}"
+152
View File
@@ -0,0 +1,152 @@
import dataclasses
import statistics
import typing
from round_titles import Findings, round_counts, round_findings
from comprehension_history import HISTORY
from todo_table import Item, items
from markdown_text import listed
from reading_cost.figures import RECORD
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
ENOUGH = 10
# The plan, and the records tools append to: none of their lines are the chunk's work.
NOT_WORK = ("todo.md", HISTORY, RECORD)
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
Landing = typing.Literal["merge", "rebase", "push"]
# A chunk's first and last commit as short hashes, its commit time, and how it reached the default branch.
Chunk = tuple[str, str, int, Landing]
# The tool's name and report call a Result an outcome, a word the code keeps for an entry of a `.outcomes.md` file: docs/decisions.md → `bin/: an outcome is an entry`.
@dataclasses.dataclass(frozen=True)
class Result:
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None where a round title lacks the 🔴 and 🟡 counts or the branch has no round; its misread is None where a round title lacks that count. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed."""
item: Item
merge: str
merged: str
shipped_with: tuple[int, ...]
lines: int
files: int
rounds_past_first: int
findings: Findings | None
landed: Landing
# A measure's name and how to read it from a Result, None where the chunk did not record it.
Measure = tuple[str, typing.Callable[[Result], int | None]]
# The scores whose median result the report gives at each guessed value.
MEDIANS: dict[str, Measure] = {"R": ("🔴 findings", lambda result: result.findings.red if result.findings else None), "S": ("lines changed", lambda result: result.lines)}
# The levels R is built from; for each, the report gives how well it orders chunks by review rounds and by 🔴 findings.
ORDERED = ("L", "E", "I")
# The scores render shows, in this order; C only on an item scored before L, E and I replaced it.
SHOWN = ("L", "E", "I", "R", "S", "C")
def shipped(before: str, after: str) -> list[Item]:
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
planned, left = items(before), items(after)
if not isinstance(planned, list) or not isinstance(left, list):
return []
kept = {item.id for item in left}
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
def results_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing) -> list[Result]:
"""What one chunk measured for each item it shipped, from `git diff --numstat` against the commit before it and its commit titles; none where it changed nothing but the plan and the records."""
changed = [row.split("\t", 2) for row in numstat.splitlines()]
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
if not work:
return []
# Git counts a binary file's lines as "-".
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
ids = [item.id for item in shipped]
return [Result(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed) for item in shipped]
def nearest(results: list[Result], given: dict[str, int], count: int = 5) -> list[Result]:
"""The results whose guesses sit closest to the given scores: the least mean squared difference over the scores both hold, the newest first among equals."""
def distance(result: Result) -> float:
shared = [name for name in given if name in result.item.scores]
return sum((given[name] - result.item.scores[name]) ** 2 for name in shared) / len(shared)
newest_first = sorted(results, key=lambda result: result.merged, reverse=True)
return sorted(newest_first, key=distance)[:count]
def report(results: list[Result]) -> list[str]:
"""Among chunks that shipped one item, since a chunk measures all its items at once, and that were merged or replayed, since a never-replayed one may hold only part of a pull request: for each score in MEDIANS, the median result at each value it was guessed at; for each level in ORDERED, how well it orders chunks by review rounds and by 🔴 findings."""
single = [result for result in results if not result.shipped_with and result.landed != "push"]
lines = []
for name, (what, measure) in MEDIANS.items():
held = [(result.item.scores[name], value) for result in single if name in result.item.scores and (value := measure(result)) is not None]
if len(held) < ENOUGH:
lines.append(f"- {name}, {what}: {too_few(len(held), name, 'its outcome')}")
continue
medians = [(guess, [value for at, value in held if at == guess]) for guess in sorted({guess for guess, _ in held})]
lines.append(f"- {name}, {what}: " + ", ".join(f"{guess} → {statistics.median(found):g} ({plural(len(found), 'chunk')})" for guess, found in medians))
for name in ORDERED:
# Each pass takes a first round whatever the change, so only the rounds after it measure how hard the change was to get right.
rows = [(result.item.scores[name], result.rounds_past_first, result.findings.red) for result in single if name in result.item.scores and result.findings is not None]
opening = f"- {name}, by review rounds past each pass's first and 🔴 findings: "
if len(rows) < ENOUGH:
lines.append(opening + too_few(len(rows), name, "both outcomes"))
continue
guesses, rounds, red = ([row[column] for row in rows] for column in range(3))
found = [rank_correlation(guesses, rounds), rank_correlation(guesses, red)]
undefined = ", since every chunk held one value" if None in found else ""
lines.append(opening + f"rank correlation {listed(['none' if value is None else f'{value:+.2f}' for value in found], 'and')}{undefined} ({plural(len(rows), 'chunk')})")
return lines
def misreads(results: list[Result]) -> list[str]:
"""Newest first, each chunk's 🔴 and 🟡 findings with how many of them a reviewer marked `[misread]`, for each chunk whose round titles count those."""
# A chunk that shipped several items has a Result for each, so one line per chunk.
chunks = {result.merge: result for result in results}
newest_first = sorted(chunks.values(), key=lambda result: result.merged, reverse=True)
lines = [f"- {result.merged} in {result.merge}: {counted(result)}" for result in newest_first if result.findings is not None and result.findings.misread is not None]
return lines or ["- None: no chunk's round titles count them."]
def too_few(held: int, name: str, what: str) -> str:
chunks = "such chunk records" if held == 1 else "such chunks record"
return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}."
def rank_correlation(guesses: list[int], results: list[int]) -> float | None:
"""Spearman's rank correlation, tied values sharing their mean rank; None where either side holds one value, which no order can rank."""
if len(set(guesses)) < 2 or len(set(results)) < 2:
return None
return statistics.correlation(ranks(guesses), ranks(results))
def ranks(values: list[int]) -> list[float]:
"""Each value's rank from 1, tied values sharing their mean rank."""
ordered = sorted(values)
return [ordered.index(value) + (ordered.count(value) + 1) / 2 for value in values]
def render(result: Result) -> str:
scores = ", ".join(f"{name} {result.item.scores[name]}" for name in SHOWN if name in result.item.scores)
merged = {"merge": f"merged {result.merged} in {result.merge}", "rebase": f"merged {result.merged} by rebase in {result.merge}", "push": f"committed {result.merged} in {result.merge}, never replayed, so perhaps part of a pull request"}[result.landed]
others = result.shipped_with
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
return f"- Item {result.item.id}, {scores}: {plural(result.lines, 'line')} in {plural(result.files, 'file')}, {at_least(result)}{plural(result.rounds_past_first, 'round')} past each pass's first, {counted(result)}; {merged}{together}. {result.item.tagline}"
def at_least(result: Result) -> str:
"""The words that mark a chunk's rounds and findings as lower bounds: rebase drops a round's commit that changed no file, so history shows a chunk that left no merge commit short."""
return "" if result.landed == "merge" else "at least "
def counted(result: Result) -> str:
"""A chunk's findings as its round titles spell them: `1 🔴, 2 🟡 (1 misread)`, the misread count left out where they lack it."""
if result.findings is None:
return "findings unknown"
misread = "" if result.findings.misread is None else f" ({result.findings.misread} misread)"
return f"{at_least(result)}{result.findings.red} 🔴, {result.findings.yellow} 🟡{misread}"
def plural(count: int, noun: str) -> str:
return f"{count} {noun}{'' if count == 1 else 's'}"
+52 -36
View File
@@ -10,9 +10,10 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from score_outcomes.anchors import anchor_lines, parse_anchors
from score_outcomes.main import chunk_log, report_text
from failure import Failure
from round_titles import Findings
from test_env import isolated_env
from todo_table import Item
from score_outcomes.outcomes import Landing, nearest, Outcome, outcomes_of, rank_correlation, render, report, shipped
from score_outcomes.results import Landing, nearest, rank_correlation, render, report, Result, results_of, shipped
TOOL = pathlib.Path(__file__).resolve().parents[1] / "score-outcomes"
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
@@ -29,8 +30,8 @@ def item(id_: int, scores: dict[str, int]) -> Item:
return Item(id_, (0, 1, 0), "", f"**Item {id_}.**", scores, (("1", None),), ())
def outcome(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, findings: tuple[int, int] | None = (0, 0), merged: str = "2026-10-13T10:00:00Z", shipped_with: tuple[int, ...] = (), levels: dict[str, int] | None = None, landed: Landing = "merge") -> Outcome:
return Outcome(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), "aaaaaaa", merged, shipped_with, lines, 1, rounds, findings, landed)
def result(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, findings: tuple[int, int] | None = (0, 0), merged: str = "2026-10-13T10:00:00Z", shipped_with: tuple[int, ...] = (), levels: dict[str, int] | None = None, landed: Landing = "merge", misread: int | None = None, merge: str = "aaaaaaa") -> Result:
return Result(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), merge, merged, shipped_with, lines, 1, rounds, None if findings is None else Findings(*findings, misread), landed)
class Shipped(unittest.TestCase):
@@ -72,47 +73,47 @@ class ChunkLog(unittest.TestCase):
self.assertEqual(chunk_log(["c2 300 300 c1", "c1 200 200 r"]), [("c2", "c2", 300, "push"), ("c1", "c1", 200, "push")])
class OutcomesOf(unittest.TestCase):
class ResultsOf(unittest.TestCase):
def test_measures_the_change_less_the_plan_and_the_tool_records_and_counts_binary_files(self):
numstat = "3\t1\ta.py\n-\t-\tlogo.png\n0\t1\t2026\n5\t0\ttodo.md\n9\t0\tdocs/reading-cost.md\n4\t0\tdocs/comprehension-history.md\n"
titles = ["Answer stability round 1: 1 🔴, 2 🟡; fix", "Answer stability round 2: 0 🔴, 1 🟡; fix", "Answer prose round 1: 0 🔴, 3 🟡", "Do it"]
found = outcomes_of([item(4, {"R": 2}), item(5, {"R": 3})], "abc1234", "2026-10-13T10:00:00Z", numstat, titles, "merge")
self.assertEqual(found[0], Outcome(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, (1, 6), "merge"))
found = results_of([item(4, {"R": 2}), item(5, {"R": 3})], "abc1234", "2026-10-13T10:00:00Z", numstat, titles, "merge")
self.assertEqual(found[0], Result(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, Findings(1, 6, None), "merge"))
self.assertEqual(found[1].shipped_with, (4,))
def test_measures_no_chunk_that_changed_only_the_plan(self):
self.assertEqual(outcomes_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", [], "merge"), [])
self.assertEqual(results_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", [], "merge"), [])
class Nearest(unittest.TestCase):
def test_lists_the_closest_guesses_first_by_the_mean_over_the_scores_both_hold(self):
found = [outcome(1, 9, 9, 9), outcome(2, 3, 5, None), outcome(3, 3, 4, 6), outcome(4, 3, 4, 9)]
found = [result(1, 9, 9, 9), result(2, 3, 5, None), result(3, 3, 4, 6), result(4, 3, 4, 9)]
self.assertEqual([each.item.id for each in nearest(found, {"R": 3, "S": 4, "C": 5}, 3)], [3, 2, 4])
def test_lists_five_by_default(self):
self.assertEqual(len(nearest([outcome(id_, 3, 4, 5) for id_ in range(6)], {"R": 3, "S": 4, "C": 5})), 5)
self.assertEqual(len(nearest([result(id_, 3, 4, 5) for id_ in range(6)], {"R": 3, "S": 4, "C": 5})), 5)
def test_compares_an_item_scored_before_l_e_and_i_by_its_r_and_s(self):
given = {"L": 2, "E": 2, "I": 3, "R": 5, "S": 4}
found = [outcome(1, 8, 4, None, levels={"L": 4, "E": 3, "I": 3}), outcome(2, 5, 4, 9, merged="2026-10-12T10:00:00Z"), outcome(3, 5, 4, None, levels={"L": 2, "E": 2, "I": 3})]
found = [result(1, 8, 4, None, levels={"L": 4, "E": 3, "I": 3}), result(2, 5, 4, 9, merged="2026-10-12T10:00:00Z"), result(3, 5, 4, None, levels={"L": 2, "E": 2, "I": 3})]
self.assertEqual([each.item.id for each in nearest(found, given)], [3, 2, 1])
def test_lists_the_newest_first_among_equals(self):
found = [outcome(1, 3, 4, 5, merged="2026-10-12T10:00:00Z"), outcome(2, 3, 4, 5, merged="2026-10-13T09:00:00Z")]
found = [result(1, 3, 4, 5, merged="2026-10-12T10:00:00Z"), result(2, 3, 4, 5, merged="2026-10-13T09:00:00Z")]
self.assertEqual([each.item.id for each in nearest(found, {"R": 3, "S": 4, "C": 5})], [2, 1])
class Report(unittest.TestCase):
def test_gives_each_guessed_values_median_outcome_once_ten_single_item_chunks_hold_it(self):
found = [outcome(id_, 2, 1 + id_ % 2, 4, lines=10 * id_, rounds=id_, findings=(1, 3)) for id_ in range(1, 11)]
lines = report(found + [outcome(11, 2, 2, None, lines=1000, findings=None, shipped_with=(12,))])
def test_gives_each_guessed_values_median_result_once_ten_single_item_chunks_hold_it(self):
found = [result(id_, 2, 1 + id_ % 2, 4, lines=10 * id_, rounds=id_, findings=(1, 3)) for id_ in range(1, 11)]
lines = report(found + [result(11, 2, 2, None, lines=1000, findings=None, shipped_with=(12,))])
self.assertIn("- R, 🔴 findings: 2 → 1 (10 chunks)", lines)
self.assertIn("- S, lines changed: 1 → 60 (5 chunks), 2 → 50 (5 chunks)", lines)
self.assertFalse([line for line in lines if line.startswith("- C")])
def test_says_how_many_chunks_it_has_under_ten(self):
self.assertIn("- S, lines changed: 1 such chunk records S and its outcome; the report needs 10.", report([outcome(1, 2, 2, 4), outcome(2, 2, 2, None, shipped_with=(1,))]))
too_few = report([outcome(1, 2, 2, None, levels={"L": 2, "E": 1, "I": 1}), outcome(2, 2, 2, None, levels={"L": 2}, findings=None)])
self.assertIn("- S, lines changed: 1 such chunk records S and its outcome; the report needs 10.", report([result(1, 2, 2, 4), result(2, 2, 2, None, shipped_with=(1,))]))
too_few = report([result(1, 2, 2, None, levels={"L": 2, "E": 1, "I": 1}), result(2, 2, 2, None, levels={"L": 2}, findings=None)])
for name in "LEI":
with self.subTest(name=name):
self.assertIn(f"- {name}, by review rounds past each pass's first and 🔴 findings: 1 such chunk records {name} and both outcomes; the report needs 10.", too_few)
@@ -122,12 +123,12 @@ class Report(unittest.TestCase):
self.assertAlmostEqual(rank_correlation([1, 1, 2, 3], [1, 2, 3, 4]), 0.949, places=3)
self.assertAlmostEqual(rank_correlation([1, 2, 3, 4], [1, 1, 2, 3]), 0.949, places=3)
def test_ranks_an_outcome_that_holds_two_values(self):
def test_ranks_a_result_that_holds_two_values(self):
self.assertAlmostEqual(rank_correlation([1, 2, 3, 4, 5], [1, 1, 2, 2, 2]), 0.866, places=3)
def test_gives_how_well_l_e_and_i_each_order_chunks_by_review_rounds_and_red_findings(self):
levels = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4]
found = [outcome(id_, 2, 2, None, rounds=level, findings=(5 - level, 0), levels={"L": level, "E": 2, "I": level}) for id_, level in enumerate(levels, 1)]
found = [result(id_, 2, 2, None, rounds=level, findings=(5 - level, 0), levels={"L": level, "E": 2, "I": level}) for id_, level in enumerate(levels, 1)]
lines = report(found)
self.assertIn("- L, by review rounds past each pass's first and 🔴 findings: rank correlation +1.00 and -1.00 (10 chunks)", lines)
self.assertIn("- I, by review rounds past each pass's first and 🔴 findings: rank correlation +1.00 and -1.00 (10 chunks)", lines)
@@ -136,19 +137,23 @@ class Report(unittest.TestCase):
class Render(unittest.TestCase):
def test_shows_an_items_l_e_and_i_before_its_r_and_s(self):
self.assertTrue(render(outcome(4, 3, 3, None, levels={"L": 2, "E": 2, "I": 1})).startswith("- Item 4, L 2, E 2, I 1, R 3, S 3:"))
self.assertTrue(render(result(4, 3, 3, None, levels={"L": 2, "E": 2, "I": 1})).startswith("- Item 4, L 2, E 2, I 1, R 3, S 3:"))
def test_names_the_items_shipped_together_and_unknown_findings(self):
self.assertEqual(render(outcome(4, 2, 3, None, lines=1, rounds=2, findings=None, shipped_with=(5, 6))), "- Item 4, R 2, S 3: 1 line in 1 file, 2 rounds past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z in aaaaaaa, with items 5, 6. **Item 4.**")
self.assertEqual(render(outcome(4, 2, 3, 4, findings=(1, 2))), "- Item 4, R 2, S 3, C 4: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**")
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa, with item 5. ", render(outcome(4, 2, 3, 4, rounds=1, shipped_with=(5,))))
self.assertEqual(render(result(4, 2, 3, None, lines=1, rounds=2, findings=None, shipped_with=(5, 6))), "- Item 4, R 2, S 3: 1 line in 1 file, 2 rounds past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z in aaaaaaa, with items 5, 6. **Item 4.**")
self.assertEqual(render(result(4, 2, 3, 4, findings=(1, 2))), "- Item 4, R 2, S 3, C 4: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**")
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa, with item 5. ", render(result(4, 2, 3, 4, rounds=1, shipped_with=(5,))))
def test_gives_the_misread_count_where_the_round_titles_do(self):
self.assertIn("1 round past each pass's first, 1 🔴, 2 🟡 (1 misread); merged", render(result(4, 2, 3, None, findings=(1, 2), misread=1)))
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡 (0 misread); merged", render(result(4, 2, 3, None, misread=0)))
def test_gives_a_rebase_merged_chunks_rounds_and_findings_as_lower_bounds(self):
self.assertEqual(render(outcome(4, 2, 3, None, findings=(1, 2), landed="rebase")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa. **Item 4.**")
self.assertIn("at least 1 round past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa", render(outcome(4, 2, 3, None, findings=None, landed="rebase")))
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="rebase")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa. **Item 4.**")
self.assertIn("at least 1 round past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa", render(result(4, 2, 3, None, findings=None, landed="rebase")))
def test_says_a_chunk_never_replayed_may_be_part_of_a_pull_request(self):
self.assertEqual(render(outcome(4, 2, 3, None, findings=(1, 2), landed="push")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; committed 2026-10-13T10:00:00Z in aaaaaaa, never replayed, so perhaps part of a pull request. **Item 4.**")
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="push")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; committed 2026-10-13T10:00:00Z in aaaaaaa, never replayed, so perhaps part of a pull request. **Item 4.**")
ANCHORS_TEXT = "# Score anchors\n\nWhy these.\n\n| Level | Items |\n|---|---|\n| L 1 | 4, 9 |\n| I 3 | 5 |\n"
@@ -173,7 +178,7 @@ class Anchors(unittest.TestCase):
self.assertEqual(parse_anchors(ANCHORS_TEXT + "| L 1 | 7 |\n"), Failure("docs/score-anchors.md names L 1 twice"))
def test_lists_each_anchor_with_what_its_chunk_measured_and_says_which_it_cannot_find(self):
lines = anchor_lines([("L 1", (4, 9))], [outcome(4, 2, 3, None, findings=(1, 2))])
lines = anchor_lines([("L 1", (4, 9))], [result(4, 2, 3, None, findings=(1, 2))])
self.assertEqual(lines, ["L 1:", "- Item 4, R 2, S 3: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**", "- Item 9: no chunk shipped it."])
def test_points_to_the_rules_where_the_project_names_no_anchors(self):
@@ -186,7 +191,7 @@ class Anchors(unittest.TestCase):
class ReportText(unittest.TestCase):
def test_lists_the_nearest_by_r_then_the_anchors_then_the_medians(self):
found = [outcome(1, 5, 3, None, merged="2026-10-13T10:00:00Z"), outcome(2, 1, 3, None, merged="2026-10-12T10:00:00Z")]
found = [result(1, 5, 3, None, merged="2026-10-13T10:00:00Z"), result(2, 1, 3, None, merged="2026-10-12T10:00:00Z")]
too_few = "such chunks record"
self.assertEqual(report_text(found, [("L 1", (2,))], {"L": 1, "E": 1, "I": 1, "S": 3}), f"""Finished items nearest L 1, E 1, I 1, so R 1, and S 3, closest first:
@@ -204,24 +209,35 @@ Median outcome at each guessed score, among chunks that shipped one item, never-
- S, lines changed: 2 {too_few} S and its outcome; the report needs 10.
- L, by review rounds past each pass's first and 🔴 findings: 0 {too_few} L and both outcomes; the report needs 10.
- E, by review rounds past each pass's first and 🔴 findings: 0 {too_few} E and both outcomes; the report needs 10.
- I, by review rounds past each pass's first and 🔴 findings: 0 {too_few} I and both outcomes; the report needs 10.""")
- I, by review rounds past each pass's first and 🔴 findings: 0 {too_few} I and both outcomes; the report needs 10.
🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:
- None: no chunk's round titles count them.""")
def test_lists_each_chunks_findings_with_their_misread_count_newest_first_once_per_chunk(self):
found = [result(1, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(2,)), result(2, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(1,)), result(3, 5, 3, None, findings=(0, 4), misread=0, merge="ccccccc", merged="2026-10-14T10:00:00Z", landed="rebase"), result(4, 5, 3, None)]
self.assertIn("""🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:
- 2026-10-14T10:00:00Z in ccccccc: at least 0 🔴, 4 🟡 (0 misread)
- 2026-10-12T10:00:00Z in bbbbbbb: 1 🔴, 2 🟡 (1 misread)""", report_text(found, [], None))
def test_ends_with_how_it_reads_chunks_merged_by_rebase_only_where_it_measured_one(self):
text = report_text([outcome(1, 5, 3, None, landed="rebase")], [], None)
text = report_text([result(1, 5, 3, None, landed="rebase")], [], None)
self.assertIn("\n\nChunks that left no merge commit:\n\n- Each is the run of commits", text.split("Median outcome")[1])
self.assertIn("a pull request that shipped nothing adds its lines, files and rounds", text)
self.assertIn("at least what history shows, and the medians count the rebased ones as shown.", text)
self.assertIn("Chunks that left no merge commit", report_text([outcome(1, 5, 3, None, landed="push")], [], None))
self.assertNotIn("Chunks that left no merge commit", report_text([outcome(1, 5, 3, None)], [], None))
self.assertIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None, landed="push")], [], None))
self.assertNotIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None)], [], None))
def test_leaves_a_never_replayed_chunk_out_of_the_s_medians_and_keeps_a_rebased_one(self):
found = [outcome(id_, 2, 2, None, lines=10 * id_, landed="rebase" if id_ == 1 else "merge") for id_ in range(1, 11)]
self.assertIn("- S, lines changed: 2 → 55 (10 chunks)", report_text(found + [outcome(11, 2, 2, None, lines=100000, landed="push")], [], None))
found = [result(id_, 2, 2, None, lines=10 * id_, landed="rebase" if id_ == 1 else "merge") for id_ in range(1, 11)]
self.assertIn("- S, lines changed: 2 → 55 (10 chunks)", report_text(found + [result(11, 2, 2, None, lines=100000, landed="push")], [], None))
def test_leaves_a_never_replayed_chunk_out_of_the_r_medians_and_the_rank_correlations(self):
levels = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4]
found = [outcome(id_, 2, 2, None, rounds=level, findings=(5 - level, 0), levels={"L": level, "E": 2, "I": level}) for id_, level in enumerate(levels, 1)]
pushed = outcome(11, 2, 2, None, rounds=9, findings=(9, 0), levels={"L": 1, "E": 2, "I": 1}, landed="push")
found = [result(id_, 2, 2, None, rounds=level, findings=(5 - level, 0), levels={"L": level, "E": 2, "I": level}) for id_, level in enumerate(levels, 1)]
pushed = result(11, 2, 2, None, rounds=9, findings=(9, 0), levels={"L": 1, "E": 2, "I": 1}, landed="push")
text = report_text(found + [pushed], [], None)
self.assertIn("- R, 🔴 findings: 2 → 2.5 (10 chunks)", text)
self.assertIn("- L, by review rounds past each pass's first and 🔴 findings: rank correlation +1.00 and -1.00 (10 chunks)", text)
@@ -229,7 +245,7 @@ Median outcome at each guessed score, among chunks that shipped one item, never-
self.assertIn("- E, by review rounds past each pass's first and 🔴 findings: rank correlation none and none, since every chunk held one value (10 chunks)", text)
def test_keeps_a_never_replayed_chunk_in_the_nearest_and_anchors_lists(self):
pushed = outcome(9, 2, 3, None, landed="push")
pushed = result(9, 2, 3, None, landed="push")
text = report_text([pushed], [("L 1", (9,))], {"L": 1, "E": 1, "I": 1, "S": 3})
nearest_section, anchors_section = text.split("Anchors in ")
self.assertIn("- Item 9, R 2, S 3:", nearest_section)
+29 -1
View File
@@ -1,9 +1,12 @@
"""A shell command's simple commands, each as its words and the directory it runs in."""
"""A shell command's simple commands, each as its words and the directory it runs in, and which tool a simple command runs through which launchers."""
import dataclasses
import posixpath
import re
import shlex
import typing
# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run.
LAUNCHERS = frozenset({"bunx", "env", "nice", "npx", "pipx", "pnpm", "run-heavy", "time", "timeout", "uvx", "yarn"})
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();&|<>")
@@ -13,6 +16,14 @@ REDIRECT = re.compile(r"&>>?|[<>]+[&|]?")
PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<![^\s;&|()])#[^\n]*""", re.DOTALL)
@dataclasses.dataclass(frozen=True)
class Launch:
"""A tool a simple command runs: the launchers it runs through, such as nice and run-heavy, and the words it is given."""
launchers: frozenset[str]
tool: str
arguments: list[str]
@dataclasses.dataclass(frozen=True)
class Simple:
words: list[str]
@@ -80,3 +91,20 @@ def uncommented(text: str) -> str:
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))
def tool_name(word: str) -> str:
"""The tool a word names, such as mutmut for `mutmut>=3,<4` or `.venv/bin/mutmut`; empty for a word that names none, such as a file name."""
named = re.fullmatch(r"([A-Za-z_-]+)(?:[<>=!~@].*)?", posixpath.basename(word))
return named.group(1) if named else ""
def launched(words: list[str], tools: typing.Collection[str]) -> Launch | None:
"""Which of the given tools the simple command runs, directly or through launchers, taking the first one named; None where it doesn't run any of them."""
names = [tool_name(word) for word in words]
# Past a launcher, the tool may follow the launcher's own options and assignments, as in nice -n 19 docker build; without one, the command itself is the tool.
reachable = names if names[:1] and names[0] in LAUNCHERS else names[:1]
at = next((i for i, name in enumerate(reachable) if name in tools), None)
if at is None:
return None
return Launch(frozenset(LAUNCHERS.intersection(names[:at])), names[at], words[at + 1:])
+43
View File
@@ -0,0 +1,43 @@
import unittest
from docker_command import capped
class Capped(unittest.TestCase):
def test_a_container_without_limits_gets_the_share_for_both(self):
for given, expected in [
(["run", "--rm", "img", "true"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "--rm", "img", "true"]),
(["-H", "unix:///d.sock", "run", "img"], ["-H", "unix:///d.sock", "run", "--memory", "6144m", "--memory-swap", "6144m", "img"]),
(["container", "create", "img"], ["container", "create", "--memory", "6144m", "--memory-swap", "6144m", "img"]),
(["--context", "run", "run", "img"], ["--context", "run", "run", "--memory", "6144m", "--memory-swap", "6144m", "img"]),
(["run", "img", "python", "-m", "pytest"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "img", "python", "-m", "pytest"]),
(["run", "img", "grep", "-m", "1", "x"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "img", "grep", "-m", "1", "x"]),
(["run", "img", "git", "tag", "-m", "1.2.3"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "img", "git", "tag", "-m", "1.2.3"]),
(["run", "-m", "6143k", "img"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "-m", "6143k", "img"]),
(["run", "img", "tool", "-m", "6"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "img", "tool", "-m", "6"]),
(["run", "img", "stress", "--memory", "2"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "img", "stress", "--memory", "2"]),
]:
with self.subTest(given):
self.assertEqual(capped(given, "6144m"), expected)
def test_a_container_s_own_limit_is_kept_and_sets_the_limit_it_lacks(self):
for given, expected in [
(["run", "-m", "10g", "img"], ["run", "--memory-swap", "10g", "-m", "10g", "img"]),
(["run", "-m", "6m", "img"], ["run", "--memory-swap", "6m", "-m", "6m", "img"]),
(["run", "--memory=12g", "img"], ["run", "--memory-swap", "12g", "--memory=12g", "img"]),
(["run", "--memory-swap", "2g", "img"], ["run", "--memory", "2g", "--memory-swap", "2g", "img"]),
(["run", "-m", "4g", "--memory-swap", "-1", "img"], ["run", "--memory-swap", "4g", "-m", "4g", "img"]),
(["run", "-m4g", "--memory-swap=0", "img", "python", "-m", "pytest"], ["run", "--memory-swap", "4g", "-m4g", "img", "python", "-m", "pytest"]),
(["run", "img", "app", "-m", "512m"], ["run", "--memory-swap", "512m", "img", "app", "-m", "512m"]),
]:
with self.subTest(given):
self.assertEqual(capped(given, "6144m"), expected)
def test_a_container_with_both_limits_or_another_docker_call_is_left_alone(self):
for given in [["run", "-m", "0", "img"], ["run", "img", "grep", "-m", "0", "x"], ["run", "-m", "10g", "--memory-swap", "12g", "img"], ["ps"], ["build", "."], ["run", "--help"], ["compose", "run", "app"], ["exec", "box", "true"]]:
with self.subTest(given):
self.assertEqual(capped(given, "6144m"), given)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -10,7 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from failure import Failure
import rank_todo
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
import todo_table
# Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it.
+25 -3
View File
@@ -4,7 +4,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from round_titles import lacks_counts, round_counts, round_findings
from round_titles import Findings, lacks_counts, past_cap, round_counts, round_findings
class Rounds(unittest.TestCase):
@@ -22,21 +22,43 @@ class Rounds(unittest.TestCase):
self.assertIn("principles", round_counts([]))
class Cap(unittest.TestCase):
def test_finds_a_round_title_past_round_3(self):
self.assertTrue(past_cap("Answer stability round 4: 0 🔴, 1 🟡; fix"))
self.assertTrue(past_cap("answer full scan round 10: x"))
self.assertFalse(past_cap("Answer stability round 3: 0 🔴, 1 🟡; fix"))
self.assertFalse(past_cap("Answer the 4 questions"))
class RoundFindings(unittest.TestCase):
def test_sums_the_counts_each_round_title_opens_with(self):
self.assertEqual(round_findings(["Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test", "Answer prose round 1: 0 🔴, 3 🟡", "Merge origin/main"]), (1, 5))
self.assertEqual(round_findings(["Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test", "Answer prose round 1: 0 🔴, 3 🟡", "Merge origin/main"]), Findings(1, 5, None))
def test_knows_no_count_when_a_round_title_or_every_round_lacks_one(self):
self.assertIsNone(round_findings(["Answer stability round 1: 1 🔴, 2 🟡; fix", "Answer prose round 1: fix the README"]))
self.assertIsNone(round_findings(["Answer stability round 1: 1 🔴, 2 🟡 fix"]))
self.assertIsNone(round_findings(["Do the work"]))
def test_sums_the_misread_findings_each_round_title_counts(self):
self.assertEqual(round_findings(["Answer stability round 1: 1 🔴, 2 🟡 (1 misread); fix", "Answer prose round 1: 0 🔴, 3 🟡 (2 misread)", "Merge origin/main"]), Findings(1, 5, 3))
self.assertEqual(round_findings(["Answer stability round 1: 0 🔴, 0 🟡 (0 misread)"]), Findings(0, 0, 0))
def test_knows_no_misread_count_when_a_round_title_lacks_one(self):
self.assertEqual(round_findings(["Answer stability round 1: 1 🔴, 2 🟡 (1 misread); fix", "Answer prose round 1: 0 🔴, 3 🟡; fix"]), Findings(1, 5, None))
def test_finds_a_round_title_without_counts(self):
self.assertTrue(lacks_counts("Answer stability round 1: fix"))
self.assertFalse(lacks_counts("Answer stability round 1: 0 🔴, 1 🟡; fix"))
self.assertTrue(lacks_counts("Answer stability round 1: 0 🔴, 1 🟡; fix"))
self.assertFalse(lacks_counts("Answer stability round 1: 0 🔴, 1 🟡 (0 misread); fix"))
self.assertFalse(lacks_counts("Answer prose round 2: 0 🔴, 0 🟡 (0 misread)"))
self.assertFalse(lacks_counts("Answer the question"))
def test_takes_a_title_counting_more_misread_findings_than_findings_as_lacking_its_counts(self):
self.assertTrue(lacks_counts("Answer stability round 1: 1 🔴, 2 🟡 (4 misread); fix"))
self.assertFalse(lacks_counts("Answer stability round 1: 1 🔴, 2 🟡 (3 misread); fix"))
self.assertIsNone(round_findings(["Answer stability round 1: 1 🔴, 2 🟡 (4 misread); fix"]))
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -10,9 +10,9 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from settings_filter import cleaned
from test_env import isolated_env
from repo_checks import ROOT
FILTER = pathlib.Path(__file__).resolve().parent / "settings_filter.py"
ROOT = FILTER.parents[1]
PICKED = json.dumps({"theme": "dark", "model": "opus[1m]", "env": {}}, indent=2)
+8 -8
View File
@@ -1,8 +1,8 @@
import re
from markdown_text import quoted
from model_routing.route import Record
from utc_stamp import STAMPED
from model_routing.route import WorkerLine
TASK = "Task: "
FINISHED = "Verdict: finished"
@@ -29,23 +29,23 @@ def escalation_block(escalation: str) -> str:
return f"Escalation:\n{quoted(escalation)}\n\n" if escalation else ""
def finished(worker: Record, evidence: str, judge: str) -> str:
def finished(worker: WorkerLine, evidence: str, judge: str) -> str:
return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{JUDGE}{judge}\n{WORKER}{worker}"
def unfinished(worker: Record, evidence: str, judge: str, escalation: str) -> str:
def unfinished(worker: WorkerLine, evidence: str, judge: str, escalation: str) -> str:
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none."""
escalated = escalation_block(escalation)
return f"{UNFINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{JUDGE}{judge}\n{WORKER}{worker}"
def interrupted(question: str, evidence: str, judge: str, escalation: str, worker: Record) -> str:
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none. worker is the record of the route the worker ran on until the interrupt."""
def interrupted(question: str, evidence: str, judge: str, escalation: str, worker: WorkerLine) -> str:
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none. worker is the line naming the route the worker ran on until the interrupt."""
escalated = escalation_block(escalation)
return f"{INTERRUPTED}\n\n{question}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{JUDGE}{judge}\n{WORKER}{worker}"
def answered(question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: Record) -> str:
def answered(question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: WorkerLine) -> str:
"""escalation and worker are as on interrupted."""
escalated = escalation_block(escalation)
return f"{ANSWERED}\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{JUDGE}{judge}\n{WORKER}{worker}"
@@ -56,12 +56,12 @@ def rejected(why: str, reply: str, judge: str) -> str:
return f"{REJECTED}: {why}\n\nReply:\n{quoted(reply)}\n\n{JUDGE}{judge}"
def stepped_up(worker: Record) -> str:
def stepped_up(worker: WorkerLine) -> str:
"""The rung the next cycle steps up to, archived as it steps, so a rerun after any exit resumes on it."""
return f"Stepped up\n\n{WORKER}{worker}"
def stopped(worker: Record, why: str) -> str:
def stopped(worker: WorkerLine, why: str) -> str:
return f"Stopped: {why}\n\n{WORKER}{worker}"
+303
View File
@@ -2545,3 +2545,306 @@ Inherited architect, decided by:
- Self-sufficiency, Locality: `bin/model_routing/route.py:13` `Record`: the archived worker line is a typed JSON record the outcome writers alone accept, with a warning that renaming a field orphans records; the legacy regex is unannotated and R + C lines fall through `rung_at` as text without a docstring saying so
- Navigation, Self-sufficiency: `bin/loop_claude/verdicts.py:1` "verdicts": its own module, with field comments stating what `entries_read=None` means
- Self-sufficiency: `bin/todo_table.py:205` `ships_alone`: the R above 5 rule is one named function, where the base held it only in the charter
## 2026-10-23T02:05:49Z, PR #359 at 72a63c5, against 545ab3a
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, Shape, Overall: `bin/model_routing/review_choice.py:21` `chosen`: the choice of each review's rung has one home, returned as a ReviewChoice; before, three functions in prompts.py each worked it out
- Locality, Shape: `bin/loop_claude/cycle/prompts.py:62` `review_launches`: the sentence builders return lists of sentences and one join adds the spaces, where each fragment had to start with a space
- Shape: `bin/loop_claude/routing.py:331` `first_route`: the parameter anchor is now called project, so docstrings no longer explain it
- Navigation, Self-sufficiency: `bin/loop_claude/routing.py:1` "module docstring": it lists the unit for each routing phase, where the base pointed to docs/decisions.md
- Navigation: `bin/loop_claude/loop/main.py:54` "loop-claude --help": about 90 lines of routing text are one paragraph that names the file for each concern
- Self-sufficiency, Navigation: `bin/loop_claude/cycle/prompts.py:1` "module docstring": new, says which function makes which sentence group and where each lands
- Locality: `bin/model_routing/ladder.py:113` `replay_applies`: the condition for when a replay applies is a named function shared by review_rungs and chosen
Inherited architect, decided by:
- Locality, Shape, Overall: `bin/loop_claude/cycle/prompts.py:55` `review_launches`: the choice is made once in chosen and the prompt code turns it into lists of sentences; the base called review_rungs again in three functions
- Shape: `bin/loop_claude/cycle/prompts.py:17` `EACH_REVIEWER`: the REVIEWS table of wording and kind pairs, filtered in two places, is gone
- Navigation, Self-sufficiency: `bin/loop_claude/routing.py:1` "module docstring": a four-line map of Start, Rerun, Step-up and Judge naming the function for each, in place of about 90 lines of routing prose in the help
- Navigation: `bin/loop_claude/loop/main.py:54` "loop-claude --help": the routing paragraph names a file for each concern
- Navigation: `bin/loop_claude/cycle/prompts.py:1` "module docstring": says which function builds which part of each prompt
- Shape, Locality: `bin/model_routing/ladder.py:113` `replay_applies`: the replay condition has one name, shared by review_rungs and chosen
- Shape: `bin/loop_claude/cycle/run.py:41` `Cycle.project`: the rename from anchor removes the repeated explanation
## 2026-10-23T03:24:42Z, PR #361 at 6f98a18, against 39dd51b
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, Shape: `bin/loop_claude/cycle/run.py:61` `run_cycle`: the step-up rides on Ruled and the states as a StepUp passed to work, ask, keep_answer, worker_start and archive_stepped, where the base's Cycle.stepped_from was hidden state that escalated() cleared on every event but HumanTyped
- Navigation, Self-sufficiency: `bin/loop_claude/escalation_mark.py:1` `escalation_mark`: the mark's rule, once spread over judge.py, verdicts.py, Route.escalated_at's comment and after_unfinished's docstring, sits in one file whose docstring lists Stamp, Step, Show and Check by function
- Shape: `bin/loop_claude/escalation_mark.py:37` `moved_to`: says what it returns, where the base's verdicts.escalation_mark was named after the concept; Escalating replaces the repeated union
- Shape, Locality: `bin/loop_claude/cycle/judge.py:164` `quotes_checked`: shrinks to calls into escalation_mark, so judge.py holds only the judge's own logic, and verbatim and plain sit beside render
- Self-sufficiency: `bin/round_titles.py:6` `CAP`: a bare constant in the base now says what it caps and which two consumers use it
Inherited architect, decided by:
- Locality, Shape: `bin/loop_claude/cycle/run.py:61` `run_cycle`: a StepUp travels through Ruled, Interrupting and Working and drops on /talk in one visible case, where the base's escalated() cleared Cycle.stepped_from by an order-dependent rule; the base's hardest place improved most
- Navigation, Self-sufficiency: `bin/loop_claude/escalation_mark.py:1` `escalation_mark`: from "the worker was stepped up twice" a reader reaches the right unit in one hop, with four labelled steps each naming its function
- Shape: `bin/loop_claude/verdicts.py:50` `Escalating`: the base's escalation_mark function returned where the mark would move; now the module carries the concept's name, moved_to says what it returns, and the type has one name
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:70` `Reply.escalation`: the comment points at code that explains the rule rather than at docs/decisions.md
- Navigation: `bin/round_titles.py:6` `CAP`: names the decision, rule-hook's round-cap and larv-review round-count, so a fourth-round page leads to the code that enforces the cap
## 2026-10-23T09:16:16Z, PR #367 at 5a56fff040dd437f8d5f94007fbfe371c874d1c4, against dcbdc970a67d07ab53d82a792c14f7b240a4b200
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | same | better | same | better |
| Inherited architect | better | same | better | better | better |
Mid A, decided by:
- Navigation, Shape: `bin/larv_review/history_changes.py:6` `history_changes`: named by its job where `git.py` named only that it calls git, and the merge-commit rule has its own unit in `history_change`
- Navigation, Shape: `bin/larv_review/history_commands.py:100` `show_places`: the module's name now fits all six entry points, where `record.py` also held commands that record nothing
- Shape: `bin/model_routing/route.py:13` `WorkerLine`: `Record`, `Route.record` and `RECORD_FIELDS` clashed with three other meanings of record; the new names match the `Worker:` line
- Shape: `bin/score_outcomes/results.py:24` `Result`: no longer collides with the archive's outcomes, at the cost of a comment explaining why the tool still says outcome
- Shape: `bin/judge_replay/replay.py:19` `archived_kind`: says it holds the archived verdict kind, where `on_record` read like a flag
Inherited architect, decided by:
- Shape, Self-sufficiency: `bin/model_routing/route.py:13` `WorkerLine`: says the value is the JSON on the `Worker:` line that ends each outcome, where `Record` overlapped the document sense and the verb
- Navigation, Shape: `bin/larv_review/history_changes.py:6` `history_changes`: a ruling-base symptom now leads to a file named for its one job, and the first-parent rule sits in one small unit
- Navigation: `bin/larv_review/history_commands.py:16` `record_ruling`: imported from a file named for the history commands it serves, not the overloaded record
- Shape: `bin/rule_hook/rules.py:91` `Checked`: no longer reuses outcome and verdict, two words the project uses for archive entries and judge verdicts
- Shape, Self-sufficiency: `bin/reading_cost/measure.py:13` `Reading`: `files` no longer borrows the seats' place, and the docstring says what both fields count
- Shape: `bin/judge_replay/replay.py:24` `Case.archived_kind`: says it is the kind the archive gave the verdict
- Self-sufficiency: `bin/score_outcomes/results.py:22` `Result`: a reader translates between result in the code and outcome in the tool's name and report, a small cost the comment explains
## 2026-10-23T09:51:07Z, PR #368 at 5e7e364, against 4a0ba59
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | better | better | same | better |
| Inherited architect | same | better | better | better | better |
Mid A, decided by:
- Locality, Shape: `bin/score_outcomes/results.py:40` `MEDIANS`: reads `result.findings.red` from the named `Findings` type where the base read `result.findings[0]` and sent the reader to `round_findings` to learn index 0 means 🔴
- Locality, Shape: `bin/score_outcomes/results.py:138` `at_least`: the lower-bound rule and its reason now live in one named function that `render` and `misreads` share, with `counted` beside it
- Shape, Locality: `bin/round_titles.py:45` `title_counts`: one parse of a round title's counts where the base matched `FINDINGS` separately in each caller; `lacks_counts` now also means inconsistent counts, a small cost
Inherited architect, decided by:
- Shape, Self-sufficiency: `bin/score_outcomes/results.py:33` `Result.findings`: a named `Findings` type in place of a bare `tuple[int, int]`, so each use reads `.red` or `.yellow` with no docstring open
- Locality: `bin/round_titles.py:45` `title_counts`: one function parses the counts after a round title's colon, so a change to the title format happens in one place
- Locality: `bin/score_outcomes/results.py:143` `counted`: `render` and `misreads` share one spelling of a chunk's findings, so the two output paths cannot drift apart
- Shape: `bin/round_titles.py:34` `lacks_counts`: the name now also covers a misread count above 🔴 plus 🟡, which a reader chasing a refusal learns only from the body; a cost that doesn't outweigh the gains
## 2026-10-23T09:51:56Z, PR #366 at e05c54a, against 4a0ba59
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | same | worse | same | same |
| Inherited architect | same | same | worse | same | same |
Mid A, decided by:
- Shape: `bin/rule_hook/rules.py:103` `heavy`: about 50 lines of command-word parsing sit in the module that holds the rule table, while rules of similar weight have their own modules; line 126 picks docker's index by a nested conditional
Inherited architect, decided by:
- Shape: `bin/rule_hook/rules.py:103` `heavy`: argv parsing for docker and mutation tools joins the rule registry, breaking the pattern of a sibling module per non-trivial rule, and rules.py now mixes registry, file checks and a shell parser
- Shape: `bin/rule_hook/rules.py:126` `heavy`: a conditional nested in another decides where docker sits in the words, which a 3am reader unpicks by hand
## 2026-10-23T12:49:21Z, PR #370 at 686c1dc, against 64d4386
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | better | better | same | better |
| Inherited architect | better | better | better | same | better |
Mid A, decided by:
- Navigation, Locality: `bin/rule_hook/heavy_command.py:1` `heavy_command`: the file name and docstring lead a cold reader to the code that decides the run-heavy rule, which sat in the middle of `rules.py:103-150` before
- Shape: `bin/rule_hook/rules.py:8` `rules`: the file drops from 256 to 207 lines and reaches the heavy-command logic through one import
- Shape, Locality: `bin/rule_hook/heavy_command.py:28` `heavy`: docker's position is two named steps, `reachable` and `docker_at`, where a nested conditional stood at `rules.py:126`
Inherited architect, decided by:
- Navigation, Shape: `bin/rule_hook/heavy_command.py:1` `heavy_command`: a file name in the `rule_hook/` listing points straight at the unit, which the base buried in the 256-line `rules.py:103-150`
- Locality: `bin/rule_hook/heavy_command.py:27` `heavy`: the rule "past a launcher docker can come anywhere, otherwise only first" reads from two plain lines, where the base held a nested conditional
- Locality, Shape: `bin/rule_hook/heavy_command.py:5` `LAUNCHERS`: the tables sit beside their only consumer, so extending them needs no search for other readers
## 2026-10-23T23:00:27Z, PR #372 at 899e8ed, against d1733a2
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | better | better | same | better |
| Inherited architect | worse | better | same | same | same |
| Maintainability senior | same | better | better | same | better |
| Junior A | same | better | better | same | better |
Mid A, decided by:
- Locality, Shape: `bin/shell_command.py:102` `launched`: one place finds the tool a command runs past its launchers, where heavy held launched, reachable, docker_at and a MUTATORS special case at once
- Shape, Locality: `bin/rule_hook/heavy_command.py:12` `heavy`: two cases and one early exit, with run-heavy read as a launcher instead of a stray word
- Shape, Navigation: `bin/docker_command.py:1` `docker_command`: named by what it holds and serving both docker rules, but at bin's root while only rule_hook reads it, against README's map
- Locality: `bin/docker_command.py:54` `helped`: unlimited leans on helpers defined below it, and helped finds the subcommand by its first occurrence
Inherited architect, decided by:
- Locality: `bin/rule_hook/heavy_command.py:12` `heavy`: four lines on launched and docker_subcommand, though LAUNCHERS now changes both docker rules together
- Navigation: `bin/docker_command.py:1` `docker_command`: README says root modules serve more than one tool, yet it serves only rule_hook, so a reader looks in rule_hook/ first
- Locality: `bin/docker_command.py:32` `unlimited`: the docstring states that the container's own arguments are read, and why python -m pytest is no limit
- Shape: `bin/shell_command.py:1` `shell_command`: the module now does two things, parsing and launcher reading, which only rule_hook uses
Maintainability senior, decided by:
- Locality, Shape: `bin/shell_command.py:102` `launched`: one function, returning a Launch, finds the tool past its launchers, where heavy did it inline with index arithmetic
- Locality, Shape: `bin/rule_hook/heavy_command.py:12` `heavy`: one branch, docker or a mutation tool, with the module no longer holding general shell and docker parsing
- Shape: `bin/docker_command.py:1` `docker_command`: README says root modules serve more than one tool, yet only rule_hook imports it
- Shape: `bin/docker_command.py:32` `unlimited`: the entry point sits between helpers, and unlimited and unlimited_container differ by an unstated input
- Locality: `bin/docker_command.py:54` `helped`: reads --help by position while heavy's LIGHT_FLAGS reads it anywhere, and neither says whether that is meant
Junior A, decided by:
- Locality, Shape: `bin/shell_command.py:102` `launched`: the steps that find a command's tool past its launchers live in one function both rules share
- Shape, Locality: `bin/rule_hook/heavy_command.py:12` `heavy`: from 13 lines mixing three parsings to 8 with a clear docker-or-mutator branch
- Shape: `bin/docker_command.py:1` `docker_command`: a truthful name and docstring, though it sits at bin's root rather than beside rule_hook's rules
- Locality: `bin/rule_hook/rules.py:140` `command_breaches`: the new rule plugs in beside run-heavy as one parallel if
## 2026-10-24T09:53:49Z, PR #373 at 3ac8c79, against eb7b506
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | worse | same | better | same |
| Inherited architect | same | worse | worse | same | worse |
| Maintainability senior | same | worse | worse | same | worse |
| Junior A | same | worse | same | same | same |
Mid A, decided by:
- Locality: `bin/rule_hook/rules.py:154` `unlimited_container`: rule-hook now encodes how run-heavy's docker puts itself on PATH, joined to it by a one-line comment
- Locality: `bin/run_heavy/main.py:65` `capping`: a stand-in docker on PATH and RUN_HEAVY_MEMORY make a container's limits depend on the environment, though the help spells it out
- Self-sufficiency: `bin/docker_command.py:24` `size`: named predicates replace a negative-lookahead regex, and swap_limit says what -1 and 0 mean
- Self-sufficiency: `bin/docker_command.py:52` `subcommand_at`: positions replace a first-match lookup that took an option's value for the subcommand
- Shape: `bin/docker_command.py:84` `capped`: the module grows from 5 functions to 13, and one line packs four conditional limit lists
Inherited architect, decided by:
- Locality, Shape: `bin/rule_hook/rules.py:154` `unlimited_container`: index arithmetic finds the words before docker, and the rule encodes how another package's PATH shim works
- Locality: `bin/rule_hook/rules.py:165` `resets_path`: reads as a guess about launchers rather than a model of them
- Locality: `bin/run_heavy/main.py:65` `capping`: whether a docker run gets limits depends on PATH order and a variable an ancestor set
- Shape: `bin/docker_command.py:39` `unset_swap`: named unset though -1 is unlimited, beside a generic zero, in a module that now reads and rewrites commands
- Shape: `bin/docker_command.py:24` `size`: replaces a hard negative-lookahead regex, offsetting in part
Maintainability senior, decided by:
- Locality: `bin/rule_hook/rules.py:154` `unlimited_container`: repeats how run-heavy's PATH trick works, so a change to run-heavy silently changes the rule, and the index arithmetic takes a second read
- Locality: `bin/machine_load/memory.py:20` `Memory.slot_share`: tuning the worker threshold ROOM_SHARE now also changes every capped container's memory, while its comment names only the worker
- Locality: `bin/run_heavy/main.py:65` `capping`: the share reaches the docker shim through an environment variable and a PATH entry, hidden state between two processes
- Shape: `bin/docker_command.py:24` `size`: the module grows to 13 functions that read and rewrite commands, with predicates named as nouns
- Shape: `bin/docker_command.py:84` `capped`: one line crosses the two limits' values over and needs the docstring
Junior A, decided by:
- Locality: `bin/rule_hook/rules.py:154` `unlimited_container`: rule-hook copies run-heavy's PATH trick, and nothing in run_heavy points back to it
- Locality: `bin/run_heavy/main.py:65` `capping`: one process sets RUN_HEAVY_MEMORY and PATH, and another reads them, so a docker run spans two processes
## 2026-10-28T01:47:11Z, PR #371 at 51faf71, against 3bde9cd
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | same | same | same | same |
| Inherited architect | same | same | same | same | same |
Mid A, decided by:
- Locality, Overall: `bin/loop_claude/loop/reload.py:28` `LoopRun.unfinished_run`: its name is one word from `Route.unfinished`, and the two reset at different times
- Locality: `bin/loop_claude/loop/main.py:214` `closed_cycle`: the order of archiving the step-up before the limit is checked has to be known, and the `or` fallback contradicts the comment above it
- Shape: `bin/loop_claude/cycle/worker.py:15` `AUTO_COMPACT_WINDOW`: the constant named for the window holds the environment variable's name
- Self-sufficiency: `bin/loop_claude/loop/main.py:151` `UNFINISHED_LIMIT`: the number rests on archive evidence the reader can't see
- Navigation: `bin/loop_claude/cycle/run.py:82` `archived_stop`: a loop-level stop goes through a cycle-level helper
Inherited architect, decided by:
- Locality, Overall: `bin/loop_claude/loop/main.py:214` `closed_cycle`: the order of its steps is easy to break, and the `or` fallback contradicts the comment above it
- Locality: `bin/loop_claude/loop/reload.py:28` `LoopRun.unfinished_run`: a rerun sets it to 0 only through the dataclass default, which the call site at `loop_run_from` doesn't say
- Navigation: `bin/loop_claude/cycle/judge.py:150` `run_judge`: the path from a rejected verdict to exit 1 crosses three files, and only some misquotes count
- Navigation, Shape: `bin/round_titles.py:8` `CAP`: the fourth-round cap lives in a module named for commit titles
- Self-sufficiency: `bin/loop_claude/loop/main.py:1` module docstring: the exit list maps a code to a cause, but no bullet links to the unit that raises it
## 2026-10-28T11:36:42Z, PR #386 at 722dd5e, against 243a9d8
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | same | same | same | same |
| Inherited architect | same | worse | better | same | same |
Inherited architect, decided by:
- Locality: `bin/routing_figures/measure.py:155` `costed`: one message's dollars now depend on every message from the same model in the chunk and on the worker's last cost-state entry, so pricing one message means holding the whole chunk's split
- Locality: `bin/routing_figures/measure.py:125` `measured`: the one-line `lacking=` count is explained only in the `ChunkFigures` docstring and in `basis`
- Shape: `bin/routing_figures/measure.py:85` `Message`: named fields replace unnamed `(at, tools, spent)` tuples and six positional arguments
- Shape: `bin/routing_figures/prices.py:33` `listed`: list-price arithmetic gets its own small module with a name that fits
## 2026-10-28T16:23:54Z, PR #387 at 0447f2e, against cde7720
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | worse | worse | same | worse |
| Inherited architect | same | worse | same | same | same |
| Maintainability senior | same | worse | same | same | same |
| Junior A | same | worse | same | same | worse |
Mid A, decided by:
- Locality, Shape, Overall: `bin/rule_hook/main.py:117` `read_breaches`: the repeat-read rule's file and transcript reads sit in main.py, apart from its logic in repeat_read.py, unlike the other rules, so changing the rule needs both files open
- Locality: `bin/rule_hook/repeat_read.py:72` `shown_lines`: whether a Read is checked turns on a text comparison of the mtime with transcript stamps, which holds only while main.modified formats the mtime as Claude Code stamps entries
- Locality: `bin/rule_hook/repeat_read.py:29` `repeat_breaches`: needs lines read one past the last shown line, a promise main.py's caller keeps with nothing enforcing it
- Shape: `bin/rule_hook/repeat_read.py:87` `results_on`: returns unnamed four-part tuples that callers unpack by position
- Shape: `bin/rule_hook/repeat_read.py:103` `written`: returns a path, while `written` in main.py names the text that may carry an override marker
- Locality: `bin/rule_hook/main.py:84` `breaches_of`: a Bash call now also reads the transcript and the file system through read_breaches
- Shape: `bin/claude_code/entries.py:100` `ToolResult`: tool-result parsing has one named home, which shrinks measure.py's `results` to one line
Inherited architect, decided by:
- Locality: `bin/rule_hook/main.py:117` `read_breaches`: the rule's I/O sits in main.py and its logic in repeat_read.py, with two contracts across the seam, the mtime stamp's format and reading one line past the last shown, that only docstrings in the other file state
- Locality: `bin/rule_hook/repeat_read.py:72` `shown_lines`: `asker` switches on a Read-only cut-off whose reason lies in a comment and the rule text, the order-dependent part of the rule
- Shape: `bin/rule_hook/repeat_read.py:87` `results_on`: untyped positional tuples and dense conditionals at :46 and :105, offset by the shared `ToolResult` parser in `bin/claude_code/entries.py:100` and measure.py's dropped duplicate
Maintainability senior, decided by:
- Locality: `bin/rule_hook/main.py:117` `read_breaches`: the rule's I/O sits in main.py and its logic in repeat_read.py; the count `max(shown) + 1` at :126 sets what an open-ended `cat` means in the other file
- Locality: `bin/rule_hook/repeat_read.py:72` `shown_lines`: `changed > touched` compares stamps as text, which holds only while `modified` in main.py formats the mtime as the transcript does; `changed` and `asker` made it the slowest unit to read
- Locality, Shape: `bin/claude_code/entries.py:107` `tool_result`: one named parser replaces measure.py's private `result_text`, though `measure.py:142` `agent_calls` still reads `part.get("id")` itself
Junior A, decided by:
- Overall, Locality: `bin/rule_hook/main.py:117` `read_breaches`: the rule's entry point, stat and file reads sit in main.py while its logic sits in repeat_read.py, so changing the rule needs both files
- Locality: `bin/rule_hook/repeat_read.py:29` `repeat_breaches`: needs lines through one past the last shown and a mtime formatted as a transcript stamp, both set up by main.py
- Locality, Shape: `bin/routing_figures/measure.py:205` `results`: one line over the shared `tool_result`, where cde7720 held a private copy of the parsing
- Shape: `bin/rule_hook/repeat_read.py:87` `results_on`: an unnamed four-field tuple unpacked by position, and `written` names a path here but the override text in main.py
+290 -241
View File
@@ -1,64 +1,175 @@
# Decisions
## larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
## bin/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names
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.
2026-10-23, larv-review, through PR #367. Serves code health: a reader can trust that one word names one thing in every tool. Before, "record" and "outcome" each named different things in three modules, and "place" in two. Each word kept the meaning it already had where renaming costs most:
2026-10-15, lilleman, set by PR #283 on 2026-10-16: an item that lifts the lowest dimension moves each goal it cites by 9, since the lowest dimension caps the overall and lifting it is worth the most to the floor. Within a chunk its work comes first; in the plan, lilleman answering that PR's review, such items compete with the others like any item and don't rank first. PR #257's scoring run found Shape lowest, at 6.25, and `todo.md` items 124 and 125 were to lift it. Release 0.3.0's scoring runs found Locality lowest, at 5.75 and 5.88, so the 9 moved from those items to the ones lifting Locality.
- An outcome: the archive's file names end in `.outcomes.md`, and the tools that read them find them by that suffix. score-outcomes' `Outcome` became `Result`, and rule-hook's became `Checked`. The command `score-outcomes` keeps its name, since renaming it would be a change of its own: files every project loads, such as `rules/todo-items.md`, name it, and so do decision titles. Its help and report keep the word its name uses.
- A record: "judge's records" is a term in `~/.claude/CLAUDE.md` → "Vocabulary", and reading-cost's help calls its file a record. A single item in such a document is an entry; the route the archive keeps is a worker line (`Route.worker_line`). The verb "to record" keeps its plain meaning.
- A place: the comprehension panel's term, also in the Vocabulary. reading-cost's `Reading.places`, how often each file was read, became `Reading.files`.
## 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.
2026-10-01, lilleman: the judge reads `docs/decisions.md` and `AGENTS.md` too, so an answer recorded there is not asked again (goal 1.2); its bar becomes whether the README or those files discriminate. 2026-10-03, implemented: when the README's premises or those files answer the worker's question, the judge quotes the answer verbatim and the worker resumes with it. The judge then sees the quote as a `[loop]` line. The worker asking it again shows the quote did not settle it, and the judge sends it to the human. A backstop of three quoted answers per cycle bounds what the judge misses, such as a reworded repeat or a worker asking without end, so the worker cannot loop unattended (goal 1.4); the fourth question that the README's premises or those files answer in one cycle goes to the human with the judge's quote. An interrupt does not reset the count, so every later question those files answer in that cycle also goes to the human. Valid while the worker writes records only in a worktree, as `CLAUDE.md` → "Working with the codebase" has it, so the records the judge reads from the checkout root are merged ones.
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: 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.
2026-10-17, implementing todo item 168: the human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude.
## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 1. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it.
## loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 1. A write by another claude inside `trust`'s read-modify-write window is lost.
2026-09-24, lilleman, extending it to every worktree. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Valid while resume re-enters a recorded worktree and trust is kept per path.
2026-09-30, lilleman: Claude Code owns and writes that file, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md` item 6 ends it.
2026-10-17, implementing todo item 168: the human answers an interrupt on loop-claude's own terminal. claude now opens on the terminal only for `/talk`, a release ready to cut and the routing calls, and the trust is marked only then.
## bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
2026-09-26, larv-review. Serves goal 2. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a call newer than the floor, like 3.12's `itertools.batched`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while `uv` can fetch the floor interpreter and no machine taking the checkout ships an older Python.
Valid while the archive's file names, the Vocabulary and the panel keep these words.
## bin/: the tools and their tests run on the host's Python, with no container
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.
## bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
2026-10-28, lilleman, through todo item 245. Serves goal 1.5: the suite gates every chunk. The suite took 198 s, 102 s of which went to rerunning it on the oldest Python README Install named, 3.11. README Install now asks for the latest stable Python as `python3`, and mypy checks every tool under `bin/` for the version Install names. README's Test line runs the tests in four pytest-xdist workers through `uvx`: 29 s on a 16-CPU machine. Four is one heavy slot's CPUs, `CPUS_PER_SLOT` in `bin/machine_load/slots.py`, so a gate under `run-heavy` loads only the slot it waits for. The line pins pytest and pytest-xdist, as `test_types.py` pins mypy, so every machine runs the gate the same way. It passes the path of `python3`, since `uvx --python python3` picks a Python uv installed itself, which may be older. The tests use stdlib `unittest` alone, and pytest only runs them, so plain `python3 -m unittest` runs the same tests one at a time and another runner can replace pytest. Valid while every machine taking the checkout gets the latest stable Python soon after its release.
## chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
2026-10-22, lilleman, through todo item 217. Serves goal 1.4: each review has a fixed cost, so more items per chunk cost less per item. Across the 165 finished chunks loop-claude archived up to that day, a chunk took a median of 1.30M tokens with one item and 1.33M with two, and three in four chunks shipped one item. The old rule also asked one PR title to state what the items achieve together; lilleman dropped it, since unrelated items that fire the same passes cost one review.
The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the highest R among a chunk's items, the median was 0.9M to 1.5M tokens at R 1 to 5, and 2.7M at R 6, where the 90th percentile was 8.8M. A risky item that runs long re-runs review over every item bundled with it. R 5 is also the least R an I 4 item gets, so an item that could take everything down shares a chunk only where its L + E is 3 or less, and an irreversible I 5 item, at R 7 or more, never does. Valid while a review's cost is mostly fixed per chunk; revisit once 30 chunks have shipped bundles under it.
## comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. 2026-10-13, lilleman: the floor blocks nothing, and `review: the comprehension check records …` says why. Valid while the scoring run keeps its four seats.
## larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
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.
2026-10-15, lilleman, set by PR #283 on 2026-10-16: an item that lifts the lowest dimension moves each goal it cites by 9, since the lowest dimension caps the overall and lifting it is worth the most to the floor. Within a chunk its work comes first; in the plan, lilleman answering that PR's review, such items compete with the others like any item and don't rank first. PR #257's scoring run found Shape lowest, at 6.25, and two items were to lift it: `todo.md` item 124, and the one PR #367 shipped, which gave "record", "outcome" and "place" one meaning each in `bin/`. Release 0.3.0's scoring runs found Locality lowest, at 5.75 and 5.88, so the 9 moved from those items to the ones lifting Locality.
## loop-claude: a `claude` that cannot start is a failed worker run, retried
2026-09-28, larv-review, declining a product-owner nit to exit at once when `claude` is missing. Serves goal 1. Claude Code's updater repoints `~/.local/bin/claude` at each new version under running loops, and a start that meets it mid-update fails with the same error as a broken install; the retry costs two minutes on the second and saves an unattended loop on the first. Valid while Claude Code updates by repointing its link.
## 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's premises or the files in the title discriminate between the alternatives. Valid while the worker's self-report stays unreliable.
2026-10-03, lilleman. Serves goals 1.2 and 1.4. When the README's premises or those files answer the worker's question, the judge quotes the answer verbatim and the worker resumes with it, so an answer recorded there is not asked again. The judge then sees the quote as a `[loop]` line. The worker asking it again shows the quote did not settle it, and the judge sends it to the human. A backstop of three quoted answers per cycle bounds what the judge misses, such as a reworded repeat or a worker asking without end, so the worker cannot loop unattended: the fourth question that the README's premises or those files answer in one cycle goes to the human with the judge's quote. An interrupt does not reset the count, so every later question they answer in that cycle also goes to the human. Valid while the worker writes records only in a worktree, as `CLAUDE.md` → "Working with the codebase" has it, so the records the judge reads from the checkout root are merged ones.
2026-10-03, lilleman. Serves goal 1.2. The judge reads `~/.claude/CLAUDE.md`, each file under `~/.claude/rules/` and each file under `~/.claude/skills/larv-review/standards/` whole. The worker follows them, so a question they answer should not reach the human. Reading whole is safe, because the judge may quote only words that appear in them, and a list of sections would need keeping current.
2026-10-03, lilleman. Serves goal 1.2. 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. Claude settled two choices lilleman's 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`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/` 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-17, lilleman, todo item 168. The human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude.
## loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
2026-09-21, lilleman. Serves goal 1. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog. Trusting every worktree `git worktree list` names spares reading which one from the transcript. Since the human answers an interrupt on loop-claude's own terminal (todo item 168), claude opens there only for `/talk`, a release ready to cut and the routing calls, and the trust is marked only then. Valid while resume re-enters a recorded worktree and trust is kept per path.
2026-09-30, lilleman. A write by another claude inside `trust`'s read-modify-write window is lost, a risk larv-review accepted on 2026-09-24. Claude Code owns and writes `~/.claude.json`, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md` item 6 ends it.
## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 shares the setup across machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session.
## loop-claude: every claude it starts bypasses permissions inside its sandbox
2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the claude an interrupt opens run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names.
## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 1. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it.
## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
2026-09-28, lilleman. Serves goals 1 and 3: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with its outcomes beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole.
## loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` → "Compact instructions" says what the summary keeps
2026-10-27, lilleman's yes to claude's evaluation through todo todo item 231. Serves goal 1.4; its counter-signal, review rounds and unfinished verdicts per chunk, is the check.
loop-claude hands each worker's claude `CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000` (`bin/loop_claude/cycle/worker.py`), and the session /talk opens gets it too. Claude Code compacts before a window fills: a 1M window at about 967k tokens, and in a probe on 2026-10-27 a 100k window at 65k and 80k, so a 200k window compacts at about 170k. The window is not set in `settings.json`, since the archive measured loop-claude's workers and interactive sessions are lilleman's. Subagents inherit the variable, which reaches every process of the session: 68 of the 994 subagent runs since 2026-10-21, 7%, passed 170k, 24 of them principles auditors, so about one in fourteen compacts once. Compacting subagents by choice would cost more than it saves, as below, but the variable cannot leave them out, and `CLAUDE.md` → "Compact instructions" has a reviewer keep the findings it has drafted. That section shapes the summary: in another probe that day, a session whose CLAUDE.md asked for its summary to end with a secret word got a summary ending with that word. Path-scoped rules leave the context at a compaction and return at the next matching read, and rule-hook holds each review launch to its rung whatever the summary keeps. `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`, handed the same way, would compact at the same point but also cap the window at 200k, so a run that Claude Code stops compacting, as it does when one tool result refills the context each time, would hit the limit instead of going on.
Why 200k. Item 231 asked for the best means to lower what a chunk spends on context, in dollars, then hours, with no loss of quality. Measured from loop-claude's archive, the 90 chunks with messages after the routing figures' reset of 2026-10-21 cost $1,215 at the list prices read on 2026-10-26 (Opus 5.5: $4 per million input tokens, $5 and $8 for 5-minute and 1-hour cache writes, $0.20 for cache reads, $20 for output; no model but Haiku 5.5 charges more above 200k). That is 0.86 of what the chunks' `cost-state` entries sum to, since some chunks' subagent transcripts are not in the archive. Worker main threads cost $375 (31%): 1-hour cache writes $149, cache reads $153, output $74. Subagents cost $840: 5-minute cache writes $379, output $274, cache reads $187, with the principles auditors at $274 over 342 runs, the stability reviewers $179 and general-purpose subagents $192. A worker starts at 41k tokens of context and peaks at a median 167k, one in ten past 358k, the largest at 848k. The worker's messages above 200k were 32% of its messages and 55% of its cost.
What reads cost, and whether a tool cuts them, measured at lilleman's ask after those figures: no tool cut a reviewer's reading without losing a finding, except a scout, which kept the stability reviewers' findings but lost the auditors' 🔴 and slowed every round; so none of them ships here. lilleman chose on 2026-10-27: workers trial a reading rule (`todo.md` item 240), reviewers get no scout, and the principles audit keeps reading the project whole. Two measures of reading: the characters a thread read, 93M in all, about 27M tokens; and the new input tokens of the messages that took results in, charged to those results, which also count what arrives beside a result, such as the agent's own previous reply. By the second measure tool results caused $620 of the $1,215, and reads (Read, Bash reads, Grep, Glob and git's diff, show and log) $537 of that: the worker's reads $140 (Bash reads $115, Read $12) of its $190 of results, the principles auditors' $133 (Read $109, Grep $22) of $139, the stability reviewers' $97 (Bash reads $79) of $106, general-purpose subagents' $84 of $97, the prose reviewers' $32, the architects' $30 and the product-owner reviewers' $21. By the first measure the worker's reads are about $45. Precision is low everywhere: of the characters a principles auditor read, 13% were in a file its report names; a stability reviewer 8%; a prose reviewer 18%; an architect 11%; the worker 4% in a file it later edited. Reading is mostly to find things and to learn what a project holds. The worker's `sed` ranges are small, median 25 lines, one in ten over 80. Of the worker's read characters, 49% were of a file it had read earlier in the thread: 36% within three messages, paging through it, and 13% later, with the file unchanged, about $6 of the $45; a reviewer's later reads of an unchanged file it had read are 1 to 2%. rule-hook's `repeat-read` now blocks a read of lines already in context.
The trials: four stability rounds and five principles rounds archived on 2026-10-23, each holding 🔴 or 🟡 findings, replayed on the project's rung as `review-replay` replays them, with the reviewer's definition changed through `--agents`; and three worker-like tasks, a search, a rename and an explanation, run on fresh clones at the project's rung. The baseline, the reviewer as it is, found 4 of its own 6 archived findings in each pass, so a variant that finds 4 or 5 of 6 does what the same reviewer does twice. The options todo item 231 named, each simulated on the 90 chunks and, where lilleman asked, tried:
- Compaction of the worker. The saving and the compactions per chunk, by the point it compacts at: 150k saves $75 at 1.0 compactions; 167k to 180k, where a 200k window compacts, $77 to $78 at 0.8 to 0.7; 200k $78 at 0.5; 300k $54 at 0.2. $78 is 21% of the workers' $375 and 6% of all spend. Compaction also caps the 36 re-writes of a whole context after a gap longer than the cache's hour or a change of rung: they cost $61, up to 785k tokens each, and would cost about $34. Compacting subagents at 150k costs more than it saves, since a compaction reads the context once more and writes a summary, and subagents are short.
- A fresh context for the review phase, handed 60k tokens of facts, saves $39. A compaction at 170k saves that too, and loop-claude would need a second session per chunk.
- Read with an offset and a limit, or Grep, in place of `cat`, `sed` and `head`. Steering the tool would not change how much is read: the worker's `sed` ranges are small already, and only 13% of its Bash-read characters came from whole files. A rule on how much to read did change it: under "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context", the three worker tasks read 45% to 60% fewer characters at the same or lower cost, every task done as well, and the rename was the one run of four that also kept the import names sorted (`todo.md` item 240). A stability reviewer under the same rule with an `outline` script on PATH, which prints a file's symbols with their line ranges, read 4% less and found 2 of 6 findings, and the workers never ran the script.
- Code-intelligence tooling: the `LSP` tool, through a pyright plugin built from the marketplace manifest with `pyright-langserver` on PATH, answers a file's symbols, a definition or the references in a few hundred characters. Under a rule telling them to use it, the stability reviewers and the workers never called it; the auditors did, read as much or more, and missed the one 🔴, 0 of 1 against the baseline's 1 of 1. Each machine would also need a server per language (goal 2). Not worth an item.
- A cap on tool results. Claude Code caps a Bash result at about 30k characters already. A PostToolUse hook capping it at 12k, which `updatedToolOutput` allows, left the stability reviewers 3 of 6 findings, two lost in one round. Read results, 59.9M characters in subagents' threads with 58% of their characters in results over 12k, are out of such a hook's reach. Not worth an item.
- A scout: Haiku 5.5 reading raw content, whole files or long output, and returning facts as path:line and the ranges worth reading, so the agent's own context holds the summary and the chosen lines. In session, as an agent under `agents/`, its first request writes 37k tokens, $0.005, and a read of a 38KB file costs $0.008 in 8 seconds. As a slim headless `claude -p` with its own system prompt, no setting sources and no dynamic sections, which keeps the subscription login, it starts at 6k tokens and $0.0003 in 3 to 5 seconds, its prefix cached across calls, and the same read costs $0.004 in 7 seconds; a direct API call and `claude --bare` need an API key, so they are out. Stability reviewers with the agent scout found 5 of 6 findings and read 29% fewer characters at 6% less cost and 14% more time; with the CLI scout 4 of 6, 38% fewer, 17% less and 39% more; the auditors with the agent scout 3 of 6, the 🔴 among the lost, at the same cost and twice the time. Workers offered the scout never called it.
- What a reviewer reads: the auditors read the project whole by design. Of their 🔴 and 🟡 findings since the reset, 47% named a file the chunk edited and 51% another file, so reading only the change would drop half of them (`review: the principles audit runs on every chunk that changes code, config or tests, reads the project whole with one auditor checking the goals and every principles file that applies, and runs on no other chunk`).
- The base context: every thread starts with `~/.claude/CLAUDE.md` (19k characters), `~/.claude/AGENTS.md` (11k, this repo's decisions, which Claude Code loads as user instructions into every project's sessions; `todo.md` item 52), the project's `AGENTS.md`, and, for the worker and general-purpose subagents, the skill listing (18k) and the agent listing (12k). Subagents' first messages wrote $97 of it. Trimming the listings would save about $20, 2%, and is not worth an item: `disableBundledSkills` would also drop `/security-review`, the security pass of record.
Quality. 19 chunks compacted between 2026-10-10 and 2026-10-22, at the compaction points Claude Code set then, 214k to 972k tokens. Per 100 worker messages they took a median 3.6 review rounds past each pass's first against 4.0 for the 68 uncompacted chunks of 100 messages or more, and 13.9 🔴 and 🟡 findings against 16.6. 4 of 19 had an unfinished verdict against 3 of 68, each 8 to 10 hours after the compaction and followed by a finished verdict within minutes; in those four verdicts the judge quoted the worker's own passages and the human's typed answers, never a summary. One cause was possible and is closed here: Claude Code writes the summary as a user entry, which `bin/claude_code/entries.py` read as the human's words, so the judge would see a `[human]` line of thousands of words and `/talk` would count it as typed; it now reads as Claude Code's. Whether compaction raises unfinished verdicts stays open until `todo.md` item 235 measures it. Two summaries read whole kept the chunk's intent, files, errors and next step in 12k to 20k characters, and the worker resumed without re-reading.
Hours. A chunk ran a median 0.7 hours from its first message to its last, one in ten past 12 hours, mostly waiting for the human or a usage limit. No option here changes that: a compaction takes 51 to 83 seconds, under a minute per chunk at 0.7 each, and a smaller context saves seconds per turn at most. Waiting on subagents took 66% of a worker's active time, so the hours lever is launching a round's reviewers together: larv-review §3 → "Waves" now launches each wave's reviewers in one message.
Valid while cache reads cost a twentieth of input and Claude Code's compaction keeps the worker's task.
## machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
2026-10-23, lilleman. Serves goal 1.5. On 2026-10-22 ai-sandbox, with 8 CPUs and 16 GiB, thrashed for hours: four to six loops ran mutation tests, full gates, `docker build`s and QEMU-booting e2e tests at once, and nothing told one loop how busy the machine was. lilleman chose both limits; no standard sets either, and GNU parallel's `--memfree`, which does the memory wait's job, has no default. A slot is a file lock, so a session that dies frees its slot. The memory wait reads `/proc/meminfo` only, and off Linux a worker starts at once. `bin/machine_load/` holds the slots and the memory share, `bin/run-heavy` takes a slot, `CLAUDE.md` → "Working with the codebase" has every session use it, and loop-claude's worker waits for the share. rule-hook's rule `run-heavy` blocks a `docker build`, and a run of a mutation tool stability-reviewer names, outside run-heavy, whether direct or inside a container. No program can tell a gate script from a light one, so only `CLAUDE.md` asks a session to run a gate under run-heavy. Valid while one machine runs several loops at once.
## machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together
2026-10-24, lilleman. Serves goal 1.5. On 2026-10-23 ai-sandbox, then with 8 CPUs and 7.6 GiB of memory, hung until a hard reset, although its one heavy command held a slot. Beside that mutation run, a reviewer's stress probes ran in `docker run` with no memory limit, each to 2 GiB. A limit makes a runaway container fail alone instead of taking the machine with it. A swap limit is needed too: without one, docker lets a container swap as much again as its memory limit, and swapping is how the machine hung. The session sizes both limits, since lilleman wants a project to run heavier work where it needs to. rule-hook reads only the `docker run` and `docker create` in a session's Bash commands. A container a script starts is out of its sight, and so is a compose service, whose limits live in its compose file. `CLAUDE.md` → "Working with the codebase" asks a session for limits there.
The heavy command in that hang started its container from the project's own script, out of rule-hook's sight. So run-heavy puts its own `docker`, `bin/run_heavy/path_entry/docker`, first on its command's `PATH`. That docker gives each `docker run` or `docker create` that lacks a limit the slot's share. The share is what a worker's quarter leaves: three quarters of MemTotal, split evenly across the slots. A container that sets one of the two limits keeps it, and gets the other as large, since docker refuses less swap than memory; an unlimited swap, `--memory-swap -1`, gives way. run-heavy cannot place the command in a cgroup instead: none is delegated to the user, and dockerd starts the containers outside the command's process tree. A compose service, and a docker named by its full path, keep no cap.
A daemon-wide cap would see every container: dockerd's `cgroup-parent`, given a memory limit. lilleman turned it down, since it is host config and would cap a project's heavy work too. Valid while sessions start their work in containers on a machine they share.
## principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
2026-10-22, lilleman asked for a rule of seven that holds at every level and is never a hard rule. Serves code health: a reader new to the project should take in each level at once. The numbers follow the sources below, since no single study sets them.
- Seven is Mark Seemann's figure in *Code That Fits in Your Head* (2021). He says the exact number matters less than having a limit the team agrees on ([Tech Lead Journal #89](https://techleadjournal.dev/episodes/89/)). The 24 lines of 80 characters are his too ([The 80/24 rule](https://blog.ploeh.dk/2019/11/04/the-80-24-rule/)).
- Four or five for things that act on each other: working memory holds about four chunks once rehearsal and grouping are blocked (Cowan, ["The magical number 4 in short-term memory"](https://www.cambridge.org/core/journals/behavioral-and-brain-sciences/article/magical-number-4-in-shortterm-memory-a-reconsideration-of-mental-storage-capacity/44023F1147D4A1D44BDC0AD226838496), 2001). Sandi Metz's rules allow four parameters, and Fowler's long-parameter-list smell starts at three or four.
- More for things found by name: a reader recognises an item in a list, so a list's length is no memory limit (Nielsen Norman Group, [Short-term memory and web usability](https://www.nngroup.com/articles/short-term-memory-and-web-usability/)). Menu studies find depth costs more than breadth, and broad levels of 16 to 64 items beat narrow ones when their labels are clear (Larson & Czerwinski, [1998](https://www.microsoft.com/en-us/research/publication/web-page-design-implications-memory-structure-scent-information-retrieval/); Dix et al., [menu breadth](https://hcibook.com/e3/online/menu-breadth)).
- A split must save more than it costs: in an eye-tracking study, extracting methods cut reading time on hard tasks and raised it on simple ones (a 2026 preprint with 32 novices, [arXiv 2602.18579](https://arxiv.org/abs/2602.18579)). John Ousterhout's deep modules and John Carmack's case for inlined code argue the same against splitting by size.
- A grouping or a recorded reason, never a split at any cost: no study supports a fixed cut-off for function length, parameter count or nesting. Re-analysis of the cited data finds no optimal function length ([Derek Jones, 2023](https://shape-of-code.com/2023/09/10/optimal-function-length-an-analysis-of-the-cited-data/)),. So a limit holds only while the comprehension panel's readers find the code it flags hard, and `agents/systems-architect.md` → "Fits in a head" says how its reviewer rates a unit past one.
Valid while the comprehension panel measures how hard a project is to read.
## reading cost and `score-outcomes`: each waits for 10 finished chunks before it shows a median
2026-10-16, lilleman, confirmed when asked. Serves goal 1.2: the answer is written once, so the same question is not asked again.
`score-outcomes` shows a score's medians only where 10 finished chunks that each shipped one item hold an outcome for that score (`ENOUGH` in `bin/score_outcomes/results.py`). The reading-cost trend waits for 10 chunks measured since its last reset: the last 5 against the 5 before them (`2 * WINDOW` in `bin/reading_cost/figures.py`). Both stay at 10.
Valid while no published standard sets either number, the reading-cost window stays 5, and until lilleman sets another.
## 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.
## 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
2026-10-08, lilleman. Serves goal 1.1: comprehension measured from real work, at no model cost (goal 1.4). loop-claude archives from the main checkout, outside any PR, so a tracked file it wrote there would dirty that checkout. So `bin/reading-cost` measures each finished chunk `docs/reading-cost.md` lacks from the archive, in the next chunk's worktree. A PR that never merges then loses no figure, and loop-claude needs no change. The figures keep a file of their own, so `docs/comprehension-history.md` keeps one writer, the comprehension check. Serves goal 4 by naming only files git tracks, and token counts. Rejected: loop-claude opening a PR of its own, one more PR per chunk and a tie to the forge; the worker measuring its own transcript before merging, which misses the chunk's tail. The figure counts new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts.
## review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
2026-09-20, lilleman. Serves goal 1.1. Its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. Valid while `/security-review` ships both.
2026-10-08, lilleman. Serves goal 1.4: run beside the full scan, `/security-review` started seconds apart from it each round and returned a near-identical report. Valid while the full scan covers what `/security-review` reports.
## review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
2026-10-08, lilleman. Serves goal 1.4. An audit of the four costliest archived chunks found nearly every finding that mattered in a pass's first round; when every fix, a nit's included, re-entered review, 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.
2026-10-13, lilleman through todo item 97. Serves goals 1.4 and 1.5. From round 2 a pass reviews only how the chunk answered its previous round, each fix and each dismissal with its reason, and reports only one that is plainly wrong or worse than the change it answered. A fix from another pass that re-enters it is still reviewed as a first round would review it, limited to its lines. Reviewing all that changed had a reviewer find new gaps in each round's fixes, so a pass ran to its cap. Valid while round-2 findings outside a round's answers keep changing nothing a user would notice.
## review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human
2026-09-28, lilleman. Serves goal 1. One counter per pass per chunk, so no fix bounces between two passes without end. Valid while one human answers the ask, in the session or from the unmerged PR.
2026-10-13, lilleman through todo item 97, implemented by claude: the cap stays at three after later rounds were narrowed, since a lower cap would ask the human more often, against goal 1, and a third round reviews only the answers to round 2's findings, so it costs little.
The cap stays at three, lilleman ruled through todo item 97: a lower cap would ask the human more often, against goal 1, and a third round reviews only the answers to round 2's findings, so it costs little. A rerun one rung up belongs to the round it reruns, so it counts toward no cap: `review: a reviewer or comprehension seat that rules the work below standard`.
2026-10-15, lilleman through todo item 144: a rerun one rung up belongs to the round it reruns, so it counts toward no cap: `review: a reviewer or comprehension seat that rules the work below standard`.
rule-hook's `round-cap` refuses a round commit titled past round 3 unless its override reason quotes the human's yes (lilleman, todo item 214). It reads only the title's number, so a fourth commit titled round 3 passes it, while `larv-review round-count` marks that pass past the cap; `todo.md` item 220 closes the gap.
## 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.
## review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
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. 2026-10-13, lilleman: an opt-out of the comprehension check no longer ends with a chunk that ships an item naming the floor, since the floor blocks nothing. 2026-10-18, lilleman, answering the review of PR #324: a project that opts out of the comprehension check voids code health in its README too: without the check the goal has no signal, and, never measured, it would weigh four times its weight forever. `rank_todo.py` refuses the plan of such a project until its README voids it. Valid while the principles audit judges every chunk that changes code, config or tests, and while the architect's and the product-owner's findings matter only to a product with consumers.
## 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. 2026-10-13, lilleman: the comprehension check blocks nothing now, so a suspension saves only the runs. Valid while such a decision names its items and the plan item that ends it.
## review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge
@@ -70,174 +181,14 @@ A reviewer's relaunch gets the report that asked and confirms or dismisses each
Valid while the ladder orders its rungs by competence.
## review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
## review: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
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.
2026-10-13, lilleman through todo item 97, implemented by claude: from round 2 a pass reviews only how the chunk answered its previous round, each fix and each dismissal with its reason, and reports only one that is plainly wrong or worse than the change it answered. A fix from another pass that re-enters it is still reviewed as a first round would review it, limited to its lines. Reviewing all that changed had a reviewer find new gaps in each round's fixes, so a pass ran to its cap. Serves goals 1.4 and 1.5. Valid while round-2 findings outside a round's answers keep changing nothing a user would notice.
2026-10-21, todo item 120: SKILL.md §3 moved the "a fix, only where …" clauses from the pass table into one re-entry table; the rule is unchanged.
## review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
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 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. Reading the default branch one merged change at a time keeps the rule working for merge commits and squash merges alike. 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 the scoring run too, so no release ends unmeasured, unless `todo.md` marks that release renamed in a `## Renamed` section (`bin/todo_table.py` → `renames`). Valid while seats reading both versions agree more often than two absolute runs do.
2026-10-13, lilleman. No published study validates simulated reader panels as a measure of how easy code is to understand, and no test of whether the panel's signal beats its noise has run. So no ruling, score or floor blocks a merge. The runs go on, so the history keeps the scores and the places the seats found hard, for later measurement. The architect, the stability reviewer and a session filing an item read the newest places, since those places are what a chunk can improve. With nothing to block, the check runs once per chunk, on the branch as review left it, in place of a run in each architecture round and a rescore after later commits. A fallen dimension no longer calls the four scoring seats either: their scores only decided the block. The base is now the newest merged change that adds any ruling or scoring run: with worse rulings merging, a base left behind them would charge one chunk's ruling with earlier chunks' falls. The newest places are the newest scoring run's and each later ruling's places a seat voted worse, so they change with each ruling. A chunk that leaves a touched place as hard says why in its PR summary, not in a decline's record, which would outlive the place.
2026-10-17, lilleman. Serves goal 1.1. Nothing checked the 2026-10-08 validity condition. The history's successive scoring runs of one PR read changed code, not near-identical code, so they cannot stand for two absolute runs. So each release's scoring run is done twice on the same head, the second recorded under `<PR> rerun at <commit>`, and `larv-review agreement` compares two rates: how often Mid A and the inherited architect vote alike overall in paired rulings, and how often their overall scores move alike between two scoring runs on one commit. It gives no verdict until the history holds 10 such pairs of runs, as `score-outcomes` waits for 10 chunks before it shows a median. The human chose the second run's cost, four more seats per release (goal 1.4), over a weaker check on the old pairs.
## 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. 2026-10-13, lilleman: the comprehension check blocks nothing now, so a suspension saves only the runs. 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, and a project opting out of the comprehension check voids code health
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. 2026-10-13, lilleman: an opt-out of the comprehension check no longer ends with a chunk that ships an item naming the floor, since the floor blocks nothing. 2026-10-18, lilleman, answering the review of PR #324: a project that opts out of the comprehension check voids code health in its README too: without the check the goal has no signal, and, never measured, it would weigh four times its weight forever. `rank_todo.py` refuses the plan of such a project until its README voids it. Valid while the principles audit judges every chunk that changes code, config or tests, and while the architect's and the product-owner's findings matter only to a product with consumers.
## review: the principles audit runs on every chunk that changes code, config or tests, and on no other chunk
2026-10-16, lilleman, answering the question on the audit's trigger that the plan held. Serves goal 1.1: a principle that no chunk checks drifts, as the stability reviewer's own copy of the principles drifted from them, until it applied `principles/technical-principles.md` as written. It costs goal 1.4: a chunk that changes code, config or tests launches one auditor for the goals and one per applicable principles file, and a code fix re-enters them. The human accepted that cost. The cost shows in tokens per finished chunk and in review rounds per chunk. Valid while the audit's findings are drift a chunk would otherwise merge, not the same whole-project findings repeated chunk after chunk: a repeat is a question on the audit's scope for the human.
## 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.
## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
2026-09-28, lilleman. Serves goals 1 and 3: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with its outcomes beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole.
## loop-claude: a `claude` that cannot start is a failed worker run, retried
2026-09-28, larv-review, declining a product-owner nit to exit at once when `claude` is missing. Serves goal 1. Claude Code's updater repoints `~/.local/bin/claude` at each new version under running loops, and a start that meets it mid-update fails with the same error as a broken install; the retry costs two minutes on the second and saves an unattended loop on the first. Valid while Claude Code updates by repointing its link.
2026-10-23, claude. Serves code health (`CLAUDE.md` → "Shared goal"): its counter-signal, reviewers raising blockers because the implementer misunderstood the current system, had no count, since no tool recorded why a finding arose. The reviewer is the one that knows, so it marks the finding (`skills/larv-review/review-findings.md` → "Misread"). The worker counts the marked 🔴 and 🟡 findings in the round's commit title, `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, which `score-outcomes` already reads for the 🔴 and 🟡 counts, so the count needs no record of its own. rule-hook's `round-title-counts` refuses a round title without the count, or with more misread findings than findings, so a title that leaves the count out never reads as zero; titles from before the count read as unknown. Only the reviewers under `agents/` mark findings. `/security-review` marks none, so its round titles count 0 misread, and the count is a floor. A bench of three readers seated as the audience chose `[misread]` right after the severity mark, which stays at a fixed place on a skimmed line, and the parenthesis `(1 misread)`, which reads as a share of the 🔴 and 🟡 counts rather than a third kind of finding, each two to one. The other half of the counter-signal, defects that keep reappearing, waits for the later fixes that `todo.md` item 110 counts. Valid while round titles are where `score-outcomes` reads a chunk's findings.
## review: an ask no user answers leaves the PR unmerged
2026-09-30, claude. Serves goal 1: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix a finding no goal lets the run decline — the run takes it; a ❓, or a fix changing a goal or a decision, is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves.
## loop-claude: every claude it starts bypasses permissions inside its sandbox
2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the claude an interrupt opens run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names.
## review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
2026-09-20, lilleman. Serves goal 1.1. Its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. Valid while `/security-review` ships both.
2026-10-08, lilleman. Serves goal 1.4: run beside the full scan, `/security-review` started seconds apart from it each round and returned a near-identical report. Valid while the full scan covers what `/security-review` reports.
## review: the premises chunk's whole review is the human's approval
2026-09-20, lilleman. Serves goal 1.1. A reviewer's finding on that chunk could only be declined by citing the goals the chunk exists to write. Valid while every decline must name a goal or a technical principle.
## workflow-bench/: the remote may show the bench cases' names and commit SHAs
2026-10-02, lilleman. Serves goal 4, which keeps credentials, transcripts and memory files off the remote; a private project's name and commit ids are none of those. Valid while the bench names only cases and commits, never their code or results.
## todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order
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. The format is mandatory in every project, as the premises are (goal 1.3); the formula and bar are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. 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, on the bar. An item under the bar is not kept; this repo's bar started at 10 and was set to 9 the same day. An Exempt cell keeps a row past the bar where a rule needs it kept.
2026-10-02, lilleman, on the purge. Setting the bar to 9 purged the 17 items under it. 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.
2026-10-02, lilleman, on re-raising findings. 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.
2026-10-02, lilleman, on the gate check. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale.
2026-10-02, lilleman, on the `principle` exemption. 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, on the goal weights: the weights in `todo.md` depart from an even spread by position, which would weigh goal 4, leaking nothing, at 0.11.
2026-10-15, lilleman: the scores get a researched method, which `todo.md` items 149 and 151 build, after PR #283 shipped the ranking, PR #296 the risk scores and PR #298 the anchors each project names for each level in `docs/score-anchors.md`; the evidence is in `docs/scoring-and-goals-research.md`. R becomes L + E + I − 2: the chance the change holds a defect, set first by its size; the chance the defect escapes tests, review and monitoring; and the worst impact dimension, each about ×10 per level. I5, irreversible, holds R at 7 or more, and I4 at 5 or more, since a severe enough consequence outranks how unlikely it is. C goes from every table and tool: what it scored beyond size, spread and novelty, which L already holds, is complexity, which adds almost nothing once size is accounted for. Items rank by value per cost, V / 2^S, and V sums each cited achieve goal's weight times how far the item moves it. A goes, and the Audience says whose value the goals serve. R stays out of the ranking and sets how carefully an item is done; an item that lowers risk scores it as value. Each release fills by priority up to a capacity it states, in place of the bar. Each README goal is `maintain`, which vetoes an item that breaks it, or `achieve`, with a signal, a counter-signal and a one-line reason, as this README's Goals now mark them; each project keeps settled decisions to test its goals against. Each part of this method holds once the item that builds it ships. 2026-10-16, lilleman: a task's L and E + I pick its rungs in place of R, as `routing: one ladder` records.
2026-10-16, PR #283: items rank by `Score = 100 * V / 2**S`. 2**S is the cost; the 100 lets a score read to one decimal. V sums, over the achieve goals an item's Moves cell names, each goal's weight times how far the item moves it, 1 to 10. Each achieve goal, in reading order, weighs 0.97 times the one before it, and the weights sum to 1. 2026-10-18, lilleman: goals should weigh almost the same. This replaced the sum-reciprocal weight, under which the goal ranked k of n achieve goals weighed (1/k) / (1 + 1/2 + … + 1/n), so the last of twelve goals weighed a twelfth of the first. The step departs from `docs/scoring-and-goals-research.md`, where sum-reciprocal weights came closest to the weights people gave. PR #319 restored the sum-reciprocal weights on a misreading of lilleman's answer, and lilleman then confirmed the step, so the sum-reciprocal weights stay dropped. The worker picked 0.97; `GOAL_STEP` sets it. A Moves column replaces A, G and Goals, and `rank_todo.py` derives the weights from README.md, so the goal weights table and the 2026-10-08 weights are gone. An item that cited only maintain goals now names the achieve goal it moves, or, as a defect restoring one, that maintain goal, as the entry below says. A panel of three readers seated as lilleman picked the spelling: two put a Moves column holding `1.1 by 8, 1.2 by 5` first, and one put `1.1: 8` first; two chose `2**S`, since a Python reader takes `^` for XOR; all three chose one decimal of `100 * V / 2**S` over three significant digits or a log. The bar moved to 0.1, lilleman's call answering the review of PR #283: on one-decimal scores it drops an item scoring under 0.05, in practice one that moves no achieve goal, and item 149 revisits it. A table in the old shape still ranks by the formula and weights it states, and ranking it says to reshape it, so no other project's commits stop; reshaping it is that project's only work until done, as `CLAUDE.md` → "Working loop" says. PR #296 dropped the C column, and put L, E and I right before R, which `rank_todo.py` writes from them: of three readers seated as lilleman, two ranked that order first, since a reader meets each level before the R it builds and R sits beside S, and the third ranked it second, after an order with S before the levels. The old shape's ranking is valid until `todo.md` item 156.
2026-10-16, lilleman, answering the review of PR #283. An item that restores a maintain goal the project breaks today is a defect: exempt as `defect`. Its Moves name that maintain goal and how much of it is broken, and the goal weighs as the heaviest achieve goal, since a broken maintain goal outranks any achieve goal. Every defect ranks by its score, so a trivial one waits behind valuable work. Only questions and then security findings rank first in their release: a question's answer may change other items, and a question waits for the human anyway, so ranking it first delays no chunk. An item names the most specific goal it moves, and a parent only for a move none of its sub-goals covers, so a sub-goal's move does not count twice; `rank_todo.py` refuses a goal named beside its own sub-goal. Each project reshapes its own `todo.md`; `CLAUDE.md` → "Working loop" makes the reshape the only work until done, as it makes writing missing premises. An item that makes this project easier to read moves code health, as the 2026-10-18 paragraph below says, and goal 1.4, since reading cost is measured in tokens per chunk. Cost gains a fixed part, F in `Score = 100 * V / (2**S + F)`: every chunk carries a cost its size does not shrink, the reading before its first commit, about 130k tokens, and its review passes, so `2**S` alone overrated tiny items. F is 8, about one S 3 change, until `todo.md` item 158 measures it.
2026-10-16, lilleman, ruling on the plan in PR #283: release 0.2.0 takes plan items 146, 152, 73, 50, 65, 84, 153 and 67, the split of `routing: one ladder`, and the question of how many chunks `score-outcomes` and the reading-cost trend wait for, ahead of their scores, to put budget and efficiency in the other projects first. A standing goal cannot capture that priority for now, so it is a one-time ruling: the later releases, and every release after 0.2.0, fill from the score again.
2026-10-18, lilleman. Serves goal 1.1: every project shares one achieve goal, code health, which `CLAUDE.md` → "Shared goal" states once and which replaces each project's own readability goal. It ranks first among a project's achieve goals, since lilleman rates it very important while the comprehension panel's overall is under 7.0. While that overall is under 7.0, or no scoring run has measured the project, it weighs four times its weight at 7.0 or above, as `UNDER_FLOOR` sets. The overall is the mean of the overall means of every scoring run on the newest scored commit in `docs/comprehension-history.md`, as `newest_scored` finds them. Two runs of one head measure it twice, and the newest alone would let their noise flip the weight: 7.13 and 6.88 on one head of another project would have. The review of PR #324 raised this choice. Weighing code health four times as much leaves the other achieve goals' weights as they are. So crossing 7.0 changes only the scores of the items that move code health, and of the defects, since a broken maintain goal weighs as the heaviest achieve goal. `larv-review record-scoring` re-ranks `todo.md` after it appends a run. A project that opts out of the comprehension check voids the goal, as `review: a project decision may opt every chunk out …` records. A README voids the goal with `**Void:** code health, since <reason>.` under `## Goals`, and an item's Moves cell names it as in `code health by 6`. A panel of three readers seated as lilleman picked both 3-0: `code health` over `code`, `health`, `C` and `0`, and the bold `Void:` line over a sentence under `## Goals` or a line under `## Audience`. The counter-signal is stated now and counted once `todo.md` item 198 ships, since no tool yet records why a finding arose. Valid while the comprehension panel's overall is how a project measures how hard it is to read.
2026-10-15, lilleman. Serves goal 1.4: loop-claude routes a chunk's first cycle on the item the chunk takes (`routing: a chunk's worker runs on the rung its item's L picks`). An item lists the items that must be done before it starts in a Blocked by column, and `rank_todo.py` ranks each blocker above every item it blocks. The table's order is `todo.md`'s only order: `rank_todo.py` fails on text beside the table under `## Items`, since a prose order there, "Release 0.3.0 takes items 125, 114 and 124 first", contradicted the table and loop-claude could not read it. A decision that wants an order sets the scores instead. An item waits while it is marked `question` or a blocker of it is still in the table, whatever the rows' order, so a release's first row that does not wait is the item a chunk takes. A blocker the table no longer holds was finished or deleted, and is dropped, so the cell shows what still blocks. A panel of three readers seated as lilleman picked the spelling: two ranked "Blocked by" first, as the cell lists only what still blocks, and all three chose bare IDs such as `12, 14` in a column right after Release, read before the tagline and kept apart from the scores. `rank_todo.py` adds the column to a table without it. The tools read cells by column name, so a later column leaves a reader on an older release working; `rank_todo.py`, which writes every column, fails on one it does not know rather than drop it.
2026-10-18, PR #312. Serves goals 1.5 and 1.1: adf-codec renamed its next release, 0.2.1, to 0.3.0, and `chunk-preflight` then called 0.2.1 finished and stopped the loop on every cycle. A change that moves a release's last items elsewhere reads the same whether it renamed the release or deferred its leftovers, so the plan says which: a `## Renamed` section holds one line `- 0.2.1 renamed to 0.3.0` per rename, which `bin/todo_table.py`'s `renames` reads. `chunk-preflight`, `loop-claude` and larv-review's scoring-run trigger skip a marked release; they read only the first version. A release whose items moved unmarked reads as finished: the loop stops, says so and names the fix, and the trigger calls a scoring run once work has landed. So a forgotten mark costs one interrupt and never lets a release end unmeasured. `rank_todo.py` fails on a line of another shape and on an item filed under a marked release, and a newest plan whose marks do not parse leaves the next release unknown. A line goes once a tag at or past its release is cut. Only a rename is marked, since an unmarked move is the deferral. A panel of three readers seated as lilleman picked the spelling 3-0 over `- 0.2.1 → 0.3.0` under `## Releases` and a `Renamed 0.2.1 = 0.3.0` line under `## Scoring`: plain words need no special character to type. Valid while a rename is the only move of a release's items that the tools must tell from finishing it.
## todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
2026-10-15, lilleman. Serves goal 1.1: a cheaper rung writes worse scores, and a wrong score routes a chunk onto the wrong rung, ranks the plan wrong and drops an item under the bar that should stay. Below the project's rung, a session or subagent may not score an item, move it between releases, split a milestone, delete an item under the bar, or rewrite a filed item. It drafts each new item, and each change to a filed item, such as a refresh a rule asks for. Before the next commit, one subagent on the project's rung or above applies and scores the drafts. One launch covers all of a chunk's drafts (goal 1.4). A security finding gets that subagent at once, since it is filed the moment it is found. Removing a finished item closes work and plans none, so any rung does it. Scoring a delegated task's L runs on any rung too: a launch on the project's rung to score each delegation would cost more than the cheaper task saves (goal 1.4).
Three places carry the rule. `rules/todo-items.md` states it and loads with `todo.md`. `CLAUDE.md`'s delegation rule launches the scoring subagent on the rung `bin/subagent-rung --plan` prints: the one the task's L picks, never below the project's, so a hard scoring task still climbs. `bin/loop_claude/cycle/prompts.py`'s `review_launches` names the same command to a worker below the project's rung, never a fixed rung, which would disagree with `--plan` on a scoring task of L 4. Valid while a worker or subagent may run below the project's rung.
## settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
2026-10-04, lilleman, answering the principles audit of PR #215. Serves goal 1: this setup is meant to run in a sandbox and to work autonomously, so tool access is granted by the sandbox, as "Always grant explicit access to data" in `principles/technical-principles.md` asks. Valid while every machine taking this checkout is such a sandbox.
## settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
2026-10-21, lilleman. Serves goal 2: Claude Code rewrites `"model"` in `settings.json` on every `/model` and plugin install, so a tracked model let one machine's pick override every other's. lilleman chose a model per machine over one synced in `env.ANTHROPIC_MODEL`, which would override a `/model` pick from the next session on. A model per machine is simpler, and loop-claude picks each project's model in `~/.claude/loop-claude-models.json` anyway. The filter also sorts the keys, since each write puts them back in Claude Code's order. The cost: a move or pull that changes `settings.json` drops the machine's model. The effort keys, `effortLevel` and `modelSettings`, stay synced: the routing decision on a chunk's worker rung relies on the effort `settings.json` gives every interactive session. Valid while Claude Code writes the model it picks into `settings.json`.
## the repo may name bender, bender-infra and ai-sandbox
2026-10-04, lilleman, answering the principles audit of PR #215. Serves goal 4, which keeps credentials, transcripts and memory files off the remote; the names of the host, its infrastructure project and the sandbox VM are none of those. Valid while the repo names them without their addresses or credentials.
## 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
2026-10-08, lilleman. Serves goal 1.1: comprehension measured from real work, at no model cost (goal 1.4). loop-claude archives from the main checkout, outside any PR, so a tracked file it wrote there would dirty that checkout. So `bin/reading-cost` measures each finished chunk `docs/reading-cost.md` lacks from the archive, in the next chunk's worktree. A PR that never merges then loses no figure, and loop-claude needs no change. The figures keep a file of their own, so `docs/comprehension-history.md` keeps one writer, the comprehension check. Serves goal 4 by naming only files git tracks, and token counts. Rejected: loop-claude opening a PR of its own, one more PR per chunk and a tie to the forge; the worker measuring its own transcript before merging, which misses the chunk's tail. The figure counts new input tokens, uncached and cache-written, because workers read mostly through Bash and subagents, where parsed paths alone miss what they read. Valid while loop-claude archives every finished chunk with its subagents' transcripts.
## 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.
## reading cost and `score-outcomes`: each waits for 10 finished chunks before it shows a median
2026-10-16, lilleman, confirmed when asked. Serves goal 1.2: the answer is written once, so the same question is not asked again.
`score-outcomes` shows a score's medians only where 10 finished chunks that each shipped one item hold an outcome for that score (`ENOUGH` in `bin/score_outcomes/outcomes.py`). The reading-cost trend waits for 10 chunks measured since its last reset: the last 5 against the 5 before them (`2 * WINDOW` in `bin/reading_cost/figures.py`). Both stay at 10.
Valid while no published standard sets either number, the reading-cost window stays 5, and until lilleman sets another.
## 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. 2026-10-16, lilleman, answering plan item 166: `reviewer-rung` is the one rule no marker overrides; the comment above it in `bin/rule_hook/rules.py` says why. 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. loop-claude's judge and the prose reviewer read them, and the stability reviewer reads "Quality". 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.
## tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
2026-10-16, lilleman asked for research on what makes tests valuable, then for these changes; claude drafted them. Serves goal 1.1, since a test that cannot catch a bug, or breaks without one, lowers quality and costs review rounds.
An audit of 196 tests sampled across eight projects found about 61% clearly valuable. Of all 196, 15% pinned wording that is not the contract, such as whole prompt sentences; 9% copied or policed the implementation, such as scanning the source with `ast`; 6% ran on real time or heavy resources; and 6% asserted something no bug could break, such as a list's length. The bullet follows these sources:
- A valuable test fails when behaviour breaks, passes after a refactor, asserts state over interactions and keeps its expected outcome narrow: *Software Engineering at Google*, chapters 11, 12 and 14; Fowler, "The Practical Test Pyramid"; Beck, "Test Desiderata"; Khorikov, *Unit Testing: Principles, Practices, and Patterns*, chapter 4.
- A test that never failed on its assertion may be tautological: Seemann, blog.ploeh.dk, 2019-10-14.
- Tests whose expected values come from the code's current output pass on a bug and fail on its fix: Charoosaei et al., arXiv 2610.11835, a preprint; Mathews & Nagappan, arXiv 2412.14137.
- Agents add mocks to tests more often than people do: Hora & Robbes, MSR 2026, arXiv 2602.00409.
- Coverage barely predicts fault detection: Inozemtseva & Holmes, ICSE 2014. Surviving mutants do predict real faults: Just et al., FSE 2014; Google's mutation testing in code review, arXiv 2102.11378.
The decision `worker: a chunk's worker writes the simplest change…` has the worker read a principle only where something names it. A reviewer sees only the finished test, so cannot tell whether a literal in it was copied from the code's output. So the rule on expected values also stands in `CLAUDE.md` → "Working loop", "Implement the simplest change that solves the item, and ship it with `/larv-review`", and the stability reviewer holds a change to the whole bullet.
Valid while the worker writes the tests that larv-review's reviewers hold to the principles.
## review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`
2026-10-18, lilleman through todo item 73. Serves goal 1.4: a report the worker does not need line by line no longer fills its context. Goal 1.1 holds because the worker reads a finding's full entry before it answers a 🔴 or 🟡.
@@ -258,6 +209,32 @@ Valid while Claude Code passes `agent_type` to hooks inside a subagent. Without
2026-10-13, lilleman through todo item 97, implemented by claude. Serves goals 1.4 and 1.5. Anthropic's Claude Code best practices: "A reviewer prompted to find gaps will usually report some, even when the work is sound… Chasing every finding leads to over-engineering." 320 of this repo's 876 commits answered a review round. So stability and product-owner drop a finding that is none of these, and stability leaves the style of comments to prose, which reads every comment a chunk touches. An architect finding that names no later change it makes harder cannot be checked, so it is dropped. The architecture pass and the comprehension check keep their whole-project view, which guards goal 1.1 as a project grows. Valid while the findings these rules drop keep changing nothing a user would notice.
2026-10-28, lilleman: prose findings stay, since Claude's prose needs them, though prose's 105 first rounds since 2026-10-21 raised 498 🟡 and only 3 🔴.
## review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
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 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 the scoring run too, so no release ends unmeasured, unless `todo.md` marks that release renamed in a `## Renamed` section (`bin/todo_table.py` → `renames`). Valid while seats reading both versions agree more often than two absolute runs do.
2026-10-13, lilleman. No published study validates simulated reader panels as a measure of how easy code is to understand, and no test of whether the panel's signal beats its noise has run. So no ruling, score or floor blocks a merge. The runs go on, so the history keeps the scores and the places the seats found hard, for later measurement. The architect, the stability reviewer and a session filing an item read the newest places: the newest scoring run's and each later ruling's places a seat voted worse. Those are the places a chunk can improve. The check runs once per chunk, on the branch as review left it. A chunk that leaves a touched place as hard says why in its PR summary, not in a decline's record, which would outlive the place.
The base is the last measured commit: the default branch's newest merged change that adds any ruling or scoring run. The human chose it 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. Reading the default branch one merged change at a time keeps the rule working for merge commits and squash merges alike. With worse rulings merging, a base left behind them would charge one chunk's ruling with earlier chunks' falls.
2026-10-17, lilleman. Serves goal 1.1. Nothing checked the 2026-10-08 validity condition. The history's successive scoring runs of one PR read changed code, not near-identical code, so they cannot stand for two absolute runs. So each release's scoring run is done twice on the same head, the second recorded under `<PR> rerun at <commit>`, and `larv-review agreement` compares two rates: how often Mid A and the inherited architect vote alike overall in paired rulings, and how often their overall scores move alike between two scoring runs on one commit. It gives no verdict until the history holds 10 such pairs of runs, as `score-outcomes` waits for 10 chunks before it shows a median. The human chose the second run's cost, four more seats per release (goal 1.4), over a weaker check on the old pairs.
## review: the premises chunk's whole review is the human's approval
2026-09-20, lilleman. Serves goal 1.1. A reviewer's finding on that chunk could only be declined by citing the goals the chunk exists to write. Valid while every decline must name a goal or a technical principle.
## review: the principles audit runs on every chunk that changes code, config or tests, reads the project whole with one auditor checking the goals and every principles file that applies, and runs on no other chunk
2026-10-16, lilleman, answering the question on the audit's trigger that the plan held. Serves goal 1.1: a principle that no chunk checks drifts, as the stability reviewer's own copy of the principles drifted from them, until it applied `principles/technical-principles.md` as written. It costs goal 1.4: a chunk that changes code, config or tests launches an auditor, and a code fix re-enters it. The human accepted that cost. The cost shows in tokens per finished chunk and in review rounds per chunk. Valid while the audit's findings are drift a chunk would otherwise merge, not the same whole-project findings repeated chunk after chunk: a repeat is a question on the audit's scope for the human.
2026-10-27, lilleman, answering the question PR #376 raised: the audit keeps reading the project whole. Since 2026-10-21, 342 auditor runs cost $274 at list prices, and of their 176 🔴 and 🟡 findings that named a file, 90 named one the chunk did not edit, which reading only the change would drop; lilleman keeps them.
2026-10-28, claude, through todo item 233. Serves goal 1.4. One auditor per round checks the README's goals with code health, and each principles file that applies. It reads the project once, where one auditor per goal set or file ran 3.8 times per chunk before.
A trial checked that it keeps goal 1.1. It replayed the 6 latest first rounds that launched two or more auditors, at most two per project, from this repo, `log`, `visthus` and `adf-codec`: 15 auditors, whose reports held 40 🔴 and 🟡 findings. Each round ran on the project's rung as `review-replay` replays it, once with its separate auditors and once with one auditor handed everything they checked, its new definition passed through `--agents`. A replayed reviewer finds a different part of its findings each time: the separate auditors found only 10 of their own 40 again. The one auditor found 12, among them 8 of those 10. So it finds as much as the separate auditors do. It missed two 🟡s on a missing or weak test, and found 4 findings they missed. No principles file keeps an auditor of its own. Asked whether those two misses should bring back separate auditors for the technical principles and for the goals with code health, lilleman chose to try the one auditor. Valid until the auditor's definition changes or a new model joins the ladder: replay the pass then, as this trial did.
## review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
2026-10-13, lilleman through todo item 108, implemented by claude. Serves goals 1.1 and 1.4. Coverage counts the lines a test runs, so a test without a meaningful assertion still raises it. A surviving mutant shows a test that would let behaviour break. Every mutant of an untested changed line survives, so mutation testing of the changed lines also shows what a coverage drop on them would. Coverage would also catch a deleted test; the stability reviewer sees one in the diff without it. Measuring coverage beside it would add cost without raising quality, so todo item 69 was dropped and `principles/technical-principles.md` replaced "Test coverage should not decline" with the mutant rule.
@@ -268,18 +245,6 @@ The run has no time cap. Limiting it to the changed lines already bounds it by t
Valid while a mutation run on a chunk's changed lines stays cheap beside the review itself.
## routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
2026-10-14, lilleman. Serves goal 1.4, and goal 1.3: one ladder, the same in every project, read by loop-claude and by the worker through `bin/subagent-rung`. The judge's rung is set by `routing: on a model judge-replay covered`. `bin/model_routing/ladder.py` holds the rungs and the steps.
The rungs, least competent first: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models, read 2026-10-14), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). That cut drops Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index falls among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scores it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price.
A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. A model off the ladder routes nothing: claude runs it at the effort its settings give. A task's L steps its worker from the project's rung: 1 and 2 one down, 3 none, 4 one up. Its E + I steps its reviewers up from the project's rung: 4 or less none, 5 one up, 6 two up, 7 three up, 8 four up. A step past either end stops there. A worker errs more the more it changes and the newer that is, which L scores; review must look harder the further a defect would escape and the more it would break, which E + I scores (goals 1.1 and 1.4). Size raises L, so a large change runs its worker higher. The steps spread the values this repo's plan held when rescored on 2026-10-16, L 1 to 4 and E + I 2 to 7, so a worker on most items runs at or below the project's rung, and a review climbs only where a defect would escape far or break much. lilleman approved the first steps on 2026-10-16 as a guess: `score-outcomes` reports how well L, E and I each order finished chunks by review rounds and 🔴 findings, and `todo.md` item 170 re-tunes the steps once 10 chunks have shipped under the steps that hold today. A change to the ladder or the steps is lilleman's.
2026-10-21, lilleman, settling the routing calls stamped 2026-10-21T20:33:29Z: L 1 steps one rung down, not two as before, so an Opus 5.5 project runs no worker on Haiku 5.5. A delegated subagent takes the same steps, so an L 1 search moves off Haiku 5.5 too: lilleman chose one set of steps for chunk workers and subagents alike, so loop-claude, `subagent-rung` and rule-hook read one table (code health). No figure yet shows whether Sonnet 5.5 searches better than Haiku 5.5, so this costs more per search for a gain nobody has measured (goal 1.4). The calls came from loop-claude's routing figures, measured at cycle 165 over 46 chunks. Chunks started on Haiku 5.5 at max took a mean 7.8 review rounds past each pass's first, against 2.8 on Sonnet 5.5 at high, and 0.2 unfinished verdicts, against 0.1. The figures also called for moving workers off Sonnet 5.5 at high, whose chunks took 0.1 unfinished verdicts against 0.0 on Opus 5.5 at medium. lilleman kept L 2 on Sonnet 5.5, since that gap rests on one or two verdicts.
Valid while the index ranks these models, and while no newer model joins the catalog.
## routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass; the seats and the security pass always on the project's
2026-10-14, lilleman. Serves goals 1.1 and 1.4.
@@ -292,21 +257,23 @@ On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on ei
Valid until the trial on real chunks shows whether a worker below the project's rung holds quality.
## routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
## routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
2026-10-14, lilleman. Serves goal 1.4.
2026-10-15, lilleman proposed running the stability reviewer on the worker's rung, and the agent proposed the replay that gates it. On 2026-10-16 lilleman asked for the prose pass to run on the worker's rung or lower, and, answering PR #296, for every pass to drop below the project's rung only where a replay shows it may. Serves goal 1.4 without giving up goal 1.1: a cheaper reviewer saves money only where it misses nothing.
Because a model switch inside a session discards its prompt cache, the worker changes rung only as the chunk starts, after every second unfinished verdict, when the judge reports a taken-in item whose L picks a higher rung, or when the judge finds the escalation trigger a worker cites in asking for a higher rung (`routing: a worker whose run ends asking for a higher rung`). loop-claude routes on the first row of the next release in `todo.md`'s table that does not wait: an item waits while it is marked `question` or a blocker of it is still in the table. Since `todo.md` holds no order but its table's (`todo.md: one table`), that row is the item the worker takes. An item the worker takes in beyond that row lifts the worker's rung once the judge reports it, after the first cycle.
`bin/review-replay <pass> <model>` replays a pass's archived rounds on the code each reviewed. It replays them first on the project's rung, then on each rung below it, highest first, down to the ladder's lowest. It stops at the first rung that misses a finding the project's rung found again. A rung qualifies only where it and each rung above it find every such 🔴 and 🟡.
Valid while a model switch inside a session discards its prompt cache.
`REPLAYED` in `bin/model_routing/ladder.py` holds each qualifying rung, by pass and project model. Where the chunk's E + I steps no review up and the worker runs no higher than the project's rung, the pass runs on that rung, even below the worker's. Otherwise the pass runs where every other pass does: the replay compared reviews on the project's rung only, never reviews on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung.
## routing: loop-claude measures review rounds and unfinished verdicts per rung every 20 cycles, and calls for a routing change when, of two rungs with 5 or more chunks each, the lower took more of either than the one above, or when 5 or more subagents of one type had reports longer than the tool results they read
The runs, each on the latest 10 rounds of Opus 5.5 projects that hold a 🔴 or 🟡:
2026-10-15, lilleman. Serves goals 1.2 and 1.4.
- 2026-10-15, stability: 40 findings, 8 of the rounds from this repo. Opus 5.5 at medium, the project's rung, found 29 of them again. Sonnet 5.5 at high missed 13 of those 29, 2 of them 🔴. No rung qualifies.
- 2026-10-18, prose: 39 findings. The project's rung found 27 of them again. Sonnet 5.5 at high missed 12 of those 27. No rung qualifies.
- 2026-10-18, stability again, since that day's change to the reviewer prompts expired the first run: 29 findings. The project's rung found 20 of them again. Sonnet 5.5 at high missed 11 of those 20, 1 of them 🔴. No rung qualifies.
The cost of a cheaper worker shows as extra review rounds and unfinished verdicts. Every 20 cycles across the archive, loop-claude measures them in code, with no model run (goal 1.4), and interrupts lilleman with the calls not raised before, when chunks routed onto a rung took more of either than chunks routed onto the next rung up, each rung with 5 chunks or more. Five keeps one odd chunk from calling for a change (goal 1.2). It also calls when the reports of 5 or more subagents of one type were longer than the tool results they read, so a delegated search cost the worker more context than it saved. `bin/routing_figures/` measures and words the calls. A loop on another project cannot commit here, so it writes the figures and the calls raised at the archive's root, and this repo's next chunk files the plan item, as `AGENTS.md` says. Off a terminal, a call is said on stderr and the loop goes on: it is about this setup, not the running project's chunk. A reset line in the calls file restarts the figures after a routing change, so they show whether the change worked.
The prose pass went first: a missed prose finding breaks no behaviour, and a later change fixes it cheaply. Sonnet 5.5 missed 44 to 55% of what the project's rung found again, in the prose pass as in both stability runs. Nothing suggests the other passes' findings are easier to find. So the architecture, principles, overrides and product-owner passes are not replayed yet: a replay would spend money with little chance of a qualifying rung (goal 1.4). `todo.md` item 196 keeps their replays in the plan. Every pass runs where `routing: a chunk's worker runs on the rung its item's L picks` puts every reviewer.
Since 2026-10-16 the reviewers may run above the worker's rung, on the one the highest E + I among their chunk's items picks, so chunks whose worker ran on a lower rung may take more rounds from stronger reviewers, and a call could blame the worker's rung for them; `todo.md` item 171 groups the rounds by the reviewers' rung too. Valid while loop-claude's archive holds every finished chunk's review rounds and unfinished verdicts.
Valid until a new model joins the ladder, which calls for a replay of every pass, or a pass's reviewer prompt changes, which calls for a replay of that pass.
## routing: a worker delegates a task only where it needs just the task's conclusion, and each subagent runs on the rung its task's L picks from the project's rung, never below the project's rung when it files or scores todo.md items
@@ -342,6 +309,14 @@ The archive quotes the judge's passage under `Escalation:` in the unfinished ver
Valid while the worker reports in its transcript the triggers that fired, and while a chunk's session transcript only grows.
## routing: loop-claude measures review rounds and unfinished verdicts per rung every 20 cycles, and calls for a routing change when, of two rungs with 5 or more chunks each, the lower took more of either than the one above, or when 5 or more subagents of one type had reports longer than the tool results they read
2026-10-15, lilleman. Serves goals 1.2 and 1.4.
The cost of a cheaper worker shows as extra review rounds and unfinished verdicts. Every 20 cycles across the archive, loop-claude measures them in code, with no model run (goal 1.4), and interrupts lilleman with the calls not raised before, when chunks routed onto a rung took more of either than chunks routed onto the next rung up, each rung with 5 chunks or more. Five keeps one odd chunk from calling for a change (goal 1.2). It also calls when the reports of 5 or more subagents of one type were longer than the tool results they read, so a delegated search cost the worker more context than it saved. `bin/routing_figures/` measures and words the calls. A loop on another project cannot commit here, so it writes the figures and the calls raised at the archive's root, and this repo's next chunk files the plan item, as `AGENTS.md` says. Off a terminal, a call is said on stderr and the loop goes on: it is about this setup, not the running project's chunk. A reset line in the calls file restarts the figures after a routing change, so they show whether the change worked.
Since 2026-10-16 the reviewers may run above the worker's rung, on the one the highest E + I among their chunk's items picks, so chunks whose worker ran on a lower rung may take more rounds from stronger reviewers, and a call could blame the worker's rung for them; `todo.md` item 171 groups the rounds by the reviewers' rung too. Valid while loop-claude's archive holds every finished chunk's review rounds and unfinished verdicts.
## routing: on a model judge-replay covered, the judge runs on the rung a review would get from the highest E + I among its chunk's items, never below the project's rung
2026-10-15, lilleman's plan, settled by the replay below. Serves goals 1.2 and 1.4, under the ladder and steps of `routing: one ladder`.
@@ -354,38 +329,112 @@ Only Opus 5.5 was replayed, so the judge of a project on another model keeps the
Valid while the archived verdicts show what a judge should return, and until a new model joins the ladder: replay then.
## routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
## routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
2026-10-15, lilleman proposed running the stability reviewer on the worker's rung, and the agent proposed the replay that gates it. On 2026-10-16 lilleman asked for the prose pass to run on the worker's rung or lower, and, answering PR #296, for every pass to drop below the project's rung only where a replay shows it may. Serves goal 1.4 without giving up goal 1.1: a cheaper reviewer saves money only where it misses nothing.
2026-10-14, lilleman. Serves goal 1.4, and goal 1.3: one ladder, the same in every project, read by loop-claude and by the worker through `bin/subagent-rung`. The judge's rung is set by `routing: on a model judge-replay covered`. `bin/model_routing/ladder.py` holds the rungs and the steps.
`bin/review-replay <pass> <model>` replays a pass's archived rounds on the code each reviewed. It replays them first on the project's rung, then on each rung below it, highest first, down to the ladder's lowest. It stops at the first rung that misses a finding the project's rung found again. A rung qualifies only where it and each rung above it find every such 🔴 and 🟡.
The rungs, least competent first: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models, read 2026-10-14), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). That cut drops Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index falls among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scores it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price.
`REPLAYED` in `bin/model_routing/ladder.py` holds each qualifying rung, by pass and project model. Where the chunk's E + I steps no review up and the worker runs no higher than the project's rung, the pass runs on that rung, even below the worker's. Otherwise the pass runs where every other pass does: the replay compared reviews on the project's rung only, never reviews on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung.
A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. A model off the ladder routes nothing: claude runs it at the effort its settings give. A task's L steps its worker from the project's rung: 1 and 2 one down, 3 none, 4 one up. Its E + I steps its reviewers up from the project's rung: 4 or less none, 5 one up, 6 two up, 7 three up, 8 four up. A step past either end stops there. A worker errs more the more it changes and the newer that is, which L scores; review must look harder the further a defect would escape and the more it would break, which E + I scores (goals 1.1 and 1.4). Size raises L, so a large change runs its worker higher. The steps spread the values this repo's plan held when rescored on 2026-10-16, L 1 to 4 and E + I 2 to 7, so a worker on most items runs at or below the project's rung, and a review climbs only where a defect would escape far or break much. lilleman approved the first steps on 2026-10-16 as a guess: `score-outcomes` reports how well L, E and I each order finished chunks by review rounds and 🔴 findings, and `todo.md` item 170 re-tunes the steps once 50 chunks have shipped under the steps that hold today. A change to the ladder or the steps is lilleman's.
The runs, each on the latest 10 rounds of Opus 5.5 projects that hold a 🔴 or 🟡:
2026-10-21, lilleman, settling the routing calls stamped 2026-10-21T20:33:29Z: L 1 steps one rung down, not two as before, so an Opus 5.5 project runs no worker on Haiku 5.5. A delegated subagent takes the same steps, so an L 1 search moves off Haiku 5.5 too: lilleman chose one set of steps for chunk workers and subagents alike, so loop-claude, `subagent-rung` and rule-hook read one table (code health). No figure yet shows whether Sonnet 5.5 searches better than Haiku 5.5, so this costs more per search for a gain nobody has measured (goal 1.4). The calls came from loop-claude's routing figures, measured at cycle 165 over 46 chunks. Chunks started on Haiku 5.5 at max took a mean 7.8 review rounds past each pass's first, against 2.8 on Sonnet 5.5 at high, and 0.2 unfinished verdicts, against 0.1. The figures also called for moving workers off Sonnet 5.5 at high, whose chunks took 0.1 unfinished verdicts against 0.0 on Opus 5.5 at medium. lilleman kept L 2 on Sonnet 5.5, since that gap rests on one or two verdicts.
- 2026-10-15, stability: 40 findings, 8 of the rounds from this repo. Opus 5.5 at medium, the project's rung, found 29 of them again. Sonnet 5.5 at high missed 13 of those 29, 2 of them 🔴. No rung qualifies.
- 2026-10-18, prose: 39 findings. The project's rung found 27 of them again. Sonnet 5.5 at high missed 12 of those 27. No rung qualifies.
- 2026-10-18, stability again, since that day's change to the reviewer prompts expired the first run: 29 findings. The project's rung found 20 of them again. Sonnet 5.5 at high missed 11 of those 20, 1 of them 🔴. No rung qualifies.
2026-10-23, lilleman: 15 chunks had shipped under today's steps. Over them, L's rank correlation with review rounds was +0.53. They held only 3 🔴 findings, too few to test E and I. 50 chunks hold about 10 at that rate, and a re-tune on fewer chunks would fit noise.
The prose pass went first: a missed prose finding breaks no behaviour, and a later change fixes it cheaply. Sonnet 5.5 missed 44 to 55% of what the project's rung found again, in the prose pass as in both stability runs. Nothing suggests the other passes' findings are easier to find. So the architecture, principles, overrides and product-owner passes are not replayed yet: a replay would spend money with little chance of a qualifying rung (goal 1.4). `todo.md` item 196 keeps their replays in the plan. Every pass runs where `routing: a chunk's worker runs on the rung its item's L picks` puts every reviewer.
Valid while the index ranks these models, and while no newer model joins the catalog.
Valid until a new model joins the ladder, which calls for a replay of every pass, or a pass's reviewer prompt changes, which calls for a replay of that pass.
## routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
## principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
2026-10-14, lilleman. Serves goal 1.4.
2026-10-22, lilleman asked for a rule of seven that holds at every level and is never a hard rule. Serves code health: a reader new to the project should take in each level at once. The numbers follow the sources below, since no single study sets them.
Because a model switch inside a session discards its prompt cache, the worker changes rung only as the chunk starts, after every second unfinished verdict, when the judge reports a taken-in item whose L picks a higher rung, or when the judge finds the escalation trigger a worker cites in asking for a higher rung (`routing: a worker whose run ends asking for a higher rung`). loop-claude routes on the first row of the next release in `todo.md`'s table that does not wait: an item waits while it is marked `question` or a blocker of it is still in the table. Since `todo.md` holds no order but its table's (`todo.md: one table`), that row is the item the worker takes. An item the worker takes in beyond that row lifts the worker's rung once the judge reports it, after the first cycle.
- Seven is Mark Seemann's figure in *Code That Fits in Your Head* (2021). He says the exact number matters less than having a limit the team agrees on ([Tech Lead Journal #89](https://techleadjournal.dev/episodes/89/)). The 24 lines of 80 characters are his too ([The 80/24 rule](https://blog.ploeh.dk/2019/11/04/the-80-24-rule/)).
- Four or five for things that act on each other: working memory holds about four chunks once rehearsal and grouping are blocked (Cowan, ["The magical number 4 in short-term memory"](https://www.cambridge.org/core/journals/behavioral-and-brain-sciences/article/magical-number-4-in-shortterm-memory-a-reconsideration-of-mental-storage-capacity/44023F1147D4A1D44BDC0AD226838496), 2001). Sandi Metz's rules allow four parameters, and Fowler's long-parameter-list smell starts at three or four.
- More for things found by name: a reader recognises an item in a list, so a list's length is no memory limit (Nielsen Norman Group, [Short-term memory and web usability](https://www.nngroup.com/articles/short-term-memory-and-web-usability/)). Menu studies find depth costs more than breadth, and broad levels of 16 to 64 items beat narrow ones when their labels are clear (Larson & Czerwinski, [1998](https://www.microsoft.com/en-us/research/publication/web-page-design-implications-memory-structure-scent-information-retrieval/); Dix et al., [menu breadth](https://hcibook.com/e3/online/menu-breadth)).
- A split must save more than it costs: in an eye-tracking study, extracting methods cut reading time on hard tasks and raised it on simple ones (a 2026 preprint with 32 novices, [arXiv 2602.18579](https://arxiv.org/abs/2602.18579)). John Ousterhout's deep modules and John Carmack's case for inlined code argue the same against splitting by size.
- A grouping or a recorded reason, never a split at any cost: no study supports a fixed cut-off for function length, parameter count or nesting. Re-analysis of the cited data finds no optimal function length ([Derek Jones, 2023](https://shape-of-code.com/2023/09/10/optimal-function-length-an-analysis-of-the-cited-data/)),. So a limit holds only while the comprehension panel's readers find the code it flags hard, and `agents/systems-architect.md` → "Fits in a head" says how its reviewer rates a unit past one.
Valid while a model switch inside a session discards its prompt cache.
Valid while the comprehension panel measures how hard a project is to read.
## 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
## chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
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. 2026-10-16, lilleman, answering plan item 166: `reviewer-rung` is the one rule no marker overrides; the comment above it in `bin/rule_hook/rules.py` says why. 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.
2026-10-22, lilleman, through todo item 217. Serves goal 1.4: each review has a fixed cost, so more items per chunk cost less per item. Across the 165 finished chunks loop-claude archived up to that day, a chunk took a median of 1.30M tokens with one item and 1.33M with two, and three in four chunks shipped one item. The old rule also asked one PR title to state what the items achieve together; lilleman dropped it, since unrelated items that fire the same passes cost one review.
## 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
The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the highest R among a chunk's items, the median was 0.9M to 1.5M tokens at R 1 to 5, and 2.7M at R 6, where the 90th percentile was 8.8M. A risky item that runs long re-runs review over every item bundled with it. R 5 is also the least R an I 4 item gets, so an item that could take everything down shares a chunk only where its L + E is 3 or less, and an irreversible I 5 item, at R 7 or more, never does. Valid while a review's cost is mostly fixed per chunk; revisit once 30 chunks have shipped bundles under it.
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.
## settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
2026-10-04, lilleman, answering the principles audit of PR #215. Serves goal 1: this setup is meant to run in a sandbox and to work autonomously, so tool access is granted by the sandbox, as "Always grant explicit access to data" in `principles/technical-principles.md` asks. Valid while every machine taking this checkout is such a sandbox.
## settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
2026-10-21, lilleman. Serves goal 2: Claude Code rewrites `"model"` in `settings.json` on every `/model` and plugin install, so a tracked model let one machine's pick override every other's. lilleman chose a model per machine over one synced in `env.ANTHROPIC_MODEL`, which would override a `/model` pick from the next session on. A model per machine is simpler, and loop-claude picks each project's model in `~/.claude/loop-claude-models.json` anyway. The filter also sorts the keys, since each write puts them back in Claude Code's order. The cost: a move or pull that changes `settings.json` drops the machine's model. The effort keys, `effortLevel` and `modelSettings`, stay synced: the routing decision on a chunk's worker rung relies on the effort `settings.json` gives every interactive session. Valid while Claude Code writes the model it picks into `settings.json`.
## tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
2026-10-16, lilleman asked for research on what makes tests valuable, then for these changes; claude drafted them. Serves goal 1.1, since a test that cannot catch a bug, or breaks without one, lowers quality and costs review rounds.
An audit of 196 tests sampled across eight projects found about 61% clearly valuable. Of all 196, 15% pinned wording that is not the contract, such as whole prompt sentences; 9% copied or policed the implementation, such as scanning the source with `ast`; 6% ran on real time or heavy resources; and 6% asserted something no bug could break, such as a list's length. The bullet follows these sources:
- A valuable test fails when behaviour breaks, passes after a refactor, asserts state over interactions and keeps its expected outcome narrow: *Software Engineering at Google*, chapters 11, 12 and 14; Fowler, "The Practical Test Pyramid"; Beck, "Test Desiderata"; Khorikov, *Unit Testing: Principles, Practices, and Patterns*, chapter 4.
- A test that never failed on its assertion may be tautological: Seemann, blog.ploeh.dk, 2019-10-14.
- Tests whose expected values come from the code's current output pass on a bug and fail on its fix: Charoosaei et al., arXiv 2610.11835, a preprint; Mathews & Nagappan, arXiv 2412.14137.
- Agents add mocks to tests more often than people do: Hora & Robbes, MSR 2026, arXiv 2602.00409.
- Coverage barely predicts fault detection: Inozemtseva & Holmes, ICSE 2014. Surviving mutants do predict real faults: Just et al., FSE 2014; Google's mutation testing in code review, arXiv 2102.11378.
The decision `worker: a chunk's worker writes the simplest change…` has the worker read a principle only where something names it. A reviewer sees only the finished test, so cannot tell whether a literal in it was copied from the code's output. So the rule on expected values also stands in `CLAUDE.md` → "Working loop", "Implement the simplest change that solves the item, and ship it with `/larv-review`", and the stability reviewer holds a change to the whole bullet.
Valid while the worker writes the tests that larv-review's reviewers hold to the principles.
## the repo may name bender, bender-infra and ai-sandbox
2026-10-04, lilleman, answering the principles audit of PR #215. Serves goal 4, which keeps credentials, transcripts and memory files off the remote; the names of the host, its infrastructure project and the sandbox VM are none of those. Valid while the repo names them without their addresses or credentials.
## todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order
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. The format is mandatory in every project, as the premises are (goal 1.3); the formula and bar are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. 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, on the bar. An item under the bar is not kept, and an Exempt cell keeps a row past the bar where a rule needs it kept. Since 2026-10-16 the bar is 0.1, lilleman's call answering the review of PR #283: on one-decimal scores it drops an item scoring under 0.05, in practice one that moves no achieve goal, and item 149 revisits it.
2026-10-02, lilleman, on re-raising findings. 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.
2026-10-02, lilleman, on the gate check. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale.
2026-10-02, lilleman, on the `principle` exemption. 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-15, lilleman: the scores follow a researched method, built by `todo.md` items 149 and 151 after PR #283 shipped the ranking, PR #296 the risk scores and PR #298 the anchors each project names for each level in `docs/score-anchors.md`; the evidence is in `docs/scoring-and-goals-research.md`. R is L + E + I − 2: the chance the change holds a defect, set first by its size; the chance the defect escapes tests, review and monitoring; and the worst impact dimension, each about ×10 per level. I5, irreversible, holds R at 7 or more, and I4 at 5 or more, since a severe enough consequence outranks how unlikely it is. R stays out of the ranking and sets how carefully an item is done; an item that lowers risk scores it as value. A task's L and E + I pick its rungs in place of R (2026-10-16, lilleman), as `routing: one ladder` records. There is no C column: what it scored beyond size, spread and novelty, which L already holds, is complexity, and that adds almost nothing once size is accounted for. There is no A column either, since the Audience says whose value the goals serve. Each README goal is `maintain`, which vetoes an item that breaks it, or `achieve`, with a signal, a counter-signal and a one-line reason, as this README's Goals mark them. Two parts are not built yet and hold once their items ship: each release fills by priority up to a capacity it states (item 149), and each project keeps 10 to 20 settled decisions to test its goals against (item 151).
2026-10-16, PR #283: items rank by `Score = 100 * V / (2**S + F)`. The 100 lets a score read to one decimal. V sums, over the achieve goals an item's Moves cell names, each goal's weight times how far the item moves it, 1 to 10. A Moves column holds `1.1 by 8, 1.2 by 5`, and `rank_todo.py` derives the weights from README.md. Each achieve goal, in reading order, weighs 0.97 times the one before it, and the weights sum to 1; The worker picked 0.97, and `GOAL_STEP` sets it. lilleman wanted goals to weigh almost the same on 2026-10-18, since under the sum-reciprocal weight the goal ranked k of n achieve goals weighed (1/k) / (1 + 1/2 + … + 1/n), so the last of twelve goals weighed a twelfth of the first. The step departs from `docs/scoring-and-goals-research.md`, where sum-reciprocal weights came closest to the weights people gave. PR #319 restored the sum-reciprocal weights on a misreading of lilleman's answer, and lilleman then confirmed the step, so they stay dropped. An item that cited only maintain goals names the achieve goal it moves, or, as a defect restoring one, that maintain goal, as the defect paragraph below says. 2**S is the cost, and F is the fixed part every chunk carries that its size does not shrink: the reading before its first commit, about 130k tokens, and its review passes, so `2**S` alone overrated tiny items. F is 8, about one S 3 change, until `todo.md` item 158 measures it. A panel of three readers seated as lilleman picked the spelling: two put a Moves column holding `1.1 by 8, 1.2 by 5` first, and one put `1.1: 8` first; two chose `2**S`, since a Python reader takes `^` for XOR; all three chose one decimal of `100 * V / 2**S` over three significant digits or a log. The columns L, E and I sit right before R, which `rank_todo.py` writes from them: of three readers seated as lilleman, two ranked that order first, since a reader meets each level before the R it builds and R sits beside S, and the third ranked it second, after an order with S before the levels. A table in the old shape still ranks by the formula and weights it states, and ranking it says to reshape it, so no other project's commits stop; reshaping it is that project's only work until done, as `CLAUDE.md` → "Working loop" says. The old shape's ranking is valid until `todo.md` item 156.
2026-10-16, lilleman, answering the review of PR #283. An item that restores a maintain goal the project breaks today is a defect: exempt as `defect`. Its Moves name that maintain goal and how much of it is broken, and the goal weighs as the heaviest achieve goal, since a broken maintain goal outranks any achieve goal. Every defect ranks by its score, so a trivial one waits behind valuable work. Only questions and then security findings rank first in their release: a question's answer may change other items, and a question waits for the human anyway, so ranking it first delays no chunk. An item names the most specific goal it moves, and a parent only for a move none of its sub-goals covers, so a sub-goal's move does not count twice; `rank_todo.py` refuses a goal named beside its own sub-goal. Each project reshapes its own `todo.md`; `CLAUDE.md` → "Working loop" makes the reshape the only work until done, as it makes writing missing premises. An item that makes this project easier to read moves code health, as the paragraph below says, and goal 1.4, since reading cost is measured in tokens per chunk.
2026-10-18, lilleman. Serves goal 1.1: every project shares one achieve goal, code health, which `CLAUDE.md` → "Shared goal" states once and which replaces each project's own readability goal. It ranks first among a project's achieve goals, since lilleman rates it very important while the comprehension panel's overall is under 7.0. While that overall is under 7.0, or no scoring run has measured the project, it weighs four times its weight at 7.0 or above, as `UNDER_FLOOR` sets. The overall is the mean of the overall means of every scoring run on the newest scored commit in `docs/comprehension-history.md`, as `newest_scored` finds them. Two runs of one head measure it twice, and the newest alone would let their noise flip the weight: 7.13 and 6.88 on one head of another project would have. The review of PR #324 raised this choice. Weighing code health four times as much leaves the other achieve goals' weights as they are. So crossing 7.0 changes only the scores of the items that move code health, and of the defects, since a broken maintain goal weighs as the heaviest achieve goal. `larv-review record-scoring` re-ranks `todo.md` after it appends a run. A project that opts out of the comprehension check voids the goal, as `review: a project decision may opt every chunk out …` records. A README voids the goal with `**Void:** code health, since <reason>.` under `## Goals`, and an item's Moves cell names it as in `code health by 6`. A panel of three readers seated as lilleman picked both 3-0: `code health` over `code`, `health`, `C` and `0`, and the bold `Void:` line over a sentence under `## Goals` or a line under `## Audience`. `score-outcomes` counts the counter-signal's misread findings per chunk, as `review: a reviewer under …` records. Valid while the comprehension panel's overall is how a project measures how hard it is to read.
2026-10-15, lilleman. Serves goal 1.4: loop-claude routes a chunk's first cycle on the item the chunk takes (`routing: a chunk's worker runs on the rung its item's L picks`). An item lists the items that must be done before it starts in a Blocked by column, and `rank_todo.py` ranks each blocker above every item it blocks. The table's order is `todo.md`'s only order: `rank_todo.py` fails on text beside the table under `## Items`, since a prose order there, "Release 0.3.0 takes items 125, 114 and 124 first", contradicted the table and loop-claude could not read it. A decision that wants an order sets the scores instead. An item waits while it is marked `question` or a blocker of it is still in the table, whatever the rows' order, so a release's first row that does not wait is the item a chunk takes. A blocker the table no longer holds was finished or deleted, and is dropped, so the cell shows what still blocks. A panel of three readers seated as lilleman picked the spelling: two ranked "Blocked by" first, as the cell lists only what still blocks, and all three chose bare IDs such as `12, 14` in a column right after Release, read before the tagline and kept apart from the scores. `rank_todo.py` adds the column to a table without it. The tools read cells by column name, so a later column leaves a reader on an older release working; `rank_todo.py`, which writes every column, fails on one it does not know rather than drop it.
2026-10-18, PR #312. Serves goals 1.5 and 1.1: adf-codec renamed its next release, 0.2.1, to 0.3.0, and `chunk-preflight` then called 0.2.1 finished and stopped the loop on every cycle. A change that moves a release's last items elsewhere reads the same whether it renamed the release or deferred its leftovers, so the plan says which: a `## Renamed` section holds one line `- 0.2.1 renamed to 0.3.0` per rename, which `bin/todo_table.py`'s `renames` reads. `chunk-preflight`, `loop-claude` and larv-review's scoring-run trigger skip a marked release; they read only the first version. A release whose items moved unmarked reads as finished: the loop stops, says so and names the fix, and the trigger calls a scoring run once work has landed. So a forgotten mark costs one interrupt and never lets a release end unmeasured. `rank_todo.py` fails on a line of another shape and on an item filed under a marked release, and a newest plan whose marks do not parse leaves the next release unknown. A line goes once a tag at or past its release is cut. Only a rename is marked, since an unmarked move is the deferral. A panel of three readers seated as lilleman picked the spelling 3-0 over `- 0.2.1 → 0.3.0` under `## Releases` and a `Renamed 0.2.1 = 0.3.0` line under `## Scoring`: plain words need no special character to type. Valid while a rename is the only move of a release's items that the tools must tell from finishing it.
## todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
2026-10-15, lilleman. Serves goal 1.1: a cheaper rung writes worse scores, and a wrong score routes a chunk onto the wrong rung, ranks the plan wrong and drops an item under the bar that should stay. Below the project's rung, a session or subagent may not score an item, move it between releases, split a milestone, delete an item under the bar, or rewrite a filed item. It drafts each new item, and each change to a filed item, such as a refresh a rule asks for. Before the next commit, one subagent on the project's rung or above applies and scores the drafts. One launch covers all of a chunk's drafts (goal 1.4). A security finding gets that subagent at once, since it is filed the moment it is found. Removing a finished item closes work and plans none, so any rung does it. Scoring a delegated task's L runs on any rung too: a launch on the project's rung to score each delegation would cost more than the cheaper task saves (goal 1.4).
Three places carry the rule. `rules/todo-items.md` states it and loads with `todo.md`. `CLAUDE.md`'s delegation rule launches the scoring subagent on the rung `bin/subagent-rung --plan` prints: the one the task's L picks, never below the project's, so a hard scoring task still climbs. `bin/loop_claude/cycle/prompts.py`'s `review_launches` names the same command to a worker below the project's rung, never a fixed rung, which would disagree with `--plan` on a scoring task of L 4. Valid while a worker or subagent may run below the project's rung.
## 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. loop-claude's judge and the prose reviewer read them, and the stability reviewer reads "Quality". 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.
## workflow-bench/: the remote may show the bench cases' names and commit SHAs
2026-10-02, lilleman. Serves goal 4, which keeps credentials, transcripts and memory files off the remote; a private project's name and commit ids are none of those. Valid while the bench names only cases and commits, never their code or results.
+100
View File
@@ -795,3 +795,103 @@ Read most (opens and searches):
## Reading cost, chunk 1034c157d8d2, finished 2026-10-22T19:29:13Z
100386 new input tokens before the first commit.
## Reading cost, chunk a38d4733c268, finished 2026-10-22T20:33:05Z
207415 new input tokens before the first commit.
## Reading cost, chunk f3378f0f2d3d, finished 2026-10-23T01:21:28Z
123377 new input tokens before the first commit.
Read most (opens and searches):
- `skills/larv-review/SKILL.md` 1
## Reading cost, chunk 1bc51e408577, finished 2026-10-23T02:06:21Z
126580 new input tokens before the first commit.
## Reading cost, chunk ed7548905fbb, finished 2026-10-23T02:32:52Z
68233 new input tokens before the first commit.
## Reading cost, chunk 0603c74b6f13, finished 2026-10-23T03:25:23Z
129754 new input tokens before the first commit.
Read most (opens and searches):
- `rules/todo-items.md` 3
## Reading cost, chunk a22f0c603ee3, finished 2026-10-23T03:33:28Z
89103 new input tokens before the first commit.
Read most (opens and searches):
- `rules/decisions.md` 1
## Reading cost, chunk bd159bdb7400, finished 2026-10-23T03:39:31Z
56989 new input tokens before the first commit.
## Reading cost, chunk b2665c534486, finished 2026-10-23T08:28:54Z
194384 new input tokens before the first commit.
Read most (opens and searches):
- `bin/score_outcomes/main.py` 3
- `bin/score_outcomes/outcomes.py` 2
- `docs/decisions.md` 2
- `rules/todo-items.md` 2
- `docs/score-anchors.md` 1
## Reading cost, chunk a4941f71602f, finished 2026-10-23T09:16:58Z
125323 new input tokens before the first commit.
Read most (opens and searches):
- `skills/larv-review/SKILL.md` 2
## Reading cost, chunk 68b123f977ca, finished 2026-10-23T12:33:45Z
169569 new input tokens before the first commit.
Read most (opens and searches):
- `rules/decisions.md` 1
## Reading cost, chunk e94dd7a98ff8, finished 2026-10-23T12:59:22Z
71809 new input tokens before the first commit.
## Reading cost, chunk 53a20666ad09, finished 2026-10-28T08:42:33Z
141210 new input tokens before the first commit.
Read most (opens and searches):
- `bin/transcript_archive/outcomes.py` 1
## Reading cost, chunk 6164ac372ce5, finished 2026-10-28T08:48:34Z
94183 new input tokens before the first commit.
## Reading cost, chunk 22d616a7a912, finished 2026-10-28T10:14:46Z
116420 new input tokens before the first commit.
## Reading cost, chunk b25d0b8f6319, finished 2026-10-28T11:11:03Z
221959 new input tokens before the first commit.
## Reading cost, chunk c596ec8546d0, finished 2026-10-28T11:37:19Z
83591 new input tokens before the first commit.
Read most (opens and searches):
- `rules/decisions.md` 1
+1 -1
View File
@@ -32,7 +32,7 @@
"type": "command"
}
],
"matcher": "Bash|Edit|MultiEdit|Write|Agent"
"matcher": "Agent|Bash|Edit|MultiEdit|Read|Write"
}
]
},
+17 -9
View File
@@ -5,7 +5,7 @@ description: Ship a work chunk through review to a merged PR; decisions land in
# larv-review — ship the chunk, review until clean, gate green, merge
You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchronously (`run_in_background: false`) and watch CI in the foreground: a headless run exits when the turn ends, and a background watcher dies with it. Never schedule a wakeup: a pending one keeps a headless run from exiting, so loop-claude neither runs its judge nor asks the human. The turn runs on until §6.
You orchestrate, fix, and ship; reviewers only report. Run every reviewer in the foreground (`run_in_background: false`), each wave's reviewers in one message (§3 → "Waves"), and watch CI in the foreground: a headless run exits when the turn ends, and a background watcher dies with it. Never schedule a wakeup: a pending one keeps a headless run from exiting, so loop-claude neither runs its judge nor asks the human. The turn runs on until §6.
**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.
@@ -24,6 +24,8 @@ The bar a chunk is reviewed to: ~/.claude/skills/larv-review/standards/quality.m
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.
**Work in the worktree.** Enter the chunk's worktree with the `EnterWorktree` tool, `path` set to it, unless the session already works there. A reviewer, a seat and the security pass's skill read the diff of the session's working directory, and a subagent starts there; from the checkout root they find the branch's diff empty.
**Reading cost.** Run `~/.claude/bin/reading-cost` in the chunk's worktree, unless loop-claude's prompt shows that `chunk-preflight` already ran it there, 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
@@ -41,13 +43,19 @@ A pass is one kind of review, a row of the table, named by its first column. Its
| 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 | changes prose a reader reads, such as docs, comments, help or error text, or the plan; one round |
A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work.
A comment is prose, not code.
**Waves.** Launch a round's passes in up to three waves. Launch each wave's reviewers in one message: Agent calls in one message run together, so a wave lasts as long as its slowest reviewer. Start a wave only once every pass of the waves before it is done ("Round cap" → "Done"): line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. Skip a wave none of whose passes runs.
1. Architecture.
2. Principles, with Full scan or Security, and Overrides.
3. Stability, Product-owner and Prose.
Give a reviewer without Bash the branch diff and `git ls-files`'s output in its prompt: some harnesses grant it Read alone.
`~/.claude/bin/larv-review` holds this section's mechanical rules: the chunk's review folder, the round count, the paired ruling's base and vote count, the scoring run's trigger, and the history's format and latest places, and its count of how often seats agree. Run it in the chunk's worktree; `~/.claude/bin/larv-review --help` states each rule. On exit 1, repair what its message names and run it again; when you cannot, ask the user.
**Reports.** Run `~/.claude/bin/larv-review review-folder` in the chunk's worktree: it makes the chunk's review folder and prints its path. In each prompt to an agent under `~/.claude/agents/`, name the file in that folder for its full report: `<pass>-round-<n>.md`. For a principles-auditor, use `principles-<yardstick>-round-<n>.md`. For a relaunch one rung up, add `-rerun` before `.md`. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names.
**Reports.** Run `~/.claude/bin/larv-review review-folder` in the chunk's worktree: it makes the chunk's review folder and prints its path. In each prompt to an agent under `~/.claude/agents/`, name the file in that folder for its full report: `<pass>-round-<n>.md`. For a relaunch one rung up, add `-rerun` before `.md`. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names.
**Precedent, then ask** — for the architecture pass and the full scan:
@@ -64,13 +72,13 @@ Give a reviewer without Bash the branch diff and `git ls-files`'s output in its
**Round cap.**
- **Round.** A round is one review by a pass's reviewer: the first, each re-entry, and the rerun after the architect returns Stage 0 questions ("Architecture" below). A relaunch one rung up ("Rung up" below) stays in its round.
- **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. Title it `Answer <pass> round <n>: <k> 🔴, <m> 🟡; …`: `<pass>` is the pass's name in lower case, such as `full scan`, and `<k>` and `<m>` are the 🔴 and 🟡 findings all the round's reviewers reported. Example: `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`. 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 `Record the comprehension check:` commit.
- **Auto-reviewer.** The external auto-reviewer (§4) is a pass of its own, each review it posts a round. Its count is the number of its reviews on the PR, less its reviews of a `Record the comprehension check:` commit, and `round-count` doesn't list it. A commit that answers one of its rounds takes an ordinary title, not an `Answer <pass> round` one, and a round that changed nothing gets no commit.
- **Count.** Close each round of a pass other than the auto-reviewer with one commit that holds the round's fixes. Title it `Answer <pass> round <n>: <k> 🔴, <m> 🟡 (<j> misread); …`: `<pass>` is the pass's name in lower case, such as `full scan`, `<k>` and `<m>` are the 🔴 and 🟡 findings all the round's reviewers reported, and `<j>` is how many of those they marked `[misread]` (review-findings.md → "Misread"); a reviewer that marks none, such as `/security-review`, adds 0. Example: `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); flag a deleted test`. 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.
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings", or settled in the PR summary per "Comprehension check" → "Places", or, for the prose pass, fixed. Resolve that round's 🟢s and ❓s per "Findings" too.
- **Cap.** A pass takes at most three rounds per chunk. Instead of a fourth, list what is open and ask the user. For the auto-reviewer, ask before the push that would summon its fourth, and hold the fixes unpushed until the answer.
- **Answer.** A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged.
- **Answer.** A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. rule-hook refuses a round commit titled past round 3 unless its `round-cap` override quotes the yes.
**Re-entry.** A fix is a change no pass has seen. A fix for a 🟢, a ❓ or a prose finding reruns no pass, whatever it changes. A round's fixes for 🔴 and 🟡 findings re-enter together: run, in the pass table's order, every pass that a row below names for any of them, a done pass included, then §4. A pass at its cap gets "Round cap" → "Cap"'s ask instead.
**Re-entry.** A fix is a change no pass has seen. A fix for a 🟢, a ❓ or a prose finding reruns no pass, whatever it changes. A round's fixes for 🔴 and 🟡 findings re-enter together: run every pass that a row below names for any of them, a done pass included, in the waves of "Waves", then §4. A pass at its cap gets "Round cap" → "Cap"'s ask instead.
| The fix | Reruns |
|---------|--------|
@@ -110,7 +118,7 @@ Launch systems-architect: review the system as a whole entered through this chan
### Principles
Launch principles-auditor on the trigger in §3: one for the README's goals and code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it, and one per file in `~/.claude/principles/` whose `Applies to` line the project meets, judged from the README, `git ls-files` and the branch diff. A file without the line applies to every project. Unsure → launch it.
Launch one principles-auditor on the trigger in §3, so the project is read once per round. Hand it the README's goals and code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it, and each file in `~/.claude/principles/` whose `Applies to` line the project meets, judged from the README, `git ls-files` and the branch diff. A file without the line applies to every project. Unsure → hand it the file.
### Comprehension check
@@ -136,7 +144,7 @@ The comprehension check records how hard the project is for its contributor to r
### Security
`/security-review` over the branch diff is the pass of record, except where the full scan runs on the same change and replaces it. Where the full scan fires but does not run — skipped on a precedent, declined at its cost prompt, or unavailable — `/security-review` runs. Launch a general-purpose subagent that invokes it through the Skill tool, edits nothing, and replies with the skill's report, or that the skill is unavailable. Invoked in your own context, the skill ends your turn on that report. Open its prompt, and that of any subagent that runs the full scan, with `You are the security pass for this chunk.`: rule-hook reads that sentence as a security launch.
`/security-review` over the branch diff is the pass of record, except where the full scan runs on the same change and replaces it. Where the full scan fires but does not run — skipped on a precedent, declined at its cost prompt, or unavailable — `/security-review` runs. Launch a general-purpose subagent that invokes it through the Skill tool, edits nothing, and replies with the skill's report, or that the skill is unavailable. Invoked in your own context, the skill ends your turn on that report. Open this subagent's prompt, and that of any subagent that runs the full scan, with `You are the security pass for this chunk.`: rule-hook reads that sentence as a security launch.
A verified HIGH inside this chunk's blast radius is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which.
+5 -1
View File
@@ -14,6 +14,10 @@ A reviewer reads and reports; it edits nothing. It writes no file but its report
A finding against a technical principle names it and the file under `~/.claude/principles/` it lives in. A finding against `~/.claude/skills/larv-review/standards/quality.md` names that file and the rule it breaks.
## Misread
Mark a 🔴 or 🟡 `[misread]`, right after its severity mark, where it arose because the implementer misread code that shipped before this change: a wrong belief about what that code does, what a name means or what a contract promises. Don't mark a finding about a defect in the change's own new code. `score-outcomes` counts the marked findings per chunk, as code health's counter-signal (`~/.claude/CLAUDE.md` → "Shared goal").
## Verdict
A review's first line, derived from the findings:
@@ -31,7 +35,7 @@ Where your report holds a finding against `~/.claude/skills/larv-review/standard
Write your full report with the Write tool to the file your prompt names. The file is the worker's input, which it searches for each finding's entry, so write it even where your harness says to return findings directly. It holds the verdict, then every finding with its place, its evidence and its fix, as your agent file shapes them. Then return only:
- the verdict line
- one line per finding, in this order: its severity mark, its place, and what is wrong, in one sentence. Where the finding breaks `standards/quality.md` or a file under `~/.claude/principles/`, end the line with that file's name. For a 🔀, end it with the reviewer it names. Example: ``🟡 `bin/example.py:42` `parse`: an empty line raises IndexError (technical-principles.md)``
- one line per finding, in this order: its severity mark, `[misread]` where you marked the finding so, its place, and what is wrong, in one sentence. Where the finding breaks `standards/quality.md` or a file under `~/.claude/principles/`, end the line with that file's name. For a 🔀, end it with the reviewer it names. Example: ``🟡 `bin/example.py:42` `parse`: an empty line raises IndexError (technical-principles.md)``
- for stability-reviewer, whether the tests passed, and at which commit
- `Rerun one rung up`, where your report ends with it
- the report's path
+159 -105
View File
@@ -6,123 +6,127 @@
`Bar = 0.1`
`Next ID = 219`
`Next ID = 251`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 211 | 0.4.0 | | | **State each routing rule once, in the docstring of the code that enforces it, and cut `loop-claude --help`'s routing paragraph to what the human running the loop needs.** | 2 | 2 | 1 | 3 | 4 | code health by 9, 1.4 by 9 | 32.9 |
| 212 | 0.4.0 | | | **Split `review_launches` into a choice of each pass's rung, made in `bin/model_routing` beside `ladder.review_rungs`, and whole prompt sentences that render that choice.** | 2 | 2 | 3 | 5 | 4 | code health by 9 | 26.9 |
| 214 | 0.4.0 | | | **Have rule-hook refuse a round commit past round 3 of its pass, unless an override quotes the human's answer, so a program holds the round cap.** | 2 | 1 | 3 | 4 | 3 | code health by 3, 1.1 by 3 | 16.6 |
| 172 | 0.4.0 | | | **Name the project's rung `project` across `bin/loop_claude`, in place of `anchor`, as `bin/model_routing/ladder.py` names it.** | 2 | 1 | 3 | 4 | 3 | code health by 3, 1.4 by 3 | 16.5 |
| 210 | 0.4.0 | | | **Hold the escalation mark in one module that states that one trigger buys one step, so a reader changes it without opening four files.** | 3 | 2 | 3 | 6 | 5 | code health by 9 | 16.2 |
| 190 | 0.4.0 | | | **Rewrite the `docs/decisions.md` entries `todo.md: one table …`, `loop-claude: a judge decides …` and `loop-claude: before it opens claude …` as the current state, so a reader no longer replays superseded paragraphs to learn what holds.** | 2 | 2 | 1 | 3 | 3 | code health by 3, 1.4 by 2 | 15.5 |
| 82 | 0.4.0 | | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 2 | 2 | 1 | 3 | 4 | code health by 4, 1.4 by 4 | 14.6 |
| 216 | 0.4.0 | | | **Make larv-review's round count agree with itself on the auto-reviewer: either title its round commits so `round-count` counts them as a pass, or have SKILL.md say they carry no `Answer <pass> round` title.** | 1 | 2 | 3 | 4 | 2 | code health by 2 | 12.0 |
| 170 | 0.4.0 | | decision | **Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 10 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.** | 2 | 2 | 3 | 5 | 2 | 1.1 by 3, 1.4 by 5 | 10.9 |
| 125 | 0.4.0 | | decision | **Give "record", "outcome" and "places" one meaning each across `bin/`, and rename `bin/larv_review/git.py` by what it holds.** | 3 | 1 | 3 | 5 | 5 | code health by 5, 1.4 by 3 | 10.2 |
| 198 | 0.4.0 | | decision | **Count, per finished chunk, the findings that arose from misreading code that had already shipped, so code health's counter-signal shows.** | 3 | 2 | 2 | 5 | 5 | code health by 3, 1.1 by 2 | 6.2 |
| 59 | 0.4.0 | | | **Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.** | 2 | 1 | 3 | 4 | 3 | 1.4 by 6 | 6.0 |
| 167 | 0.4.0 | | | **Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.** | 3 | 2 | 3 | 6 | 2 | 1.1 by 4 | 5.6 |
| 6 | 0.4.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 3 | 3 | 3 | 7 | 3 | 1.1 by 5 | 5.3 |
| 1 | 0.5.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 |
| 218 | 0.5.0 | 170 | | **Drop `LEGACY_WORKER` from `bin/model_routing/route.py`, so `route_from` reads only the JSON record.** | 1 | 2 | 1 | 2 | 1 | code health by 2 | 14.4 |
| 123 | 0.5.0 | | | **Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.** | 2 | 1 | 2 | 3 | 5 | code health by 5, 1.4 by 5 | 11.0 |
| 139 | 0.5.0 | | | **Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.** | 3 | 1 | 2 | 4 | 5 | code health by 5, 1.4 by 5 | 11.0 |
| 158 | 0.5.0 | | decision | **Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 |
| 215 | 0.5.0 | | | **Decode a reload's handed JSON with a decoder for `LoopRun` and its `Route`, in place of `decoded_as`'s generic one with its two sentinels and `Route.fits` hook.** | 2 | 1 | 3 | 4 | 3 | code health by 2 | 9.0 |
| 49 | 0.5.0 | | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 6 | 8.4 |
| 105 | 0.5.0 | | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 6 | 8.0 |
| 162 | 0.5.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 7.8 |
| 175 | 0.5.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 7.8 |
| 183 | 0.5.0 | | | **Merge the two 2026-10-13 paragraphs of `docs/decisions.md` → `loop-claude: a judge decides each interrupt …` into one.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 7.2 |
| 184 | 0.5.0 | | | **Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 7.2 |
| 116 | 0.5.0 | | | **Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 5 | 7.0 |
| 203 | 0.5.0 | | | **Make `bin/repo_checks` fail on a `todo.md` citation of a `docs/decisions.md` title that no heading holds.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 5 | 7.0 |
| 113 | 0.5.0 | | | **Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.** | 3 | 2 | 2 | 5 | 4 | 1.1 by 5, 1.4 by 5 | 6.8 |
| 112 | 0.5.0 | | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 6 | 6.3 |
| 124 | 0.5.0 | | decision | **Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.** | 4 | 1 | 3 | 6 | 6 | code health by 5, 1.4 by 3 | 5.7 |
| 81 | 0.5.0 | | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4 | 5.6 |
| 102 | 0.5.0 | | | **Give loop-claude's retry delay an environment override, so the black-box test stops replacing `time.sleep` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 4 | 5.6 |
| 173 | 0.5.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 |
| 101 | 0.5.0 | | principle | **Have `larv_review/record.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 5 | 5.3 |
| 110 | 0.5.0 | | | **Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.** | 3 | 2 | 2 | 5 | 5 | 1.1 by 6, 1.4 by 6 | 4.9 |
| 12 | 0.5.0 | | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 6 | 4.2 |
| 135 | 0.5.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 4.2 |
| 171 | 0.5.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 4.0 |
| 196 | 0.5.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and add any rung a run qualifies to `REPLAYED`.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 4.0 |
| 68 | 0.5.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 3.5 |
| 181 | 0.5.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
| 192 | 0.5.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
| 193 | 0.5.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 3.4 |
| 194 | 0.5.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
| 202 | 0.5.0 | | | **Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 3.4 |
| 77 | 0.5.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 3.2 |
| 4 | 0.5.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 3.2 |
| 187 | 0.5.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 3.0 |
| 149 | 0.5.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 3.0 |
| 165 | 0.5.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 2.9 |
| 151 | 0.5.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 2.9 |
| 156 | 0.5.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 2.8 |
| 201 | 0.5.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 2.6 |
| 5 | 0.5.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 2.5 |
| 155 | 0.5.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 3 | 2 | 2 | 5 | 5 | 1.4 by 6 | 2.4 |
| 51 | 0.5.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 2.1 |
| 169 | 0.5.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.1 |
| 174 | 0.5.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 2 | 1.1 by 1 | 1.4 |
| 197 | 0.5.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 2 | 2 | 3 | 5 | 2 | 1.5 by 1 | 1.3 |
| 52 | 0.5.0 | | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 4 | 3 | 4 | 9 | 6 | 1.1 by 4 | 0.9 |
| 246 | 0.4.0 | | owner | **Give each review pass at most two rounds per chunk, with no third round and no ask for one: a fix answering round 2 merges once the gate passes.** | 3 | 2 | 3 | 6 | 3 | 1.2 by 5, 1.5 by 3, 1.4 by 2 | 10.0 |
| 244 | 0.4.0 | | owner | **Open every line loop-claude prints to its terminal with the machine's local time, as in `2026-10-28 11:46:01`.** | 2 | 2 | 1 | 3 | 3 | 1.5 by 2 | 1.9 |
| 247 | 0.4.0 | | owner | **Count each finished chunk's escaped defects, the later commits that fix code it shipped, in `score-outcomes` and the routing figures.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4 | 1.7 |
| 243 | 0.4.0 | | owner | **Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4 | 0.9 |
| 226 | 0.5.0 | | question | **Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 2, 1.5 by 2 | 4.0 |
| 248 | 0.5.0 | | question | **Answer whether the `rule-hook:` decision should name every rule that takes no override, `repeat-read`, `reviewer-report` and `reviewer-rung`, with each one's reason.** | 1 | 2 | 1 | 2 | 1 | 1.2 by 2 | 3.3 |
| 250 | 0.5.0 | | | **Move the repeat-read rule's transcript, mtime and file reads from `bin/rule_hook/main.py` into `bin/rule_hook/repeat_read.py`, behind one `*_breaches` entry point like the other rules, and name the tuple `results_on` returns.** | 2 | 1 | 3 | 4 | 3 | code health by 3 | 13.5 |
| 235 | 0.5.0 | | decision | **Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and file an item where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 2, 1.4 by 3 | 6.8 |
| 167 | 0.5.0 | | | **Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.** | 3 | 2 | 3 | 6 | 2 | 1.1 by 4 | 5.6 |
| 6 | 0.5.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 3 | 3 | 3 | 7 | 3 | 1.1 by 5 | 5.3 |
| 240 | 0.5.0 | | decision | **Give loop-claude's worker prompt the reading rule "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context", and keep it only where the 20 chunks after it hold the 20 before's review rounds, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk.** | 1 | 2 | 3 | 4 | 2 | 1.4 by 3 | 4.0 |
| 249 | 0.5.0 | | | **Have rule-hook's Edit, MultiEdit and Write checks read only a regular file, so a FIFO or device as `file_path` no longer hangs or floods the hook.** | 1 | 1 | 3 | 3 | 2 | 1.5 by 2 | 2.6 |
| 1 | 0.6.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 |
| 229 | 0.6.0 | | | **Keep the rule for which commands reach run-heavy's docker beside that docker in `bin/run_heavy/capped_docker.py`, so rule-hook's `docker-run-memory` asks it instead of repeating run-heavy's PATH rules.** | 2 | 1 | 3 | 4 | 2 | code health by 3 | 18.0 |
| 219 | 0.6.0 | | | **Name the project's rung `project` in `bin/judge_replay/main.py`, `bin/subagent_rung/main.py` and `bin/review_replay/main.py`, in place of `anchor`, as `bin/model_routing/ladder.py` and `bin/loop_claude` name it.** | 1 | 1 | 3 | 3 | 2 | code health by 2 | 12.0 |
| 224 | 0.6.0 | | | **Split `docs/decisions.md` → `todo.md: one table of items, …`'s 420-word scoring paragraph into one paragraph per choice, and drop the sentences that tell how the goal weights changed.** | 1 | 1 | 1 | 1 | 2 | code health by 2 | 12.0 |
| 123 | 0.6.0 | | | **Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.** | 2 | 1 | 2 | 3 | 5 | code health by 5, 1.4 by 5 | 11.0 |
| 139 | 0.6.0 | | | **Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.** | 3 | 1 | 2 | 4 | 5 | code health by 5, 1.4 by 5 | 11.0 |
| 158 | 0.6.0 | | decision | **Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 |
| 215 | 0.6.0 | | | **Decode a reload's handed JSON with a decoder for `LoopRun` and its `Route`, in place of `decoded_as`'s generic one with its two sentinels and `Route.fits` hook.** | 2 | 1 | 3 | 4 | 3 | code health by 2 | 9.0 |
| 237 | 0.6.0 | | principle | **Give `judge` and `judge_once` in `bin/loop_claude/cycle/judge.py` a record of the inputs they share, in place of nine and eight parameters, or record why they stay.** | 2 | 1 | 2 | 3 | 3 | code health by 2 | 9.0 |
| 242 | 0.6.0 | | principle | **Run each case of a table-driven test in its own `subTest`, and split each test that checks several behaviours, so one failure does not hide the others and names its case.** | 2 | 1 | 1 | 2 | 3 | code health by 2 | 9.0 |
| 49 | 0.6.0 | | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 6 | 8.4 |
| 105 | 0.6.0 | | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 6 | 8.0 |
| 162 | 0.6.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 7.8 |
| 175 | 0.6.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 7.8 |
| 230 | 0.6.0 | | | **Have larv-review file one ambitious refactor item, aimed at the lowest-scoring dimension, whenever a scoring run leaves any score under 7.0, so such a project always holds a plan item meant to reach 7.0.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 7, 1.2 by 4 | 7.7 |
| 184 | 0.6.0 | | | **Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 7.2 |
| 221 | 0.6.0 | | | **Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`.** | 3 | 1 | 3 | 5 | 5 | code health by 4 | 7.2 |
| 116 | 0.6.0 | | | **Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 5 | 7.0 |
| 203 | 0.6.0 | | | **Make `bin/repo_checks` fail on a `todo.md` citation of a `docs/decisions.md` title that no heading holds.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 5 | 7.0 |
| 113 | 0.6.0 | | | **Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.** | 3 | 2 | 2 | 5 | 4 | 1.1 by 5, 1.4 by 5 | 6.8 |
| 112 | 0.6.0 | | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 6 | 6.3 |
| 124 | 0.6.0 | | decision | **Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.** | 4 | 1 | 3 | 6 | 6 | code health by 5, 1.4 by 3 | 5.7 |
| 81 | 0.6.0 | | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4 | 5.6 |
| 173 | 0.6.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 |
| 101 | 0.6.0 | | principle | **Have `larv_review/history_commands.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 5 | 5.3 |
| 110 | 0.6.0 | | decision | **Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.** | 3 | 2 | 2 | 5 | 5 | 1.1 by 6, 1.4 by 6 | 4.9 |
| 12 | 0.6.0 | | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 6 | 4.2 |
| 102 | 0.6.0 | | | **Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 3 | 1.1 by 4 | 4.2 |
| 135 | 0.6.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 4.2 |
| 171 | 0.6.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 4.0 |
| 196 | 0.6.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and add any rung a run qualifies to `REPLAYED`.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 4.0 |
| 68 | 0.6.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 3.5 |
| 181 | 0.6.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
| 192 | 0.6.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
| 193 | 0.6.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 3.4 |
| 194 | 0.6.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
| 202 | 0.6.0 | | | **Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 3.4 |
| 77 | 0.6.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 3.2 |
| 4 | 0.6.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 3.2 |
| 187 | 0.6.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 3.0 |
| 220 | 0.6.0 | | decision | **Have rule-hook also count a pass's earlier round commits on the branch, so a fourth commit titled round 3 is refused too.** | 3 | 2 | 3 | 6 | 3 | 1.4 by 3 | 3.0 |
| 149 | 0.6.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 3.0 |
| 165 | 0.6.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 2.9 |
| 151 | 0.6.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 2.9 |
| 156 | 0.6.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 2.8 |
| 201 | 0.6.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 2.6 |
| 5 | 0.6.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 2.5 |
| 155 | 0.6.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 3 | 2 | 2 | 5 | 5 | 1.4 by 6 | 2.4 |
| 51 | 0.6.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 2.1 |
| 169 | 0.6.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.1 |
| 174 | 0.6.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 1 | 1.1 by 1 | 1.7 |
| 52 | 0.6.0 | | principle | **Move this checkout out of Claude Code's own directory, or record why it stays, since Claude Code loads the checkout's `AGENTS.md` as the user's instructions into every project's sessions.** | 4 | 3 | 4 | 9 | 6 | 1.1 by 4, 1.4 by 2 | 1.4 |
| 197 | 0.6.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 2 | 2 | 3 | 5 | 2 | 1.5 by 1 | 1.3 |
| 170 | 0.7.0 | | decision | **Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 50 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.** | 2 | 2 | 3 | 5 | 2 | 1.1 by 3, 1.4 by 5 | 10.9 |
| 218 | 0.7.0 | 170 | | **Drop `LEGACY_WORKER` from `bin/model_routing/route.py`, so `route_from` reads only JSON worker lines.** | 1 | 2 | 1 | 2 | 1 | code health by 2 | 14.4 |
## Details
### 211. State each routing rule once, in the docstring of the code that enforces it, and cut `loop-claude --help`'s routing paragraph to what the human running the loop needs.
### 246. Give each review pass at most two rounds per chunk, with no third round and no ask for one: a fix answering round 2 merges once the gate passes.
Release 0.3.0's scoring runs (PR #324 at c713910) named `bin/loop_claude/loop/main.py:1` "loop-claude --help" at two seats in both runs: "a 160-line spec whose routing paragraph carries about 15 rules, re-describing what routing.py, ladder.py and retry.py enforce" (Maintainability senior), and "its routing paragraphs packing every rule into one block that routed and after_verdict need open" (Junior A). Mid A named `:259` `after_verdict`: "the 164-line docstring is the only full map of routing, and after_verdict chains it all in one expression". This lowers Locality: to change `routed` or `after_verdict`, a reader opens the help for rules the code enforces. Split `after_verdict`'s one expression into named steps. Make "loop-claude --help" and `after_verdict` easier to read. Item 184 rewraps two of the help's lines.
lilleman's call, 2026-10-28, from a measurement of every repo's round titles since 2026-10-21. Round 1 ran 357 times and found 59 🔴. Round 2 ran about 200 times and found 12 🔴, mostly in round 1's fixes. Rounds 3 and later ran about 110 times and found no 🔴, at about $125 of review at list prices. Asks for a fourth or fifth round were 24 of the 59 interrupts in that time. Until this ships, lilleman answered no to a fourth principles round in PR #387, due only to tests a stability fix added after principles approved the code twice, and had the chunk merge without it.
### 212. Split `review_launches` into a choice of each pass's rung, made in `bin/model_routing` beside `ladder.review_rungs`, and whole prompt sentences that render that choice.
- Replace `docs/decisions.md` → `review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human` with the new cap, and update its title in `AGENTS.md`. Its reason for three, that a lower cap asks the human more often, no longer holds once nothing asks.
- Change `skills/larv-review/SKILL.md` → "Round cap" → "Cap", and every place it says three rounds or a fourth: the auto-reviewer included.
- Have rule-hook's `round-cap` refuse a round commit titled past round 2, with no override. Settle item 220 inside this change, since it guards the same cap; drop it if this change makes it moot.
- `bin/round_titles.py:4` `CAP` and `bin/rule_hook/rules.py:55` `round-title-counts` are places the comprehension seats found hard: the cap lives in SKILL.md prose while the code only counts. Make them easier to read.
Release 0.3.0's scoring runs named `bin/loop_claude/cycle/prompts.py:46` `review_launches` at three seats in both runs (first run: PR #324 at c713910; rerun: PR #324 rerun at c713910). Junior A, rerun: "with ladder.review_rungs, REPLAYED and escalation_rungs open at once". Mid A: "fragments that each start with a space, so no whole prompt is visible without running it in your head" (first run), and "routing policy and English wording interleaved" (rerun). Maintainability senior, rerun: "which conditional sentences reach which prompt means tracing fresh, routed_by, resumed, rungs_held and stepped_to". This lowers Locality, since choosing a rung needs the ladder's units open, and Shape, since one unit holds both policy and wording. Make `review_launches` easier to read.
### 244. Open every line loop-claude prints to its terminal with the machine's local time, as in `2026-10-28 11:46:01`.
### 214. Have rule-hook refuse a round commit past round 3 of its pass, unless an override quotes the human's answer, so a program holds the round cap.
lilleman's call, 2026-10-28, who also chose the spelling: `YYYY-MM-DD HH:MM:SS` in the machine's local time, never UTC, so the human sees when each line happened, such as how long a question has waited. Today about 27 `print` calls across `bin/loop_claude/` write bare lines to stderr. Route them through one function that adds the stamp, taking the time from `Effects.now` so tests can fix it. A line of a multi-line message, such as a question, gets the stamp only on its first line.
Release 0.3.0's inherited architect named `bin/round_titles.py:4` `CAP` in the first run (PR #324 at c713910): "no program loops the reviewers; the cap lives in SKILL.md prose and the code only counts rounds and prints a note". The same seat named `bin/rule_hook/rules.py:55` `round-title-counts` in the rerun: "no program blocks a fourth review round; rule-hook checks only the counts inside a round's title". This lowers Self-sufficiency: a reader of `CAP` must know larv-review's "Round cap" to learn what holds it. The cap is `docs/decisions.md` → `review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human`. Make `CAP` and `round-title-counts` easier to read.
### 247. Count each finished chunk's escaped defects, the later commits that fix code it shipped, in `score-outcomes` and the routing figures.
### 172. Name the project's rung `project` across `bin/loop_claude`, in place of `anchor`, as `bin/model_routing/ladder.py` names it.
lilleman's call, 2026-10-28. Escaped defects are the counter-signal of goals 1 and 1.1, and nothing counts them, so nobody can tell whether review spending prevents defects or only polishes. A review costs about 56% of a chunk's dollars. Count, for each finished chunk, the later commits on the default branch that fix lines it added: a fix item's chunk, a `defect` item, or a 🔴 marked `[misread]` whose lines `git blame` traces to the earlier chunk. Show the count per chunk and its median per rung in `score-outcomes` and `routing-figures.md`, so a cheaper review pipeline can be judged against it. Measure on every project in loop-claude's archive.
The architecture pass of PR #296 found one rung under two names: `bin/model_routing/ladder.py` calls it `project`, while `bin/loop_claude/routing.py`, `cycle/prompts.py`, `cycle/run.py`'s `Cycle.anchor` and `loop/main.py` call it `anchor`, and gloss it as "anchor, the project's rung" in docstring after docstring. A reader works out that the two are one rung each time. Make `bin/loop_claude/routing.py`'s `first_route` easier to read.
### 243. Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.
### 210. Hold the escalation mark in one module that states that one trigger buys one step, so a reader changes it without opening four files.
lilleman's call, 2026-10-28: with several loops running, each asks on its own terminal, so the human jumps between terminals to find which wait. On 2026-10-28 three of five loops waited on round-cap questions at once. Today `put_question` in `bin/loop_claude/cycle/interrupt.py` reads the answer with `input()`, and nothing outside that terminal sees a question.
Release 0.3.0's scoring runs found the mark spread out (first run: PR #324 at c713910; rerun: PR #324 rerun at c713910). `bin/model_routing/route.py:66` `Route.escalated_at`: "the escalation mark lives in six units across four files" (Junior A, first run), "one concept spread over five files" (Mid A, rerun). `bin/loop_claude/cycle/judge.py:153` `escalation_mark`: "no single place states that one trigger buys one step" (Maintainability senior, rerun). `bin/loop_claude/cycle/run.py:45` `Cycle.stepped_from` and `:69` `escalated`: "state outside the state machine, cleared on every event but HumanTyped" (Mid A, rerun). `bin/loop_claude/cycle/judge.py:216` `quotes_checked` checks the escalation against `Grounds.since_step` beside the quoted answer: "three quote checks follow different rules" (Junior A, rerun). This lowers Locality: changing the mark means opening `route.py`, `judge.py`, `run.py` and `routing.py` together. Move the mark's stamping, `STEP_LINE`, the since-step grounds and their check, and the step's state into one module, and make `stepped_from` part of the cycle's state machine. Make `Route.escalated_at`, `escalation_mark`, `Cycle.stepped_from`, `escalated` and `quotes_checked` easier to read. The archive's `Worker:` record holds the mark as `escalated_at`, so a rerun keeps it; the move keeps that field. `escalation_mark` now lives in `bin/loop_claude/verdicts.py`.
- Each loop, as it asks, writes one file per session under `~/.local/state/loop-claude/`, holding the project, the question, when it was asked, its pid and whether `/talk` is offered, and removes it once answered or stopped.
- While it waits, the loop takes the first answer from either its terminal or the app, so a loop keeps working with no app running.
- The app lists the waiting loops oldest first and sends a typed one-line answer to the loop it is meant for. A loop whose pid is gone drops off the list.
- `/talk` from the app runs `claude --resume` for that session in the app's terminal; the loop then waits, as `talk` does today, until a human turn appears in the transcript.
- A release ready to cut, which today opens the session at once, shows in the app too.
- It runs on the host's Python with the standard library, such as `curses`, as `docs/decisions.md` → `bin/: the tools and their tests run on the host's Python` has it.
### 190. Rewrite the `docs/decisions.md` entries `todo.md: one table …`, `loop-claude: a judge decides …` and `loop-claude: before it opens claude …` as the current state, so a reader no longer replays superseded paragraphs to learn what holds.
Bench the app's command name and how it shows a question with readers seated as the README's audience before it ships. An answer reaching the wrong loop is the worst failure: a test sends answers to two waiting loops and checks each gets its own. The change touches `loop-claude --help` in `bin/loop_claude/loop/main.py`, which the comprehension seats found hard: make it easier to read where it describes the interrupt.
Found by the prose review of PR #312, which judged both entries to read as amendment logs, each paragraph correcting an earlier one. The rewrite keeps each paragraph's date and reason only where it still explains a rule that holds, and drops superseded states. It covers items 157 and 183, which reshape paragraphs of the same two entries. The prose review of PR #335 found the trust entry, `loop-claude: before it opens claude …`, made of four dated paragraphs, and a 2026-10-21 paragraph on item 120 that records a move which changed no rule; drop that paragraph.
### 226. Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.
### 82. Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.
Found by review of PR #370. Today `uv run mutmut run`, `poetry run mutmut run`, `python3 -m mutmut run`, `sudo docker build .`, `docker image build .` and `docker compose up --build` pass the rule, which `docs/decisions.md` → `machine load: …` and `RULES["run-heavy"]` describe as blocking docker builds and mutation runs. The rule's own text says a gate script isn't checked since no program can tell it from a light one, so the human decides where the line sits. Say what the rule's "checked" text promises either way. Where the answer widens the rule, the change touches `heavy` in `bin/rule_hook/heavy_command.py`, which the comprehension seats found hard: make it easier to read.
"Deterministic order", in `principles/technical-principles.md`, raised by the principles audit of PR #224: their order carries no meaning, so two chunks adding a decision conflict at the end, and a reader cannot find a title by scanning.
### 248. Answer whether the `rule-hook:` decision should name every rule that takes no override, `repeat-read`, `reviewer-report` and `reviewer-rung`, with each one's reason.
### 216. Make larv-review's round count agree with itself on the auto-reviewer: either title its round commits so `round-count` counts them as a pass, or have SKILL.md say they carry no `Answer <pass> round` title.
Filed from PR #387's architecture round 1. The decision's 2026-10-16 addendum says `reviewer-rung` is the one rule no marker overrides. `reviewer-report` already took no marker, and PR #387 adds `repeat-read`, so three rules take none, each with its reason in a comment above it in `bin/rule_hook/rules.py`; only `reviewer-report`'s is also in a decision, the `review:` one. A reader of the decision, the judge included, believes every other rule takes an override. The fix rewords the title and the addendum to name all three; it changes a decision, so it is lilleman's.
`skills/larv-review/SKILL.md` §3 "Round cap" makes the external auto-reviewer a pass of its own and each review it posts a round, and says each round closes with a commit titled `Answer <pass> round <n>: <k> 🔴, <m> 🟡; …`. It also says the auto-reviewer's count is the number of its reviews on the PR. `larv-review round-count` (`bin/larv_review/main.py` `round_count`) answers an `Answer auto-reviewer round <n>:` commit with "auto-reviewer: <n>, not a pass: check the commit title", because `bin/review_passes.py` `PASSES`, the list `bin/repo_checks/test_reviewer_launches.py` holds SKILL.md's table to, leaves it out on purpose. A worker who follows the skill therefore gets a warning. Found by round 2 of PR #354's principles pass (item 121).
### 250. Move the repeat-read rule's transcript, mtime and file reads from `bin/rule_hook/main.py` into `bin/rule_hook/repeat_read.py`, behind one `*_breaches` entry point like the other rules, and name the tuple `results_on` returns.
### 170. Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 10 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.
Found by the paired ruling of PR #387: all four seats ruled Locality worse at `read_breaches`, `modified` and `first_lines` in `main.py`. The rule's reads sit there while its logic sits in `repeat_read.py`, and two contracts cross the seam: `modified` must stamp the mtime as the transcript stamps entries, since `shown_lines` compares the two as text, and `first_lines` must read one line past the last shown one, which `repeat_breaches` needs. Make these places easier to read: keep both contracts inside `repeat_read.py`, the way `todo_check.py` and `reviewer_report.py` do their own reads. Replace `results_on`'s positional four-part tuple with a named type, and rename `repeat_read.written`, which names a path while `written` in `main.py` names the text that may carry an override marker.
`docs/decisions.md` → `routing: one ladder…` calls the steps lilleman approved on 2026-10-16 a first guess. Once 10 chunks that each shipped one item scored with L, E and I have merged, read `score-outcomes`' rank correlations for L, E and I and the routed-chunks table of `routing-figures.md`, and propose new steps to lilleman, whose call they are. Only chunks merged since PR #339 set today's steps count: 7 so far, those of items 117, 126, 131, 122, 207, 130 and 154. Start this item when there are 10.
### 235. Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and file an item where any rose.
### 125. Give "record", "outcome" and "places" one meaning each across `bin/`, and rename `bin/larv_review/git.py` by what it holds.
The inherited architect of PR #257's scoring run named `bin/reading_cost/measure.py:16` `Reading` and `bin/larv_review/git.py:6` `history_changes`, and found each word used for several concepts. "Record": the history writer `larv_review/record.py`, the judge's `loop_claude/project/records.py`, and `reading_cost/figures.py`'s `RECORD`. "Outcome": `transcript_archive/outcomes.py`, `score_outcomes/outcomes.py` `Outcome` and `rule_hook/rules.py` `Outcome`. "Places": `comprehension_history.Place` and `Reading.places`. `larv_review/git.py` holds history logic, not a git runner. Make `Reading` and `history_changes` easier to read.
### 198. Count, per finished chunk, the findings that arose from misreading code that had already shipped, so code health's counter-signal shows.
Code health's counter-signal (`CLAUDE.md` → "Shared goal") has no count, since no tool records why a finding arose. Have each reviewer tag a finding that arose because the implementer misread code that had already shipped, and have `score-outcomes` count the tagged findings per finished chunk. Item 110's later fixes stand for the defects that keep reappearing.
### 59. Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.
Raised by the product-owner review of PR #211. The resumed worker gets the judge's quote of the work remaining, but a worker that still thinks the chunk done can answer each cycle the same way, and each cycle costs a worker and a judge run (goal 1.4).
`docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` expects a saving of about 6% of all spend with no rise in the other figures. Measure from loop-claude's archive as that decision did: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars at list prices, cache reads included, from the chunk's `cost-state` entry, which counts the compaction calls that no message's usage records; the routing figures now put such dollars in. A chunk ran under the window when its first worker started after that decision merged.
### 167. Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.
@@ -132,6 +136,14 @@ rule-hook checks Agent calls (item 163) but no Skill calls. A worker that invoke
Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost.
### 240. Give loop-claude's worker prompt the reading rule "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context", and keep it only where the 20 chunks after it hold the 20 before's review rounds, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk.
lilleman's call, 2026-10-27, answering PR #376's trials, recorded in `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…`: three worker-like tasks each ran four ways, as workers run today, with an outline tool, with the LSP tool and under the rule, and only the rule cut reading, by 45% to 60%, at the same or lower cost and with the tasks done as well. The rule is for workers, so it goes into the prompt loop-claude gives a chunk's worker (`bin/loop_claude/cycle/prompts.py`), not into `CLAUDE.md`, which reviewers load too and where the one reviewer run under a like rule found 2 of 6 findings. A worker that reads less may misread more, so measure the 20 chunks after the rule merges against the 20 before, as item 235 measures the compaction window, and drop the rule where any of those figures rose.
### 249. Have rule-hook's Edit, MultiEdit and Write checks read only a regular file, so a FIFO or device as `file_path` no longer hangs or floods the hook.
Found by the stability review of PR #387. `read` in `bin/rule_hook/main.py`, which serves these checks, opens the target with `pathlib.Path(path).read_text` whatever it is. A FIFO without a writer hangs rule-hook until Claude Code's hook timeout, and a path such as `/dev/zero` makes it read without bound. rule-hook runs on every such call in every session. Reuse the check `modified` in the same file makes, `stat.S_ISREG` before any read, and have `read` return `""` for any other path. A test passes a FIFO and expects the check to finish.
### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.
It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read.
@@ -140,9 +152,17 @@ It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost
The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 3).
### 218. Drop `LEGACY_WORKER` from `bin/model_routing/route.py`, so `route_from` reads only the JSON record.
### 229. Keep the rule for which commands reach run-heavy's docker beside that docker in `bin/run_heavy/capped_docker.py`, so rule-hook's `docker-run-memory` asks it instead of repeating run-heavy's PATH rules.
PR #357 archived the route as a JSON record, and kept `LEGACY_WORKER` to read the `Worker:` lines an older loop-claude wrote as sentences. The routing figures still count chunks whose archive holds such lines: 51 when PR #357 shipped, every chunk finished after the reset of 2026-10-21T22:16:41Z. Item 170 changes the routing steps, after which `AGENTS.md` has a `Reset` appended to `routing-calls-raised.md`, and the figures then count only chunks that hold records. So this item waits for item 170. Before starting, check that `routing-calls-raised.md` holds a `Reset` stamped after PR #357's merge; where none does, block this item on the next item that changes the ladder or its steps instead. Delete `LEGACY_WORKER`, `legacy_fields`, the tests that read sentences (in `bin/loop_claude/test_loop_claude.py` and `bin/routing_figures/test_routing_figures.py`), and the sentence on them in "loop-claude --help". Reword `route_from`'s docstring, and the comment at `Rung.__str__` in `bin/model_routing/ladder.py`, which gives the old lines as a reason `parse` must keep reading that spelling.
The paired ruling of PR #373 found Locality worse with all four seats, and named `bin/rule_hook/rules.py` `unlimited_container` and `resets_path` first. rule-hook exempts a `docker run` under run-heavy only where run-heavy's docker will run it: docker named bare, with PATH left as run-heavy set it. That knowledge of how `run_heavy/main.py` `capping` puts `PATH_ENTRY` first lives in rule-hook, so a change to run-heavy silently changes what the rule lets through. Move the predicate, with its words-before-docker index arithmetic made plain, next to `PATH_ENTRY`, and have the rule call it. Make the two places easier to read, as the seats named them.
### 219. Name the project's rung `project` in `bin/judge_replay/main.py`, `bin/subagent_rung/main.py` and `bin/review_replay/main.py`, in place of `anchor`, as `bin/model_routing/ladder.py` and `bin/loop_claude` name it.
Item 172 renamed `anchor` to `project` across `bin/loop_claude`, after release 0.3.0's inherited architect named `bin/loop_claude/cycle/judge.py:68` `Reply.bundled`: "the project's rung is also called anchor". Three tools outside it still call the same rung `anchor`: `bin/judge_replay/main.py:54` (`anchor = arguments_or_exit(...)`, a `Rung` parsed from the model argument), `bin/subagent_rung/main.py:26` (`anchor = project_rung(model)`), and `bin/review_replay/main.py:74`, `:100` and `:180`, with `findings_found`'s docstring. While the name differs between tools, a reader works out each time that the two are one rung. The rename keeps behaviour. `bin/score_outcomes/anchors.py` uses `anchor` for score anchors, a different thing, and keeps the name.
### 224. Split `docs/decisions.md` → `todo.md: one table of items, …`'s 420-word scoring paragraph into one paragraph per choice, and drop the sentences that tell how the goal weights changed.
Found by the prose review of PR #368. The paragraph that opens `2026-10-16, PR #283: items rank by` covers the formula, F, the goal weights, the panels' spelling picks, the column order and the old shape, and grew a sentence per chunk. A reader looking for what F is, or why `2**S`, searches all of it. Its sentences on how the goal weights changed over time, such as the one on PR #319, describe past states, not what holds; git history keeps them.
### 123. Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.
@@ -160,6 +180,14 @@ F is 8 until then, about one S 3 change, lilleman's call in PR #283. A chunk cos
Release 0.3.0's Mid A (PR #324 at c713910) named `bin/loop_claude/loop/reload.py:43` `decoded_as`: "a generic decoder with two sentinels and a duck-typed fits hook defined on Route". This lowers Shape: `decoded_as` is generic over any type, yet `decode_handed` calls it with one dataclass, `LoopRun`. Keep what it does today: a field added since the running script started may be missing, and a handed dataclass holding a field its `RETIRED` names decodes as None where its type allows None, and is rejected otherwise. Make `decoded_as` easier to read.
### 237. Give `judge` and `judge_once` in `bin/loop_claude/cycle/judge.py` a record of the inputs they share, in place of nine and eight parameters, or record why they stay.
Found by the principles audit of PR #376. "About seven things per level" in `principles/technical-principles.md`: `judge` takes nine parameters and `judge_once` eight, past the four or five for things that act on each other, with no recorded reason. Both take root, task, premises, records, entries, escalated_at, rung and effects, which one record could carry.
### 242. Run each case of a table-driven test in its own `subTest`, and split each test that checks several behaviours, so one failure does not hide the others and names its case.
"Tests" in `principles/technical-principles.md`. The principles audit of PR #380 found test bodies that loop over their cases without `subTest`, some checking several behaviours at once: `bin/judge_replay/test_judge_replay.py:38`, `:139`, `:176`; `bin/loop_claude/test_loop_claude.py:590`; `bin/machine_load/test_machine_load.py:19`, `:31`; `bin/rule_hook/test_rule_hook.py:480`; `bin/subagent_rung/test_subagent_rung.py:32`, `:43`, `:45`; `bin/test_settings_filter.py:28`; `bin/test_statusline.py:102`. The first failing case stops the loop, and without a message the failure doesn't say which case broke. Split the tests that check several behaviours at once, `test_judge_replay.py:176` and `test_subagent_rung.py:43-46`, into one test per behaviour ("One behaviour per test").
### 49. Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.
DRY, in `principles/technical-principles.md`: the list is copied by hand, and sessions work from the copy.
@@ -178,14 +206,28 @@ The chunk that ships this item files a copy of it in the release after the one i
Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. Before that, in item 140's chunk, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure the counter-signals beside them: goal 1.4's review rounds and unfinished verdicts, and goal 1.5's 🔴 findings, per chunk, since a worker that reads less may start sooner and need more rounds or let more defects through. Where time or tokens did not fall, or a counter-signal rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong.
### 183. Merge the two 2026-10-13 paragraphs of `docs/decisions.md` → `loop-claude: a judge decides each interrupt …` into one.
### 230. Have larv-review file one ambitious refactor item, aimed at the lowest-scoring dimension, whenever a scoring run leaves any score under 7.0, so such a project always holds a plan item meant to reach 7.0.
They say the same thing for `~/.claude/rules/` (item 95) and `~/.claude/skills/larv-review/standards/` (item 104), and the entry grows a paragraph per chunk. Raised by the prose review of PR #308.
Today `larv-review record-scoring` prints a `Floor:` line naming each mean under 7.0 (`bin/larv_review/history_commands.py:52`), and larv-review §3 → "Record" only commits the run and lists its scores. No rule turns that line into plan items. The places seats name reach the plan only when another item happens to touch one, so a project under 7.0 can stay there with no item aimed at it.
The human set the shape on 2026-10-26: the item filed is one ambitious refactor, not touch-ups. It restructures the area behind the lowest dimension's places, sized to lift that dimension to 7.0, and quotes the places it answers. Its tagline names the comprehension floor, so its chunk runs a scoring run, and a run still under 7.0 files the next one. The chain stops when every score reaches 7.0.
Settle in the change:
- Where the rule lives: larv-review §3 → "Record", and whether `record-scoring` prints the step beside `Floor:` so no worker misses it. Seats already found `Floor:` unclear: `docs/comprehension-history.md:1536` says decision titles disagree on whether the floor blocks.
- Duplicates: a release ends with two scoring runs, and an earlier run's item may still be open. While one such item is open, a later run refreshes its places instead of filing another. The item a chunk ships doesn't count as open, so its own scoring run files the next one.
- Ranking: `docs/decisions.md` → `larv-review: within a chunk lifting a project towards the comprehension floor, …` moves such an item's goals by 9 and lets it compete like any other item. Say whether an ambitious refactor, likely above R 5 and so shipping alone, keeps both the move by 9 and that ranking.
Once it ships, `~/code/log` drops its item 98, which does the same by hand, and revises the decisions that cite it.
### 184. Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at.
In `bin/loop_claude/loop/main.py`'s docstring, the line holding "of one PR, is finished" and the one ending "Each of these opens with its UTC time." run to 107 and 159 columns. Raised by the prose review of PR #308.
### 221. Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`.
"Validate data and build DTOs as early as possible", in `principles/technical-principles.md`, raised 🟢 by the principles audit of item 210's PR. `read_transcript` (`bin/claude_code/transcript.py:16`) returns raw `dict`s, so each consumer, such as `render` beside it and `since_step` in `bin/loop_claude/escalation_mark.py`, calls the helpers in `bin/claude_code/entries.py` (`human_text`, `loop_text`, `assistant_parts`, `tool_call`) to work out an entry's kind again. Parse each line once into types such as a human turn, a loop-claude prompt and an assistant turn, and have every consumer of `claude_code.entries` under `bin/` take those types. The change touches the escalation mark, which the comprehension seats found hard at `bin/loop_claude/cycle/judge.py:153` `escalation_mark` before item 210 moved it: make `since_step` in `bin/loop_claude/escalation_mark.py`, and `Grounds.since_step` and `judge_prompt` in `bin/loop_claude/cycle/judge.py`, easier to read.
### 116. Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.
`score-outcomes` reports the median 🔴 count at each guessed R, and how well L orders chunks by 🔴 findings; the part of R a 🔴 tests is L. Where most chunks have no 🔴, every median reads 0 and the rank correlation rests on the few that have one, which tells a scorer little. No round title held counts before PR #254, so how often a chunk has a 🔴 is not yet known.
@@ -210,17 +252,13 @@ Shape scored 6.25 in PR #257's run. `bin/` held about 30 entries then: 6 launche
"Errors as values", in `principles/technical-principles.md`, raised by the principles audit of PR #224: `bench.py` raises `KeyError` and `CalledProcessError`, and `pool.map` re-raises the first while the other threads run on unreported.
### 102. Give loop-claude's retry delay an environment override, so the black-box test stops replacing `time.sleep` through `sitecustomize`.
Found by the principles audit of PR #242. `bin/loop_claude/test_black_box.py:113-114` swaps the global `time.sleep`, the shape "Functional core, imperative shell" bans. An override of the delay lets the test run the code as production runs it.
### 173. Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.
Raised by the overrides pass of PR #296. The hook imports the main checkout's `rank_todo.py`, so while a branch of this repo changes the table's shape, every commit touching `todo.md` needs a `todo-rank-check` override: 33 log lines across four branches, the score-outcomes, plan-136, plan-148 and item-146 ones. The hook then checks nothing, and the rule rests on the worker chaining the branch's own check. Run another repo's `bin/rank_todo.py` never: that would run its code before every commit.
### 101. Have `larv_review/record.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.
### 101. Have `larv_review/history_commands.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.
Found by the principles audit of PR #242, against "Functional core, imperative shell" (`principles/technical-principles.md`). `bin/larv_review/record.py:67` reads `time.time()`, then checks git (`:70`, `commit_exists`) and the history file (`:75`) inside the function that parses the seats file and decides. A test cannot fix the heading's time, and every test of `read_seats` touches the real checkout.
Found by the principles audit of PR #242, against "Functional core, imperative shell" (`principles/technical-principles.md`). `bin/larv_review/history_commands.py:87` reads `time.time()`, then checks git (`:90`, `commit_exists`) and the history file (`:92`) inside the function that parses the seats file and decides. A test cannot fix the heading's time, and every test of `read_seats` touches the real checkout.
### 110. Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.
@@ -232,6 +270,10 @@ The repo has no CI, so larv-review's gate is the local run, and larv-review's Ga
When CI runs a rule check, such as one of `bin/rule-hook`'s, let `<!-- rule-override <rule>: <reason> -->` in the PR body override it.
### 102. Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.
Found by the principles audit of PR #242. `bin/loop_claude/test_black_box.py:117-118` swaps the global `time.sleep`, the shape "Functional core, imperative shell" bans, and the audit of PR #376 found the same block swapping `machine_load.memory.MEMINFO` at lines 120-123. An override of each lets the test run the code as production runs it.
### 135. Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.
The maintainability senior and the inherited architect of PR #257's scoring run named `bin/loop_claude/loop/reload.py:38` `fingerprint` and `:50` `exec_if_edited`: the fingerprint covers every `bin/**/*.py`, so editing `statusline.py` or `rank_todo.py` re-execs a running loop. Make `fingerprint` easier to read.
@@ -308,6 +350,10 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic
Before PR #310, reports reached the worker as the Agent call's result, a median 19k tokens per chunk (2026-10-08, 68 archived transcripts). Now a reviewer returns its verdict and one line per finding, and the worker reads a 🔴 or 🟡 finding's entry from the report file. `reading-cost` counts only tracked files (`bin/reading_cost/measure.py`), and `routing-figures` counts only the Agent call's result (`bin/routing_figures/measure.py`), so neither sees the report reads. Found by the architecture review of PR #310.
### 220. Have rule-hook also count a pass's earlier round commits on the branch, so a fourth commit titled round 3 is refused too.
Found by the principles pass of PR #360 (item 214). rule-hook's `round-cap` reads only the number in the title being committed (`bin/round_titles.py` `past_cap`), while `larv-review round-count` (`round_counts`) also counts repeated numbers, so a fourth commit titled `Answer stability round 3: …` passes the hook. Have `bash_breaches` in `bin/rule_hook/main.py` read the titles of `<default branch>..HEAD` in each round commit's checkout, with the hook's guarded git (`bin/rule_hook/git.py`), and refuse the commit when `round_counts(titles)` already holds 3 for its pass. The hook must not fetch from origin, as `git_repo.default_branch` does; it already has a lookup that needs no fetch, `local_default_branch` in `bin/rule_hook/override_log.py`. A `git commit --amend` must not count the commit it replaces. Hard part: the hook runs on every commit, so a slow or failing lookup must not block the commit. The change touches `bin/round_titles.py` `CAP`, which the comprehension seats found hard; make it easier to read.
### 149. Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.
A release's capacity is a sum of its items' cost, as the formula counts it. Each project states its own; the human sets the first value per project. Nothing is deleted by score.
@@ -344,7 +390,7 @@ The key names the project's session, archive folder and models entry. `project_k
### 155. Lower the reading cost of the files a chunk reads most before its first commit.
`bin/reading-cost` on 2026-10-22: the median of the last 5 chunks is 100,386 new input tokens before their first commit, up from 73,910 for the 5 before them. The files read most over the last 5 were `skills/larv-review/SKILL.md`, 3 times, and `rules/todo-items.md`, 2 times. The chunk that ships this item runs `bin/reading-cost --reset`.
`bin/reading-cost` on 2026-10-28: the median of the last 5 chunks is 125,323 new input tokens before their first commit, up from 89,103 for the 5 before them. The files read most over the last 5 were `skills/larv-review/SKILL.md`, 2 times, then `bin/transcript_archive/outcomes.py` and `rules/decisions.md`, once each. The chunk that ships this item runs `bin/reading-cost --reset`.
### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.
@@ -356,12 +402,20 @@ The hook judges a call before it runs, and `changed` in `bin/rule_hook/todo_chec
### 174. In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.
The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/cycle/prompts.py` asks the worker to name each item it takes with its L and E + I, and `fresh` uses it only where an item routed the chunk. In an unrouted chunk the judge has no levels to report, so neither the taken-in L nor the taken-in E + I lifts the worker, the reviewers or the judge, and the first prompt names no reviewers' rung for a higher E + I.
The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/cycle/prompts.py` asks the worker to name each item it takes with its L and E + I, and `fresh` uses it only where an item routed the chunk. In an unrouted chunk the judge has no levels to report, so neither the taken-in L nor the taken-in E + I lifts the worker or the judge.
### 52. Move this checkout out of Claude Code's own directory, or record why it stays, since Claude Code loads the checkout's `AGENTS.md` as the user's instructions into every project's sessions.
"One owner per value" and "Prefer the vendor-neutral option", in `principles/technical-principles.md`: git, Claude Code and loop-claude all write `~/.claude`, kept apart only by the `.gitignore` allowlist, and the repo's records live in a vendor directory. Claude Code also loads `~/.claude/AGENTS.md`, this checkout's decision titles, as the user's instructions into every session of every project, so a worker on another project reads this repo's decisions as if they held there. That cost about $25 of cache writes and reads at list prices since 2026-10-21: 10.7k characters, about 2.7k tokens, in each of 1,084 threads.
### 197. Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.
`bin/loop_claude/effects.py` hands loop-claude Python's builtin `input`, and nothing under `bin/` imports `readline`, so the terminal gets no line editing: fixing a typo means erasing back to it. `effects.input` reads the answer to both of loop-claude's questions: the interrupt, in `cycle/interrupt.py`'s `put_question`, and the pick of the project's model, in `project/model_choice.py`'s `ask_for_model`. Importing `readline` in `effects.py` gives both line editing, at two costs. It moves the prompt from stderr to stdout, while the question above it stays on stderr. `test_black_box.py` waits for the prompt on stderr. `readline`'s bracketed paste takes a pasted block whole, so an answer can hold several lines. `prompts.typed_answer` ends the answer at its first blank line, so the judge would read the rest of such a paste as loop-claude's words. The product-owner review of PR #308 raised the interrupt's case. lilleman, 2026-10-18: "Not super-important, but a bit irritating."
### 52. Record why this checkout lives in Claude Code's own directory, or move it out and link it in.
### 170. Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 50 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.
"One owner per value" and "Prefer the vendor-neutral option", in `principles/technical-principles.md`: git, Claude Code and loop-claude all write `~/.claude`, kept apart only by the `.gitignore` allowlist, and the repo's records live in a vendor directory.
`docs/decisions.md` → `routing: one ladder…` calls the steps a first guess. Start this item once 50 chunks have merged since PR #339 set today's steps, each shipping one item scored with L, E and I. By 2026-10-23, 15 had: those of items 117, 126, 122, 207, 130, 154, 186, 66, 121, 213, 137, 212, 214, 210 and 216. Then read `score-outcomes`' rank correlations for L, E and I and the routed-chunks table of `routing-figures.md`, and propose new steps to lilleman, whose call they are.
### 218. Drop `LEGACY_WORKER` from `bin/model_routing/route.py`, so `route_from` reads only JSON worker lines.
PR #357 archived the route as JSON on each `Worker:` line, and kept `LEGACY_WORKER` to read the lines an older loop-claude wrote as sentences. The routing figures still count chunks whose archive holds such lines: 51 when PR #357 shipped, every chunk finished after the reset of 2026-10-21T22:16:41Z. A chunk that changes the routing steps has a `Reset` appended to `routing-calls-raised.md`, after which the figures count only chunks whose worker lines are JSON. This item waits for item 170 whether or not 170 changes the steps, as lilleman decided on 2026-10-23. Before starting, check that `routing-calls-raised.md` holds a `Reset` stamped after PR #357's merge; where none does, ask lilleman whether to append one. Delete `LEGACY_WORKER`, `legacy_fields`, the tests that read sentences (in `bin/loop_claude/test_loop_claude.py` and `bin/routing_figures/test_routing_figures.py`), and the sentence on them in "loop-claude --help". Reword `route_from`'s docstring, and the comment at `Rung.__str__` in `bin/model_routing/ladder.py`, which gives the old lines as a reason `parse` must keep reading that spelling.