Compare commits

...

310 Commits

Author SHA1 Message Date
lilleman 261fb1d215 Record the comprehension check: paired ruling better against 64023b5 2026-10-22 22:32:09 +02:00
lilleman 3f8e175229 Answer stability round 3: 0 🔴, 0 🟡; approved 2026-10-22 22:28:48 +02:00
lilleman 6d4d37948c Answer product-owner round 2: 0 🔴, 0 🟡; approved 2026-10-22 22:18:33 +02:00
lilleman 37f11f720b Answer principles round 2: 0 🔴, 0 🟡; approved, and build quotes_checked's interrupt by keyword 2026-10-22 22:18:33 +02:00
lilleman 6e481939bf Answer stability round 2: 0 🔴, 1 🟡; assert archived_route says nothing when it reads a route or finds none 2026-10-22 22:18:33 +02:00
lilleman 23730a991d Answer security round 1: 0 🔴, 0 🟡; no findings 2026-10-22 22:12:29 +02:00
lilleman db904b9659 Answer prose round 1: 0 🔴, 9 🟡; reword the help, the routing and main docstrings, the changelog entry and item 218 2026-10-22 22:12:29 +02:00
lilleman 0b02f8d376 Answer product-owner round 1: 0 🔴, 1 🟡; item 218 waits for item 170 2026-10-22 22:12:29 +02:00
lilleman 1f4a5e81ef Answer stability round 1: 0 🔴, 1 🟡; test that an unfinished verdict steps from the route its cycle ended on 2026-10-22 22:12:29 +02:00
lilleman f6594bc048 Answer principles round 1: 0 🔴, 2 🟡; block item 218 on item 170, name record_fields and RECORD_FIELDS, say an unreadable Worker line on stderr 2026-10-22 22:12:29 +02:00
lilleman c5fdaf43f6 Answer architecture round 2: 0 🔴, 0 🟡; approved 2026-10-22 22:01:05 +02:00
lilleman cb48719493 Answer architecture round 1: 0 🔴, 4 🟡; move verdicts out of cycle, derive RECORDED, type the archived worker as Record, drop stale help names 2026-10-22 22:00:09 +02:00
lilleman c3ae228639 Name PR #357 in item 218 2026-10-22 21:46:53 +02:00
lilleman 10fb7a21bc Refresh item 155 with the latest reading-cost medians 2026-10-22 21:46:46 +02:00
lilleman d1f2004e77 Remove item 137 from the plan, and file item 218 to drop the prose reader 2026-10-22 21:46:36 +02:00
lilleman 851d7d7c79 Archive the route as a JSON record, hand routing the verdict, and name after_unfinished and the judge's highest levels taken in by what they do 2026-10-22 21:46:36 +02:00
lilleman 0782ac6721 Append the reading-cost figure of the last finished chunk 2026-10-22 21:46:36 +02:00
lilleman 7285b2bb27 Merge pull request 'Compute the next release, and whether work has landed towards it, in one function that chunk_pick and larv-review's scoring trigger share' (#356) from item-213 into main 2026-10-22 21:28:45 +02:00
lilleman 277a52f0cb Remove item 213 from the plan 2026-10-22 21:28:42 +02:00
lilleman 1d6f7328fb Merge remote-tracking branch 'origin/main' into item-213
# Conflicts:
#	todo.md
2026-10-22 21:25:15 +02:00
lilleman a6fb79dabb Answer prose round 1: 0 🔴, 2 🟡; define work landing in landed_towards again and reword the docstrings 2026-10-22 21:24:57 +02:00
lilleman aa8b12b896 Answer principles round 2: 0 🔴, 0 🟡; approved 2026-10-22 21:16:14 +02:00
lilleman f690eb2477 Answer principles round 1: 0 🔴, 4 🟡; have next_release take the plan's items and spell out each expected pick 2026-10-22 21:15:07 +02:00
lilleman 2ba78bb3c9 Merge pull request 'Bundle every unblocked item of a release that fires the same review passes, whatever its purpose, and ship each item above R 5 alone' (#355) from item-216 into main 2026-10-22 21:15:04 +02:00
lilleman 88d21b38a5 Answer prose round 1: 0 🔴, 2 🟡; renumber the chunk's item to 217 after main took 216, define R where CLAUDE.md first uses it, and reword the changelog, decision and docstring 2026-10-22 21:14:49 +02:00
lilleman 35b3c90db9 Merge remote-tracking branch 'origin/main' into item-216 2026-10-22 21:11:45 +02:00
lilleman 20c231457d Compute the next release, and whether work has landed towards it, in one function that chunk_pick and larv-review's scoring trigger share 2026-10-22 21:10:41 +02:00
lilleman b37f34b211 Answer stability round 2: 0 🔴, 0 🟡; no finding 2026-10-22 21:08:49 +02:00
lilleman 77ef932576 Answer principles round 3: 0 🔴, 0 🟡; no finding 2026-10-22 21:08:01 +02:00
lilleman 682181bc3b Answer stability round 1: 1 🔴, 1 🟡; restore the import order, and decide ships-alone from L, E and I so an unranked row counts 2026-10-22 21:07:27 +02:00
lilleman fbdb6c9f08 Answer principles round 2: 0 🔴, 0 🟡; decide ships-alone in one predicate both modules call 2026-10-22 20:56:45 +02:00
lilleman 64023b5bcd Merge pull request 'List larv-review's passes in one place that round_titles and the ladder derive from, and check the pass table against it' (#354) from item-121 into main 2026-10-22 20:56:44 +02:00
lilleman 71d5e82d3a Record the comprehension check: paired ruling for PR #354, better 2026-10-22 20:56:22 +02:00
lilleman 6150c5289e Answer product-owner round 1: 0 🔴, 0 🟡; no finding 2026-10-22 20:55:02 +02:00
lilleman 8c3298f673 Answer principles round 1: 0 🔴, 2 🟡; state the R cap in chunk-preflight's help and output, correct the decision's I 4 claim, and pin the cap at 5 in tests 2026-10-22 20:55:02 +02:00
lilleman 64d399f7f5 Answer security round 1: 0 🔴, 0 🟡; no finding 2026-10-22 20:52:16 +02:00
lilleman 7042a75266 Hold the pass table's reviewer column to the agents and tidy item 216's detail 2026-10-22 20:51:53 +02:00
lilleman b189e797fc Record the last chunk's reading cost, and refresh item 155 on the rise 2026-10-22 20:51:24 +02:00
lilleman b8ab075663 Answer stability round 2: 0 🔴, 0 🟡; approved 2026-10-22 20:50:29 +02:00
lilleman 0acb1286a0 Answer principles round 2: 0 🔴, 1 🟡; import the pass list from review_passes everywhere and file item 216 for the auto-reviewer 2026-10-22 20:50:29 +02:00
lilleman cf80a9d925 Answer architecture round 2: 0 🔴, 2 🟡; move the pass-list test beside review_passes and read the pass table by one pattern 2026-10-22 20:50:29 +02:00
lilleman 8468cc8ee0 Bundle every unblocked item of a release that fires the same review passes, whatever its purpose, and ship each item above R 5 alone 2026-10-22 20:47:52 +02:00
lilleman 6de74f0f63 Answer prose round 1: 0 🔴, 4 🟡; reworded the pass list comments and the test docstring 2026-10-22 20:44:29 +02:00
lilleman c5e458c3de Answer stability round 1: 0 🔴, 3 🟡; fixed in the architecture round's commit 2026-10-22 20:44:29 +02:00
lilleman e7dc6a9956 Answer principles round 1: 0 🔴, 6 🟡; fixed in the architecture round's commit 2026-10-22 20:44:29 +02:00
lilleman 1f9536d664 Answer architecture round 1: 0 🔴, 2 🟡; move the pass list to review_passes, check the pass table by one pattern 2026-10-22 20:44:18 +02:00
lilleman bb152a1964 File item 216: bundle items of one release that fire the same passes, whatever their purpose, and ship each item above R 5 alone 2026-10-22 20:36:47 +02:00
lilleman 6cff688951 List larv-review's passes in one place that round_titles and the ladder derive from, and check the pass table against it 2026-10-22 20:25:37 +02:00
lilleman e2033abbaf Record the reading cost of the previous chunk 2026-10-22 20:25:37 +02:00
lilleman c959471930 Merge pull request 'Move the 9 from the Shape items to the items that lift Locality, and split the floor item by place' (#353) from item-209 into main 2026-10-22 20:13:30 +02:00
lilleman 486c5a9fc6 Answer prose round 1: 0 🔴, 5 🟡; credit each quote to its entry, reword items 123, 137, 210, 214 and 215, and say the decision's items were to lift Shape 2026-10-22 20:09:15 +02:00
lilleman bd98bb40ee Move the 9 from the Shape items to the items that lift Locality, and split the floor item by place 2026-10-22 20:05:18 +02:00
lilleman 640b213c0b Record the reading cost of the previous chunk 2026-10-22 20:05:18 +02:00
lilleman ef47283d12 Merge pull request 'Read the status line's branch through git_repo.git, and state the comprehension-floor rule as it holds' (#352) from item-204 into main 2026-10-22 19:58:01 +02:00
lilleman 9e08a2b5c6 Answer prose round 1: 0 🔴, 5 🟡; state the weight rule once with its date, reword item 209, and keep the changelog and comments to what a reader needs 2026-10-22 19:55:09 +02:00
lilleman bb6224bbb2 Answer stability round 2: 0 🔴, 0 🟡; approved 2026-10-22 19:51:48 +02:00
lilleman a8e669d683 Answer principles round 2: 0 🔴, 0 🟡; keep the cite of items 124 and 125 that their decision mark needs, file item 209 for their weight, and say the docstring means bin/'s tools 2026-10-22 19:51:48 +02:00
lilleman c29f9e6fd1 Answer product-owner round 1: 0 🔴, 0 🟡; approved 2026-10-22 19:50:09 +02:00
lilleman 0b002b0d10 Answer security round 1: 0 🔴, 0 🟡; no vulnerabilities found 2026-10-22 19:50:09 +02:00
lilleman 919124eb00 Answer stability round 1: 0 🔴, 2 🟡; both fixed in the principles round's commit 2026-10-22 19:50:09 +02:00
lilleman 87f41071f2 Answer principles round 1: 0 🔴, 6 🟡; cut the false status-line exception, split the branch test, and date the lowest-dimension rule without Shape's score 2026-10-22 19:50:09 +02:00
lilleman 2fefab6b2e Read the status line's branch through git_repo.git, and state the comprehension-floor rule as it holds 2026-10-22 19:43:26 +02:00
lilleman 52ba0591fa Merge pull request 'Move the 0.5.0 items scoring 14 or more to 0.4.0' (#351) from plan-0.4.0-additions into main 2026-10-22 19:34:17 +02:00
lilleman 1ba097d17c Move the 0.5.0 items scoring 14 or more to 0.4.0 2026-10-22 19:34:08 +02:00
lilleman 2e4318bfc4 Merge pull request 'Add the principle of about seven things per level, and have the architect read its limits from it' (#350) from item-208 into main 2026-10-22 19:27:26 +02:00
lilleman 057808ad25 Answer prose round 1: 0 🔴, 4 🟡; point the architect's probes at the principle, ask for a grouping or a reason in place of 'never a verdict', and say what a level costs 2026-10-22 19:24:14 +02:00
lilleman 5805bd2287 Record the last finished chunk's reading cost, and refresh item 155 on the rise 2026-10-22 19:21:43 +02:00
lilleman 4008c60e76 Add the principle of about seven things per level, and have the architect read its limits from it 2026-10-22 19:21:09 +02:00
lilleman 79c66db183 Merge pull request 'Park a session's files outside its checkout in the chunk's review folder, since a headless session has no scratchpad' (#349) from item-186 into main 2026-10-22 13:12:52 +02:00
lilleman d08926b552 Answer prose round 1: 0 🔴, 3 🟡; reword the three sentences, record the folder's other uses and add a changelog entry 2026-10-22 13:09:55 +02:00
lilleman b223adfd26 Park a session's files outside its checkout in the chunk's review folder, since a headless session has no scratchpad 2026-10-22 13:05:16 +02:00
lilleman 539a7ec8d5 Merge pull request 'Keep a command's words together across a redirect in shell_command's segments' (#348) from item-154 into main 2026-10-22 13:02:50 +02:00
lilleman d6ec236771 Answer prose round 1: 0 🔴, 2 🟡; answered in the stability round's commit, which rewords the docstring and the REDIRECT comment 2026-10-22 12:59:05 +02:00
lilleman 136adb6a51 Answer principles round 2: 0 🔴, 2 🟡; answered in the stability round's commit 2026-10-22 12:59:05 +02:00
lilleman 16b1ffc05e Answer stability round 2: 0 🔴, 1 🟡; drop the two tests that asserted a misparse of process substitution 2026-10-22 12:59:05 +02:00
lilleman cd2f487df2 Answer principles round 1: 0 🔴, 3 🟡; answered in the stability round's commit, with the docstring and operator comment 2026-10-22 02:40:13 +02:00
lilleman 6b23808127 Answer stability round 1: 1 🔴, 2 🟡; end the command at a glued &< and pin each redirect form 2026-10-22 02:40:13 +02:00
lilleman 18c284c1fe Keep a command's words together across a redirect in shell_command's segments 2026-10-22 02:31:04 +02:00
lilleman 3e8f9deef6 Record the reading cost of the last chunk 2026-10-22 02:31:04 +02:00
lilleman f46809693b Merge pull request 'Move the vote counting out of larv-review's votes, so reading a votes file decides nothing' (#347) from item-130 into main 2026-10-22 02:24:42 +02:00
lilleman 4b783ac67b Answer prose round 1: 0 🔴, 2 🟡; reword the votes and surplus docstrings and rename two tests 2026-10-22 02:21:46 +02:00
lilleman e32accd08c Answer stability round 1: 1 🔴, 0 🟡; sort record.py's imports and build the tally after the surplus check 2026-10-22 02:20:19 +02:00
lilleman e419bc5cb0 Answer principles round 1: 0 🔴, 0 🟡; leave the 🟢 on surplus's parameter name, which split's already shadows overall 2026-10-22 02:20:19 +02:00
lilleman 8cdbff5fba Move the vote counting out of larv-review's votes, so reading a votes file decides nothing 2026-10-22 02:11:03 +02:00
lilleman 028d722b94 Merge pull request 'Have larv-review's scoring-run trigger count unreleased changes as chunk-preflight does' (#346) from item-207 into main 2026-10-22 02:07:37 +02:00
lilleman 31fb1a0093 Answer prose round 1: 0 🔴, 5 🟡; say what landed_towards returns and fails on, point --help at it, reword the changelog entry and two test names, and leave the README as it was 2026-10-22 02:07:24 +02:00
lilleman 68c44f3128 Answer principles round 3: 0 🔴, 0 🟡 2026-10-22 02:00:34 +02:00
lilleman 0f60cac9ba Answer stability round 3: 0 🔴, 0 🟡 2026-10-22 02:00:34 +02:00
lilleman 8974031c2d Answer principles round 2: 0 🔴, 0 🟡; the 🟢 comment fix is in the stability round's commit 2026-10-22 01:59:19 +02:00
lilleman 10abbaff9f Answer stability round 2: 0 🔴, 1 🟡; test the refusal on a ref that doesn't exist instead of a mock, and say why only Next names a release to empty 2026-10-22 01:59:19 +02:00
lilleman f6f2ec86b1 Answer security round 1: 0 🔴, 0 🟡 2026-10-22 01:54:08 +02:00
lilleman c554746f8e Answer stability round 1: 0 🔴, 3 🟡; answered in the principles round's commit 2026-10-22 01:54:08 +02:00
lilleman 8e1d166534 Answer principles round 1: 0 🔴, 3 🟡; take the next release from chunk_item's pick, read default_plan once, and test the changelog, the next release and the unreadable case 2026-10-22 01:54:08 +02:00
lilleman 4e5902fcc5 Name larv_review's import of chunk_pick in the README 2026-10-22 01:43:15 +02:00
lilleman 591db4a33e Have larv-review's scoring-run trigger count unreleased changes as chunk-preflight does 2026-10-22 01:43:04 +02:00
lilleman b9963df226 Merge pull request 'Spell out the judge's prompt in judge.py and call the worker the worker in it' (#345) from item-122 into main 2026-10-22 01:32:13 +02:00
lilleman 616a1119bc Answer stability round 2: 0 🔴, 0 🟡 2026-10-22 01:32:12 +02:00
lilleman 57c28f6571 Answer principles round 2: 0 🔴, 0 🟡 2026-10-22 01:32:12 +02:00
lilleman e7dbff791a Answer prose round 1: 0 🔴, 1 🟡; reword the recorded-answer paragraph, drop the repeated [loop] definition and the double possessive. The since_step comment's 🟢 is declined: the suggested wording claims the mark stays 0 until a step-up, which the code doesn't show 2026-10-22 01:29:15 +02:00
lilleman 7d6d5b274f Answer stability round 1: 0 🔴, 2 🟡; answered in the principles round's commit 2026-10-22 01:25:28 +02:00
lilleman 86a4523d9f Answer principles round 1: 0 🔴, 3 🟡; list the human's rule files once in the finished rule, split the dense paragraphs and the test 2026-10-22 01:25:28 +02:00
lilleman eb17a4080d Spell out the judge's prompt in judge.py and call the worker the worker in it 2026-10-22 01:18:08 +02:00
lilleman c0b31427c0 Record the reading cost of the last finished chunk 2026-10-22 01:18:07 +02:00
lilleman cf11a0f866 Merge pull request 'Describe the archive layout where it lives, and make help, decisions and the README easier to read' (#344) from item-131 into main 2026-10-22 01:11:41 +02:00
lilleman b57dc461c6 Restore override_log.py, whose docstring edit duplicated its code 2026-10-22 01:11:35 +02:00
lilleman 9e4aebb3ff Answer prose round 1: 0 🔴, 4 🟡; fix this_chunks's and segments's cases, move the decision's validity to its first paragraph, name ladder.py and reflow the help, trim the README sentence 2026-10-22 01:03:03 +02:00
lilleman b78accf55a Answer product-owner round 1: 0 🔴, 0 🟡; the 🟢 is answered in the prose round's commit 2026-10-22 01:03:02 +02:00
lilleman 26f1ef018d Describe the transcript archive's layout where it lives, and make help, decision and comment prose easier to find 2026-10-22 00:58:28 +02:00
lilleman 2f8760b7c6 Merge pull request 'State when work has landed towards a release once, in work_landed' (#343) from item-126 into main 2026-10-22 00:52:52 +02:00
lilleman 46c9dbe131 Answer prose round 1: 0 🔴, 1 🟡; decline restating the rule in the help, since the item asks it to point to work_landed; reword the rest 2026-10-22 00:49:58 +02:00
lilleman 41b8cc9a2d Remove item 126 and file item 207 2026-10-22 00:47:46 +02:00
lilleman 02f69a45dd Answer stability round 1: 0 🔴, 0 🟡; no change 2026-10-22 00:46:54 +02:00
lilleman 84e6c3e343 Answer product-owner round 1: 0 🔴, 1 🟡; work_landed's docstring now holds the whole condition, in the principles round's commit 2026-10-22 00:46:54 +02:00
lilleman 703a58279a Answer principles round 1: 0 🔴, 2 🟡; rename landed to committed, drop the back-pointer, hold the whole condition in work_landed 2026-10-22 00:46:54 +02:00
lilleman d459c2315b State when work has landed towards a release once, in work_landed 2026-10-22 00:43:40 +02:00
lilleman 45b2444a70 Merge pull request 'Give todo_table.items one way to say a plan has no items table' (#342) from item-117 into main 2026-10-22 00:42:23 +02:00
lilleman 2f10b900b5 Answer prose round 1: 0 🔴, 0 🟡; name the class in NoItemsTable's docstring 2026-10-22 00:39:32 +02:00
lilleman 756b42934b Reword NoItemsTable's docstring 2026-10-22 00:38:45 +02:00
lilleman 55fc24401f Answer stability round 2: 0 🔴, 0 🟡; no change 2026-10-22 00:38:41 +02:00
lilleman ec9e2098b8 Answer principles round 2: 0 🔴, 0 🟡; no change 2026-10-22 00:38:41 +02:00
lilleman c2c9faa31f Answer stability round 1: 0 🔴, 0 🟡; no change 2026-10-22 00:37:47 +02:00
lilleman b9e597398e Answer principles round 1: 0 🔴, 1 🟡; test the no-table message apart from the unreadable one 2026-10-22 00:37:47 +02:00
lilleman f0ece378c0 Give todo_table.items one way to say a plan has no items table 2026-10-22 00:32:30 +02:00
lilleman f429e256de Merge pull request 'Cut release 0.3.0' (#341) from release-0.3.0 into main 2026-10-22 00:27:26 +02:00
lilleman 666d681562 Cut release 0.3.0 2026-10-22 00:27:19 +02:00
lilleman 20325bf352 Merge pull request 'Move item 170 to release 0.4.0, where 10 chunks will have shipped under today's steps' (#340) from item-170 into main 2026-10-22 00:26:34 +02:00
lilleman 190378b05f Move item 170 to release 0.4.0, where 10 chunks will have shipped under today's steps 2026-10-22 00:26:29 +02:00
lilleman 723189bc2d Merge pull request 'Step a task's worker one rung down for L 1, as for L 2' (#339) from item-206 into main 2026-10-22 00:16:40 +02:00
lilleman 5f91fe6649 Answer stability round 2: 0 🔴, 0 🟡; nothing to fix 2026-10-22 00:13:34 +02:00
lilleman 8a4c2e1b56 Answer principles round 2: 0 🔴, 0 🟡; ask the refused reviewer for a rung other than the worker's 2026-10-22 00:13:34 +02:00
lilleman 4c929e66a9 Answer security round 1: 0 🔴, 0 🟡; nothing to fix 2026-10-22 00:12:12 +02:00
lilleman 3efc6ca391 Answer product-owner round 1: 0 🔴, 0 🟡; nothing to fix 2026-10-22 00:12:12 +02:00
lilleman 7cf6924e2e Answer stability round 1: 0 🔴, 0 🟡; nothing to fix 2026-10-22 00:12:12 +02:00
lilleman ed2e12d99d Answer principles round 1: 0 🔴, 2 🟡; test the bottom clamp again and name the goal one set of steps serves 2026-10-22 00:09:42 +02:00
lilleman 1b8d65dbf6 Answer prose round 1: 0 🔴, 2 🟡; say which steps item 170 counts and where the figures come from 2026-10-22 00:09:01 +02:00
lilleman 3dda22672f Step a task's worker one rung down for L 1, as for L 2 2026-10-22 00:05:23 +02:00
lilleman b79105a207 File item 206: step L 1 one rung down 2026-10-21 23:58:17 +02:00
lilleman 0e64d4b2c9 Merge pull request 'Record the ruling on the routing calls: L1 steps one rung down' (#338) from routing-ruling-l1 into main 2026-10-21 23:48:15 +02:00
lilleman a588075a4a Answer prose round 1: 0 🔴, 2 🟡; state the ruling as a change still to land 2026-10-21 23:48:06 +02:00
lilleman 18b52f66a1 Measure the reading cost of the last chunk 2026-10-21 23:44:46 +02:00
lilleman 628dce646f Record the ruling on the routing calls: L1 steps one rung down 2026-10-21 23:40:52 +02:00
lilleman 722f76b299 Merge pull request 'Start loop-claude's worker with ScheduleWakeup disallowed' (#337) from item-199 into main 2026-10-21 22:42:12 +02:00
lilleman a94e4c78b8 Answer prose round 1: 0 🔴, 1 🟡; reword the wakeup paragraph, the changelog entry and the comment 2026-10-21 22:38:53 +02:00
lilleman d7c4873481 Answer security round 1: 0 🔴, 0 🟡; no fix 2026-10-21 22:37:33 +02:00
lilleman a558ef09b7 Answer principles round 1: 0 🔴, 0 🟡; no fix 2026-10-21 22:37:29 +02:00
lilleman d1230a515e Answer stability round 1: 0 🔴, 0 🟡; label the test's cases and fix a paragraph's wording 2026-10-21 22:37:29 +02:00
lilleman 14e323ef01 Start loop-claude's worker with ScheduleWakeup disallowed 2026-10-21 22:35:39 +02:00
lilleman 4a4bebf87b Record the reading cost of the last chunk 2026-10-21 22:35:39 +02:00
lilleman eb3abd12a0 Merge pull request 'Make the contributor a standing member of every project's audience' (#336) from item-29 into main 2026-10-21 22:29:31 +02:00
lilleman a3b2923002 Merge origin/main into item-29 2026-10-21 22:29:28 +02:00
lilleman 64d4a2394d Merge pull request 'Measure each chunk by its merge time' (#327) from item-200 into main 2026-10-21 22:28:38 +02:00
lilleman 453a8e3b94 Answer prose round 1: 0 🔴, 4 🟡; reword the contributor sentences 2026-10-21 22:26:19 +02:00
lilleman 7eb2a91a13 Merge remote-tracking branch 'origin/main' into item-200
# Conflicts:
#	CHANGELOG.md
#	todo.md
2026-10-21 22:25:42 +02:00
lilleman 10495b8852 Answer product-owner round 4: 0 🔴, 1 🟡; the changelog says what changes for rebase and pushed projects 2026-10-21 22:25:20 +02:00
lilleman 2407689747 Make the contributor a standing member of every project's audience 2026-10-21 22:23:55 +02:00
lilleman 6f58a0e5c2 Merge pull request 'Give settings.json's model one writer per machine, and sort its keys' (#335) from item-21 into main 2026-10-21 22:20:21 +02:00
lilleman 1dd65de56f Record the comprehension check: paired ruling better against dec19c5 2026-10-21 22:20:15 +02:00
lilleman 33645b00e4 Answer stability round 3: 0 🔴, 0 🟡 2026-10-21 22:18:18 +02:00
lilleman 8e0c2d50f8 Answer principles round 3: 0 🔴, 0 🟡 2026-10-21 22:18:18 +02:00
lilleman b580d3991e Answer product-owner round 2: 0 🔴, 0 🟡 2026-10-21 22:14:24 +02:00
lilleman 250b29bc66 Answer stability round 2: 0 🔴, 0 🟡 2026-10-21 22:14:24 +02:00
lilleman 651695a695 Answer prose round 1: 0 🔴, 8 🟡; one copy of the git steps, in README, true claims about the synced effort and the filter, and the trust entry added to item 190 2026-10-21 22:14:24 +02:00
lilleman b7261987ad Answer principles round 2: 0 🔴, 1 🟡; main parses and checks settings.json, so cleaned takes a dict and never raises 2026-10-21 22:14:24 +02:00
lilleman d08a128d0f Answer security round 1: 0 🔴, 0 🟡 2026-10-21 21:59:53 +02:00
lilleman 80270c6b17 Answer product-owner round 1: 1 🔴, 1 🟡; the stability round's commit holds the fixes, and Install now says to pick a model on each new machine 2026-10-21 21:59:53 +02:00
lilleman 1f8edb8e2e Answer principles round 1: 2 🔴, 5 🟡; the stability round's commit holds the fixes, and the filter now exits 1 on a file that holds no JSON object, AGENTS.md reads staged changes too, and the mypy targets are sorted 2026-10-21 21:59:53 +02:00
lilleman b57704d237 Answer stability round 1: 2 🔴, 3 🟡; anchor .gitattributes to the root settings.json, sort the new imports, isolate the checkout tests from the host's git, start a new install's Update at git fetch, fix the filter's docstring 2026-10-21 21:59:53 +02:00
lilleman d18b064e43 Answer architecture round 2: 0 🔴, 0 🟡; cite the synced effort without the model 2026-10-21 21:41:31 +02:00
lilleman 7665087e1e Answer architecture round 1: 1 🔴, 2 🟡; split the filter's pure core out of main, stage settings.json before Update's move, read the stored settings in a repo check 2026-10-21 21:38:50 +02:00
lilleman 7c3800337a Give settings.json's model one writer per machine, and sort its keys 2026-10-21 21:26:40 +02:00
lilleman 4fbe529cfe Record the reading cost of the last finished chunk 2026-10-21 21:26:40 +02:00
lilleman 10de59bc08 Merge pull request 'Make larv-review's round cap and re-entry easier to read' (#334) from item-120 into main 2026-10-21 20:27:23 +02:00
lilleman 64ca83ac94 Remove the finished item 120 and add it to the changelog 2026-10-21 20:27:20 +02:00
lilleman 84779764b2 Answer prose round 1: 1 🔴, 2 🟡; a fix for a 🟢, ❓ or prose finding reruns no pass whatever it changes, rows follow the pass table, decision title follows 2026-10-21 20:24:17 +02:00
lilleman f5f6b660f2 Rewrite larv-review's Re-entry as one table of which passes a fix reruns 2026-10-21 20:19:27 +02:00
lilleman 5de35893cd Record the reading cost of the last finished chunk 2026-10-21 20:19:27 +02:00
lilleman dec19c5595 Merge pull request 'Run every tool's git through git_repo.git, with rule-hook's guards as an option' (#333) from item-114 into main 2026-10-21 20:16:23 +02:00
lilleman a8aefd2566 Record the comprehension check: paired ruling better against fda48ac 2026-10-21 20:16:13 +02:00
lilleman 7c7a398e42 Answer stability round 2: 0 🔴, 0 🟡; no finding 2026-10-21 20:11:26 +02:00
lilleman 185efb9bea Answer principles round 2: 0 🔴, 0 🟡; test located on a path holding a newline, limit run_scores' comment to bin/ 2026-10-21 20:11:26 +02:00
lilleman 50dcb55d51 Answer security round 1: 0 🔴, 0 🟡; no finding 2026-10-21 20:05:36 +02:00
lilleman 7c97005154 Answer prose round 1: 0 🔴, 5 🟡; reword the guards, code_of and the floor decision, file item 205 2026-10-21 20:05:36 +02:00
lilleman d48344aa6d Answer product-owner round 1: 0 🔴, 0 🟡; no finding 2026-10-21 20:05:36 +02:00
lilleman f391e52ac3 Answer stability round 1: 0 🔴, 4 🟡; test that rule-hook runs git guarded and that reading-cost lists the checkout from a subfolder 2026-10-21 20:05:36 +02:00
lilleman 3ae89c3acf Answer principles round 1: 0 🔴, 2 🟡; test every guard, name a non-UTF-8 file name as an exit 1, fail on a malformed rev-parse 2026-10-21 20:05:36 +02:00
lilleman 3fc6790bee Answer architecture round 2: 0 🔴, 0 🟡; no finding 2026-10-21 19:45:00 +02:00
lilleman 8bee9cb765 Answer architecture round 1: 0 🔴, 3 🟡; type Effects.git, list the guards one per line, say how code_of guesses the worktree 2026-10-21 19:44:18 +02:00
lilleman a261669735 Run every tool's git through git_repo.git, with rule-hook's guards as an option 2026-10-21 19:35:15 +02:00
lilleman 583b85eea8 Merge pull request 'Retitle the comprehension-floor decision to say the floor doesn't block anything, define the comprehension terms and explain OVERRIDE' (#332) from item-119 into main 2026-10-21 19:22:05 +02:00
lilleman d789f0fd12 Answer stability round 2: 0 🔴, 0 🟡; no finding 2026-10-21 19:21:43 +02:00
lilleman 3f266751a3 Answer principles round 2: 0 🔴, 0 🟡; no finding 2026-10-21 19:21:43 +02:00
lilleman e37af925e8 Answer security round 1: 0 🔴, 0 🟡; no finding 2026-10-21 19:19:59 +02:00
lilleman 04d42a40eb Answer prose round 1: 0 🔴, 3 🟡; answered in the commit above 2026-10-21 19:19:59 +02:00
lilleman 12f5c18d46 Answer stability round 1: 0 🔴, 4 🟡; answered in the commit above 2026-10-21 19:19:59 +02:00
lilleman b20dc28f5b Answer principles round 1: 1 🔴, 6 🟡; correct the OVERRIDE comment, scope the floor title to the chunk and file the citation check 2026-10-21 19:19:59 +02:00
lilleman 1a1da8f94d Retitle the comprehension-floor decision to say the floor doesn't block anything, define the comprehension terms and explain OVERRIDE 2026-10-21 19:16:54 +02:00
lilleman bff8872e9b Append the reading-cost figure of the last finished chunk 2026-10-21 19:02:33 +02:00
lilleman 531c4dae25 Merge pull request 'Merge item 182 into item 197, which names the file both questions read through' (#331) from merge-182-197 into main 2026-10-21 18:48:31 +02:00
lilleman 747f28adf5 Answer prose round 1: 0 🔴, 3 🟡; say what each readline cost breaks, and name both questions' readers 2026-10-21 18:48:26 +02:00
lilleman dcc7149a02 Merge item 182 into item 197, which names the file both questions read through 2026-10-21 18:44:06 +02:00
lilleman 48f9c86dd2 Merge pull request 'Plan 0.3.0 as the day-to-day items scoring over 10 plus every item scoring 30 or more, and move the rest to 0.4.0 and 0.5.0' (#330) from plan-day-to-day into main 2026-10-21 18:42:10 +02:00
lilleman 80d9e9656f Move the 0.3.0 items scoring over 5 and up to 10 to 0.4.0, and those scoring 5 or less to 0.5.0 2026-10-21 18:42:03 +02:00
lilleman 7c0e50b52e Plan 0.3.0 as the items that change day-to-day work in projects plus those scoring 30 or more, 0.4.0 as the rest scoring 20 or more, and 0.5.0 as the remainder 2026-10-21 18:38:07 +02:00
lilleman 456991a722 Merge pull request 'File item 201: save tmux setups and restore them after a reboot, once the human has said what they need' (#329) from file-201 into main 2026-10-21 18:27:56 +02:00
lilleman c4cc7c11b5 Answer prose round 1: 0 🔴, 2 🟡; list item 201's questions with their subjects, and file item 202 to add the negation rule to prose.md 2026-10-21 18:26:25 +02:00
lilleman 2096fe2c7e File item 201: save tmux setups and restore them after a reboot, once the human has said what they need 2026-10-21 18:21:25 +02:00
lilleman d7dd3dc289 Merge pull request 'File item 199: start loop-claude's worker with ScheduleWakeup disallowed' (#325) from item-199 into main 2026-10-21 18:20:28 +02:00
lilleman 0df7377a2b Answer prose round 1: 0 🔴, 3 🟡; item 199 corrects SKILL.md's wakeup claim, drops the unproven notification claim, and its tagline promises only that the judge runs 2026-10-21 18:18:24 +02:00
lilleman 243cbe83b9 Answer prose round 3: 0 🔴, 1 🟡; the help's count of 10 names the chunks it counts, and the rewrapped paragraphs 2026-10-21 18:17:40 +02:00
lilleman 7518bc7f77 Shorten the score-outcomes changelog line to measuring each chunk by its merge time 2026-10-21 18:15:45 +02:00
lilleman dc79ebf828 Move the score-outcomes line under a new Unreleased section, since 0.2.0 shipped without it 2026-10-21 18:15:26 +02:00
lilleman cdd22de313 Merge remote-tracking branch 'origin/main' into item-200 2026-10-21 18:15:04 +02:00
lilleman a81047f5f6 Finish item 111, and state score-outcomes' change in one changelog line 2026-10-21 18:14:53 +02:00
lilleman 646f7a7df5 Reword item 111 to measure each chunk by its merge time, whatever the merge method 2026-10-21 18:14:45 +02:00
lilleman 21d8cab43f Answer principles round 3: 0 🔴, 6 🟡; split the five-behaviour rebase test into five on one fixture 2026-10-21 18:14:30 +02:00
lilleman 70cc5c9a0a Answer stability round 3: 0 🔴, 4 🟡; the medians' note names the rebased chunks it counts 2026-10-21 18:13:59 +02:00
lilleman a300dc32b7 Name no other project in item 199, and keep ID 200 for the item the item-200 branch files 2026-10-21 18:12:41 +02:00
lilleman 1bd192ecc7 File item 199: start loop-claude's worker with ScheduleWakeup disallowed 2026-10-21 18:12:20 +02:00
lilleman 92f8204702 Leave chunks that were never replayed out of score-outcomes' medians and rank correlations 2026-10-21 17:56:38 +02:00
lilleman 9a5c24aa68 Merge pull request 'Cut release 0.2.0' (#328) from release-0.2.0 into main 2026-10-21 17:56:06 +02:00
lilleman 4447aabbb3 Cut release 0.2.0 2026-10-21 17:55:58 +02:00
lilleman 6b6b82803d Sort the score-outcomes imports by their first binding 2026-10-21 17:15:53 +02:00
lilleman 58939766d3 Answer stability round 1: 1 🔴, 3 🟡; read chunks by one pure function, and skip chunks that never changed todo.md 2026-10-21 17:02:21 +02:00
lilleman 3d51ebc5df Measure each chunk by one rule: a merge commit, or a run of commits sharing one commit time 2026-10-21 16:47:51 +02:00
lilleman 2296cb9119 File item 200 for rebase-merged chunks, and leave squash and fast-forward in item 111 2026-10-21 16:36:23 +02:00
lilleman 13e3a71367 Drop the squash claim from the score-outcomes changelog line, since no test covers it 2026-10-21 14:56:57 +02:00
lilleman e4145b8e1d Measure chunks in projects that merge by rebase, as runs of commits sharing one commit time 2026-10-21 14:54:22 +02:00
lilleman fda48ac44c Merge pull request 'State code health as every project's first achieve goal, weighed four times while the comprehension overall is under 7.0, unless a README voids it' (#324) from item-189 into main 2026-10-18 22:01:40 +02:00
lilleman ef57520cf3 Answer overrides round 2: 0 🔴, 0 🟡; four more todo-rank-check overrides accepted 2026-10-18 22:01:18 +02:00
lilleman 5a495fd58e Record the comprehension check: paired ruling same against e6223f7; two scoring runs at c713910, overall 6.25 each 2026-10-18 21:59:47 +02:00
lilleman c7139106c7 Name no other project in the code-health decision 2026-10-18 21:49:34 +02:00
lilleman fcf119ffec Answer prose round 1: 0 🔴, 11 🟡; make rank_todo.py's help and docstrings true for code health, define the overall before its use, split the changelog's upgrade steps into a list, retitle the todo.md decision so its bar attaches to the table, and fix the nits 2026-10-18 21:49:01 +02:00
lilleman 2ea929a8be Answer principles round 3: 0 🔴, 0 🟡; no finding 2026-10-18 21:19:55 +02:00
lilleman e787286a48 Answer product-owner round 2: 0 🔴, 0 🟡; no finding 2026-10-18 21:19:55 +02:00
lilleman 8587e4f160 Answer stability round 2: 0 🔴, 0 🟡; no finding 2026-10-18 21:19:55 +02:00
lilleman 353058defd Answer product-owner round 1: 0 🔴, 1 🟡; fixed in the stability round 1 commit: the changelog and the goals rule say to file an item that drops a restated goal and repoints the goals after it; an under-bar re-rank fails record-scoring, a misspelt void names its spelling, and a commit matches by prefix 2026-10-18 21:12:19 +02:00
lilleman 6bb7b28b92 Answer principles round 2: 0 🔴, 3 🟡; fixed in the stability round 1 commit: rank_file, the true scoring_runs docstring and a second averaged pair; the help's exit paragraph rewrapped 2026-10-18 21:12:19 +02:00
lilleman eafcefe0da Answer stability round 1: 0 🔴, 6 🟡; pin the averaged overall with a second pair and a run with no Mean row, test a plan record-scoring reads but cannot rank, share rank_file between rank_todo.py and record-scoring, read the history path from HISTORY, make the comments and larv-review's help true 2026-10-18 21:12:19 +02:00
lilleman 1605d80cc5 Answer overrides round 1: 0 🔴, 0 🟡; all three todo-rank-check overrides accepted 2026-10-18 20:29:19 +02:00
lilleman f091d8b698 Answer security round 1: 0 🔴, 0 🟡; no finding 2026-10-18 20:29:19 +02:00
lilleman 390d1f1f83 Answer principles round 1: 0 🔴, 6 🟡; average the overall over the newest scored commit's runs, re-rank through rank_todo's functions and say not to record again, tie the help to UNDER_FLOOR and FLOOR, add code health to the working loop's premises, loop-claude's first prompt and two more agents, and fix items 114, 124 and 125's details 2026-10-18 20:29:19 +02:00
lilleman 3081d50f0f Answer architecture round 2: 0 🔴, 0 🟡; say which goals an old-shape item may name, and name larv-review's import of rank_todo in README 2026-10-18 20:08:13 +02:00
lilleman 8e0060be08 Answer architecture round 1: 1 🔴, 10 🟡; move FLOOR into comprehension_history, renumber the counter-signal item 198, void code health on a comprehension-check opt-out, add code health to every goal check, fail record-scoring on a failed re-rank, reuse overall_cells, and ease Scoring, parse_item and parse_moves 2026-10-18 20:04:36 +02:00
lilleman 9e6715e0bf Merge remote-tracking branch 'origin/main' into item-189
# Conflicts:
#	todo.md
2026-10-18 19:58:38 +02:00
lilleman 6e050148ef Refresh the reading-cost item with the rise item 189's chunk measured, and move it to 0.3.0 2026-10-18 19:29:38 +02:00
lilleman 50edcca42f Describe code health in the changelog 2026-10-18 19:29:24 +02:00
lilleman 2a961f267c State code health as every project's first achieve goal, weighed four times while the comprehension overall is under 7.0, unless a README voids it 2026-10-18 19:29:09 +02:00
lilleman 1bfc91559a Merge pull request 'File item 197: edit an answer at loop-claude's terminal questions with the arrow keys' (#323) from file-197 into main 2026-10-18 19:19:39 +02:00
lilleman 78077a5896 Answer prose round 1: 0 🔴, 1 🟡; the tagline names loop-claude's terminal questions, and the detail quotes the human exactly 2026-10-18 19:17:31 +02:00
lilleman aa279a319a Refresh item 155's reading-cost figures 2026-10-18 19:16:13 +02:00
lilleman d0758a0735 File item 197: edit an answer at loop-claude's prompt with the arrow keys 2026-10-18 19:15:49 +02:00
lilleman e6223f7126 Merge pull request 'Run each review pass on its own rung, lowered only where a replay of its rounds shows a lower rung finds what the project's rung finds' (#322) from item-159 into main 2026-10-18 19:00:38 +02:00
lilleman ab93b7356e Answer principles round 4: 0 🔴, 0 🟡; no finding 2026-10-18 19:00:37 +02:00
lilleman dba2e74321 Record the comprehension check: paired ruling same against 2911d3f 2026-10-18 18:57:46 +02:00
lilleman 49e86fdbb9 Answer prose round 1: 0 🔴, 6 🟡; state the replayed rung's conditions in the decision's title, separate the seats in the reviewers' title, reword the validity clause, the lost-input error, the changelog and the module docstrings, and fix the nits 2026-10-18 18:46:52 +02:00
lilleman cfa16c65b5 Answer stability round 2: 0 🔴, 1 🟡; test that a round naming an input written before it began is replayed on the copy 2026-10-18 18:39:58 +02:00
lilleman 6703d48800 Answer principles round 3: 0 🔴, 0 🟡; no finding 2026-10-18 18:39:58 +02:00
lilleman bf6300bcd5 Answer product-owner round 2: 0 🔴, 0 🟡; no finding 2026-10-18 18:39:58 +02:00
lilleman da17ed5c32 Answer stability round 1: 0 🔴, 4 🟡; skip a replayed round whose prompt names an input rewritten after it began, pin judge-replay's lowest candidate, compute the review rungs once per prompt, and name the replay's candidates and callback 2026-10-18 18:32:10 +02:00
lilleman 69e1c5f3f7 Answer product-owner round 1: 0 🔴, 1 🟡; keep the four unreplayed passes in the plan as item 196, cite it in the decision, and record the stability rerun 2026-10-18 18:32:10 +02:00
lilleman 68c2cdfa8b Answer security round 1: 0 🔴, 0 🟡; no finding 2026-10-18 18:09:39 +02:00
lilleman 56e9049938 Answer principles round 2: 0 🔴, 0 🟡; no finding 2026-10-18 18:09:39 +02:00
lilleman bc242b2998 Answer principles round 1: 0 🔴, 3 🟡; lower a replayed pass only while the worker runs no higher than the project's rung, confine every agent under agents/ again, type REPLAYED's keys as passes and test its rungs, and state why the other passes are not replayed 2026-10-18 18:08:03 +02:00
lilleman ec2a16b371 Answer architecture round 2: 0 🔴, 0 🟡; no finding 2026-10-18 18:00:44 +02:00
lilleman 2fbd504734 Answer architecture round 1: 3 🔴, 3 🟡; restore the reviewer-table check tied to SKILL.md and the round titles, render each lowered pass as an exception sentence, move review-replay's argument parsing into the shared reader, split reviewed_in, and rename the package in item 114 2026-10-18 17:59:46 +02:00
lilleman fc13a1100e Generalise stability-replay to review-replay of any pass, and route each pass on its own rung so a replay may lower one pass alone 2026-10-18 17:04:33 +02:00
lilleman 2911d3f4cc Merge pull request 'Accept an escalation quote only from transcript entries after the worker's last step-up, so a later trigger steps the worker again' (#321) from item-180 into main 2026-10-18 14:16:36 +02:00
lilleman 207ba120b5 Record the comprehension check: paired ruling same against 0462980 2026-10-18 14:16:24 +02:00
lilleman 862137b1be Answer architecture round 2: 0 🔴, 0 🟡; no finding 2026-10-18 14:12:56 +02:00
lilleman 8ef6dcb7a8 Answer principles round 2: 0 🔴, 0 🟡; no finding 2026-10-18 14:12:48 +02:00
lilleman 306b040b46 Answer stability round 2: 0 🔴, 0 🟡; no finding 2026-10-18 14:12:48 +02:00
lilleman eec084a4e8 Answer security round 1: 0 🔴, 0 🟡; no finding 2026-10-18 14:08:16 +02:00
lilleman baefcbb037 Answer product-owner round 1: 0 🔴, 0 🟡; the upgrade note added in 5bc3247 2026-10-18 14:08:16 +02:00
lilleman 0202bc60f9 Answer principles round 1: 0 🔴, 0 🟡; the step line and the replay's mark comment fixed in 5bc3247 2026-10-18 14:08:16 +02:00
lilleman e652e7aed7 Answer prose round 1: 0 🔴, 7 🟡; reworded in 5bc3247 2026-10-18 14:08:16 +02:00
lilleman 5bc3247aec Answer stability round 1: 1 🔴, 7 🟡; check an escalation against the worker's own lines after the mark, cover the escalated and capped steps 2026-10-18 14:08:16 +02:00
lilleman 2bba66ac0a Answer architecture round 1: 0 🔴, 6 🟡; show the judge the mark, carry the entries read on the verdict, name the checked texts 2026-10-18 13:50:06 +02:00
lilleman 1ed305f1e2 Expect the escalation's mark on the archived worker lines of the black-box tests 2026-10-18 13:30:57 +02:00
lilleman 3a8e4e6f75 Accept an escalation quote only from transcript entries after the worker's last step-up 2026-10-18 13:24:05 +02:00
lilleman 07369f1164 Append the reading-cost figure of the last finished chunk 2026-10-18 13:24:05 +02:00
lilleman 1601c92f09 Merge pull request 'Reinstate the 0.97 goal step, which lilleman wants after all, and record why the sum-reciprocal weights stay dropped' (#320) from item-188 into main 2026-10-18 13:14:33 +02:00
lilleman ca32d0d446 Answer overrides round 1: 0 🔴, 0 🟡; override accepted 2026-10-18 13:14:32 +02:00
lilleman e70f61dad4 Answer product-owner round 1: 0 🔴, 0 🟡; the step stays 0.97 2026-10-18 13:12:52 +02:00
lilleman 2d07bbff63 Answer stability round 1: 0 🔴, 0 🟡; no finding 2026-10-18 13:12:52 +02:00
lilleman 9c9f26ba57 Answer security round 1: 0 🔴, 0 🟡; no finding 2026-10-18 13:12:52 +02:00
lilleman fc7c2301b5 Answer principles round 1: 0 🔴, 1 🟡; Next ID kept at 196 2026-10-18 13:12:52 +02:00
lilleman 612ba0d4e4 Answer prose round 1: 0 🔴, 3 🟡; shorten the weights passage, and keep Next ID at 196 so the filed item 195 is not reused 2026-10-18 13:12:52 +02:00
lilleman bb60e9dffd Reinstate the 0.97 goal step, which lilleman wants after all, and record why the sum-reciprocal weights stay dropped 2026-10-18 13:07:16 +02:00
lilleman 5a9b084bfb Revert "Merge pull request 'Restore the sum-reciprocal goal weights, which the research found fit best, and record dropping the flat step' (#319) from item-188 into main"
This reverts commit 489465c56f, reversing
changes made to 9bed420f21.
2026-10-18 13:06:59 +02:00
lilleman 489465c56f Merge pull request 'Restore the sum-reciprocal goal weights, which the research found fit best, and record dropping the flat step' (#319) from item-188 into main 2026-10-18 12:58:26 +02:00
lilleman 9a1adcef42 Answer overrides round 2: 0 🔴, 0 🟡; override accepted 2026-10-18 12:55:53 +02:00
lilleman 917166e186 Answer product-owner round 1: 0 🔴, 0 🟡; the parent goal's weight filed as item 195 2026-10-18 12:54:37 +02:00
lilleman a1089442c4 Answer stability round 1: 0 🔴, 0 🟡; no finding 2026-10-18 12:54:37 +02:00
lilleman c8f53bbcc4 Answer security round 1: 0 🔴, 0 🟡; no finding 2026-10-18 12:54:37 +02:00
lilleman bdc1d463cb Answer principles round 1: 0 🔴, 1 🟡; the parent goal's weight is outside this chunk and filed as a question, item 195 2026-10-18 12:54:37 +02:00
lilleman 5d430dbd9a Answer prose round 1: 0 🔴, 3 🟡; state the weights and the choice in separate sentences, and file the parent goal's weight as a question 2026-10-18 12:54:37 +02:00
lilleman bfdb886ef7 Restore the sum-reciprocal goal weights, which the research found fit best, and record dropping the flat step 2026-10-18 12:42:22 +02:00
lilleman 9bed420f21 Merge pull request 'Drop the question on defects' lead, which the 2026-10-16 decision answers' (#318) from item-191 into main 2026-10-18 11:43:58 +02:00
lilleman 2e518e0bcc Drop the question on defects' lead, which the 2026-10-16 decision answers 2026-10-18 11:43:53 +02:00
lilleman 9a28cba0be Merge pull request 'Weigh each achieve goal 0.97 times the one above it, so a goal far down a project's list counts almost as much as its first' (#317) from item-188 into main 2026-10-18 11:43:03 +02:00
lilleman ef454d263e Answer overrides round 3: 0 🔴, 0 🟡; override accepted 2026-10-18 11:40:16 +02:00
lilleman d0a50abc8b Answer prose round 1: 0 🔴, 5 🟡; fold the changelog entry into the weights bullet, shorten the help and decision wording, correct items 191-194 2026-10-18 11:39:32 +02:00
lilleman f36eee0ec7 Answer product-owner round 1: 0 🔴, 0 🟡; no finding 2026-10-18 11:33:27 +02:00
lilleman 9eb26ed727 Answer stability round 1: 0 🔴, 0 🟡; no finding 2026-10-18 11:33:27 +02:00
lilleman d41d42baa5 Answer principles round 2: 0 🔴, 0 🟡; check the step in the help, mark item 192 principle 2026-10-18 11:33:27 +02:00
lilleman c9bfc96aaf Answer overrides round 1: 0 🔴, 0 🟡; override accepted 2026-10-18 11:27:45 +02:00
lilleman f0d4740367 Answer security round 1: 0 🔴, 0 🟡; no finding 2026-10-18 11:27:45 +02:00
lilleman 1a433205a6 Answer principles round 1: 0 🔴, 3 🟡; split the weight test, name the step as the implementer's pick, file the other findings 2026-10-18 11:27:45 +02:00
lilleman 80a90a803e Weigh each achieve goal 0.97 times the one above it, so a goal far down a project's list counts almost as much as its first 2026-10-18 11:17:32 +02:00
lilleman 0462980bd4 Merge pull request 'Move the next chunk's pick into one module, so git_repo only runs git and todo_table only parses the plan' (#316) from item-177 into main 2026-10-18 11:10:19 +02:00
102 changed files with 3493 additions and 1535 deletions
+1
View File
@@ -0,0 +1 @@
/settings.json filter=settings
+6 -3
View File
@@ -4,6 +4,7 @@
# un-ignore authored config only.
*
!.gitattributes
!.gitignore
!AGENTS.md
!CHANGELOG.md
@@ -51,7 +52,11 @@
!bin/reading_cost/*.py
!bin/repo_checks/
!bin/repo_checks/*.py
!bin/review-replay
!bin/review_folder.py
!bin/review_passes.py
!bin/review_replay/
!bin/review_replay/*.py
!bin/round_titles.py
!bin/rule-hook
!bin/routing_figures/
@@ -63,10 +68,8 @@
!bin/score-outcomes
!bin/score_outcomes/
!bin/score_outcomes/*.py
!bin/settings_filter.py
!bin/shell_command.py
!bin/stability-replay
!bin/stability_replay/
!bin/stability_replay/*.py
!bin/statusline.py
!bin/subagent-rung
!bin/subagent_rung/
+10 -7
View File
@@ -2,7 +2,7 @@
Decisions live in `docs/decisions.md`:
- larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension
- 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`
@@ -12,10 +12,10 @@ Decisions live in `docs/decisions.md`:
- 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 trigger names fixes like it; 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 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
- 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
@@ -26,8 +26,9 @@ Decisions live in `docs/decisions.md`:
- 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, each README achieve goal weighed by its position, the first heaviest, held to its bar, ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; the table's order is the plan's only order
- 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
@@ -40,19 +41,21 @@ Decisions live in `docs/decisions.md`:
- 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 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, the seats and the security pass always on the project's
- 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 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: 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: the stability reviewer runs no lower than the project's rung while the worker runs below it, until `stability-replay` shows a lower rung finding every 🔴 and 🟡 the project's rung finds
- 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
## Working rules
- `routing-calls-raised.md` sits at the root of loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Each of its lines is a call or a `Reset`, with a stamp. A call is new when it is stamped after the latest `Reset` and after the latest stamp that `todo.md` or `docs/decisions.md` → `routing:` cites. When there are new calls, file one `todo.md` item to settle them, or refresh the item already filed. Its detail quotes those calls with their stamps, and the routed-chunks table of `routing-figures.md` beside it, never the project names its other tables hold. A change to the ladder, its steps or the delegation rule is the human's. The chunk that settles the calls cites the latest stamp it settled in `docs/decisions.md` → `routing:`, whatever the human decided, so they are not filed again. Once a chunk that changes the ladder, its steps or the delegation rule has merged, append `- <UTC time> Reset` to `routing-calls-raised.md`: the figures then count only chunks finished after it, and its calls may be raised again.
- When `~/.claude/settings.json` has uncommitted changes, commit them on a branch of their own and merge them through a PR: Claude Code writes that file from any session. Read their diff first. When it holds a credential, such as a token in `env` or `mcpServers`, ask the human to move it out of the file, and commit only once it is gone. A token in `env` moves to the shell profile; a server in `mcpServers` moves to `~/.claude.json` with `claude mcp add --scope user`.
- When `~/.claude/settings.json` has uncommitted changes, commit them on a branch of their own and merge them through a PR: Claude Code writes that file from any session. Read their diff first: `git diff HEAD -- settings.json`, which shows staged changes too. An empty diff means only the model or the key order changed: `git add settings.json` takes the file off `git status`, with nothing to commit. When the diff holds a credential, such as a token in `env` or `mcpServers`, ask the human to move it out of the file, and commit only once it is gone. A token in `env` moves to the shell profile; a server in `mcpServers` moves to `~/.claude.json` with `claude mcp add --scope user`.
## Scoring run
+33 -4
View File
@@ -2,18 +2,47 @@
## Unreleased
- 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.
- A new technical principle, "About seven things per level", sets soft limits on what a reader takes in at once: the parameters and branches of a function, the methods of a class, the files and folders in a folder, the sections of a document and the components of a system. Aim for four or five of the things that act on each other, such as parameters. Things found by name, such as files named by locale, may run far past seven. Crossing a limit asks you to group the things or record why they stay. The systems-architect reviewer now reads its limits from this principle. It rates a unit that crosses a limit with no recorded reason a 🟡, where it used to be a 🔴, and no longer asks for the limits as merge-gate rules.
- The comprehension panel's base worktree and a build probe's output now go in a folder under the chunk's review folder in `~/.local/state/larv-review/`. Both used to go in a session scratchpad, which loop-claude's headless sessions don't have.
- rule-hook now reads `git > out commit -m x` as one git commit, as the shell runs it. A redirect used to split a command in two, so such a commit escaped `commit-one-line`, `round-title-counts` and `todo-rank-check`.
- `larv-review needs-scoring-run` now calls a scoring run for the release `chunk-preflight` names as next, not for the earliest release in the plan. It also counts a change as unreleased the way `chunk-preflight` does: an entry under `CHANGELOG.md` → `## Unreleased`, or, where there is no such section, a commit after the newest `v*` tag (any commit when there is none). Before, a chunk that moved the next release's last items to a later release without shipping them called a scoring run, while `chunk-preflight` called that release unplanned.
- README → Install now says that every machine taking this checkout must be a sandbox with no direct access to a production environment, since `settings.json` runs Claude Code in auto mode with the dangerous-mode prompt skipped. Before, it asked for a sandbox only for `loop-claude`.
## 0.3.0
- A task scored L 1 now routes its worker, or a delegated subagent such as a search, one rung below the project's rung, as L 2 does; it used to go two rungs below. On an Opus 5.5 project that is Sonnet 5.5 at high, not Haiku 5.5 at max: chunks started on Haiku 5.5 took more review rounds and unfinished verdicts.
- loop-claude's worker now starts with `ScheduleWakeup` disallowed. A worker that scheduled a wakeup kept `claude -p` running after its turn ended, so loop-claude neither ran the judge nor asked you, and the chunk stalled until someone killed the worker.
- Every project's audience now includes the contributor, the person who reads the code to change it. A README doesn't list them; only its `**Void:** code health` line drops them. larv-review's comprehension check now measures how hard the project is for them to read.
- `score-outcomes` now also measures projects that merge by rebase: each run of commits that share one commit time counts as a chunk. Add `docs/score-anchors.md` to those projects too. A chunk that was pushed or fast-forwarded may hold only part of its pull request, so the medians and rank correlations leave it out.
- `settings.json` no longer carries a model: each machine keeps the one you pick with `/model`. Git's clean filter `bin/settings_filter.py` drops `"model"` and sorts the keys, so neither a pick nor Claude Code's key order can reach a commit. Update now starts with `git add settings.json`: without it, Update's `git checkout -f` drops the machine's model. On upgrade, on each machine:
1. Turn the filter on in `~/.claude`: `git config filter.settings.clean bin/settings_filter.py`.
2. Pick a model with `/model`. Until you do, Claude Code runs its default model; this repo set `opus` before.
- larv-review's "Re-entry" is now one table of which passes a fix reruns, and the pass table's triggers say only when a pass first runs. The rule is unchanged; a fix for a 🟢, a ❓ or a prose finding still reruns no pass.
## 0.2.0
- Every project now shares one achieve goal, code health: the code is easy to understand and change safely. `CLAUDE.md` → "Shared goal" states it, with its signal and counter-signal. `rank_todo.py` ranks it first among a project's achieve goals. A project's overall is the overall mean of the newest scoring run in `docs/comprehension-history.md`, averaged with every other run on its commit. While that overall is under 7.0, or no run has measured the project, code health weighs four times as much as it does at 7.0 or above. An item's Moves cell names it as in `code health by 6`. A README voids it with `**Void:** code health, since <reason>.` under `## Goals`, and `rank_todo.py` then refuses an item that names it. `larv-review record-scoring` re-ranks `todo.md` after it appends a run, and exits 1 where `rank_todo.py` would, keeping the run. Expect items that make code easier to read to rank higher in every project. On upgrade:
1. Move every machine to this release before any of them ranks a plan another machine shares: an older `rank_todo.py` scores it without code health and rejects a `code health` cell.
2. Void code health in each project that opts out of the comprehension check, or `rank_todo.py` refuses its plan.
3. Run `rank_todo.py` in each project that keeps code health. It re-scores every item, so until then `rank_todo.py --check` fails, and rule-hook holds the project's next `todo.md` commit.
4. In each project whose README restates code health as a goal of its own, file an item to drop that goal and point the Moves cells citing it at `code health`. Dropping it renumbers the goals after it, so the same item repoints every Moves cell and decision citing them; `rank_todo.py` cannot tell a cell left pointing at the wrong goal.
- `stability-replay <model>` is now `review-replay <pass> <model>`, and replays any pass an agent under `agents/` reviews, such as `review-replay prose claude-opus-5-5`. It now tries every rung below the project's, down to the ladder's lowest. Its runs on the prose and stability passes of Opus 5.5 projects found no rung below the project's that finds every 🔴 and 🟡 the project's rung finds: Sonnet 5.5 at high missed 12 of 27 prose findings and 11 of 20 stability findings. So every pass stays where it runs. A rung a future run finds lowers only its pass, once `REPLAYED` in `bin/model_routing/ladder.py` names it, and only where the chunk's E + I steps no review up and the worker runs no higher than the project's rung; there it may run below the worker's rung.
- `chunk-preflight` names the release it finds finished and ready to cut, or to be planned first, wherever todo.md has named that release since the last cut.
- Each reviewer under `agents/` now writes its full report to a file that larv-review names in the reviewer's prompt, in a folder per chunk under `~/.local/state/larv-review/`. It returns only its verdict and one line per finding, so a review takes less of the worker's context. The worker reads a finding's full entry before it fixes or answers a 🔴 or 🟡. Each reviewer now holds Write. `rule-hook` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`; no override waives this rule. Each chunk's folder stays after the merge, so `stability-replay` can replay a round that reads an earlier round's report. It replays on a copy of the folder.
- Each reviewer under `agents/` now writes its full report to a file that larv-review names in the reviewer's prompt, in a folder per chunk under `~/.local/state/larv-review/`. It returns only its verdict and one line per finding, so a review takes less of the worker's context. The worker reads a finding's full entry before it fixes or answers a 🔴 or 🟡. Each reviewer now holds Write. `rule-hook` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`; no override waives this rule. Each chunk's folder stays after the merge, so `review-replay` can replay a round that reads an earlier round's report. It replays on a copy of the folder.
- `loop-claude` asks an interrupt's question on its own terminal and resumes the worker headless with your one-line answer, so the loop no longer waits for you to leave a claude session. Type `/talk` instead to open the worker's session in claude, as every interrupt did before, to read the diff or discuss first. A release ready to cut opens that session at once. Pressing Enter on an empty answer stops the loop, exit 2. Keys typed before the question shows are dropped, and a pasted answer keeps only its first line; type `/talk` for a longer one. The judge counts that answer as yours, like one typed in claude: the chunk stays open until the answer is recorded, where a later chunk could need it.
- `todo.md` may mark a renamed release in a `## Renamed` section, one line per rename, such as `- 0.2.1 renamed to 0.3.0`. `chunk-preflight` and `loop-claude` then skip that release when they pick the next one, and larv-review's scoring-run trigger calls no run for it. Without the mark, a release named since the last tag whose items all moved to other releases reads as finished: `chunk-preflight` says it is ready to cut and the loop stops for you, and the trigger calls a scoring run. `rank_todo.py` fails on a `## Renamed` line of another shape, and on an item filed under a release it marks. Before you move a machine to this release, add the line to the `todo.md` of every project that renamed a release since its last tag, or its loop stops for that release's cut.
- When a worker's run ends with a question and a request for a higher rung, `loop-claude` now steps the worker one rung up as the judge interrupts, or as it answers the question with a quote from `README.md` or another file it may quote. The judge must quote a passage showing that the escalation trigger the run cites fired. Before, the step was lost for an answered question, and the worker carried on from the answer on its old rung. The step has the same limits as the step on an unfinished verdict, and no later ruling of that cycle carries a second escalation. The archive's interrupt and quoted-answer outcomes now name the worker's rung.
- When a worker's run ends with a question and a request for a higher rung, `loop-claude` now steps the worker one rung up as the judge interrupts, or as it answers the question with a quote from `README.md` or another file it may quote. The judge must quote a passage showing that the escalation trigger the run cites fired. Before, the step was lost for an answered question, and the worker carried on from the answer on its old rung. The step has the same limits as the step on an unfinished verdict. An escalation trigger that fired before the worker's last step-up doesn't step it again, so one trigger buys one step. A trigger that fires after the step steps the worker again, in the same cycle or a later one. A chunk left open across the upgrade to this release starts with no step-up on record, so a trigger that already stepped its worker may step it once more. The archive's interrupt and quoted-answer outcomes now name the worker's rung.
- A scoring run due because a release's items ran out costs four more seats: it is done twice on one head. `larv-review agreement` compares how often Mid A and the inherited architect vote alike in paired rulings with how often their overall scores move the same way between the two runs. After 10 such pairs it gives a verdict, and on `Assumption fails:` larv-review asks you whether to keep the paired ruling.
- `workflow-bench/bench.py` gives each run a fixed list of allowed tools. Before, it skipped every permission check. A run may launch agents, run `/security-review`, edit its clone (not the clone's `.git/` or `.claude/`) and its report, and read its clone and the copy of `~/.claude` it benches. For git it gets one command, `workflow-bench/review_git.py`, and no bare `git`. The wrapper runs `log`, `diff`, `show`, `status`, `ls-files`, `add` and `commit -m` on the run's clone, whatever the working directory. It allows only the options it lists for each, and refuses an argument that names a path outside the clone. git runs with no global or system config, hook, pager or editor. A run loads no settings or MCP servers from `~/.claude` or from the case's clone, so their hooks and extra directories do not apply to it. Every other call is denied. Expect a benched review that needs another git command, or to run a project's code or tests, to say in its report that it could not.
- Every goal in `README.md` → Goals is marked `**Maintain:**`, a state to hold, or `**Achieve:**`, a direction to pursue. Each achieve goal has a signal, a counter-signal and a one-line reason under it. A change that breaks a maintain goal is redesigned or dropped, whatever it scores: `rules/todo-items.md` says so, and larv-review's goal alignment step no longer merges such a PR. `rules/goals-and-audience.md` states the form for every project's README. Expect larv-review to stop a PR on a maintain goal where it asked you before.
- Reshape every project's `todo.md` to the new shape below: until it is reshaped, that is the project's only work, as it is while README.md lacks Goals and Audience, and `rank_todo.py` says so. First move every machine to this release: an older release rejects the new formula, so it fails on every reshaped `todo.md`. Then mark the README's goals `**Maintain:**` or `**Achieve:**`, score each item's L, E and I, and set a bar on the new scale below the score of every item to keep, since the old bar would drop most items. Until then, an old-shape `todo.md` still ranks by its own formula and weights.
- `todo.md` ranks items by value per cost: this setup's own plan uses `Score = 100 * V / (2**S + 8)`, where 8 is a chunk's fixed cost, about one size-3 change, and `rank_todo.py --help` shows it. A Moves column replaces A, G and Goals, naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`. V sums each named goal's weight times its move. `rank_todo.py` weighs each achieve goal by its position in README.md, the first heaviest, so the goal weights table goes. An item names the most specific goal it moves, never a goal beside its own sub-goal. `rules/todo-items.md` and `rank_todo.py --help` show the new shape.
- `todo.md` ranks items by value per cost: this setup's own plan uses `Score = 100 * V / (2**S + 8)`, where 8 is a chunk's fixed cost, about one size-3 change, and `rank_todo.py --help` shows it. A Moves column replaces A, G and Goals, naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`. V sums each named goal's weight times its move. `rank_todo.py` weighs each achieve goal 0.97 times the one above it in README.md, so a goal far down the list still counts almost as much as the first and the goal weights table goes. The weights sum to 1: 5 achieve goals weigh 0.212 down to 0.188, 15 weigh 0.082 down to 0.053. An item names the most specific goal it moves, never a goal beside its own sub-goal. `rules/todo-items.md` and `rank_todo.py --help` show the new shape.
- L, E and I replace C, and set R. L is the chance the change holds a defect, from 1 to 4; E the chance a defect escapes tests and review, from 1 to 3; I the damage it would do, from 1 to 5, counting every project and session that runs the change. `rules/todo-items.md` defines each level in words, and `rank_todo.py` writes R as L + E + I − 2, at least 7 when I is 5 and at least 5 when I is 4. The table's score columns are `| L | E | I | R | S |`. `score-outcomes` takes `L E I S`, and reports how well L, E and I each order finished chunks by review rounds and 🔴 findings.
- `loop-claude` routes a chunk's worker on its item's L, from two rungs below the project's rung at L 1 to one above it at L 4. It routes the reviewers on the highest E + I among the chunk's items, counting each item the worker takes in: one rung above the project's for each point past 4, never below the worker's rung. It runs the judge of an Opus 5.5 project on the rung that highest E + I picks, never below the project's, and keeps it there when the worker steps up. The comprehension seats and the security pass stay on the project's rung. rule-hook holds each reviewer launch to the reviewers' rung, which `loop-claude` hands the worker in `LOOP_CLAUDE_REVIEWER_RUNG`. A delegated task's subagent takes the rung its L picks: `subagent-rung` takes L in place of R + C. Until a project reshapes its `todo.md`, every chunk there runs on the project's rung. Expect reviews of items whose defects would escape far or break much to cost more, and escalation from an item of L 4 to reach Fable 5.1 only with your yes.
- `loop-claude` routes a chunk's worker on its item's L, from two rungs below the project's rung at L 1 to one above it at L 4. It routes the reviewers on the highest E + I among the chunk's items, counting each item the worker takes in: one rung above the project's for each point past 4, never below the worker's rung. It runs the judge of an Opus 5.5 project on the rung that highest E + I picks, never below the project's, and keeps it there when the worker steps up. The comprehension seats and the security pass stay on the project's rung. rule-hook holds each reviewer launch to the reviewers' rung, which it works out from the E + I `loop-claude` hands the worker in `LOOP_CLAUDE_ESCAPE_AND_IMPACT`. A delegated task's subagent takes the rung its L picks: `subagent-rung` takes L in place of R + C. Until a project reshapes its `todo.md`, every chunk there runs on the project's rung. Expect reviews of items whose defects would escape far or break much to cost more, and escalation from an item of L 4 to reach Fable 5.1 only with your yes.
- An item that restores a maintain goal the project breaks today is exempt as `defect`, and its Moves may name that maintain goal, weighed as the heaviest achieve goal. A defect ranks by its score like any item. Only two kinds rank ahead of the rest of their release: questions first, since an answer may change other items, then security items.
- The stability reviewer applies `principles/technical-principles.md` as written, in place of its own copies of it. Its test-data check now asks for UUID v7, where it asked for randomised UUIDs.
- larv-review's principles audit is a pass of its own, and runs on every chunk that changes code, config or tests, not only on one with an architectural decision. A chunk of prose or planning alone skips it.
+21 -5
View File
@@ -4,14 +4,14 @@
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
- **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count.
- **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
- **Plan `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
- **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one.
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once.
- **Read the README's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and the items that may join it; read further only what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs.
- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which four things hold: one PR title states what they achieve together, without listing them; they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
- **Work one chunk at a time, and put every item that can share its review into it.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The items need not share a purpose. An item whose risk R, in `todo.md`, is above 5 ships alone: it joins no chunk, and none joins it. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need not fire the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open.
- **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the README's `## Audience`, picks it.
- **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. Take its expected values from the item, never from the code. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file under `~/.claude/principles/` only when the item changes it, a finding or a record you write names it, or you decline a finding.
@@ -20,6 +20,17 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
- **Open each `todo.md` item or ticket with a bold one-sentence tagline**, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- **File a security finding the moment it is found.** A security finding — a leaked credential, secret or PII, an auth bypass, an injection — goes under the next release, marked `security`, naming the exposure and the path it reaches. `~/.claude/bin/rank_todo.py` ranks it first in its release, after only the open questions, which wait for me. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
## Shared goal
Every project pursues the achieve goal below, ranked above every achieve goal its README states. A project whose code nobody will maintain voids it with one line under `## Goals`, before the numbered goals: `**Void:** code health, since <reason>.` So does a project that opts out of the comprehension check, since the goal then has no signal. An item's Moves cell names it as in `code health by 6`, and `rank_todo.py --help` says how much it weighs.
**Achieve:** Code health: the code is easy to understand and change safely.
- Signal: the comprehension panel's overall score rises, always. Under 7.0 it is very important.
- Counter-signal: defects keep reappearing in functionality that already shipped, or reviewers raise blockers because the implementer misunderstood the current system.
- Why: a score that rises while changes still misread the code measures the wrong thing.
Fewer items shipped per release is a price this goal accepts, not a counter-signal.
## Prose
Everything written — chat, commit messages, comments, docs, code — is in **English**. Prose meets four priorities, in this order. When two pull against each other, the higher one wins.
@@ -66,7 +77,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
4. A review rules the work below standard: systems-architect's BLOCK, a finding against larv-review's `standards/quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up").
When one fires, hand the hard part, edits included, to a subagent on the rung loop-claude's prompt names, one above yours. Open the subagent's prompt with the marker loop-claude's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung loop-claude's prompt names. Ask the human before going higher. Where loop-claude's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread.
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create.
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`~/.claude/bin/larv-review review-folder` prints it), and removes no image or file it did not create.
- Check `README.md` first for build, test, install, and codegen commands, and fix one that misbehaves in the same change. Refresh `README.md` whenever you change what it describes, keeping it true, not longer.
- Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest, a `docker run` line or a file a Bash command writes, pin a container image to its full patch version and a GitHub Action to a semver tag.
@@ -94,17 +105,22 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
## Vocabulary
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/`.
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md` or the judge's records.
- **gate** — the merge gate: the checks a PR passes before it merges.
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer, or `/talk` to open the worker's session with `claude --resume`; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
- **judge's records** — the files the judge reads beside the README's premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`.
- **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling.
- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them.
- **place** — the smallest addressable unit, such as a function or a section heading, that a seat names with its `path:line` when it judges how hard the project is to read there.
- **plan** — `todo.md`.
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`.
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`, with code health ("Shared goal") first among the goals unless the README voids it.
- **project's rung** — the cheapest rung on loop-claude's routing ladder of the project's model, which is the model loop-claude's prompt names as the project's, or else your own.
- **release** — a semver version the human cuts.
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap".
- **scoring run** — each seat scores the project from 1 to 10, overall and on each dimension. `larv-review` §3 → "Comprehension check" says which seats score and when one is due.
- **seat** — one simulated reader of the comprehension panel, launched per `~/.claude/skills/comprehension-panel/SKILL.md`.
- **session** — a Claude Code session: one id, what `claude --resume` continues.
- **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them.
- **worker** — the headless claude that runs the task in a cycle, in the chunk's session.
+20 -6
View File
@@ -35,6 +35,8 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it.
## Install
Take this checkout only onto a machine that is a sandbox with no direct access to a production environment, such as a dedicated VM: `settings.json` runs Claude Code in auto mode with the dangerous-mode prompt skipped.
Claude Code may already have created `~/.claude`, where `git clone` refuses to run, so make the repository in place:
```sh
@@ -43,7 +45,7 @@ git init
git remote add origin ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git
```
Then run Update's commands.
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:
@@ -54,14 +56,25 @@ claude plugin install code-review@claude-plugins-official
claude plugin install rust-analyzer-lsp@claude-plugins-official
```
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run `loop-claude` only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interactive ones included, skips every permission prompt.
Have git store `settings.json` without `"model"`, so a model you pick with `/model` stays on this machine and never reaches a commit:
```sh
git config filter.settings.clean bin/settings_filter.py
```
Then pick a model with `/model`.
After a pick, `git status` may list `settings.json`, and a `git pull` that changes the file refuses to run. `git add settings.json` stages no change and clears both. Once it is staged, such a pull goes through and drops the model: pick it again.
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt.
## Update
Move a machine that takes tagged releases to the latest tag. The move discards every uncommitted change to a file the latest tag tracks, such as a `settings.json` Claude Code wrote. List the uncommitted changes to files the checkout tracks, and the tag it is on:
Move a machine that takes tagged releases to the latest tag. The move discards every uncommitted change to a file the latest tag tracks, such as a hook Claude Code wrote into `settings.json`. Git counts a model pick as such a change until `git add settings.json`, so stage it first. List the uncommitted changes to files the checkout tracks, and the tag it is on:
```sh
cd ~/.claude
git add settings.json
git fetch --tags origin
git status
```
@@ -72,7 +85,7 @@ To keep an uncommitted change, merge it per `AGENTS.md` → "Working rules" and
git checkout -f "$(git tag -l 'v*' --sort=-v:refname | head -n 1)"
```
Then do what `CHANGELOG.md` asks of each version since the old tag, such as a new step under Install.
Then, where the tag changed `settings.json`, pick the model again with `/model`, and do what `CHANGELOG.md` asks of each version since the old tag, such as a new step under Install.
## Release
@@ -89,9 +102,10 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
- `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.
- `stability-replay <model>` replays archived stability reviews of 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; `stability-replay --help` states the replay. Run it only in a sandbox, like loop-claude: each replayed reviewer has Bash and skips every permission prompt, and an archived prompt may name paths on the host.
- `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.
@@ -110,7 +124,7 @@ pytest_add_cli_args=-k
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.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `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 `stability_replay` share `rung_replay/`: the rung search, and the argument, candidate rungs and exits. It 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 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. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
## Tracking a new file
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Use this agent for larv-review's overrides pass."
tools: Read, Grep, Glob, Write
---
You rule on each override of a rule `~/.claude/bin/rule-hook` enforces. The prompt gives you the lines `rule-hook overrides` printed, each with its rule and reason, and the branch diff. Read each rule and its stated exceptions in `~/.claude/bin/rule_hook/rules.py` → `RULES`, how an override is written and logged in the docstring of `~/.claude/bin/rule_hook/main.py`, and the project's `README.md` → "Goals" and "Audience".
You rule on each override of a rule `~/.claude/bin/rule-hook` enforces. The prompt gives you the lines `rule-hook overrides` printed, each with its rule and reason, and the branch diff. Read each rule and its stated exceptions in `~/.claude/bin/rule_hook/rules.py` → `RULES`, how an override is written and logged in the docstring of `~/.claude/bin/rule_hook/main.py`, and the project's `README.md` → "Goals" and "Audience", with code health (`~/.claude/CLAUDE.md` → "Shared goal") among the goals unless the README voids it.
For each override:
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Use this agent for larv-review's principles pass: one yardstick ch
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`.
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.
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.
+1 -1
View File
@@ -46,7 +46,7 @@ Before anything else, **read the shared principles** at `~/.claude/principles/`.
## Your Output Format
Report only a defect a persona hits, a requirement of the plan or the README's goals that the change breaks, or a breach of a technical principle. Friction that is none of these is not a finding.
Report only a defect a persona hits, a requirement of the plan, the README's goals or code health (`~/.claude/CLAUDE.md` → "Shared goal", unless the README voids it) that the change breaks, or a breach of a technical principle. Friction that is none of these is not a finding.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict:
+1 -1
View File
@@ -129,7 +129,7 @@ Every PR gets at least this sweep.
## Output Format
Report only a defect, a requirement of the plan or the README's goals that the change breaks, a breach of a technical principle, and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out.
Report only a defect, a requirement of the plan, the README's goals or code health (`~/.claude/CLAUDE.md` → "Shared goal", unless the README voids it) that the change breaks, a breach of a technical principle, and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis, mutation — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with:
- **Location**: File and line/function
+7 -13
View File
@@ -30,7 +30,7 @@ You are an elite Systems Architect with decades of experience designing software
- An external contract shaped for the consumer's task, evolvable without breaking them
- One implementation per concept — duplication only with a stated, deliberate reason
- Methods, files, and modules that each hold a single responsibility — overgrown ones get split
- Units that fit in a head — the thresholds of Fits in a head, crossed only with a stated reason
- Units that fit in a head — the fractal test of Fits in a head
Short-term pragmatism on these points compounds into long-term decay. Push back firmly when asked to compromise on them. Pragmatism is welcome on implementation details, not on structural choices. A change that violates one of these fundamentals is a 🔴, never softened to "the one change I'd make before merge", "acceptable for now", or "worth doing later".
@@ -40,15 +40,9 @@ Short-term pragmatism on these points compounds into long-term decay. Push back
## Fits in a head
Working memory holds about seven chunks (Code That Fits in Your Head). So at every altitude — system, component, class, method — the thing in view must be graspable with the details below abstracted away. This is the fractal test: zoom in anywhere and what you see still fits. A design only comprehensible by holding two levels at once has failed it, however clean each level looks in isolation.
At every altitude — system, component, class, method — the thing in view must be graspable with the details below abstracted away. This is the fractal test: zoom in anywhere and what you see still fits. A design only comprehensible by holding two levels at once has failed it, however clean each level looks in isolation. A new developer should explain what the system does from its structure in under 30 minutes; where they cannot, find the level that fails.
The thresholds, each a prompt and never a verdict:
- a new developer explains what the system does from its structure in under 30 minutes
- a system of a handful of components; a component of a handful of modules
- a call chain reaches persistence or response in at most ~7 hops
- a method: cyclomatic complexity at most **7**; fits an **80×24 terminal window** (~24 lines); at most **~7 things a reader must track at once** (variables, branches, in-flight states — the chunks of working memory)
Crossing one demands action or a stated reason. A unit over a threshold is first a prompt to check responsibilities: if it holds several, split along the concept boundaries. If it genuinely holds one but still crosses, that is not a pass — decompose it into named steps a reader can follow one at a time, or record the concrete reason it must stay whole (a table-like switch, a generated file). "Single responsibility" answers the count of responsibilities, never the count of things a reader must hold in their head. Under the thresholds: leave it and say so. Where a merge gate exists, the method thresholds run in its static analysis as machine rules — a recorded suppression carrying its concrete reason is the stated reason this section demands (see Delivery). A core method nobody can hold in their head is a structural finding, never style: the test applies at every zoom level, method included.
The limits per level are the technical principle "About seven things per level" in `~/.claude/principles/technical-principles.md`. A unit over one is first a prompt to check responsibilities: if it holds several, split along the concept boundaries. If it holds one, decompose it into named steps a reader can follow one at a time, or let it stay whole for a reason the principle accepts. "Single responsibility" answers the count of responsibilities, never the count of things a reader must hold in their head. A unit past a limit with no recorded reason is a 🟡. It is a 🔴 only where you name what a reader cannot hold: the failed fractal test is the defect, never the count. A core method nobody can hold in their head is a structural finding, never style.
## Operating Mode: Staged
@@ -142,7 +136,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d
- **One enforced path to production.** The pipeline is the only way code reaches any environment. A manual deploy lane or a human-waivable gate is a bypass, and the bypass is the finding — a gate people route around launders unverified changes as verified.
- **The merge gate is fast, deterministic, and blocks on both tests and static analysis.** It admits only quick, hermetic checks (minutes, not an hour); slow or probabilistic suites run scheduled outside it (see Testability). A slow gate breeds long-lived branches; incomplete work hides behind flags with an owner and an expiry, not behind a branch.
- **Static analysis is its own quality dimension, not a kind of testing.** Tests sample points in the input space; types and analyzers quantify over it. Types at full strictness, warnings-as-errors, and the Fits in a head thresholds as machine rules belong in the gate from the first commit — strictness is near-impossible to retrofit, so it is skeleton, never ceremony.
- **Static analysis is its own quality dimension, not a kind of testing.** Tests sample points in the input space; types and analyzers quantify over it. Types at full strictness and warnings-as-errors belong in the gate from the first commit — strictness is near-impossible to retrofit, so it is skeleton, never ceremony.
- **Deployment is designed, not improvised.** Build one artifact and promote it — a per-environment build voids what the gate verified. Config comes from the environment. Rollback is a standing requirement, which forces expand–contract migrations with N-1 compatibility between running code and schema; an unrollbackable change is a defect class. A deploy completes when the post-deploy smoke confirms the surface (see Testability).
- **Dependencies follow a strategy.** Each one earns its existence (Core Philosophy); versions are locked; updates flow small-and-often through the gate via automation. Automation presupposes the gate — on a gateless project the finding is the missing gate, not the missing bot.
- **The horizon prices the ceremony, never the skeleton.** Gate, one-command deploy path, lockfiles, and analyzer strictness are day-one requirements at any production horizon. Environment count, progressive delivery (canary, blue-green), and provenance depth are ceremony, priced by the recorded horizon and blast radius ("Hunt the imagined requirement" cuts the unrecorded). The Stage 0 promotion event converts a spike's deferral into a finding: re-review on promotion includes this front.
@@ -151,7 +145,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d
You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review.
**Verdict and severities: ~/.claude/skills/larv-review/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon).
**Verdict and severities: ~/.claude/skills/larv-review/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit failing the fractal test of Fits in a head, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon).
Every finding, except a place the prompt hands you, names a concrete later change this PR makes harder, such as "a second forge needs edits in four modules"; a concern that names none is too vague to check, so leave it out.
@@ -169,7 +163,7 @@ Focus on architectural alignment:
- Does it add complexity that could be avoided — including by relaxing the requirement that forces it? If a simpler design gets almost the same result, name it and the behavior delta rather than accepting the complex shape as given.
- Does it duplicate a concept that already exists instead of reusing it? (see "One concept, one implementation".)
- Does it build generality for a scale or future the Stage 0 record doesn't name? Same weight as unreasoned duplication (see "Hunt the imagined requirement").
- Does it push a core unit past a Fits in a head threshold?
- Does it push a core unit past a limit of "About seven things per level" in `~/.claude/principles/technical-principles.md`?
- Does it match the patterns documented in the README?
- Take the language and framework as given — only reopen foundational choices when the work itself does (see Evaluating Foundational Choices).
@@ -183,7 +177,7 @@ This is where unjustified duplication and accidental complexity get caught. Run
1. **Inventory the core concepts.** List the handful of ideas the system is really built on (e.g. "the navigation menu", "a list+filter+paginate page", "a form", "the request context"). For each, find *every* place it is implemented.
2. **One concept, one implementation — or a stated reason.** If a concept is implemented more than once, each copy must point to a concrete reason it cannot be the shared one. No reason → collapse to one. Slight, undesigned variation between copies is the signature of copy-paste drift, not deliberate design.
3. **Trace to the bottom — and walk the long chains.** Follow the central data structures and abstractions down to their foundation. Can you hold the core in your head? Is anything obscure, implicit, or magical on the way down? A core you cannot explain to the bottom is the defect, even when every layer looks tidy. Then pick the system's key operations and follow each call chain end-to-end (entry point → … → persistence/response). Every hop must add a decision, a transformation, or a boundary that earns its keep; a pass-through layer that only forwards is change amplification plus cognitive load with no payoff — name the collapse concretely (which layer folds into which). A chain, like a unit, must fit in a head (the hop threshold under Fits in a head).
3. **Trace to the bottom — and walk the long chains.** Follow the central data structures and abstractions down to their foundation. Can you hold the core in your head? Is anything obscure, implicit, or magical on the way down? A core you cannot explain to the bottom is the defect, even when every layer looks tidy. Then pick the system's key operations and follow each call chain end-to-end (entry point → … → persistence/response). Every hop must add a decision, a transformation, or a boundary that earns its keep; a pass-through layer that only forwards is change amplification plus cognitive load with no payoff — name the collapse concretely (which layer folds into which). A chain, like a unit, must fit in a head (the limit on hops in "About seven things per level" in `~/.claude/principles/technical-principles.md`).
4. **Naming and placement.** If a name, or its location in the tree, does not tell a new reader what it is and where it belongs, that is a defect — not a note. Names come from the domain glossary; the hierarchy should mirror the architecture with no translation. When a subsystem has been consolidated into its own folder/namespace, confirm *every* member lives there: a collaborator stranded in the parent (typically one the refactor didn't scope in, so it predates the move) breaks the mirror as badly as a misnamed file — a finding even when nothing imports it wrongly. Check both directions: the sibling in the parent that should have moved in, and the file inside the subfolder that actually belongs to a different layer. Ask of each remaining sibling in the parent: why is this *here* and not *there* with its peers? "It predated the move" is not a reason. Enumerate what's left in the parent namespace and justify each one, rather than only inspecting the files that changed.
5. **A flat directory is a smell at scale.** Count the files in each source directory. One folder holding many modules with no sub-structure (rule of thumb: **more than ~15–20 source files**, or a directory a newcomer can't skim to locate a concern) hides the architecture instead of mirroring it — the larger it grows, the more it costs to navigate, and "we'll group it later" never comes. This is a structural defect, not cosmetic polish: flag it and **propose a concrete grouping by concern**, naming which files go into which folder (e.g. `http/`, `auth/`, `admin/`, `plugin-host/`, `ui/`), derived from the core concepts the inventory already surfaced; co-locate tests with their module. Push for the reorganization rather than merely noting the count. The only thing that excuses a large flat tree is the project documenting it as a deliberate, reasoned deviation (and even then, re-test the reason as the file count climbs).
6. **Price the reasoned complexity too.** Essential-looking complexity has a requirement behind it. For each hotspot that survives the steps above, name that requirement, then sketch the design without it. When a much simpler near-equivalent exists, report the trade as a finding: the simpler shape, the exact functionality delta, and the complexity saved. A requirement nobody has priced is not a decision — offer the trade once, plainly, and let the owner accept or reject it.
+56 -20
View File
@@ -4,7 +4,7 @@ import re
from git_repo import commits_since, file_at, git, newest_release_tag
from failure import Failure
from todo_table import Item, items, next_item, renames
from todo_table import Item, items, next_item, release_of, renames
from markdown_text import sections
@dataclasses.dataclass(frozen=True)
@@ -20,9 +20,20 @@ class LastCut:
todos_since: list[str] | Failure
@dataclasses.dataclass(frozen=True)
class Upcoming:
"""The next release, and whether work has landed towards it, as `~/.claude/CLAUDE.md` → "Working loop" uses both."""
# The earliest release after the last cut that todo.md has named since that cut or the plan holds; without a cut, the plan's earliest. None where there is none.
release: tuple[int, int, int] | None
# Whether it is the plan's earliest release. Without a cut, it always is, even where the plan holds no item.
is_earliest: bool
# Whether work has landed towards it: one or more changes are unreleased, as unreleased_changes counts them.
landed: bool | Failure
@dataclasses.dataclass(frozen=True)
class Next:
"""The plan's earliest release is the next release: the earliest after the last cut that todo.md has named since that cut. Without a cut, the plan's earliest release is the next."""
"""The plan's earliest release is the next release."""
# None where the plan holds no item.
release: tuple[int, int, int] | None
# The item the next chunk takes first, next_item's pick; None where every item waits or the plan holds none.
@@ -36,15 +47,15 @@ class Cut:
@dataclasses.dataclass(frozen=True)
class Finished:
"""The next release holds no item, and changes are unreleased."""
class ReadyToCut:
"""The next release holds no item, and work has landed towards it."""
# The next release, None where todo.md has named none since the cut.
release: tuple[int, int, int] | None
@dataclasses.dataclass(frozen=True)
class Unplanned:
"""The next release holds no item, and no change is unreleased."""
"""The next release holds no item, and no work has landed towards it."""
# The next release, None where todo.md has named none since the cut.
release: tuple[int, int, int] | None
@@ -54,8 +65,8 @@ class Unknown:
"""todo.md's texts since the cut, or the changes since it, cannot be read."""
# How the plan stands to the last cut, the version x.y.z the newest v* tag names, with the item the next chunk takes first where there is one.
Pick = Next | Cut | Finished | Unplanned | Unknown
# How the plan stands to the last cut, with the item the next chunk takes first where there is one.
Pick = Next | Cut | ReadyToCut | Unplanned | Unknown
@dataclasses.dataclass(frozen=True)
@@ -91,28 +102,53 @@ def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Fa
def chunk_item(found: list[Item], cut: LastCut) -> Pick:
"""The pick from todo.md's items, weighed against the last cut. Routing and chunk-preflight both pick with it, so they name one item."""
return standing(cut.tag, unreleased_changes(cut), min((item.release for item in found), default=None), next_item(found), named_releases(cut.todos_since))
upcoming = next_release(found, cut)
return standing(upcoming, next_item(found)) if isinstance(upcoming, Upcoming) else upcoming
def standing(tag: str | None | Failure, changes: int | Failure, earliest: tuple[int, int, int] | None, first: Item | None, named: set[tuple[int, int, int]] | Failure) -> Pick:
"""How the plan stands to tag, the newest v* tag.
def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown:
"""The next release after cut, and whether work has landed towards it. found holds the plan's items.
earliest is the plan's earliest release, None where the plan holds no item, and first is next_item's pick. changes counts the unreleased changes. named holds each release todo.md named since the tag.
Cut where the plan files items under the last cut's version or earlier, and Unknown where todo.md's texts since the cut cannot be read.
"""
tagged = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", tag) if isinstance(tag, str) else None
if tagged is None:
return Next(earliest, first)
cut_version = tuple(int(part) for part in tagged.groups())
earliest = min((item.release for item in found), default=None)
cut_version = version_of(cut.tag)
if cut_version is None:
return Upcoming(earliest, True, landed(cut))
if earliest is not None and earliest <= cut_version:
return Cut(earliest)
named = named_releases(cut.todos_since)
if isinstance(named, Failure):
return Unknown()
first_named = min((release for release in named if release > cut_version), default=None)
if earliest is not None and (first_named is None or earliest <= first_named):
return Next(earliest, first)
if isinstance(changes, Failure):
after = {release for release in named if release > cut_version}
if earliest is not None:
after.add(earliest)
release = min(after, default=None)
return Upcoming(release, earliest is not None and earliest == release, landed(cut))
def version_of(tag: str | None | Failure) -> tuple[int, int, int] | None:
"""The version x.y.z named by tag, the newest v* tag; None where it names none."""
tagged = re.fullmatch(r"v([0-9]+\.[0-9]+\.[0-9]+)", tag) if isinstance(tag, str) else None
return None if tagged is None else release_of(tagged[1])
def landed(cut: LastCut) -> bool | Failure:
"""Whether work has landed since cut: one or more changes are unreleased."""
changes = unreleased_changes(cut)
return changes if isinstance(changes, Failure) else changes > 0
def standing(upcoming: Upcoming, first: Item | None) -> Next | ReadyToCut | Unplanned | Unknown:
"""How the plan stands to upcoming, the next release. first is next_item's pick, which the pick holds where it is Next.
Unknown where the next release holds no item and the unreleased changes cannot be counted.
"""
if upcoming.is_earliest:
return Next(upcoming.release, first)
if isinstance(upcoming.landed, Failure):
return Unknown()
return Finished(first_named) if changes else Unplanned(first_named)
return ReadyToCut(upcoming.release) if upcoming.landed else Unplanned(upcoming.release)
def unreleased_changes(cut: LastCut) -> int | Failure:
+6 -6
View File
@@ -2,10 +2,10 @@
import pathlib
import re
from chunk_pick import chunk_item, Cut, Finished, LastCut, Unknown, Unplanned
from chunk_pick import chunk_item, Cut, LastCut, ReadyToCut, Unknown, Unplanned
from failure import Failure
from chunk_preflight.gathered import Forge, NoItem, Plan
from todo_table import item_details, items, version
from todo_table import item_details, items, NoItemsTable, version
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
@@ -17,18 +17,18 @@ def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem:
if isinstance(todo, Failure):
return NoItem(f"{where} cannot be read: {todo.reason}.")
found = items(todo)
if isinstance(found, NoItemsTable):
return NoItem(f"{where} holds no items table.")
if isinstance(found, Failure):
return NoItem(f"{where} cannot be read: {found.reason}.")
if found is None:
return NoItem(f"{where} holds no items table.")
pick = chunk_item(found, cut)
if isinstance(pick, Cut):
return NoItem(f"{where} files items under release {version(pick.release)}, which is not after the last cut, {cut.tag}; ask the human which release they belong to.")
if isinstance(pick, Unknown):
return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.")
if isinstance(pick, Finished | Unplanned):
if isinstance(pick, ReadyToCut | Unplanned):
upcoming = f"release {version(pick.release)}, the next after the last cut, {cut.tag}" if pick.release else f"the next release after the last cut, {cut.tag}"
if isinstance(pick, Finished):
if isinstance(pick, ReadyToCut):
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
first = pick.item
+3 -1
View File
@@ -1,5 +1,5 @@
"""The lines the preflight prints, stated from what it gathered."""
from todo_table import bundle_candidates, Item, version
from todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone, version
from failure import Failure
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran
from chunk_pick import LastCut, unreleased_entries
@@ -66,6 +66,8 @@ def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]:
def bundled(plan: Plan) -> list[str]:
first, candidates = plan.first, bundle_candidates(plan.items, plan.first)
if ships_alone(first):
return [f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."]
if not candidates:
return [f"- No other item of release {version(first.release)} may join item {first.id}'s chunk."]
listed = [f" - item {item.id}, {levels(item)}, S {item.scores['S']}: {item.tagline}" for item in candidates]
+2 -1
View File
@@ -26,7 +26,8 @@ holds it, the plan loop-claude routes on. It prints:
- the open pull requests whose head is the item's branch, each by its number and URL, as gh lists
them on a github.com origin, and else as tea does. No title reaches the output;
- the items of that release that a chunk taking the item may take too: those that are not
questions and that no item outside the chunk blocks;
questions, that have R 5 or less, and that no item outside the chunk blocks; none where the
item's own R is above 5;
- each file or folder git tracks that the item's tagline or detail names in backticks, with a
file's lines or a folder's files, and the item's tagline and detail;
- what `rank_todo.py --check todo.md`, `larv-review needs-scoring-run <ID>`, `reading-cost` and
+13 -7
View File
@@ -17,7 +17,7 @@ from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
from chunk_preflight.facts import open_pulls, render
BIN = pathlib.Path(__file__).resolve().parents[1]
README = "# Project\n\n## Goals\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n"
README = "# Project\n\n## Goals\n\n**Void:** code health, since the plan's scores weigh goal 1 alone.\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n"
# Item 3 is the next release's first item that does not wait; 7 waits only on 3, 5 is a question, 8 waits on 5, 9 is in a later release.
TODO = """# todo
@@ -34,7 +34,7 @@ TODO = """# todo
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 5 | 0.2.0 | | question | **Ask first.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 56.2 |
| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |
| 7 | 0.2.0 | 3 | | **Do the thing after.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
| 8 | 0.2.0 | 5 | | **Do the answered thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
@@ -46,7 +46,7 @@ TODO = """# todo
Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.
"""
# The plan once item 3 has shipped: item 7 no longer waits, and its detail names the files.
SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.")
SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.")
# The plan once release 0.2.0 has shipped all its items: only release 0.3.0's item 9 is left.
LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
# An items table that holds no row.
@@ -260,7 +260,7 @@ class ChunkPreflightTool(unittest.TestCase):
done = repo.preflight(CHUNK_PREFLIGHT_TIMEOUT="1")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("as last fetched", done.stdout)
self.assertIn("item 3, L 4, E + I 5", done.stdout)
self.assertIn("item 3, L 2, E + I 5", done.stdout)
self.assertIn("`reading-cost` exited 0", done.stdout)
def test_lists_the_open_pull_requests_with_gh_on_a_github_origin(self):
@@ -315,7 +315,7 @@ class Render(unittest.TestCase):
def test_states_the_earliest_releases_first_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self):
said = rendered(item_facts())
self.assertIn("origin/main's todo.md: 0.2.0", said)
self.assertIn("item 3, L 4, E + I 5", said)
self.assertIn("item 3, L 2, E + I 5", said)
self.assertIn("> Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.", said)
self.assertIn("item 7, L 1, E + I 2, S 1: **Do the thing after.**", said)
self.assertNotIn("item 8,", said)
@@ -329,8 +329,13 @@ class Render(unittest.TestCase):
self.assertIn("No other item", said)
self.assertNotIn("item 7,", said)
def test_states_that_an_item_above_r_5_ships_alone(self):
said = rendered(item_facts(TODO.replace("| 2 | 2 | 3 | 5 | 3 |", "| 3 | 2 | 3 | 6 | 3 |")))
self.assertIn("Item 3 has R above 5, so it ships alone.", said)
self.assertNotIn("item 7,", said)
def test_states_an_unscored_level_as_unscored(self):
unscored = TODO.replace("| L | E | I | R | S |", "| R | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|").replace("| 4 | 2 | 3 | 7 | 3 |", "| 7 | 3 |").replace("| 1 | 1 | 1 | 1 | 1 |", "| 1 | 1 |")
unscored = TODO.replace("| L | E | I | R | S |", "| R | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|").replace("| 2 | 2 | 3 | 5 | 3 |", "| 5 | 3 |").replace("| 1 | 1 | 1 | 1 | 1 |", "| 1 | 1 |")
self.assertIn("item 3, L unscored, E + I unscored", rendered(item_facts(unscored)))
def test_states_the_unreleased_entries_and_else_the_commits_since_the_last_cut(self):
@@ -410,13 +415,14 @@ class Plans(unittest.TestCase):
self.assertIn("waits", waits.why)
self.assertIn("0.2.0", waits.why)
self.assertIn("Permission denied", planned(Failure("Permission denied"), CUT, "origin/main").why)
self.assertIn("L 'x'", planned(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), CUT, "origin/main").why)
self.assertIn("L 'x'", planned(TODO.replace("| 2 | 2 | 3 | 5 |", "| x | 2 | 3 | 5 |"), CUT, "origin/main").why)
self.assertIn("details cannot be read", planned(TODO + "```\n", CUT, "origin/main").text)
def test_tells_a_plan_with_no_items_table_from_one_whose_table_holds_no_item(self):
without = planned("", CUT, "origin/main").why
self.assertIn("origin/main", without)
self.assertIn("no items table", without)
self.assertNotIn("cannot be read", without)
empty = planned(EMPTY, LastCut(None, "", 4, []), "origin/main").why
self.assertIn("holds no item", empty)
self.assertNotIn("no items table", empty)
+1 -1
View File
@@ -67,7 +67,7 @@ def human_text(entry: dict) -> str | None:
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; the previous run ended before the chunk was finished."}}
def loop_text(entry: dict) -> str | None:
"""What a -p prompt of loop-claude's told the agent."""
"""What loop-claude told the worker in a -p prompt."""
text = content(entry)
return text if entry.get("type") == "user" and entry.get("promptSource") == "sdk" and isinstance(text, str) else None
+53 -5
View File
@@ -9,6 +9,8 @@ from utc_stamp import utc
ARCHITECT = "Inherited architect"
DECIDED_BY = "decided by"
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it blocks nothing.
FLOOR = decimal.Decimal("7.0")
HARDEST_FIRST = "hardest first"
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
HISTORY = "docs/comprehension-history.md"
@@ -104,15 +106,61 @@ def entries(history: str) -> list[Entry]:
def latest_places(history: str) -> str | None:
"""The places seats found hard from the oldest entry on the commit of the newest entry, by time, that is a scoring run or holds scoring seats' places: in it and each later entry, each ruled place opening with a dimension its seat's vote counted as worse, and every scoring seat's place. Each entry's places come under its heading, oldest first; with no such entry, it starts at the oldest entry. None when no place counts."""
found = sorted(entries(history), key=lambda entry: entry.time)
scored = [index for index, entry in enumerate(found) if not entry.paired or entry.scored_places]
newest_commit = found[scored[-1]].commit if scored else None
start = next((index for index in scored if found[index].commit == newest_commit), 0)
"""The places seats found hard since the newest scored commit, under each entry's heading, oldest first; None when no place counts.
They start at the first of newest_scored's entries, so a rerun of one head adds to the run before it. Where no entry counts as scoring the project, they start at the oldest entry. From there, each entry gives every scoring seat's place, and each ruled place opening with a dimension its seat voted worse."""
found = by_time(entries(history))
newest = newest_scored(found)
start = found.index(newest[0]) if newest else 0
parts = [placed(entry, worse_places(entry) + labelled_bullets(entry.body, SCORED_PLACES)) for entry in found[start:]]
return "\n".join(part for part in parts if part) or None
def latest_overall(history: str) -> decimal.Decimal | Failure | None:
"""The mean of the overall means of newest_scored's entries, since a rerun of one head measures it again; None where no entry counts as scoring the project."""
overalls = []
for entry in newest_scored(by_time(entries(history))):
overall = run_overall(entry)
if isinstance(overall, Failure):
return overall
overalls.append(overall)
return sum(overalls, decimal.Decimal(0)) / len(overalls) if overalls else None
def newest_scored(found: list[Entry]) -> list[Entry]:
"""In found's order, the entries that count as scoring the project on the newest scored commit, the commit of the last such entry; empty where none counts. A commit matches by prefix, since a heading may write it at any length from 7 characters."""
scoring = [entry for entry in found if scored(entry)]
return [entry for entry in scoring if entry.commit.startswith(scoring[-1].commit) or scoring[-1].commit.startswith(entry.commit)] if scoring else []
def run_overall(run: Entry) -> decimal.Decimal | Failure:
"""The overall cell of the Mean row of an entry that counts as scoring the project."""
try:
overall = decimal.Decimal(overall_cells(run).get(MEAN, ""))
except decimal.InvalidOperation:
overall = None
return overall if overall is not None and overall.is_finite() else Failure(f"{HISTORY}'s scoring run {run.heading} has no Mean row ending in its overall, which sets code health's weight")
def overall_cells(entry: Entry) -> dict[str, str]:
"""Each table row's last non-empty cell, by its first cell: a seat's overall vote in a ruling table, whether it has five votes or the older single `Vote`, or its overall score, or the Mean row's, in a scoring table."""
return {name: cells[-1] for name, cells in table_rows(entry.body).items() if cells and cells[-1]}
def scoring_runs(found: list[Entry]) -> list[Entry]:
"""The scoring runs among the entries, oldest first. Unlike scored, it leaves out a ruling from before PR #255 that holds scoring seats' places: there overall_cells reads each voting seat's vote, not its score."""
return [entry for entry in by_time(found) if not entry.paired]
def by_time(found: list[Entry]) -> list[Entry]:
return sorted(found, key=lambda entry: entry.time)
def scored(entry: Entry) -> bool:
"""Whether the entry counts as scoring the project: a scoring run, or a ruling from before PR #255 that holds scoring seats' places."""
return not entry.paired or bool(entry.scored_places)
def worse_places(entry: Entry) -> list[tuple[str, list[str]]]:
"""Under each of a ruling's seat labels, the bullets that open with a dimension that seat's vote counted as worse; Overall counts as one."""
worse = worse_votes(entry.body)
+32 -8
View File
@@ -1,21 +1,45 @@
"""Run git, in the current directory or a given one, and read the checkout, its default branch and its files."""
"""Run git, in the current directory or a given one, and read the checkout, its default branch and its files.
Every tool in bin/ starts git through `git` here."""
import os
import re
import subprocess
from failure import Failure
# A -c outranks the checkout's own config. Each transport gets its own line, since a config's protocol.<name>.allow outranks protocol.allow.
GUARD_SETTINGS = [
"core.fsmonitor=false",
"log.showSignature=false",
"protocol.allow=never",
"protocol.ext.allow=never",
"protocol.file.allow=never",
"protocol.git.allow=never",
"protocol.http.allow=never",
"protocol.https.allow=never",
"protocol.ssh.allow=never",
]
def git(*args: str, cwd: str | None = None, timeout: float | None = None) -> str | Failure:
"""What git printed, run in cwd, else in the current directory. A Failure where git cannot start, exits non-zero, prints text that is not UTF-8, or still runs after timeout seconds, which stops it."""
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> str | Failure:
"""What git printed, run in cwd, else in the current directory.
A Failure where git cannot start, exits non-zero, prints text that is not UTF-8, or still runs after timeout seconds, which stops it.
guarded turns off the fsmonitor, the signature check, each transport GUARD_SETTINGS names and a partial clone's fetch of its missing objects. It is for a checkout whose config may name a program.
"""
command = " ".join(args)
guards = [option for setting in GUARD_SETTINGS for option in ("-c", setting)] if guarded else []
# GIT_NO_LAZY_FETCH needs git 2.44.
env = {**os.environ, "GIT_NO_LAZY_FETCH": "1"} if guarded else None
try:
ran = subprocess.run(["git", *args], capture_output=True, cwd=cwd, encoding="utf-8", timeout=timeout)
ran = subprocess.run(["git", *guards, *args], capture_output=True, cwd=cwd, encoding="utf-8", env=env, timeout=timeout)
except UnicodeDecodeError as failure:
return Failure(f"git {' '.join(args)} printed text that is not UTF-8: {failure}")
return Failure(f"git {command} printed text that is not UTF-8: {failure}")
except (OSError, ValueError) as failure:
return Failure(f"git could not start: {failure}")
return Failure(f"git {command} could not start: {failure}")
except subprocess.TimeoutExpired:
return Failure(f"git {' '.join(args)}: stopped after {timeout} s")
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
return Failure(f"git {command}: stopped after {timeout} s")
return ran.stdout if ran.returncode == 0 else Failure(f"git {command}: {ran.stderr.strip()}")
def top() -> str | Failure:
+15 -6
View File
@@ -28,28 +28,30 @@ import typing
from transcript_archive.location import archive_root, transcript_of
from transcript_archive.read import archived_outcomes
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind
from project_key import checkout_of
from rung_replay.command import down_from, failed, limited_exit, project_rung_or_exit, projects_on
from loop_claude.effects import Effects
from failure import Failure
from rung_replay.search import first_reply, replayed
from loop_claude.cycle.judge import judge_once, Verdict
from loop_claude.cycle.judge import judge_once
from claude_code.reply import Limited
from model_routing.ladder import lowest_worker_rung, project_rung, Rung
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from claude_code.transcript import read_transcript
from model_routing.ladder import Rung
from loop_claude.stop import Stop
from loop_claude.verdicts import Verdict
TOOL = "judge-replay"
USAGE = f"{TOOL} <model>, a model on the routing ladder"
PER_KIND = 15
# The effort settings.json gave every judge before loop-claude routed it; the archived verdicts came from it.
REFERENCE_EFFORT = "xhigh"
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
anchor = project_rung_or_exit(TOOL, argv, __doc__)
anchor = arguments_or_exit(TOOL, argv, __doc__, USAGE, model_argument)
if isinstance(anchor, int):
return anchor
cases = archived_cases(anchor.model, archive_root(home, env), home)
@@ -59,13 +61,19 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
return failed(TOOL, f"no archived verdicts of projects on {anchor.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
cases = sample(cases, PER_KIND)
reference = Rung(anchor.model, REFERENCE_EFFORT)
replay = replayed(cases, reference, down_from(anchor), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
# The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge.
replay = replayed(cases, reference, down_from(anchor, lowest_worker_rung(anchor)), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
if isinstance(replay, Limited):
return limited_exit(TOOL, replay)
print(report(anchor.model, reference, cases, replay))
return 0
def model_argument(argv: list[str]) -> Rung | None:
"""The project's rung of the one model argv names; None for any other argv."""
return project_rung(argv[0]) if len(argv) == 1 else None
def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure:
projects = projects_on(model, home)
if isinstance(projects, Failure):
@@ -91,5 +99,6 @@ def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) ->
return verdict_kind(Failure(records.reason))
if isinstance(entries, Failure):
return verdict_kind(entries)
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, case.task, premises, records, entries, rung, effects))
# 0 for the route's mark, as before any step-up: the replay compares verdict kinds, and a mark changes only which escalation quotes count.
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, case.task, premises, records, entries, 0, rung, effects))
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
+1 -1
View File
@@ -6,7 +6,7 @@ import typing
from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, task_of, UNFINISHED
from failure import Failure
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from rung_replay.search import Replay
from model_routing.ladder import Rung
+15 -8
View File
@@ -13,7 +13,7 @@ from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINIS
from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from judge_replay import main
from rung_replay.search import Miss, Replay, Tried
from model_routing.ladder import Rung
@@ -122,22 +122,30 @@ class Main(unittest.TestCase):
@staticmethod
def verdict(interrupt, evidence):
output = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False}
output = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False}
return {"type": "result", "structured_output": output}
def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
# Haiku misses the interrupt; Sonnet and Opus return both.
# Sonnet misses the interrupt; Opus returns both.
def reply(rung, interrupted):
return self.verdict(interrupted and rung.model != "claude-haiku-5-5", f"said {INTERRUPTED if interrupted else FINISHED}")
return self.verdict(interrupted and rung.model != "claude-sonnet-5-5", f"said {INTERRUPTED if interrupted else FINISHED}")
code, out, err = self.run_main(["claude-opus-5-5"], reply)
self.assertEqual(code, 0, err)
self.assertEqual({cwd for _, _, cwd in self.calls}, {str(self.home / "code" / "proj")})
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]], [("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "medium"), ("claude-sonnet-5-5", "high"), ("claude-haiku-5-5", "max")])
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]], [("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "medium"), ("claude-sonnet-5-5", "high")])
self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out)
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n"))
for said in ("The task an agent was given:\nDo it.", "1. Ship.", "From ~/.claude/CLAUDE.md:\nBe kind."):
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-opus-5-5 at medium effort\n"))
for said in ("The task the worker was given:\nDo it.", "1. Ship.", "From ~/.claude/CLAUDE.md:\nBe kind."):
self.assertIn(said, self.prompts[0])
# The replay shows the judge the whole transcript, with no step-up marked in it.
self.assertNotIn("[step]", self.prompts[0])
def test_tries_no_rung_below_the_lowest_a_worker_routes_to_where_every_rung_returns_every_verdict(self):
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
self.assertEqual(code, 0, err)
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]][-1], ("claude-sonnet-5-5", "high"))
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n"), out)
def test_stops_at_the_projects_rung_and_names_none_when_it_misses(self):
code, out, _ = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted and rung == REFERENCE, f"said {INTERRUPTED if interrupted else FINISHED}"))
@@ -158,7 +166,6 @@ class Main(unittest.TestCase):
code, out, _ = self.run_main(["claude-opus-5-5"], reply)
self.assertEqual(code, 0)
self.assertEqual(sum(model == "claude-sonnet-5-5" for model, _, _ in self.calls), 6)
self.assertNotIn("claude-haiku-5-5", {model for model, _, _ in self.calls})
self.assertIn("claude-opus-5-5 at medium effort missed 0.", out)
self.assertTrue(out.endswith(": claude-opus-5-5 at medium effort\n"))
+2 -7
View File
@@ -1,17 +1,12 @@
import decimal
from comprehension_history import counted_vote, entries, Entry, table_rows
from comprehension_history import counted_vote, entries, Entry, overall_cells, scoring_runs
from larv_review.seats import FIRST_SEATS
# Matches score-outcomes, which waits for 10 finished chunks before it shows a median.
MIN_PAIRS = 10
def overall_cells(entry: Entry) -> dict[str, str]:
"""Each table row's last non-empty cell, by its first cell: a seat's overall vote in a ruling table, whether it has five votes or the older single `Vote`, or its overall score in a scoring table."""
return {name: cells[-1] for name, cells in table_rows(entry.body).items() if cells and cells[-1]}
def ruling_agreement(found: list[Entry]) -> list[bool]:
"""For each paired ruling that holds both of the first seats' overall votes, whether they counted alike."""
first, second = FIRST_SEATS
@@ -23,7 +18,7 @@ def run_agreement(found: list[Entry]) -> list[bool]:
"""For each commit scored at least twice, whether the first two seats' overall scores moved the same way, up, down or not at all, from its first run to its second. Both runs read one tree, so the pair is the ruling those seats would make from absolute scores on code that did not change."""
first, second = FIRST_SEATS
runs: dict[str, list[dict[str, decimal.Decimal]]] = {}
for entry in sorted((each for each in found if not each.paired), key=lambda each: each.time):
for entry in scoring_runs(found):
cells = overall_cells(entry)
if first in cells and second in cells:
runs.setdefault(entry.commit, []).append({first: decimal.Decimal(cells[first]), second: decimal.Decimal(cells[second])})
+1 -10
View File
@@ -1,5 +1,5 @@
from git_repo import commits_since, file_at, full_history, git, newest_release_tag
from failure import Failure
from git_repo import file_at, full_history, git
from comprehension_history import HISTORY, HistoryChange
@@ -20,12 +20,3 @@ def history_changes(default: str) -> list[HistoryChange] | Failure:
return after
changes.append(HistoryChange(commit, before, after))
return changes
def committed_since_release(default: str) -> bool | Failure:
"""Whether the default branch holds a commit after its newest `v*` tag, or any commit when it has none."""
newest = newest_release_tag(default)
if isinstance(newest, Failure):
return newest
count = commits_since(newest, default)
return count if isinstance(count, Failure) else count > 0
+14 -12
View File
@@ -29,12 +29,10 @@ another round. It also lists each name in such a title that is not a pass.
needs-scoring-run takes the IDs of the todo.md items the chunk ships, none when it ships none, and
prints why the chunk is due a scoring run, or `No scoring run due.` It is due when the chunk ships
an item whose tagline names the comprehension floor, or when it leaves a release with no item in
the checkout's todo.md, less the shipped items, and work has landed towards that release. Work has
landed when the chunk ships one of the release's items, or when the release is the earliest the
default branch's todo.md names and the default branch has a commit after its newest v* tag, or has
no v* tag. A release the checkout's todo.md marks renamed in its ## Renamed section, as
`- 0.2.1 renamed to 0.3.0`, is due none.
an item whose tagline names the comprehension floor. It is also due when the chunk leaves a release
with no item in the checkout's todo.md, once the shipped items are set aside, and work has landed
towards that release; bin/larv_review/plan.py's `work_landed` and `landed_towards` say when. A release the checkout's
todo.md marks renamed in its ## Renamed section, as `- 0.2.1 renamed to 0.3.0`, is due none.
A second scoring run of one head names itself `<PR or branch> rerun at <commit>`, so record-scoring
does not refuse it as a repeat of the first.
@@ -72,7 +70,9 @@ prints `Ruling:` and appends the ruling.
record-scoring takes the scores file of a run needs-scoring-run calls, whose first line names no
`, against`, and the same item IDs, and exits 1 when they call no run. It appends the seats' scores
and their means, rounded half up to two decimals, prints the means and, when a mean is under the
floor of {floor}, a line opening `Floor:` naming each one.
floor of {floor}, a line opening `Floor:` naming each one. Then it ranks the checkout's todo.md as
rank_todo.py does, since the overall sets the weight of code health, the goal every project shares,
and exits 1 where rank_todo.py would, with the run recorded.
places prints the places seats found hard since the newest scored commit: the places of each scoring
run on it, and,
@@ -91,22 +91,24 @@ time and the seats file's first line. Each commit that line names must be in the
when the history already holds an entry on what that line reads.
Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that
breaks the shape above, or when git cannot start, finds no checkout or no default branch, cannot
fetch origin for ruling-base, needs-scoring-run or record-scoring, or cannot read or write the
history, todo.md or the review folder.
breaks the shape above, a todo.md that fails rank_todo.py after record-scoring records a run, or
when git cannot start, finds no checkout or no default branch, cannot fetch origin for ruling-base,
needs-scoring-run or record-scoring, or cannot read or write the history, todo.md or the review
folder.
"""
import pathlib
import re
import sys
import typing
from round_titles import CAP, PASSES, round_counts
from round_titles import CAP, round_counts
from git_repo import default_branch, git, top
from failure import Failure
from larv_review.scoring import FLOOR
from comprehension_history import FLOOR
from larv_review.git 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 review_folder import REPORTS, review_folder
+35 -12
View File
@@ -1,29 +1,49 @@
import pathlib
from larv_review.git import committed_since_release
from chunk_pick import Cut, default_plan, LastCut, next_release, Unknown
from failure import Failure
from git_repo import file_at, top
from todo_table import Item, items, renames, version
from todo_table import Item, items, NoItemsTable, renames, version
from git_repo import top
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool, renamed: set[tuple[int, int, int]]) -> list[str] | Failure:
"""Why the plan calls a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, landed whether the default branch holds a commit after its newest release tag, and renamed the releases the chunk's plan marks renamed.
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: tuple[int, int, int] | None, renamed: set[tuple[int, int, int]]) -> list[str] | Failure:
"""Why the plan calls a scoring run, empty when it does not.
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured, short of one renamed as below. Work has landed when the chunk ships one of the release's items, or when the release is the earliest one `before` names and `landed` holds. A release the chunk's plan marks renamed is due none.
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. A release the chunk's plan marks renamed is due none.
before is the default branch's plan and after the chunk's. ships holds the IDs of the items the chunk ships. landed is the next release where work has landed towards it, else None (`landed_towards`). renamed holds the releases the chunk's plan marks renamed.
"""
plan = {item.id: item for item in before + after}
if unknown := sorted(set(ships) - set(plan)):
return Failure(f"neither plan holds item {', '.join(map(str, unknown))}")
shipped = [plan[id_] for id_ in ships]
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if "comprehension floor" in item.tagline.lower()]
next_release = min((item.release for item in before), default=None)
for release in emptied(before, after, shipped, renamed):
if any(item.release == release for item in shipped) or (release == next_release and landed):
if work_landed(release, shipped, landed):
# SKILL.md → "Second run" keys on this wording.
reasons.append(f"leaves release {version(release)} with no plan item")
return reasons
# larv-review --help points here rather than restating the rule, so the rule is written once.
def work_landed(release: tuple[int, int, int], shipped: list[Item], landed: tuple[int, int, int] | None) -> bool:
"""Whether work has landed towards release, for the scoring-run trigger. It has when the chunk ships one of the release's items. It has too when release equals landed: the default branch's next release, once work has landed towards it."""
return any(item.release == release for item in shipped) or release == landed
def landed_towards(found: list[Item], cut: LastCut) -> tuple[int, int, int] | None | Failure:
"""The next release on the default branch, once work has landed towards it: once one or more changes are unreleased, as `chunk_pick.unreleased_changes` counts them. None where there is no next release, or no change is unreleased. found is the default branch's plan."""
upcoming = next_release(found, cut)
if isinstance(upcoming, Unknown):
return Failure("could not tell the next release: the default branch's todo.md history cannot be read")
# Cut's release is the last cut's version or earlier, so no work lands towards it.
if isinstance(upcoming, Cut):
return None
if isinstance(upcoming.landed, Failure):
return Failure(f"could not tell whether work landed towards the next release: {upcoming.landed.reason}")
return upcoming.release if upcoming.landed else None
def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed: set[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
"""Each release the default branch's plan or a shipped item names that the chunk's plan, less the shipped items, names no longer, unless the chunk's plan marks it renamed."""
named = {item.release for item in before + shipped}
@@ -36,7 +56,8 @@ def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
checkout = top()
if isinstance(checkout, Failure):
return checkout
before = file_at(default, "todo.md")
held = default_plan(checkout, default)
before = held.todo
if isinstance(before, Failure):
return before
try:
@@ -44,18 +65,20 @@ def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read todo.md: {failure}")
# While a chunk reshapes todo.md into one table, the default branch's todo.md has no items table.
planned = items(before) or []
planned = items(before)
if isinstance(planned, NoItemsTable):
planned = []
if isinstance(planned, Failure):
return Failure(f"{default}'s todo.md: {planned.reason}")
chunk = items(after)
if chunk is None:
if isinstance(chunk, NoItemsTable):
return Failure("the checkout's todo.md has no items table; rank_todo.py --help shows one")
if isinstance(chunk, Failure):
return Failure(f"the checkout's todo.md: {chunk.reason}")
renamed = renames(after)
if isinstance(renamed, Failure):
return Failure(f"the checkout's todo.md: {renamed.reason}")
landed = committed_since_release(default)
landed = landed_towards(planned, held.cut)
if isinstance(landed, Failure):
return landed
return scoring_run_due(planned, chunk, ids, landed, renamed)
+25 -6
View File
@@ -2,14 +2,15 @@ import pathlib
import time
from larv_review.agreement import agreement_report
from comprehension_history import appended, DIMENSIONS, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
from comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
from git_repo import commit_exists, top
from larv_review.ruling import counted, overall, ruling, split, votes
from larv_review.ruling import counted, overall, ruling, split, surplus, votes
from failure import Failure
from larv_review.scoring import FLOOR, means, under_floor
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
from larv_review.scoring import means, under_floor
from larv_review.plan import plan_reasons
import rank_todo
from file_writes import replace_file
from larv_review.seats import scores, seats_file, SeatsFile
def record_ruling(votes_file: pathlib.Path) -> Failure | None:
@@ -21,8 +22,10 @@ def record_ruling(votes_file: pathlib.Path) -> Failure | None:
if isinstance(written, Failure):
return written
counts = counted(seats_read.seats, written)
tally = ", ".join(f"{seat.name} {vote_text(DIMENSIONS[-1], overall(written[seat.name]), overall(counts[seat.name]))}" for seat in seats_read.seats)
overall_votes = [overall(each) for each in counts.values()]
if surplus(overall_votes):
return Failure(f"{' and '.join(FIRST_SEATS)} both count as {overall_votes[0]} overall, which settles the ruling; drop the other seats' lines")
tally = ", ".join(f"{seat.name} {vote_text(DIMENSIONS[-1], overall(written[seat.name]), overall(counts[seat.name]))}" for seat in seats_read.seats)
if split(overall_votes):
print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the votes file, and run this again.")
return None
@@ -47,7 +50,23 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> F
print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, scoring.means))}.")
if under := under_floor(scoring.means):
print(f"Floor: {', '.join(under)} under the floor of {FLOOR}.")
return append(given.read, scoring_entry(named.title, scoring))
if unrecorded := append(given.read, scoring_entry(named.title, scoring)):
return unrecorded
return rerank()
def rerank() -> Failure | None:
"""Rank the checkout's todo.md again as rank_todo.py does, since the overall sets code health's weight, and fail where rank_todo.py would. The run stays recorded whatever happens, so those failures say to settle todo.md and run rank_todo.py on it, not to record the run again."""
checkout = top()
if isinstance(checkout, Failure):
return checkout
todo = pathlib.Path(checkout, "todo.md")
ranked = rank_todo.rank_file(todo)
if isinstance(ranked, Failure):
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
if ranked.under_bar:
return Failure(f"recorded the run and ranked {todo}, but the lines above name items now under the bar. Settle each as its line says, then run rank_todo.py on {todo}, not record-scoring again")
return None
def scored_seats(given: SeatsFile) -> ScoringRun | Failure:
+6 -4
View File
@@ -6,7 +6,7 @@ VOTES = ("better", "same", "worse")
def votes(seats: list[Seat]) -> dict[str, list[str]] | Failure:
"""Each seat's five votes as written, in DIMENSIONS' order."""
"""Each seat's five votes as written, in DIMENSIONS' order. Fails unless the seats come in a votes file's order and each seat's vote line and places have its shape. `counted` decides what the votes count as."""
names = [seat.name for seat in seats]
if names[:2] != list(FIRST_SEATS) or names[2:] not in ([], list(SPLIT_SEATS)):
return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their overall votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}")
@@ -18,9 +18,6 @@ def votes(seats: list[Seat]) -> dict[str, list[str]] | Failure:
if unnamed := [place for place in seat.places if not place_dimensions(place)]:
return Failure(f"{seat.name}'s place does not open with the dimensions it moves, each one of {', '.join(DIMENSIONS)}, then `: `: {unnamed[0]}")
said[seat.name] = line
first, second, *more = (overall(each) for each in counted(seats, said).values())
if more and first == second:
return Failure(f"{' and '.join(FIRST_SEATS)} both count as {first} overall, which settles the ruling; drop the other seats' lines")
return said
@@ -38,6 +35,11 @@ def names_a_place(seat: Seat, dimension: str) -> bool:
return any(PLACE.search(place) and (dimension == DIMENSIONS[-1] or dimension in place_dimensions(place)) for place in seat.places)
def surplus(overall: list[str]) -> bool:
"""Whether seats beyond the first two voted, though the first two agree overall: their agreement settles the ruling by itself."""
return len(overall) > 2 and overall[0] == overall[1]
def split(overall: list[str]) -> bool:
"""Whether only the first two seats voted overall and they differ, so two more must vote: two votes that differ cannot reach a lead of two."""
return len(overall) == 2 and overall[0] != overall[1]
+1 -3
View File
@@ -1,8 +1,6 @@
import decimal
from comprehension_history import DIMENSIONS
FLOOR = decimal.Decimal("7.0")
from comprehension_history import DIMENSIONS, FLOOR
def means(lines: list[list[str]]) -> list[decimal.Decimal]:
+130 -21
View File
@@ -13,14 +13,15 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from larv_review.agreement import agreement_report, ruling_agreement, run_agreement
from comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
import comprehension_history
from larv_review.ruling import counted, ruling, split, votes
from larv_review.ruling import counted, ruling, split, surplus, votes
from failure import Failure
from test_env import isolated_env
from todo_table import Item, items
from todo_table import Item, items, NoItemsTable
from larv_review.plan import landed_towards, plan_reasons, scoring_run_due
from chunk_pick import LastCut
from larv_review.scoring import means, under_floor
from larv_review.ruling_base import measured_commit
from larv_review.seats import score_line, scores, seats_file
from larv_review.plan import scoring_run_due
TOOL = pathlib.Path(__file__).resolve().parents[1] / "larv-review"
SCORING = "## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mean | 7.00 |\n"
@@ -67,9 +68,14 @@ class Seats(unittest.TestCase):
self.assertIsInstance(votes([Seat("Mid A", said("better"), ["`a.py:3` `f`: Locality: x"]), seats[1]]), Failure)
self.assertEqual(votes(seats), {seat.name: written[seat.name] for seat in seats})
def test_refuses_two_more_seats_once_the_first_two_agree_overall(self):
def test_reads_the_other_two_seats_even_when_the_first_two_agree_overall(self):
seats = [Seat(name, said(vote), ["Overall: `f.py:1` `f`: x"]) for name, vote in (("Mid A", "worse"), ("Inherited architect", "worse"), ("Maintainability senior", "better"), ("Junior A", "better"))]
self.assertIsInstance(votes(seats), Failure)
self.assertEqual(list(votes(seats)), [seat.name for seat in seats])
def test_flags_seats_beyond_the_first_two_when_those_agree_overall(self):
self.assertTrue(surplus(["worse", "worse", "better", "better"]))
self.assertFalse(surplus(["worse", "worse"]))
self.assertFalse(surplus(["worse", "same", "better", "better"]))
def test_takes_the_first_two_seats_then_the_other_two_in_order_and_each_dimensions_vote(self):
first = [Seat("Mid A", said("same"), []), Seat("Inherited architect", said("same"), [])]
@@ -161,6 +167,8 @@ class History(unittest.TestCase):
first, rerun, other = (run.format(time=time, pr=pr, commit=commit, line=line) for time, pr, commit, line in (("2026-10-08T12:00:00Z", "PR #1", "aaaaaaa", 1), ("2026-10-08T13:00:00Z", "PR #1 rerun", "aaaaaaa", 2), ("2026-10-09T12:00:00Z", "PR #2", "bbbbbbb", 3)))
self.assertEqual(latest_places(appended(appended("", first), rerun)), first + "\n" + rerun)
self.assertEqual(latest_places(appended(appended(appended("", first), rerun), other)), other)
in_full = rerun.replace("aaaaaaa", "aaaaaaa" + "0" * 33)
self.assertEqual(latest_places(appended(appended("", first), in_full)), first + "\n" + in_full)
def scored(time: str, pr: str, commit: str, mid: str, architect: str) -> str:
@@ -258,50 +266,77 @@ class Base(unittest.TestCase):
class ScoringRunDue(unittest.TestCase):
def test_reads_each_rows_id_release_and_tagline(self):
self.assertEqual(items(todo("| 3 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")), [item(3, (0, 1, 0))])
self.assertIsNone(items("# todo\n"))
self.assertEqual(items("# todo\n"), NoItemsTable("todo.md holds no items table"))
self.assertIsInstance(items("# todo\n"), Failure)
self.assertIsInstance(items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")), Failure)
def test_is_due_for_an_item_naming_the_floor(self):
plan = [item(1, (0, 1, 0), "**Lift the project to the Comprehension floor.**"), item(2, (0, 1, 0))]
self.assertEqual(scoring_run_due(plan, plan, [1], True, set()), ["ships item 1, which names the comprehension floor"])
self.assertIsInstance(scoring_run_due(plan, plan, [9], True, set()), Failure)
self.assertEqual(scoring_run_due(plan, plan, [1], (0, 1, 0), set()), ["ships item 1, which names the comprehension floor"])
self.assertIsInstance(scoring_run_due(plan, plan, [9], (0, 1, 0), set()), Failure)
def test_is_due_when_the_chunk_ships_a_releases_last_item(self):
plan = [item(1, (0, 1, 0)), item(2, (0, 2, 0))]
self.assertEqual(scoring_run_due(plan, plan, [1], False, set()), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(plan, plan + [item(3, (0, 1, 0))], [1], True, set()), [])
self.assertEqual(scoring_run_due(plan, plan, [1], None, set()), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(plan, plan + [item(3, (0, 1, 0))], [1], (0, 1, 0), set()), [])
def test_is_due_when_the_chunk_removes_the_next_releases_last_item_after_work_landed(self):
before = [item(1, (0, 1, 0)), item(2, (0, 1, 0)), item(3, (0, 2, 0))]
after = [item(2, (0, 1, 0)), item(3, (0, 2, 0))]
self.assertEqual(scoring_run_due(before, after, [2], True, set()), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(before, after, [], True, set()), [])
self.assertEqual(scoring_run_due(before, after, [2], (0, 1, 0), set()), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(before, after, [], (0, 1, 0), set()), [])
emptied = [item(3, (0, 2, 0))]
self.assertEqual(scoring_run_due(before, emptied, [2], False, set()), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(before, emptied, [], True, set()), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(before, emptied, [], False, set()), [])
self.assertEqual(scoring_run_due(before, emptied, [2], None, set()), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(before, emptied, [], (0, 1, 0), set()), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(before, emptied, [], None, set()), [])
def test_is_not_due_when_the_chunk_marks_the_next_release_renamed(self):
before = [item(1, (0, 2, 1)), item(2, (0, 3, 0))]
renamed = {(0, 2, 1)}
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 4, 0))], [], True, renamed), [])
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], True, renamed), [])
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 4, 0))], [], (0, 2, 1), renamed), [])
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], (0, 2, 1), renamed), [])
dropped = [item(1, (0, 2, 1)), item(3, (0, 2, 1)), item(2, (0, 3, 0))]
self.assertEqual(scoring_run_due(dropped, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], True, renamed), [])
self.assertEqual(scoring_run_due(dropped, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], (0, 2, 1), renamed), [])
def test_is_due_when_the_chunk_defers_the_next_releases_last_items_unmarked(self):
before = [item(1, (0, 2, 1)), item(2, (0, 3, 0))]
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], True, set()), ["leaves release 0.2.1 with no plan item"])
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], (0, 2, 1), set()), ["leaves release 0.2.1 with no plan item"])
def test_words_the_emptied_release_reason_as_skill_md_s_second_run_quotes_it(self):
skill = (pathlib.Path(__file__).resolve().parents[2] / "skills" / "larv-review" / "SKILL.md").read_text()
self.assertIn("`leaves release … with no plan item`", skill)
reasons = scoring_run_due([item(1, (0, 1, 0))], [], [], True, set())
reasons = scoring_run_due([item(1, (0, 1, 0))], [], [], (0, 1, 0), set())
self.assertRegex(reasons[0], r"^leaves release [0-9.]+ with no plan item$")
def test_is_not_due_when_a_later_release_loses_its_last_item_unshipped(self):
before = [item(1, (0, 1, 0)), item(3, (0, 2, 0))]
self.assertEqual(scoring_run_due(before, before[:1], [], True, set()), [])
self.assertEqual(scoring_run_due(before, before[:1], [], (0, 1, 0), set()), [])
class LandedTowards(unittest.TestCase):
def test_names_the_next_release_only_where_a_change_is_unreleased(self):
plan = [item(1, (0, 2, 0))]
changelog = "# Changelog\n\n## Unreleased\n\n- Did a thing.\n"
self.assertEqual(landed_towards(plan, LastCut("v0.1.0", changelog, 0, [])), (0, 2, 0))
self.assertEqual(landed_towards(plan, LastCut("v0.1.0", "# Changelog\n\n## Unreleased\n", 3, [])), None)
self.assertEqual(landed_towards(plan, LastCut("v0.1.0", "", 3, [])), (0, 2, 0))
self.assertEqual(landed_towards(plan, LastCut(None, "", 0, [])), None)
def test_names_no_release_where_the_plan_files_items_under_the_last_cut_or_names_none_after_it(self):
changelog = "# Changelog\n\n## Unreleased\n\n- Did a thing.\n"
self.assertIsNone(landed_towards([item(1, (0, 1, 0))], LastCut("v0.1.0", changelog, 0, [])))
self.assertIsNone(landed_towards([], LastCut("v0.1.0", changelog, 0, [""])))
def test_names_the_next_release_where_the_plan_holds_no_item_for_it(self):
named = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 1 | 0.2.0 | | | **Do 1.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
changelog = "# Changelog\n\n## Unreleased\n\n- Did a thing.\n"
self.assertEqual(landed_towards([item(2, (0, 3, 0))], LastCut("v0.1.0", changelog, 0, [f"## Items\n\n{named}"])), (0, 2, 0))
def test_fails_where_the_changes_or_the_next_release_cannot_be_read(self):
plan = [item(1, (0, 2, 0))]
self.assertIsInstance(landed_towards(plan, LastCut("v0.1.0", Failure("unreadable"), Failure("count unreadable"), [])), Failure)
self.assertIsInstance(landed_towards([], LastCut("v0.1.0", "", 3, Failure("log unreadable"))), Failure)
class LarvReviewTool(unittest.TestCase):
@@ -377,6 +412,24 @@ class LarvReviewTool(unittest.TestCase):
self.commit("Mark 0.1.0 renamed", {"todo.md": todo(*rows) + "\n## Renamed\n\n- 0.1.0 renamed to 0.2.0\n"})
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
def test_counts_work_landed_from_the_changelogs_unreleased_entries_where_it_has_that_section(self):
self.git("tag", "v0.0.1")
self.commit("Commit after the tag", {"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n## 0.0.1\n"})
self.git("push", "-q", "origin", "HEAD:main")
rows = ("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")
self.commit("Move 0.1.0's item to 0.2.0 and log a change", {"todo.md": todo(*rows), "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- The chunk's own change.\n\n## 0.0.1\n"})
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
self.git("reset", "-q", "--hard", "HEAD~1")
self.commit("Log a change", {"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Did a thing.\n\n## 0.0.1\n"})
self.git("push", "-q", "origin", "HEAD:main")
self.commit("Move 0.1.0's item to 0.2.0", {"todo.md": todo(*rows)})
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "Scoring run due: the chunk leaves release 0.1.0 with no plan item.\n")
def test_refuses_where_the_default_branchs_unreleased_changes_cannot_be_read(self):
self.addCleanup(os.chdir, os.getcwd())
os.chdir(self.checkout)
self.assertIsInstance(plan_reasons("no-such-ref", []), Failure)
def test_refuses_a_checkout_plan_whose_renamed_section_does_not_parse(self):
self.commit("Break the mark", {"todo.md": todo("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |") + "\n## Renamed\n\nsoon\n"})
broken = self.run_tool("needs-scoring-run")
@@ -418,6 +471,13 @@ class LarvReviewTool(unittest.TestCase):
self.assertEqual(recorded[0].ruled_places, [Place("bin/a.py", "f")] * 2)
self.assertIn("| Junior A | same | same | same | same | same (voted worse, naming no place) |", history.read_text())
def test_refuses_the_other_seats_lines_once_the_first_two_agree_overall(self):
lines = f"PR #2 at {self.start}, against {self.start}\n\n" + "\n".join(f"{seat}: {said('worse')}\n\n- Overall: `bin/a.py:3` `f`: hard\n" for seat in ("Mid A", "Inherited architect", "Maintainability senior", "Junior A"))
ran = self.run_tool("record-ruling", self.seats_file(lines))
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("both count as worse overall, which settles the ruling; drop the other seats' lines", ran.stderr)
self.assertFalse((self.checkout / "docs" / "comprehension-history.md").exists())
def test_records_a_ruling_whose_dimension_fell_and_takes_no_scores_file(self):
place = "\n\n- Locality, Overall: `bin/a.py:3` `f`: shorter\n\n"
votes_file = self.seats_file(f"PR #2 at {self.start}, against {self.start}\n\nMid A: {said('better', 'worse')}{place}Inherited architect: {said('better', 'worse')}{place}", "votes.md")
@@ -438,6 +498,7 @@ class LarvReviewTool(unittest.TestCase):
uncalled = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats))
self.assertEqual(uncalled.returncode, 1)
self.assertIn("no plan item or release calls this scoring run", uncalled.stderr)
self.plan()
ran = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("\nFloor: Locality 6.50, Self-sufficiency 6.50 under the floor of 7.0.\n", ran.stdout)
@@ -447,6 +508,54 @@ class LarvReviewTool(unittest.TestCase):
self.assertIn("Inherited architect, would restructure first:", text)
self.assertEqual(entries(text)[0].scored_places, [Place("bin/a.py", "f")] * 4)
def plan(self, readme="# P\n\n## Goals\n\n1. **Achieve:** A.\n", bar="0.1"):
"""Commit and push the README.md and a todo.md whose item 1, alone in release 0.1.0, moves code health, each item scored as before any scoring run."""
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
# Before any scoring run code health weighs four times its weight at an overall of 7.0: 4 / 1.97 against goal 1's 0.97 / 1.97.
rows = "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 101.5 |\n| 2 | 0.2.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 3 | 73.9 |\n"
self.commit("Plan", {"README.md": readme, "todo.md": f"# todo\n\n## Scoring\n\n`Score = 100 * V / 2**S`\n\n`Bar = {bar}`\n\n`Next ID = 3`\n\n## Items\n\n" + header + rows})
self.git("push", "-q", "origin", "HEAD:main")
def record_sevens(self):
"""Run record-scoring for item 1 on a scores file in which every seat scores 7 throughout."""
line = "Navigation 7, Locality 7, Shape 7, Self-sufficiency 7, Overall 7"
seats = "".join(f"\n{seat}: {line}\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
return self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
def test_reports_a_plan_it_cannot_read_yet_keeps_the_run(self):
# This checkout has no README.md beside its todo.md.
ran = self.record_sevens()
self.assertEqual(ran.returncode, 1)
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: {self.checkout / 'README.md'}: not found", ran.stderr)
self.assertIn("not record-scoring again", ran.stderr)
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
def test_reports_a_plan_it_reads_but_cannot_rank_yet_keeps_the_run(self):
self.plan(readme="# P\n\n## Goals\n\n**Void:** code health, since it is a probe.\n\n1. **Achieve:** A.\n")
ran = self.record_sevens()
self.assertEqual(ran.returncode, 1)
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: item 1 names code health, which README.md voids", ran.stderr)
self.assertIn("not record-scoring again", ran.stderr)
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
def test_reranks_todo_md_by_the_overall_it_records(self):
self.plan()
ran = self.record_sevens()
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("| code health by 1 | 25.4 |", (self.checkout / "todo.md").read_text())
def test_fails_once_its_re_rank_leaves_an_item_under_the_bar_yet_keeps_the_run(self):
self.plan(bar="30")
ran = self.record_sevens()
self.assertEqual(ran.returncode, 1)
todo = self.checkout / "todo.md"
# At an overall of 7.0 item 1 falls from 101.5 to 25.4.
self.assertIn(f"{todo}: item 1 scores 25.4, under the bar 30; delete it, or mark it with a reason the bar does not apply\n", ran.stderr)
self.assertIn("recorded the run", ran.stderr)
self.assertIn("not record-scoring again", ran.stderr)
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
def test_prints_the_places_seats_found_hard_since_the_newest_scoring_run(self):
self.assertEqual(self.run_tool("places").stdout, "Seats found no places hard.\n")
self.commit("Record a scoring run", {"docs/comprehension-history.md": appended("", SCORING + "\nJunior A, hardest first:\n\n- `bin/b.py:4` `h`: long\n")})
+66 -93
View File
@@ -7,9 +7,9 @@ from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typ
from claude_code.reply import claude_reply, Limited
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.project.records import HUMAN_RULE_NAMES
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 markdown_text import listed
from model_routing.route import on_its_scale
from claude_code.transcript import render
from loop_claude.cycle.retry import retried
@@ -21,7 +21,7 @@ from claude_code.entries import structured_output
JUDGE_PROMPT_CHARS = 400000
INTERRUPT_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
"- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither "
"- the worker asks the human anything, seeks approval, or says a decision is the human's, and neither "
"README.md nor the records settle the matter\n"
"- it asks again a question a [loop] line already answered\n"
"- it carried on under an assumption that decides the deliverable, that the human could "
@@ -31,46 +31,50 @@ INTERRUPT_RULES = (
"outside the repo, or a release ready to cut, which only the human may publish\n"
"- it flags that the goals, the plan in todo.md or the task itself is unclear, missing or in need of change\n"
"- it chose between alternatives that neither README.md nor the records discriminate "
"between - neither rules the rejected one out - and the choice materially changes the deliverable\n"
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
"between - neither rules the rejected one out - and the choice materially changes the deliverable\n\n"
"interrupt=false otherwise. Bookkeeping the worker settled silently - what to document, wording, "
"where a note goes - is not on its own a reason to interrupt. A run that ends asking loop-claude for a higher "
"rung is no reason to interrupt either; one that asks the human's yes to a higher rung is. The human may have replied inside the transcript, on a [human] line: judge only what "
"is still open, never a question they already answered there. A [loop] line is what loop-claude told "
"the agent, such as an answer quoted from README.md or the records.\n\n"
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
"rung is no reason to interrupt either; one that asks the human's yes to a higher rung is.\n\n"
"The human may have replied inside the transcript, on a [human] line: judge only what "
"is still open, never a question they already answered there.\n\n"
"Where the worker asked or flagged something itself, the question is that one, in the worker's own "
"wording; never construct another from facts it stated."
)
QUOTE_RULES = (
"Where README.md or the records answer the agent's own question and no [loop] line has "
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the agent is "
"Where README.md or the records answer the worker's own question and no [loop] line has "
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the worker is "
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
"outranks finished."
)
FINISHED_RULES = (
"The chunk is the piece of work the agent is on, shipped as one pull request. "
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}. An answer counts as recorded "
f"where README.md or the records above hold it, {', '.join(HUMAN_RULE_NAMES)} included. It also counts where "
f"the transcript shows the agent writing it into {ANSWER_DESTINATIONS}; writing it into "
f"{listed(HUMAN_RULE_NAMES, 'or')} does not count. finished=false when work remains that a further run can "
"The chunk is the piece of work the worker is on, shipped as one pull request.\n\n"
"finished=true when the chunk is complete: merged, or nothing remains that the worker could do on "
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}.\n\n"
"An answer counts as recorded where README.md or the records above already hold it, the human's rules "
"(~/.claude/CLAUDE.md, ~/.claude/rules/, ~/.claude/skills/larv-review/standards/) included. "
f"It also counts where the transcript shows the worker writing it into {ANSWER_DESTINATIONS}, "
"but not into one of the human's rules.\n\n"
"finished=false when work remains that a further run can "
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
)
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)
class Reply:
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."})
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the worker's question, quoted verbatim, without elisions. Empty otherwise."})
# Routes the next cycle's worker. Counting the item the chunk was routed on is harmless: loop-claude never steps the worker down.
bundled: int = dataclasses.field(metadata={"description": "The highest L the agent 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 bundled routes the worker.
bundled_escape_and_impact: int = dataclasses.field(metadata={"description": "The highest E + I the agent states for a todo.md item it took into this chunk; 0 when it states none."})
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 agent's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of an earlier transcript passage showing the trigger fired after any earlier such request, such as a review round's commit title or the agent's report of the finding or failing test. 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 agent's question; else what shows the chunk finished or the work remaining."})
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."})
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."})
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."})
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the worker's question that the answer field answers. Empty otherwise."})
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (chunk_pick.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed.
release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."})
@@ -91,45 +95,16 @@ class Rejected(Failure):
reply: str
@dataclasses.dataclass(frozen=True)
class Interrupt:
evidence: str
question: str
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
escalation: str = ""
# The bundled L the judge saw, 0 for none, as on Unfinished: an escalation steps up from the rung that item picks.
bundled: int = 0
release_ready: bool = False
@dataclasses.dataclass(frozen=True)
class QuotedAnswer:
"""The agent asked a question that README.md or the records answer. The answer field quotes the passage."""
evidence: str
question: str
answer: str
# As on Interrupt.
escalation: str = ""
bundled: int = 0
@dataclasses.dataclass(frozen=True)
class Finished:
evidence: str
@dataclasses.dataclass(frozen=True)
class Unfinished:
evidence: str
# The bundled L the judge saw, 0 for none.
bundled: int = 0
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
escalation: str = ""
# The bundled E + I the judge saw, 0 for none.
bundled_escape_and_impact: int = 0
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
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.
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
def verdict_from(output: object) -> Verdict | Failure:
@@ -139,30 +114,31 @@ def verdict_from(output: object) -> Verdict | Failure:
# type(), not isinstance(): JSON true is no integer.
if type(output.get(name)) is not kind:
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
# A bundled level off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
bundled = output["bundled"] if 0 <= output["bundled"] <= HIGHEST_L else 0
# An L taken in off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
likelihood = output["highest_likelihood_taken_in"] if 0 <= output["highest_likelihood_taken_in"] <= HIGHEST_L else 0
if output["interrupt"]:
if not output["question"].strip():
return Failure("the judge interrupted without a question")
return Interrupt(output["evidence"], output["question"], output["escalation"], bundled, output["release_ready"])
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, release_ready=output["release_ready"])
if output["answer"].strip():
if not output["question"].strip():
return Failure("the judge quoted an answer without a question")
return QuotedAnswer(output["evidence"], output["question"], output["answer"], output["escalation"], bundled)
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood)
if output["finished"]:
return Finished(output["evidence"])
bundled_escape_and_impact = output["bundled_escape_and_impact"] if on_its_scale(output["bundled_escape_and_impact"]) else 0
return Unfinished(output["evidence"], bundled, output["escalation"], bundled_escape_and_impact)
escape_and_impact = output["highest_escape_and_impact_taken_in"] if on_its_scale(output["highest_escape_and_impact_taken_in"]) else 0
return Unfinished(output["evidence"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, highest_escape_and_impact_taken_in=escape_and_impact)
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
return retried("judge", lambda: judge_once(root, task, premises, records, entries, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
return retried("judge", lambda: judge_once(root, task, premises, records, entries, escalated_at, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
def judge_once(root: str, task: str, premises: str, records: str, entries: list[dict], rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run on the transcript's entries, as judge retries it; judge-replay replays it."""
prompt, shown = judge_prompt(task, premises, records, render(entries, typed_answer))
return run_judge(root, judge_args(rung), prompt, shown, f"{premises}\n\n{records}", effects)
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."""
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
def judge_args(rung: Rung) -> list[str]:
@@ -175,13 +151,8 @@ def judge_args(rung: Rung) -> list[str]:
]
def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run. Each quote in its verdict is checked word for word, since stitched fragments can say what their source does not:
- the evidence, against shown (the transcript as the judge saw it), its fragments in order: a misquote is Rejected, which judge retries;
- a quoted answer, against quotable: a misquote puts the question to the human;
- an escalation, against shown: a misquote drops it, so the worker's rung holds.
quotes_checked checks the last two. Neither misquote is a Failure, which would otherwise exit an unattended loop.
"""
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."""
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
if isinstance(reply, Failure | Limited):
return reply
@@ -189,32 +160,34 @@ def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str
replied = json.dumps(reply, ensure_ascii=False)
if isinstance(verdict, Failure):
return Rejected(verdict.reason, replied)
if not grounded(verdict.evidence, shown):
if not grounded(verdict.evidence, grounds.shown):
return Rejected(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else ""), replied)
return quotes_checked(verdict, shown, quotable)
return quotes_checked(verdict, grounds)
def quotes_checked(verdict: Verdict, shown: str, quotable: str) -> Verdict:
"""The verdict with its quoted answer and its escalation checked, as run_judge says; a quoted answer put to the human keeps the escalation it carried."""
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable):
verdict = Interrupt(verdict.evidence, verdict.question, verdict.escalation, verdict.bundled)
if isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) and verdict.escalation and not verbatim(verdict.escalation, shown):
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."""
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
def judge_prompt(task: str, premises: str, records: str, rendered_transcript: str) -> tuple[str, str]:
"""The prompt, and the part of the transcript it shows, which the judge's evidence must quote."""
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]
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"
f"The task an agent was given:\n{task}\n\n"
"What the agent did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\n"
f"The task the worker was given:\n{task}\n\n"
"What the worker did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\n"
)
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 = rendered_transcript[max(0, len(rendered_transcript) - room):]
return f"{head}{shown}\n\n{JUDGE_RULES}", shown
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}")
def grounded(evidence: str, rendered_transcript: str) -> bool:
+60 -27
View File
@@ -1,8 +1,9 @@
from model_routing.ladder import climbed, LADDER, position, review_rungs, ReviewKind, Rung
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
from loop_claude.routing import escalation_rungs
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
from markdown_text import listed, quoted
from review_passes import REVIEWERS
from claude_code.transcript import Typed
# Where the judge may quote an answer from, named as the human and the worker see them; of README.md the judge sees only the premises.
@@ -10,15 +11,18 @@ 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.
REVIEWS: tuple[tuple[str, ReviewKind], ...] = (("each reviewer", "reviewer"), ("each comprehension seat", "seat"), ("the security pass's subagent", "security"))
# 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"))
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:
"""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 choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
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}"
def routed_by(route: Route, anchor: Rung | None) -> str:
@@ -41,21 +45,32 @@ def preflight_failed(reason: str) -> str:
def review_launches(route: Route, anchor: Rung | None) -> str:
"""Which reviews to launch on a rung other than the worker's, and on which; 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.
"""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.
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.`
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.`
"""
if anchor is None:
return ""
rungs = review_rungs(anchor, route.rung, route.reviewed_on())
launched: dict[Rung, list[str]] = {}
for reviews, kind in REVIEWS:
if rungs[kind] != route.rung:
launched.setdefault(rungs[kind], []).append(reviews)
launches = "".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())
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"{launches}{scan}{planning}{taken_in_launches(route, anchor)}"
return f"{shared_launches(rungs, reviewers, route, anchor)}{lowered_launches}{scan}{planning}{taken_in_launches(route, anchor)}"
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}
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())
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(route: Route, anchor: Rung) -> str:
@@ -63,12 +78,12 @@ def taken_in_launches(route: Route, anchor: Rung) -> str:
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.`
"""
reviewers = review_rungs(anchor, route.rung, route.reviewed_on())["reviewer"]
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):
rung = review_rungs(anchor, route.rung, escape_and_impact)["reviewer"]
if position(rung) > position(reviewers):
higher.setdefault(rung, escape_and_impact)
# 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()]
@@ -85,25 +100,43 @@ def rung_named(rung: Rung, route: Route, anchor: Rung) -> str:
def escalation(route: Route, anchor: Rung | None) -> str:
"""The prompt's escalation sentences, the marker's among them. Empty 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."""
"""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.
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`.`
"""
if anchor 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."
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)]
if not rungs:
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}"
return " " + " ".join((
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 ""
resumed_higher = 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 such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to {rungs[-1]}."
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}{resumed_higher}"
return " " + " ".join((
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 sentence naming the rung one above a reviewer's and a seat's, on which each reruns when it asks; empty off the ladder, and leaving out one already on the top rung."""
"""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.
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.`
"""
if anchor is None or route.rung not in LADDER:
return ""
rungs = review_rungs(anchor, route.rung, route.reviewed_on())
launched = (("reviewer", rungs["reviewer"]), ("comprehension seat", rungs["seat"]))
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}"
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))
rerun = {name: climbed(rung, 1) for name, rung in launched if rung != LADDER[-1]}
if not rerun:
return ""
@@ -149,7 +182,7 @@ def typed_answer(prompt: str) -> Typed | None:
def stepped_to(route: Route, anchor: 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}.{rungs_held(route, anchor)} A further request for a higher rung steps you up no more in this cycle." 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, anchor)}" if stepped else ""
def past_the_cap(question: str, answer: str, cap: int) -> str:
+13 -21
View File
@@ -3,12 +3,13 @@ import pathlib
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 claude_code.session import delete_session, Session, session_open, transcript_file
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.cycle.judge import Finished, Interrupt, judge, QuotedAnswer, Rejected, Unfinished, Verdict
from loop_claude.routing import judge_rung, stepped_by_ruling
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.cycle.judge import judge, Rejected
from transcript_archive import outcomes
from loop_claude.paths import Paths
from loop_claude.cycle import prompts
@@ -43,8 +44,6 @@ class Cycle:
# 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
# Whether an interrupt or a quoted answer of this cycle took an escalation, after which no ruling of the cycle carries one.
escalation_spent: bool = False
@dataclasses.dataclass(frozen=True)
@@ -73,15 +72,15 @@ def escalated(cycle: Cycle, event: Event) -> Cycle:
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 event.verdict.escalation):
if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and cycle.anchor):
return cycle
route = stepped_by_ruling(cycle.anchor, cycle.route, event.verdict.bundled) if cycle.anchor else cycle.route
return dataclasses.replace(cycle, route=route, stepped_from=cycle.route if route != cycle.route else None, escalation_spent=True)
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 stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
path = transcript_file(cycle.session)
failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(str(cycle.route), why), cycle.effects.now()) if path else None
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 Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
@@ -139,7 +138,7 @@ def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None:
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)), str(cycle.stepped_from or cycle.route))
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):
return Stop(1, failure.reason)
return None
@@ -149,15 +148,8 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
entries = read_transcript(transcript_path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, entries, judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
return verdict if isinstance(verdict, Stop) else Ruled(unspent(verdict, cycle.escalation_spent))
def unspent(verdict: Verdict, spent: bool) -> Verdict:
"""The verdict without its escalation once an interrupt or a quoted answer of the cycle took one. The judge may quote a different passage for the trigger that already stepped the route, and no comparison of quotes tells the two apart, so one trigger buys one step. It lives here, not in judge.quotes_checked, since it reads the cycle, and judge-replay replays the judge alone."""
if spent and isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) and verdict.escalation:
return dataclasses.replace(verdict, escalation="")
return verdict
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)
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
@@ -171,7 +163,7 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
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, str(cycle.stepped_from or cycle.route))
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):
return Stop(1, failure.reason)
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
@@ -184,7 +176,7 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
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(str(cycle.route))) if cycle.stepped_from else (outcome,):
for kept in (outcome, outcomes.stepped_up(cycle.route.record())) if cycle.stepped_from else (outcome,):
if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now()):
return failure
return None
@@ -197,7 +189,7 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
outcome = outcomes.finished(str(cycle.route), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(str(cycle.route), verdict.evidence, str(judge_of(cycle)), verdict.escalation)
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)
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)):
+1 -1
View File
@@ -1,6 +1,6 @@
import dataclasses
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
# A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records.
QUOTED_ANSWERS_PER_CYCLE = 3
+2
View File
@@ -47,6 +47,8 @@ def worker_args(session: Session, worker: Rung, prompt: str, resume: bool) -> li
*start,
"--output-format", "stream-json",
"--permission-mode", "bypassPermissions",
# A pending wakeup keeps claude -p from exiting, which holds back the judge.
"--disallowedTools", "ScheduleWakeup",
"--verbose",
*worker.flags(),
]
+11 -2
View File
@@ -6,10 +6,19 @@ import termios
import time
import typing
from failure import Failure
import git_repo
# 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
class Git(typing.Protocol):
"""Runs git in cwd, as git_repo.git does."""
def __call__(self, *args: str, cwd: str) -> str | Failure: ...
class Streaming(typing.Protocol):
"""A started claude whose stream-json lines arrive as it works."""
@@ -25,7 +34,7 @@ class Effects:
# Drops what was typed on the terminal and not yet read.
discard_typed: typing.Callable[[], None]
execv: typing.Callable[[str, list[str]], None]
git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
git: Git
input: typing.Callable[[str], str]
local_time: typing.Callable[[float], str]
now: typing.Callable[[], float]
@@ -54,7 +63,7 @@ def system_effects() -> Effects:
claude_on_terminal=lambda args, cwd, env: subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode,
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
execv=os.execv,
git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True),
git=git_repo.git,
input=input,
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)),
now=time.time,
+121 -97
View File
@@ -4,10 +4,11 @@ usage: loop-claude <task>
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first
worker prompt also quotes the premises, which choose between ways to deliver the chunk's todo.md
items, or else the task, and never widen them. A judge then reads the transcript's end, the
premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's
~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
worker prompt also quotes the premises. They, with code health
(~/.claude/CLAUDE.md → "Shared goal") ranked first unless README.md voids it, choose between ways
to deliver the chunk's todo.md items, or else the task, and never widen them. A judge then reads
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md,
and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker
@@ -38,17 +39,10 @@ facts itself.
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
copied to $LOOP_CLAUDE_TRANSCRIPTS/<key>/<chunk>/<sha256>.jsonl (default
~/.claude/loop-claude-transcripts), named by its hash. <chunk> is the hash of the transcript's first
line with a timestamp, the same for every cycle of a chunk. Beside the copy, <sha256>.outcomes.md
holds the verdict, with the transcript passage the judge rested it on, any passage it quoted to
show an escalation trigger fired, and the judge's rung; each answer the judge quoted, with the
question it answers and any passage it quoted to show an escalation trigger fired; each judge
reply the loop rejected, with the reason and the reply as json; and why the loop stopped. Each of these opens with its UTC time. Claude Code keeps a folder per
session beside its transcript, holding the subagents' transcripts among other files; that folder,
and every other file named after the session except the transcript, are copied into
<chunk>/session/. A file there is replaced only by a version that grew from it. A file Claude Code
rewrote lands beside its copy as <name>.<hash of its content>.
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
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.
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,
@@ -56,72 +50,98 @@ the session /talk opens and the judge on another rung; a project without an entr
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.
Where that 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. The
item's E + I picks the reviewers' rung, stepping up from the cheapest rung by REVIEW_STEPS there,
never below the worker's rung. 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 for the reviewers, 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 reviewers', in
LOOP_CLAUDE_WORKER_RUNG, LOOP_CLAUDE_PROJECT_RUNG and LOOP_CLAUDE_REVIEWER_RUNG, and rule-hook
refuses a review launched below the rung named for it. 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.stepped). 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.stepped_by_ruling), and no later ruling of that cycle carries a second escalation. 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. Each finished or unfinished verdict, interrupt,
quoted answer, stop and step-up in the archive names the worker's rung, with the item, L and E + I
that routed the chunk, and any taken-in E + I that picks a higher review rung, which is archived as
a step-up too. A rerun resumes an open chunk on the latest
route named there, and counts its unfinished verdicts afresh. 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 worker'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
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.
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.
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.
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.
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.
@@ -163,18 +183,18 @@ import pathlib
import sys
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.loop.routing_check import check_routing
from loop_claude.project.checkout import checkout_root
from loop_claude.cycle.run import Cycle, run_cycle
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.cycle.judge import Finished, Unfinished
from loop_claude.routing import first_route, kept, routed_item, stepped
from loop_claude.verdicts import Finished
from loop_claude.project.model_choice import get_or_ask_models
from todo_table import Item
from transcript_archive.read import latest_worker
@@ -228,43 +248,44 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
# 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)
loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), item)
route = loop_run.route or Route(Rung(models.worker))
route = routed(loop_run.route, anchor, 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))
if isinstance(concluded, Stop):
return concluded
# The route the cycle ended on, which a step-up at an interrupt or a quoted answer may have raised and archived, is the one the verdict steps from.
ended = dataclasses.replace(loop_run, route=concluded.route if anchor else None)
before, loop_run = ended.route, after_verdict(ended, anchor, concluded.verdict)
if stop := archive_step(archive_folder, session, loop_run, before, effects):
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):
return stop
def routed(loop_run: LoopRun, anchor: Rung | None, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> LoopRun:
"""The loop run with its chunk's route, or None when the project's model is off the ladder. A chunk keeps its route, or on a rerun the one its archive last names,
while that is at or above the rung its item's L picks from anchor, the project's rung; else the plan item routes it afresh."""
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.
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.
"""
if anchor is None:
return dataclasses.replace(loop_run, route=None)
route = loop_run.route or archived()
return dataclasses.replace(loop_run, route=route if route and kept(route, anchor) else first_route(anchor, item()))
return Route(Rung(model))
route = route or archived()
return route if route and kept(route, anchor) else first_route(anchor, item())
def after_verdict(loop_run: LoopRun, anchor: Rung | None, verdict: Finished | Unfinished) -> LoopRun:
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."""
verdict = concluded.verdict
if isinstance(verdict, Finished):
return dataclasses.replace(loop_run, route=None, unfinished_evidence="")
route = stepped(anchor, loop_run.route, verdict.bundled, bool(verdict.escalation)).taking_in(verdict.bundled_escape_and_impact) if anchor and loop_run.route else loop_run.route
route = after_unfinished(anchor, concluded.route, verdict) if anchor else concluded.route
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence)
def archive_step(archive_folder: pathlib.Path, session: Session, loop_run: LoopRun, before: Route | None, effects: Effects) -> Stop | None:
"""Archives the rung an unfinished verdict stepped the chunk up to, or the higher E + I it took in; the verdict itself names the route its cycle ran on."""
if not (before and loop_run.route) or str(loop_run.route) == str(before):
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():
return None
path = transcript_file(session)
failure = archive(archive_folder, path, loop_run.task, outcomes.stepped_up(str(loop_run.route)), effects.now()) if path else None
failure = archive(archive_folder, path, task, outcomes.stepped_up(after.record()), effects.now()) if path else None
return Stop(1, failure.reason) if failure else None
@@ -275,7 +296,10 @@ def archived_route(archive_folder: pathlib.Path, session: Session) -> Route | No
if isinstance(worker, Failure):
print(f"routing the chunk afresh: {worker.reason}", file=sys.stderr)
return None
return route_from(worker) if worker else None
route = route_from(worker) if worker else None
if worker and route is None:
print(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", file=sys.stderr)
return route
def chunk_start(session: Session, preflight: pathlib.Path, root: str, effects: Effects) -> tuple[str, typing.Callable[[], Item | None]]:
+1 -1
View File
@@ -22,7 +22,7 @@ class LoopRun:
root: str
task: str
unfinished_evidence: str
# None until the chunk is routed, and where the project's model is off the ladder.
# Set by each unfinished verdict; None before the chunk's first one, and once it finishes.
route: Route | None = None
+7 -15
View File
@@ -1,25 +1,17 @@
import pathlib
from failure import Failure
from loop_claude.effects import Effects
from loop_claude.stop import Stop
def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop:
try:
found = effects.git(["rev-parse", "--show-toplevel"], str(cwd))
except OSError as failure:
return Stop(1, f"could not start git: {failure.strerror}")
if found.returncode != 0:
return Stop(1, found.stderr.strip())
return found.stdout.strip()
found = effects.git("rev-parse", "--show-toplevel", cwd=str(cwd))
return Stop(1, found.reason) if isinstance(found, Failure) else found.strip()
def worktrees(root: str, effects: Effects) -> list[str]:
found = [root]
try:
listing = effects.git(["worktree", "list", "--porcelain"], root)
except OSError:
return found
if listing.returncode == 0:
found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")]
return sorted(set(found))
listing = effects.git("worktree", "list", "--porcelain", cwd=root)
listed = [] if isinstance(listing, Failure) else [line.split(" ", 1)[1] for line in listing.splitlines() if line.startswith("worktree ")]
return sorted({root, *listed})
+28 -20
View File
@@ -3,8 +3,9 @@ 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 failure import Failure
from todo_table import Item, items
from todo_table import Item, items, NoItemsTable
from model_routing.route import Route
UNFINISHED_PER_STEP = 2
@@ -17,9 +18,11 @@ JUDGE_REPLAYED = ("claude-opus-5-5",)
def routed_item(todo: str, cut: LastCut) -> Item | Failure | None:
"""The item chunk_pick.chunk_item picks from todo.md, weighed against the last cut; None when there is none, or it lacks L, E or I."""
found = items(todo)
if isinstance(found, NoItemsTable):
return None
if isinstance(found, Failure):
return found
pick = chunk_item(found or [], cut)
pick = chunk_item(found, cut)
takes = pick.item if isinstance(pick, Next) else None
return takes if takes and takes.likelihood and takes.escape_and_impact else None
@@ -61,27 +64,32 @@ def escalation_cap(anchor: Rung, route: Route) -> Rung:
return climbed(item_rung(anchor, route), ESCALATION_CAP)
def stepped(anchor: Rung, route: Route, bundled: int, escalated: bool) -> Route:
"""The route after one more unfinished verdict. Its rung never falls below taken_in's. It steps up one rung on every second unfinished verdict, or on an escalation the judge found while the rung is below escalation_cap; where both fall on one verdict, it steps once.
def after_unfinished(anchor: Rung, route: Route, verdict: Unfinished) -> Route:
"""The route the next cycle runs on after an unfinished verdict.
bundled and escalated are the verdict's fields, not the verdict, since loop_claude.cycle.judge imports this module through prompts.
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.
"""
rung = taken_in(anchor, route, bundled)
unfinished = route.unfinished + 1
if unfinished >= UNFINISHED_PER_STEP or (escalated and below_cap(anchor, route, rung)):
return stepped_from(route, rung)
return dataclasses.replace(route, rung=rung, unfinished=unfinished)
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)):
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 stepped_by_ruling(anchor: Rung, route: Route, bundled: int) -> Route:
"""The route after the judge's interrupt or quoted answer carried an escalation: taken_in's rung, one rung up while that is below escalation_cap. Neither is an unfinished verdict, so the count of those restarts only with a step."""
rung = taken_in(anchor, route, bundled)
return stepped_from(route, rung) if below_cap(anchor, route, rung) else dataclasses.replace(route, rung=rung)
def after_ruling(anchor: 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)
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)
def stepped_from(route: Route, rung: Rung) -> Route:
"""The route one rung above rung, with the count of unfinished verdicts restarted."""
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0)
def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
"""The route one rung above rung, with the count of unfinished verdicts restarted and the mark at escalated_at."""
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0, escalated_at=escalated_at)
def below_cap(anchor: Rung, route: Route, rung: Rung) -> bool:
@@ -89,9 +97,9 @@ def below_cap(anchor: Rung, route: Route, rung: Rung) -> bool:
return position(rung) < position(escalation_cap(anchor, route))
def taken_in(anchor: Rung, route: Route, bundled: int) -> Rung:
"""kept_rung, raised to the rung bundled picks from anchor; bundled is the highest L the judge saw the worker take into the chunk, 0 for none."""
return highest(kept_rung(anchor, route), worker_rung(anchor, bundled)) if bundled else kept_rung(anchor, 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 judge_rung(judge_model: str, route: Route) -> Rung:
+24 -20
View File
@@ -21,6 +21,10 @@ from test_env import isolated_env
BIN = pathlib.Path(__file__).resolve().parents[1]
TASK = "Do the next chunk."
# How the archive records a worker that runs off the ladder.
OFF_LADDER = '{"model": "worker-model"}'
# How a reload hands that worker's route.
OFF_LADDER_ROUTE = {"rung": {"model": "worker-model", "effort": ""}, "item": 0, "likelihood": 0, "escape_and_impact": 0, "unfinished": 0, "escape_and_impact_taken_in": 0, "escalated_at": 0}
# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role,
@@ -129,8 +133,8 @@ def worker(**step):
return {"role": "worker", **step}
def judge(interrupt=False, finished=False, evidence="working", question="", bundled=0, bundled_escape_and_impact=0, escalation="", release_ready=False, **step):
verdict = {"answer": "", "bundled": bundled, "bundled_escape_and_impact": bundled_escape_and_impact, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
def judge(interrupt=False, finished=False, evidence="working", question="", highest_likelihood_taken_in=0, highest_escape_and_impact_taken_in=0, escalation="", release_ready=False, **step):
verdict = {"answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
return {"role": "judge", "verdict": verdict, **step}
@@ -327,7 +331,7 @@ class Premises(unittest.TestCase):
(checkout.temp / "fake-bin" / "git").unlink()
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.stderr.strip(), "could not start git: No such file or directory")
self.assertTrue(run.stderr.startswith("git rev-parse --show-toplevel could not start: "), run.stderr)
def test_makes_no_worktree_for_a_readme_without_premises(self):
checkout = Checkout(self)
@@ -371,7 +375,7 @@ class Cycles(unittest.TestCase):
self.assertIsNone(argument(workers[1], "--name"))
self.assertEqual(argument(workers[2], "--session-id"), session)
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
self.assertIn("main or master", argument(workers[0], "-p"))
self.assertNotIn(TASK, argument(workers[1], "-p"))
self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p"))
@@ -386,9 +390,9 @@ class Cycles(unittest.TestCase):
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout)
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
self.assertEqual(sorted(copies), ["<UTC> Stopped: Ctrl-C\n\nWorker: worker-model\n", "<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: worker-model\n", "<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: worker-model\n"])
self.assertIn('"text": "landed-it"', copies["<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: worker-model\n"])
self.assertIn('"text": "next chunk"', copies["<UTC> Stopped: Ctrl-C\n\nWorker: worker-model\n"])
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn('"text": "next chunk"', copies[f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n"])
self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1)
def test_routes_the_worker_by_its_items_l_and_steps_it_up_within_the_chunk(self):
@@ -398,7 +402,7 @@ class Cycles(unittest.TestCase):
run = checkout.run([
worker(say="one"), judge(evidence="one"),
worker(say="two"), judge(evidence="two"),
worker(say="three"), judge(evidence="three", bundled=4),
worker(say="three"), judge(evidence="three", highest_likelihood_taken_in=4),
worker(say="four"), judge(finished=True, evidence="four"),
worker(say="next chunk"),
])
@@ -414,8 +418,8 @@ class Cycles(unittest.TestCase):
self.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)})
self.assertIn("loop-claude runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 4.", argument(workers[0], "-p"))
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: claude-opus-5-5 at medium effort, routed by item 4's L of 2 and E + I of 3\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\n", outcomes)
self.assertIn("<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\n", outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self):
checkout = Checkout(self)
@@ -460,8 +464,8 @@ class Cycles(unittest.TestCase):
("claude-opus-5-5", "high"),
])
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 4 and E + I of 5\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5\n", outcomes)
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5\n", outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self):
checkout = Checkout(self)
@@ -477,9 +481,9 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"])
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-opus-5-5", "high"), ("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "xhigh")])
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn("<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5\n", "".join(outcomes))
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
self.assertNotIn("at max effort", "".join(outcomes))
self.assertIn("Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 4 and E + I of 5\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5\n", "".join(outcomes))
self.assertIn('Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_and_judge_on_it(self):
checkout = Checkout(self)
@@ -491,7 +495,7 @@ class Cycles(unittest.TestCase):
self.assertEqual((argument(first, "--model"), argument(first, "--effort")), ("claude-sonnet-5-5", "high"))
ruling = next(call for call in run.calls if call["role"] == "judge")
self.assertEqual((argument(ruling, "--model"), argument(ruling, "--effort")), ("claude-opus-5-5", "medium"))
self.assertIn("Judge: claude-opus-5-5 at medium effort\nWorker: claude-sonnet-5-5 at high effort", "".join(checkout.archived().values()))
self.assertIn('Judge: claude-opus-5-5 at medium effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", ', "".join(checkout.archived().values()))
self.assertIn("Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.", argument(first, "-p"))
def test_routes_the_judge_and_the_reviewers_on_the_highest_e_plus_i_the_worker_takes_in(self):
@@ -499,7 +503,7 @@ class Cycles(unittest.TestCase):
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
checkout.commit_plan(CHEAP)
run = checkout.run([
worker(say="one"), judge(evidence="one", bundled_escape_and_impact=6),
worker(say="one"), judge(evidence="one", highest_escape_and_impact_taken_in=6),
worker(say="two"), judge(finished=True, evidence="two"),
worker(say="next chunk"),
])
@@ -509,8 +513,8 @@ class Cycles(unittest.TestCase):
self.assertEqual({argument(call, "--effort") for call in workers}, {"high"})
self.assertIn("Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 6 taken into the chunk.", argument(workers[1], "-p"))
outcomes = "".join(checkout.archived().values())
self.assertIn("<UTC> Stepped up\n\nWorker: claude-sonnet-5-5 at high effort, routed by item 4's L of 2 and E + I of 3, taking in an E + I of 6\n", outcomes)
self.assertIn("Judge: claude-opus-5-5 at xhigh effort\nWorker: claude-sonnet-5-5 at high effort, routed by item 4's L of 2 and E + I of 3, taking in an E + I of 6\n", outcomes)
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
self.assertIn('Judge: claude-opus-5-5 at xhigh effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
def test_a_rerun_resumes_an_open_chunk_on_the_rung_it_last_ran(self):
checkout = Checkout(self)
@@ -647,7 +651,7 @@ class Interrupt(unittest.TestCase):
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"])
[(copy, verdict)] = checkout.archived().items()
self.assertEqual(copy, (checkout.transcripts()[0]).read_text())
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: worker-model\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: worker-model\n")
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n")
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
session = argument(run.calls[0], "--session-id")
@@ -857,7 +861,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": None} 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} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5,", run.stdout)
outside = checkout.temp / "outside"
+317 -167
View File
@@ -12,6 +12,7 @@ import sys
import tempfile
import time
import unittest
import unittest.mock
import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
@@ -22,17 +23,26 @@ from chunk_pick import DefaultPlan, LastCut
from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python
from claude_code import entries, reply, session
from failure import Failure
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
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 transcript_archive import outcomes, write
from loop_claude import paths, routing
from transcript_archive.location import project_archive
from model_routing.route import Route, route_from
from model_routing.route import Record, Route, route_from
from loop_claude.stop import Stop
from utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
# How the archive records a worker that runs off the ladder.
OFF_LADDER = '{"model": "worker-model"}'
# How it records routes by item 179's L of 2 and E + I of 5, on Routing's rungs.
SONNET_179 = '{"model": "claude-sonnet-5-5", "effort": "high", "item": 179, "likelihood": 2, "escape_and_impact": 5}'
OPUS_179_AT_3 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 3}'
OPUS_179_AT_6 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 6}'
CWD = pathlib.Path("/c")
NOW = 1790000000
@@ -62,7 +72,7 @@ class FakeEffects:
claude_on_terminal=self.on_terminal_claude,
discard_typed=lambda: self.calls.append(("discard_typed", None)),
execv=self.execv,
git=lambda args, cwd: self.answer("git", args),
git=lambda *args, cwd: self.answer("git", list(args)),
input=lambda prompt: self.answer("input", prompt),
local_time=lambda seconds: f"<{seconds}>",
now=lambda: NOW,
@@ -106,17 +116,18 @@ def ran(stdout="", code=0, stderr=""):
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False):
reply = {"answer": answer, "bundled": 0, "bundled_escape_and_impact": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "release_ready": release_ready}
reply = {"answer": answer, "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "release_ready": release_ready}
return ran(json.dumps({"structured_output": reply}))
class Worker:
"""A worker claude: writes a line to the session's transcript, then streams a result."""
def __init__(self, home, prompted=False):
def __init__(self, home, prompted=False, text="working"):
self.home = home
# Whether it records its -p prompt in the transcript first, as claude does.
self.prompted = prompted
self.text = text
def __call__(self, args):
flag = "--session-id" if "--session-id" in args else "--resume"
@@ -127,7 +138,7 @@ class Worker:
handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(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": "working"})) + "\n")
handle.write(json.dumps(assistant({"type": "text", "text": self.text})) + "\n")
return Streamed(0)
@@ -207,30 +218,30 @@ class Cycles(unittest.TestCase):
def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"])
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIsNone(session.transcript_file(self.session))
def test_a_fresh_worker_reads_the_preflights_facts_and_a_resumed_one_does_not(self):
worker = Worker(self.paths.claude_code_transcripts.parent)
fake = FakeEffects(streams=[worker, worker], claude=[judged("unfinished"), judged("finished")])
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working"))
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3))
self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")).verdict, Finished("working"))
fresh, resumed = (args[args.index("-p") + 1] for args in fake.made("stream_claude"))
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_reviewers_in_its_environment(self):
def test_a_worker_is_handed_the_projects_rung_its_own_and_its_reviews_e_plus_i_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))
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_REVIEWER_RUNG": "claude-opus-5-5 at high effort"}])
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"}])
def test_the_claude_an_interrupt_resumes_is_handed_the_same_rungs_as_the_worker(self):
def answer(args):
with open(session.transcript_file(self.session), "a") as handle:
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=[ran()])
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))
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(cycle).verdict, Finished("working"))
@@ -239,21 +250,21 @@ class Cycles(unittest.TestCase):
def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session_with_the_judges_evidence(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working"))
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3))
self.assertTrue(session.transcript_file(self.session))
self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")).verdict, Unfinished("working"))
self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")).verdict, Unfinished("working", entries_read=4))
workers = fake.made("stream_claude")
self.assertIn("--session-id", workers[0])
self.assertIn("--resume", workers[1])
self.assertIn("as the work remaining:\n\n> working\n\nThe chunk is finished once", workers[1][workers[1].index("-p") + 1])
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"] * 2)
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2)
def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3)
self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1)
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()])
self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(130, ""))
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: worker-model\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n\nWorker: worker-model\n"])
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n\nWorker: {OFF_LADDER}\n"])
def test_each_judge_reply_the_loop_rejects_is_archived_with_why_beside_the_verdict_that_follows(self):
unfilled = ran(json.dumps({"structured_output": {"interrupt": False}}))
@@ -265,7 +276,7 @@ class Cycles(unittest.TestCase):
"Task: Do it.\n\n"
f"{stamp} Judge reply rejected: the judge's reply has no answer of type string\n\nReply:\n> {unfilled.stdout}\n\nJudge: judge-model\n\n"
f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n"
f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"])
f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
def test_stops_when_a_rejected_reply_cannot_be_archived(self):
self.archive.parent.mkdir(parents=True)
@@ -292,7 +303,7 @@ class Cycles(unittest.TestCase):
(folder / "custom-title.json").write_text("first")
(folder.parent / f"{self.session.id}.orphaned-1.jsonl").write_text("o\n")
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 3, claude=[judged("unfinished"), judged("finished"), judged("unfinished")])
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working"))
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3))
[chunk] = self.archive.iterdir()
kept = chunk / "session" / str(self.session.id)
self.assertEqual((chunk / "session" / f"{self.session.id}.orphaned-1.jsonl").read_text(), "o\n")
@@ -308,7 +319,7 @@ class Cycles(unittest.TestCase):
self.assertEqual(stat.S_IMODE((kept / "subagents" / "agent-a.jsonl").stat().st_mode), 0o600)
folder.mkdir()
(folder / "custom-title.json").write_text("third")
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working"))
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3))
[next_chunk] = set(self.archive.iterdir()) - {chunk}
self.assertEqual(sorted(path.read_text() for path in (next_chunk / "session" / str(self.session.id)).glob("custom-title.json*")), ["third"])
@@ -326,17 +337,17 @@ class Cycles(unittest.TestCase):
with open(session.transcript_file(self.session), "a") as handle:
handle.write(json.dumps(human("the second")) + "\n")
return 0
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer], git=[ran()])
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer], git=[""])
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working"))
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"])
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=4))
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
judge_prompts = [stdin for args, stdin in fake.made("claude")]
self.assertEqual(len(judge_prompts), 2)
self.assertNotIn("the second", judge_prompts[0])
self.assertIn("[human] the second", judge_prompts[1])
self.assertIn("From README.md:\n## Goals", judge_prompts[0])
self.assertIn("The task an agent was given:\nDo it.", judge_prompts[0])
self.assertIn("The task the worker was given:\nDo it.", judge_prompts[0])
def test_a_question_the_records_answer_resumes_the_worker_with_the_answer_three_times_a_cycle(self):
answered = judged("quoted", answer="Use *A*.")
@@ -348,21 +359,21 @@ class Cycles(unittest.TestCase):
self.assertEqual(len(fake.made("stream_claude")), 4)
self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answered: Which one? ===\nUse *A*."), 3)
self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
quoted = "2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: worker-model\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
quoted = f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
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))
with contextlib.redirect_stdout(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5))
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
first, resumed = fake.made("stream_claude")
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}.{prompts.rungs_held(concluded.route, Routing.OPUS)} A further request for a higher rung steps you up no more in this cycle."))
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, Routing.OPUS)}"))
self.assertNotIn("went through", first[first.index("-p") + 1])
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {Route(Routing.SONNET, 179, 2, 5)}\n"
stepped = f"Stepped up\n\nWorker: {Route(Routing.OPUS, 179, 2, 5)}\n"
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {SONNET_179}\n"
stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n"
kept = "".join(self.archived_outcomes())
self.assertIn(f"Z {answered}\n20", kept)
self.assertIn(f"Z {stepped}", kept)
@@ -374,14 +385,44 @@ class Cycles(unittest.TestCase):
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())
self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {Route(Routing.SONNET, 179, 2, 5)}\n", kept)
self.assertIn(f"Stepped up\n\nWorker: {Route(Routing.OPUS, 179, 2, 5)}\n", kept)
self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {SONNET_179}\n", kept)
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))
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))
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))
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))
self.assertEqual([args[args.index("--effort") + 1] for args in fake.made("stream_claude")], ["high", "medium", "high"])
def test_an_escalation_quoted_from_before_the_workers_last_step_up_steps_nothing_and_a_later_one_reaches_the_verdict(self):
for escalation, verdict in (("round 2: 🔴", Unfinished("working", entries_read=4)), ("working", Unfinished("working", 0, "working", entries_read=4))):
with self.subTest(escalation=escalation):
self.session = session.session_named(f"A proj {escalation} loop-claude", self.paths.claude_code_transcripts)
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))
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)))
def test_an_answer_typed_at_the_terminal_resumes_the_worker_headless_and_the_judge_reads_it_as_the_humans(self):
worker = Worker(self.paths.claude_code_transcripts.parent, prompted=True)
fake = FakeEffects(streams=[worker, worker], claude=[judged("interrupt"), judged("unfinished")], inputs=["Use B."])
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working"))
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=6))
self.assertIn("\nWhich one?\n", said.getvalue())
self.assertEqual(fake.made("claude_on_terminal"), [])
resumed = fake.made("stream_claude")[1]
@@ -399,7 +440,7 @@ class Cycles(unittest.TestCase):
cycle = dataclasses.replace(self.cycle(fake), anchor=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))
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
first, resumed = fake.made("stream_claude")
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
typed = resumed[resumed.index("-p") + 1]
@@ -421,7 +462,7 @@ class Cycles(unittest.TestCase):
with open(session.transcript_file(self.session), "a") as handle:
handle.write(json.dumps(human("cut")) + "\n")
return 0
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt", release_ready=True), judged("finished")], on_terminal_claude=[answer], git=[ran()])
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt", release_ready=True), judged("finished")], on_terminal_claude=[answer], git=[""])
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
self.assertEqual(fake.made("input"), [])
@@ -462,7 +503,7 @@ class Cycles(unittest.TestCase):
stop = run.run_cycle(self.cycle(fake))
self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session"))
self.assertTrue(session.session_open(self.session))
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: worker-model\n"])
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: {OFF_LADDER}\n"])
def test_stops_when_the_worker_leaves_no_transcript(self):
fake = FakeEffects(streams=[Streamed(0)])
@@ -522,7 +563,7 @@ class Limits(unittest.TestCase):
def test_the_judge_reports_a_limit_whatever_its_exit_code(self):
reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"})
fake = FakeEffects(claude=[ran(reply, code=1, stderr="limited")])
self.assertEqual(judge.run_judge("/r", [], "", "", "", fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"))
self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds("", "", ""), fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"))
def test_reads_only_a_rejecting_events_whole_seconds(self):
for info, want in [({"status": "rejected", "resetsAt": NOW}, NOW), ({"status": "allowed", "resetsAt": NOW}, None), ({"status": "rejected", "resetsAt": True}, None), ({"status": "rejected"}, None), ("rejected", None)]:
@@ -562,7 +603,7 @@ class Interrupts(unittest.TestCase):
with tempfile.TemporaryDirectory() as home:
path = pathlib.Path(home, "t.jsonl")
path.write_text(json.dumps(human("a")) + "\n")
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
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())
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"))
@@ -571,7 +612,7 @@ class Interrupts(unittest.TestCase):
with tempfile.TemporaryDirectory() as home:
path = pathlib.Path(home, "t.jsonl")
path.write_text(json.dumps(human("a")) + "\n")
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
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())
self.assertEqual(fake.terminal_environments, [handed])
@@ -613,7 +654,7 @@ class RoutingCheck(unittest.TestCase):
def test_hands_the_terminal_over_once_for_each_new_call(self):
self.chunks(5, 4)
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
fake = FakeEffects(on_terminal_claude=[0], git=[""])
stop, said = self.check(fake)
self.assertIsNone(stop)
call = "Explore subagents' reports took more of the worker's context than their searches would have."
@@ -630,7 +671,7 @@ class RoutingCheck(unittest.TestCase):
def test_stamps_the_figures_and_the_calls_raised_when_it_measures(self):
self.chunks(5, 4)
(self.root / "routing-calls-raised.md").write_text("# Routing calls raised\n\n- 2026-10-14T10:02:00Z Reset\n")
self.check(FakeEffects(on_terminal_claude=[0], git=[ran()]))
self.check(FakeEffects(on_terminal_claude=[0], git=[""]))
figures = (self.root / "routing-figures.md").read_text()
self.assertIn(f"Measured {utc(NOW)}, at cycle 20 across", figures)
self.assertIn("that finished after the reset of 2026-10-14T10:02:00Z", figures)
@@ -656,7 +697,7 @@ class RoutingCheck(unittest.TestCase):
def test_stops_when_claude_cannot_start_for_the_calls(self):
self.chunks(5, 4)
stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[ran()]))
stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[""]))
self.assertEqual(stop, Stop(1, "could not start claude for the routing calls: No such file or directory"))
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
@@ -703,6 +744,16 @@ TODO = """# todo
"""
def unfinished(likelihood=0, escalated_at=None):
"""An unfinished verdict: the worker took in an item of that L, 0 for none, and the judge found an escalation after reading escalated_at transcript entries, None for none."""
return Unfinished("e", escalation="round 2: 🔴" if escalated_at is not None else "", highest_likelihood_taken_in=likelihood, entries_read=escalated_at)
def interrupted(likelihood=0, escalated_at=None):
"""An interrupt, its arguments as unfinished's."""
return Interrupt("e", "q", escalation="round 2: 🔴" if escalated_at is not None else "", highest_likelihood_taken_in=likelihood, entries_read=escalated_at)
class Routing(unittest.TestCase):
OPUS = Rung("claude-opus-5-5", "medium")
HIGH = Rung("claude-opus-5-5", "high")
@@ -737,44 +788,51 @@ class Routing(unittest.TestCase):
def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self):
self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO, NO_CUT)), Route(self.HIGH, 3, 4, 5))
cheap = routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), NO_CUT)
self.assertEqual(routing.first_route(self.OPUS, cheap), Route(Rung("claude-haiku-5-5", "max"), 3, 1, 5))
self.assertEqual(routing.first_route(self.OPUS, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5))
self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS))
def test_steps_up_a_rung_after_every_second_unfinished_verdict(self):
once = routing.stepped(self.OPUS, Route(self.OPUS, 3, 3, 4), 0, False)
once = routing.after_unfinished(self.OPUS, Route(self.OPUS, 3, 3, 4), unfinished())
self.assertEqual(once, Route(self.OPUS, 3, 3, 4, unfinished=1))
self.assertEqual(routing.stepped(self.OPUS, once, 0, False), Route(self.HIGH, 3, 3, 4))
self.assertEqual(routing.stepped(self.OPUS, Route(LADDER[-1], unfinished=1), 0, False).rung, LADDER[-1])
self.assertEqual(routing.after_unfinished(self.OPUS, once, unfinished()), Route(self.HIGH, 3, 3, 4))
self.assertEqual(routing.after_unfinished(self.OPUS, Route(LADDER[-1], unfinished=1), unfinished()).rung, LADDER[-1])
def test_steps_up_to_the_rung_a_bundled_items_l_picks_and_never_down(self):
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS), 4, False).rung, self.HIGH)
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 4, False).rung, self.XHIGH)
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, unfinished=1), 4, False).rung, self.XHIGH)
def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self):
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.HIGH)
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.XHIGH), unfinished(4)).rung, self.XHIGH)
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.XHIGH)
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
low = Route(Rung("claude-haiku-5-5", "max"), 3, 1, 3, unfinished=1)
self.assertEqual(routing.stepped(self.OPUS, low, 0, False).rung, self.SONNET)
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 0, False).rung, low.rung)
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 2, False).rung, self.SONNET)
low = Route(self.SONNET, 3, 1, 3, unfinished=1)
self.assertEqual(routing.after_unfinished(self.OPUS, low, unfinished()).rung, self.OPUS)
self.assertEqual(routing.after_unfinished(self.OPUS, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung)
self.assertEqual(routing.after_unfinished(self.OPUS, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.OPUS)
def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung(self):
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5), 0, True), Route(self.XHIGH, 3, 4, 5))
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH, 3, 4, 5), 0, True), Route(self.MAX, 3, 4, 5))
self.assertEqual(routing.stepped(self.OPUS, Route(self.MAX, 3, 4, 5), 0, True), Route(self.MAX, 3, 4, 5, unfinished=1))
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), 0, True), Route(self.XHIGH, 3, 4, 5))
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 0, True), Route(self.XHIGH, unfinished=1))
self.assertEqual(routing.stepped(self.OPUS, Route(self.SONNET, 3, 2, 4), 4, True), Route(self.HIGH, 3, 2, 4, unfinished=1))
def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self):
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.HIGH, 3, 4, 5), unfinished(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.MAX, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.MAX, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.XHIGH), unfinished(escalated_at=7)), Route(self.XHIGH, unfinished=1))
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.HIGH, 3, 2, 4, unfinished=1))
def test_keeps_the_mark_through_a_step_no_escalation_took(self):
self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.HIGH, 3, 3, 4, escalated_at=5))
def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self):
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), 0), Route(self.XHIGH, 3, 4, 5))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5), 0), Route(self.MAX, 3, 4, 5))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1), 0), Route(self.MAX, 3, 4, 5, unfinished=1))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.SONNET, 3, 2, 4), 0), Route(self.OPUS, 3, 2, 4))
self.assertEqual(routing.after_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.after_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.MAX, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.after_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.after_ruling(self.OPUS, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7))
self.assertEqual(routing.after_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2))
def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self):
self.assertEqual(routing.after_ruling(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.HIGH, 3, 1, 3, escalated_at=2))
def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self):
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.OPUS, 3, 3, 4), 4), Route(self.XHIGH, 3, 3, 4))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5), 4), Route(self.MAX, 3, 4, 5))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1), 4), Route(self.MAX, 3, 4, 5, unfinished=1))
self.assertEqual(routing.after_ruling(self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.XHIGH, 3, 3, 4, escalated_at=7))
self.assertEqual(routing.after_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.MAX, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.after_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.MAX, 3, 4, 5, unfinished=1))
def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self):
taken = Route(self.OPUS, 3, 3, 4).taking_in(6)
@@ -789,8 +847,8 @@ class Routing(unittest.TestCase):
self.assertEqual(Route(self.OPUS).taking_in(0), Route(self.OPUS))
def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self):
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 0, False).rung, self.OPUS)
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 2, False).rung, self.OPUS)
self.assertEqual(routing.after_unfinished(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS)
self.assertEqual(routing.after_unfinished(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS)
def test_runs_the_judge_on_the_rung_its_chunks_items_e_plus_i_picks_never_below_the_projects(self):
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 5)), self.HIGH)
@@ -824,42 +882,47 @@ 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_in_a_line_it_reads_back(self):
def test_archives_the_route_as_a_json_record_it_reads_back_field_by_field(self):
route = Route(self.HIGH, 3, 4, 5)
self.assertEqual(str(route), "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5")
self.assertEqual(route_from(str(route)), route)
self.assertEqual(route_from(str(Route(self.HIGH))), Route(self.HIGH))
self.assertEqual(str(Route(Rung("worker-model"))), "worker-model")
self.assertIsNone(route_from("worker-model"))
taken = Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7)
self.assertEqual(str(taken), "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 7")
self.assertEqual(route_from(str(taken)), taken)
unrouted = Route(self.HIGH, escape_and_impact_taken_in=6)
self.assertEqual(str(unrouted), "claude-opus-5-5 at high effort, taking in an E + I of 6")
self.assertEqual(route_from(str(unrouted)), unrouted)
self.assertIsNone(route_from("claude-opus-5-5 at high effort, taking in an E + I of 9"))
self.assertIsNone(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 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_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))
def test_reads_no_route_from_a_line_whose_levels_are_off_their_scales_or_an_r_plus_c_route_wrote(self):
for line in ("claude-opus-5-5 at high effort, routed by item 3's L of 5 and E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's L of 0 and E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 9", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 1", "claude-opus-5-5 at high effort, routed by item 3's R + C of 11"):
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_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_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))
self.assertEqual(route_from("claude-opus-5-5 at high effort"), Route(self.HIGH))
self.assertEqual(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 7, escalated at transcript entry 12"), Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12))
self.assertEqual(route_from("claude-opus-5-5 at high effort, taking in an E + I of 6"), Route(self.HIGH, escape_and_impact_taken_in=6))
for line in ("worker-model", "claude-opus-5-5 at high effort, routed by item 3's L of 5 and E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's R + C of 11"):
with self.subTest(line=line):
self.assertIsNone(route_from(line))
def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self):
def run_with(route=None):
return main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=route)
item = routing.routed_item(TODO, NO_CUT)
archived = Route(self.XHIGH, 3, 4, 5)
def never():
raise AssertionError("not asked")
self.assertIsNone(main.routed(run_with(archived), None, never, never).route)
self.assertEqual(main.routed(run_with(archived), self.OPUS, never, never).route, archived)
self.assertEqual(main.routed(run_with(), self.OPUS, lambda: archived, never).route, archived)
self.assertEqual(main.routed(run_with(), self.OPUS, lambda: None, lambda: item).route, Route(self.HIGH, 3, 4, 5))
self.assertEqual(main.routed(run_with(Route(self.SONNET)), self.OPUS, never, lambda: None).route, Route(self.OPUS))
self.assertEqual(main.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model")))
self.assertEqual(main.routed(archived, self.OPUS, "claude-opus-5-5", never, never), archived)
self.assertEqual(main.routed(None, self.OPUS, "claude-opus-5-5", lambda: archived, never), archived)
self.assertEqual(main.routed(None, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.HIGH, 3, 4, 5))
self.assertEqual(main.routed(Route(self.SONNET), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
cheap = Route(self.SONNET, 4, 2, 3)
self.assertEqual(main.routed(run_with(cheap), self.OPUS, never, never).route, cheap)
self.assertEqual(main.routed(run_with(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3)), self.OPUS, never, lambda: None).route, Route(self.OPUS))
self.assertEqual(main.routed(cheap, self.OPUS, "claude-opus-5-5", never, never), cheap)
self.assertEqual(main.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
class RouteSources(unittest.TestCase):
@@ -878,15 +941,23 @@ class RouteSources(unittest.TestCase):
with tempfile.TemporaryDirectory() as home:
opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects"))
archive = pathlib.Path(home, "archive")
self.assertIsNone(main.archived_route(archive, opened))
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
transcript.parent.mkdir(parents=True)
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
self.assertIsNone(main.archived_route(archive, opened))
route = Route(Rung("claude-opus-5-5", "high"), 3, 4, 5)
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIsNone(main.archived_route(archive, opened))
transcript.parent.mkdir(parents=True)
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(str(route), "working", "j", ""), NOW))
self.assertEqual(main.archived_route(archive, opened), route)
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.record(), "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))
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')
(chunk,) = archive.iterdir()
chunk.chmod(0)
try:
@@ -902,8 +973,23 @@ 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, Finished("x")), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
self.assertEqual(main.after_verdict(run_with, self.OPUS, Unfinished("new", 4)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new"))
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"))
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))
raised = Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=5)
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1))
def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self):
off_ladder = Route(Rung("worker-model"))
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
self.assertEqual(main.after_verdict(run_with, None, run.Concluded(Unfinished("new", 4, "round 2: 🔴", entries_read=9), off_ladder)).route, off_ladder)
def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4, escalated_at=2))
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", 0, "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=9))
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2))
def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self):
with tempfile.TemporaryDirectory() as home:
@@ -914,18 +1000,17 @@ 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(str(before), "working", "j", ""), NOW))
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence="", route=before), self.OPUS, Unfinished("working", 4))
self.assertIsNone(main.archive_step(archive, opened, after, before, FakeEffects().effects()))
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.record(), "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))
self.assertIsNone(main.archive_step(archive, opened, after, after.route, FakeEffects().effects()))
self.assertIsNone(main.archive_step(archive, opened, after, None, FakeEffects().effects()))
finished = main.after_verdict(after, self.OPUS, Finished("done"))
self.assertIsNone(main.archive_step(archive, opened, finished, after.route, FakeEffects().effects()))
self.assertIsNone(main.archive_step(archive, opened, "Do it.", after.route, after.route, FakeEffects().effects()))
finished = main.after_verdict(after, self.OPUS, run.Concluded(Finished("done"), after.route))
self.assertIsNone(main.archive_step(archive, opened, "Do it.", after.route, finished.route, FakeEffects().effects()))
self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
blocked = pathlib.Path(home, "blocked")
blocked.write_text("")
stop = main.archive_step(blocked, opened, after, before, FakeEffects().effects())
stop = main.archive_step(blocked, opened, "Do it.", before, after.route, FakeEffects().effects())
self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript"))
def test_archives_a_higher_e_plus_i_taken_in_so_a_rerun_keeps_it(self):
@@ -937,9 +1022,9 @@ 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(str(before), "working", "j", ""), NOW))
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence="", route=before), self.OPUS, Unfinished("working", 0, bundled_escape_and_impact=6))
self.assertIsNone(main.archive_step(archive, opened, after, before, FakeEffects().effects()))
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.record(), "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))
@@ -1087,15 +1172,29 @@ class WorkerArgs(unittest.TestCase):
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 such request: 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\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))
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")
offer = " 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 such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`."
offer = " 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`."
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus))
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus))
def test_launches_each_pass_a_replay_lowered_on_its_replays_rung_and_reruns_it_one_above(self):
opus, haiku = Rung("claude-opus-5-5", "medium"), Rung("claude-haiku-5-5", "low")
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): haiku}):
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, self.FACTS)
on_it = prompts.resumed("", Route(haiku, 3, 1, 4), opus)
launched = " Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung. Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose."
rerun = " 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."
self.assertIn(f"whether or not it is item 3.{launched}", below)
self.assertIn(" Where 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,", below)
self.assertIn(f"{rerun} After your first read", below)
self.assertIn(f"loop-claude runs you on claude-haiku-5-5 at low effort.{launched}", on_it)
self.assertIn(" Where an item you take into the chunk has an E + I of 5 or more,", on_it)
self.assertTrue(on_it.endswith(rerun))
def test_names_the_rung_a_reviewer_or_seat_reruns_on_one_above_its_own(self):
opus = Rung("claude-opus-5-5", "medium")
both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`."
@@ -1121,6 +1220,13 @@ class WorkerArgs(unittest.TestCase):
self.assertNotIn("--session-id", resumed)
self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once"))
def test_disallows_a_wakeup_so_a_worker_that_ends_its_turn_exits(self):
opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects"))
for resume in (False, True):
with self.subTest(resume=resume):
args = worker.worker_args(opened, Rung("m"), "Do it.", resume=resume)
self.assertEqual(args[args.index("--disallowedTools") + 1], "ScheduleWakeup")
class Records(unittest.TestCase):
def test_heads_each_record_by_its_name_the_humans_rules_last(self):
@@ -1163,11 +1269,42 @@ class Records(unittest.TestCase):
class JudgePrompt(unittest.TestCase):
def test_shows_the_transcripts_tail_and_returns_what_it_showed(self):
prompt, shown = judge.judge_prompt("Do it.", "## Goals", "", "old " + "x" * judge.JUDGE_PROMPT_CHARS + " new")
self.assertTrue(shown.endswith(" new"))
self.assertNotIn("old", shown)
self.assertIn(shown, prompt)
entries = [assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})]
prompt, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 0)
self.assertTrue(grounds.shown.endswith("\n\nnew"))
self.assertNotIn("old", grounds.shown)
self.assertIn(grounds.shown, prompt)
self.assertLessEqual(len(prompt), judge.JUDGE_PROMPT_CHARS)
self.assertEqual(grounds.since_step, "old " + "x" * judge.JUDGE_PROMPT_CHARS + "\n\nnew")
self.assertEqual(grounds.quotable, "## Goals\n\n")
def test_the_judge_prompt_and_schema_call_the_worker_the_worker(self):
prompt, _ = judge.judge_prompt("Do it.", "## Goals", "", [assistant({"type": "text", "text": "done"})], 1)
self.assertNotRegex(prompt + json.dumps(judge.JUDGE_SCHEMA), r"\b[Aa]gent")
def test_the_judge_prompt_names_every_rule_the_judge_reads_from_the_human(self):
self.assertEqual([name for name in records.HUMAN_RULE_NAMES if name not in judge.JUDGE_RULES], [])
def test_shows_the_judge_where_the_worker_last_stepped_up_and_checks_an_escalation_only_after_it(self):
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"})]
prompt, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 1)
self.assertRegex(prompt, "round 2: 🔴\n\n\\[step\\] [^\n]+\n\nround 3: 🔴\n\n")
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.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):
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})]
_, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 1)
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "old x", entries_read=3), grounds), Unfinished("e", entries_read=3))
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "new", entries_read=3), grounds), Unfinished("e", 0, "new", entries_read=3))
def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self):
typed = prompts.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)
entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})]
_, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 1)
self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown)
class Grounded(unittest.TestCase):
@@ -1196,77 +1333,91 @@ class Grounded(unittest.TestCase):
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Finished("e"))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "release_ready": False}), Unfinished("e"))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "release_ready": False}), Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Finished("e"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "release_ready": False}), Unfinished("e"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "release_ready": False}), Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
def test_takes_a_bundled_l_on_its_scale_and_counts_any_other_as_none(self):
reply = {"answer": "", "bundled_escape_and_impact": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "bundled": 4}), Unfinished("e", 4))
self.assertEqual(verdict_from({**reply, "bundled": True}), Failure("the judge's reply has no bundled of type integer"))
for bundled in (5, 13, -1):
with self.subTest(bundled=bundled):
self.assertEqual(verdict_from({**reply, "bundled": bundled}), Unfinished("e", 0))
def test_takes_the_highest_l_taken_in_on_its_scale_and_counts_any_other_as_none(self):
reply = {"answer": "", "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Unfinished("e", 4))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": True}), Failure("the judge's reply has no highest_likelihood_taken_in of type integer"))
for highest_likelihood_taken_in in (5, 13, -1):
with self.subTest(highest_likelihood_taken_in=highest_likelihood_taken_in):
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": highest_likelihood_taken_in}), Unfinished("e", 0))
def test_takes_a_bundled_e_plus_i_on_its_scale_and_counts_any_other_as_none(self):
reply = {"answer": "", "bundled": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": 6}), Unfinished("e", 0, bundled_escape_and_impact=6))
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": 2}), Unfinished("e", 0, bundled_escape_and_impact=2))
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": False}), Failure("the judge's reply has no bundled_escape_and_impact of type integer"))
for bundled in (1, 9, -1):
with self.subTest(bundled=bundled):
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": bundled}), Unfinished("e", 0))
def test_takes_the_highest_e_plus_i_taken_in_on_its_scale_and_counts_any_other_as_none(self):
reply = {"answer": "", "highest_likelihood_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 6}), Unfinished("e", 0, highest_escape_and_impact_taken_in=6))
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 2}), Unfinished("e", 0, highest_escape_and_impact_taken_in=2))
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": False}), Failure("the judge's reply has no highest_escape_and_impact_taken_in of type integer"))
for escape_and_impact in (1, 9, -1):
with self.subTest(escape_and_impact=escape_and_impact):
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": escape_and_impact}), Unfinished("e", 0))
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self):
reply = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
reply = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
self.assertEqual(verdict_from(reply), Unfinished("e", 0, "round 2: 🔴"))
self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e"))
self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string"))
def test_takes_an_escalation_quote_on_an_interrupt(self):
reply = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
reply = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴"))
self.assertEqual(verdict_from({**reply, "bundled": 4}), Interrupt("e", "Which one?", "round 2: 🔴", 4))
self.assertEqual(verdict_from({**reply, "bundled": 5}), Interrupt("e", "Which one?", "round 2: 🔴"))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Interrupt("e", "Which one?", "round 2: 🔴", 4))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), Interrupt("e", "Which one?", "round 2: 🔴"))
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self):
shown = "The agent: round 2: 🔴. Which one?"
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: 🔴"), shown, ""), Interrupt("e", "q", "round 2: 🔴"))
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: … 🔴"), shown, ""), Interrupt("e", "q"))
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "round 3: 🔴"), shown, ""), Unfinished("e"))
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q", "round 2: 🔴"))
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: … 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q"))
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e"))
def test_takes_an_escalation_quote_and_a_bundled_l_on_a_quoted_answer(self):
reply = {"answer": "A.", "bundled": 4, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
def test_takes_an_escalation_quote_and_the_highest_l_taken_in_on_a_quoted_answer(self):
reply = {"answer": "A.", "highest_likelihood_taken_in": 4, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴", 4))
self.assertEqual(verdict_from({**reply, "bundled": 5}), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self):
shown = "The agent: round 2: 🔴. Which one?"
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: 🔴"), shown, "A."), QuotedAnswer("e", "q", "A.", "round 2: 🔴"))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: … 🔴"), shown, "A."), QuotedAnswer("e", "q", "A."))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A.", "round 2: 🔴"))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: … 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A."))
def test_puts_a_quoted_answer_the_records_do_not_hold_to_the_human_with_the_escalation_it_carried(self):
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴", 4), "The agent: round 2: 🔴.", "A."), Interrupt("e", "q", "round 2: 🔴", 4))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴", 4), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴", 4))
def test_puts_a_quoted_answer_the_records_do_not_hold_word_for_word_to_the_human(self):
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there"), "shown", "the records"), Interrupt("e", "q"))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "the records"), "shown", "From the records: the records"), QuotedAnswer("e", "q", "the records"))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there"), judge.Grounds("shown", "shown", "the records")), Interrupt("e", "q"))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "the records"), judge.Grounds("shown", "shown", "From the records: the records")), QuotedAnswer("e", "q", "the records"))
def test_drops_an_escalation_from_every_ruling_of_a_cycle_once_an_interrupt_took_one(self):
self.assertEqual(run.unspent(Unfinished("e", 0, "round 2: 🔴"), True), Unfinished("e"))
self.assertEqual(run.unspent(Interrupt("e", "q", "another passage"), True), Interrupt("e", "q"))
self.assertEqual(run.unspent(QuotedAnswer("e", "q", "A.", "another passage"), True), QuotedAnswer("e", "q", "A."))
self.assertEqual(run.unspent(Unfinished("e", 0, "round 2: 🔴"), False), Unfinished("e", 0, "round 2: 🔴"))
def test_drops_an_escalation_quote_found_only_in_the_transcript_entries_before_the_workers_last_step_up(self):
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"}), assistant({"type": "text", "text": "working"})]
def judged_on(mark, escalation):
return judge.judge_once("/r", "Do it.", "## Goals", "", entries, mark, Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation=escalation)]).effects())
self.assertEqual(judged_on(0, "round 2: 🔴"), Unfinished("working", 0, "round 2: 🔴", entries_read=3))
self.assertEqual(judged_on(1, "round 2: 🔴"), Unfinished("working", entries_read=3))
self.assertEqual(judged_on(1, "round 3: 🔴"), Unfinished("working", 0, "round 3: 🔴", entries_read=3))
self.assertEqual(judged_on(1, "round 2: 🔴\n\nround 3: 🔴"), Unfinished("working", entries_read=3))
self.assertEqual(judged_on(3, "round 3: 🔴"), Unfinished("working", entries_read=3))
def test_drops_an_escalation_quote_that_only_loop_claudes_prompts_or_the_humans_lines_repeat_after_the_step_up(self):
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), {**human("as the work remaining: round 2: 🔴"), "promptSource": "sdk"}, human("round 2: 🔴 again"), assistant({"type": "text", "text": "working"})]
verdict = judge.judge_once("/r", "Do it.", "## Goals", "", entries, 1, Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation="round 2: 🔴")]).effects())
self.assertEqual(verdict, Unfinished("working", entries_read=4))
def test_takes_evidence_from_before_the_workers_last_step_up(self):
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "working"})]
verdict = judge.judge_once("/r", "Do it.", "## Goals", "", entries, 1, Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects())
self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2))
class LoopRuns(unittest.TestCase):
@@ -1358,8 +1509,7 @@ class ExitContract(unittest.TestCase):
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
("loop/routing_check.py", "raise_calls", "1", "f'could not start claude for the routing calls:", "claude cannot start for an interrupt"),
("project/checkout.py", "checkout_root", "1", "f'could not start git:", git),
("project/checkout.py", "checkout_root", "1", "found.stderr.strip()", git),
("project/checkout.py", "checkout_root", "1", "found.reason", git),
("project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_),
("project/model_choice.py", "read_models_file", "1", 'f"could not read {saved}: {getattr(', models_),
("project/model_choice.py", "read_models_file", "1", "f'could not read {saved}: not an object", models_),
@@ -1413,7 +1563,7 @@ class JudgeFailures(unittest.TestCase):
class Worktrees(unittest.TestCase):
def test_lists_the_root_alone_when_git_cannot_start(self):
fake = FakeEffects(git=[FileNotFoundError(2, "No such file or directory")])
fake = FakeEffects(git=[Failure("git worktree list --porcelain could not start: [Errno 2] No such file or directory: 'git'")])
self.assertEqual(checkout.worktrees("/r", fake.effects()), ["/r"])
+53
View File
@@ -0,0 +1,53 @@
"""The verdicts cycle.judge.verdict_from builds from the judge's reply. They sit outside cycle/, since routing reads them and cycle imports routing."""
import dataclasses
@dataclasses.dataclass(frozen=True)
class Interrupt:
evidence: str
question: str
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
escalation: str = ""
# 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.
entries_read: int | None = None
@dataclasses.dataclass(frozen=True)
class QuotedAnswer:
"""The worker asked a question that README.md or the records answer. The answer field quotes the passage."""
evidence: str
question: str
answer: str
# As on Interrupt.
escalation: str = ""
highest_likelihood_taken_in: int = 0
entries_read: int | None = None
@dataclasses.dataclass(frozen=True)
class Finished:
evidence: str
@dataclasses.dataclass(frozen=True)
class Unfinished:
evidence: str
# As on Interrupt; the worker also rises to the rung that L picks.
highest_likelihood_taken_in: int = 0
# As on Interrupt.
escalation: str = ""
# The highest E + I the judge saw the worker take into the chunk, 0 for none.
highest_escape_and_impact_taken_in: int = 0
# As on Interrupt.
entries_read: int | None = None
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
+13 -21
View File
@@ -25,19 +25,20 @@ single tracked file.
Below the table it names:
- each run it skipped because its commit is not in the checkout;
- each run it could not score because its places name no measured unit, or every one;
- each file left out of its run because it does not parse on this Python.
- each file left out of its run because git's output for it is not UTF-8, because git cannot show
it, or because it does not parse on this Python.
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the history
cannot be read, or no scoring run could be scored.
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, a tracked
file's name is not UTF-8, the history cannot be read, or no scoring run could be scored.
"""
import pathlib
import statistics
import subprocess
import sys
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score, tracked_places
from comprehension_history import entries, Entry
from failure import Failure
from git_repo import git
from metric_bench.python_units import measured, python_units, Unit
@@ -66,7 +67,7 @@ def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] |
"""The checkout that holds the history, the history's path and its text."""
if given and not given.parent.is_dir():
return Failure(f"could not read {given}: no folder {given.parent}")
found = git(["rev-parse", "--show-toplevel"], str(given.parent) if given else None)
found = git("rev-parse", "--show-toplevel", cwd=str(given.parent) if given else None)
if isinstance(found, Failure):
return found
history = given or pathlib.Path(found.strip(), "docs", "comprehension-history.md")
@@ -89,7 +90,7 @@ def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[s
rows = []
notes = []
for run in scored_runs(entries(text)):
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
if isinstance(missing := git("cat-file", "-e", f"{run.commit}^{{commit}}", cwd=top), Failure):
notes.append(f"Skipped, its commit is not in {top}: {run.heading} ({missing.reason})")
continue
scored = run_scores(run, top)
@@ -109,23 +110,22 @@ def noted(notes: list[str]) -> str:
def run_scores(run: Entry, top: str) -> tuple[RunScores | None, list[str]] | Failure:
"""The run's scores, and why each file that does not parse was left out."""
listed = git(["ls-tree", "-r", "-z", "--name-only", run.commit], top)
"""The run's scores, and why each file left out was: git could not show it as UTF-8, or it does not parse."""
# A tracked name that is not UTF-8 fails the run rather than reading with its bytes replaced.
listed = git("ls-tree", "-r", "-z", "--name-only", run.commit, cwd=top)
if isinstance(listed, Failure):
return listed
tracked = list(filter(None, listed.split("\0")))
units: list[Unit] = []
unparsed = []
for path in filter(measured, tracked):
source = git(["show", f"{run.commit}:{path}"], top)
if isinstance(source, Failure):
return source
found = python_units(path, source)
source = git("show", f"{run.commit}:{path}", cwd=top)
found = source if isinstance(source, Failure) else python_units(path, source)
if isinstance(found, Failure):
unparsed.append(found.reason)
else:
units += found
log = git(["-c", "core.quotePath=false", "log", "--no-merges", "--format=tformat:@@", "--name-only", run.commit], top)
log = git("-c", "core.quotePath=false", "log", "--no-merges", "--format=tformat:@@", "--name-only", run.commit, cwd=top)
if isinstance(log, Failure):
return log
places, dropped = tracked_places(run.scored_places, tracked)
@@ -147,14 +147,6 @@ def cell(score: Score) -> str:
return "constant" if score.constant else f"AUC {score.auc:.2f}, top k {score.top_k:.2f}"
def git(args: list[str], cwd: str | None) -> str | Failure:
try:
ran = subprocess.run(["git", *args], capture_output=True, cwd=cwd, encoding="utf-8", errors="replace")
except OSError as failure:
return Failure(f"could not start git: {failure.strerror}")
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
def failed(failure: Failure) -> int:
print(failure.reason, file=sys.stderr)
return 1
+13
View File
@@ -247,6 +247,19 @@ class BlackBox(unittest.TestCase):
ran = self.run_tool(top)
self.assertIn("Not scored, its places name no measured unit or every one: 2026-10-07T12:00:00Z, PR #0", ran.stdout)
def test_leaves_out_and_names_a_file_that_is_not_utf_8(self):
top = self.project("")
pathlib.Path(top, "b.py").write_bytes(b"# caf\xe9\n")
env = isolated_env()
subprocess.run(["git", "add", "b.py"], cwd=top, check=True, env=env)
subprocess.run(["git", "commit", "-qm", "b"], cwd=top, check=True, env=env)
commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=top, check=True, capture_output=True, text=True, env=env).stdout.strip()
pathlib.Path(top, "docs", "comprehension-history.md").write_text(f"# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at {commit}\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n")
ran = self.run_tool(top)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("Left out of 2026-10-08T12:50:49Z, PR #1", ran.stdout)
self.assertIn("b.py", ran.stdout.split("Left out of")[1])
def test_reads_the_checkout_that_holds_a_history_named_from_elsewhere(self):
top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n")
ran = self.run_tool(tempfile.gettempdir(), str(pathlib.Path(top, "docs", "comprehension-history.md")))
+19 -10
View File
@@ -3,10 +3,12 @@ import dataclasses
import re
import typing
from review_passes import ReviewedPass, REVIEWERS
# How Rung.__str__ spells a rung that names an effort, and Rung.parse reads it back.
WORDING = re.compile(r"(?P<model>\S+) at (?P<effort>\S+) effort")
# What a review launch reviews: a reviewer, a comprehension seat or the security pass.
ReviewKind = typing.Literal["reviewer", "seat", "security"]
# What a review launch reviews: such a pass, a comprehension seat or the security pass.
ReviewKind = ReviewedPass | typing.Literal["seat", "security"]
@dataclasses.dataclass(frozen=True)
@@ -34,7 +36,7 @@ class Rung:
return Rung(model, effort)
return Rung(family.model, effort) if effort else family
# The one spelling of a rung. It is persisted, so changing it routes every stored chunk afresh: parse no longer reads their rungs.
# 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.
def __str__(self) -> str:
return f"{self.model} at {self.effort} effort" if self.effort else self.model
@@ -60,9 +62,11 @@ LADDER = (
Rung("claude-fable-5-1", "max"),
)
# The rungs a task's L steps its worker from the project's rung.
WORKER_STEPS = {1: -2, 2: -1, 3: 0, 4: 1}
WORKER_STEPS = {1: -1, 2: -1, 3: 0, 4: 1}
# The rungs a task's E + I steps a review up from the project's rung; an E + I under 5 steps none.
REVIEW_STEPS = {5: 1, 6: 2, 7: 3, 8: 4}
# The rung a pass's replay chose for the projects on a model: docs/decisions.md → `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`.
REPLAYED: dict[tuple[ReviewedPass, str], Rung] = {}
def project_rung(model: str) -> Rung | None:
@@ -96,14 +100,19 @@ def stepped_up(rung: Rung) -> Rung:
def review_rungs(project: Rung, worker: Rung, escape_and_impact: int) -> dict[ReviewKind, Rung]:
"""The rung each kind of review in a chunk runs on, where its worker runs on worker and its item has that E + I. The reviewers run on the higher of the worker's rung and review_floor's."""
reviewers = highest(worker, review_floor(project, escape_and_impact))
return {kind: review_rung(kind, project, reviewers) for kind in typing.get_args(ReviewKind)}
"""The rung each kind of review in a chunk runs on, where its worker runs on worker and its item has that E + I.
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):
rungs |= {kind: rung for (kind, model), rung in REPLAYED.items() if model == project.model}
return rungs
def review_rung(kind: ReviewKind, project: Rung, reviewers: Rung) -> Rung:
"""The rung a review of kind runs on: a reviewer on the reviewers' rung; a seat or the security pass on the project's, so the seats score every chunk on one rung, and the security pass spends no more than the project chose."""
return reviewers if kind == "reviewer" else 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))
def highest(*rungs: Rung) -> Rung:
+42 -30
View File
@@ -1,5 +1,6 @@
"""A chunk's route: its worker's rung and the plan item that picked it, in the words the archive records each verdict's worker in."""
"""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."""
import dataclasses
import json
import re
import typing
@@ -8,17 +9,10 @@ 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"
# An archived worker line: the rung, then the item and the levels that routed it, if any, then the E + I taken in, if any. A line an older loop-claude wrote names an R + C in place of L and E + I: archived_worker reads only its rung, for the routing figures; with no levels, route_from returns None and the chunk routes afresh.
ROUTED = 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]+))?")
class ArchivedWorker(typing.NamedTuple):
"""What an archived worker line names: the worker's rung, the item that routed it, its L and E + I, and the E + I taken in; 0 for each it does not name."""
rung: Rung
item: int
likelihood: int
escape_and_impact: int
escape_and_impact_taken_in: int
# 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.
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]+))?")
HIGHEST_ESCAPE_AND_IMPACT = LEVELS["E"] + LEVELS["I"]
@@ -46,6 +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.
# 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
@@ -55,15 +50,17 @@ 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.
escalated_at: int = 0
def __post_init__(self) -> None:
# Raises on a programming error only, so nothing catches it: route_from and the reload decoder check levels_fit before they build a route.
# Raises on a programming error only, so nothing catches it: route_from and the reload decoder check fits before they build a route.
if not levels_fit(self.item, self.likelihood, self.escape_and_impact, self.escape_and_impact_taken_in):
raise ValueError(f"a route by item {self.item} cannot hold an L of {self.likelihood}, an E + I of {self.escape_and_impact} and an E + I taken in of {self.escape_and_impact_taken_in}")
@staticmethod
def fits(fields: typing.Mapping[str, typing.Any]) -> bool:
"""Whether a route may be built from these fields, as the reload decoder asks of a handed one."""
"""Whether a route may be built from these fields."""
return levels_fit(fields.get("item", 0), fields.get("likelihood", 0), fields.get("escape_and_impact", 0), fields.get("escape_and_impact_taken_in", 0))
def taking_in(self, escape_and_impact: int) -> "Route":
@@ -74,25 +71,40 @@ 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 __str__(self) -> str:
"""What the archive records as each verdict's worker; ROUTED reads it back."""
routed = f", routed by item {self.item}'s L of {self.likelihood} and E + I of {self.escape_and_impact}" if self.item else ""
taken_in = f", taking in an E + I of {self.escape_and_impact_taken_in}" if self.escape_and_impact_taken_in else ""
return f"{self.rung}{routed}{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 archived_worker(worker: str) -> ArchivedWorker | None:
"""What an archived worker line names; None for a model run off the ladder."""
found = ROUTED.fullmatch(worker)
rung = Rung.parse(found["rung"]) if found else None
if not (found and rung):
return None
return ArchivedWorker(rung, *(int(found[name] or 0) for name in ("item", "likelihood", "escape_and_impact", "escape_and_impact_taken_in")))
# 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"))
def route_from(worker: str) -> Route | None:
"""The route an archived worker line names; None for a model run off the ladder, or a route by anything but levels on their scales."""
archived = archived_worker(worker)
if archived is None or not levels_fit(archived.item, archived.likelihood, archived.escape_and_impact, archived.escape_and_impact_taken_in):
"""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)
if fields is None or not Route.fits(fields):
return None
return Route(archived.rung, archived.item, archived.likelihood, archived.escape_and_impact, escape_and_impact_taken_in=archived.escape_and_impact_taken_in)
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in RECORD_FIELDS})
def record_fields(record: str) -> dict[str, typing.Any] | None:
"""The fields of a record Route.record wrote; None for any other text."""
try:
fields = json.loads(record)
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}):
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
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."""
found = LEGACY_WORKER.fullmatch(line)
rung = Rung.parse(found["rung"]) if found else None
if not (found and rung):
return None
return {"model": rung.model, "effort": rung.effort, **{name: int(value or 0) for name, value in found.groupdict().items() if name != "rung"}}
+31 -16
View File
@@ -1,11 +1,14 @@
import pathlib
import sys
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, project_rung, review_floor, review_rung, review_rungs, Rung, stepped_up, worker_rung, WORKER_STEPS
from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, position, project_rung, review_floor, review_rungs, Rung, stepped_up, worker_rung, WORKER_STEPS
from model_routing import ladder
from todo_table import LEVELS
from review_passes import REVIEWERS
OPUS = Rung("claude-opus-5-5", "medium")
@@ -25,7 +28,7 @@ class Ladder(unittest.TestCase):
def test_steps_a_workers_rung_by_its_l_from_the_projects_rung(self):
position = LADDER.index(OPUS)
self.assertEqual([LADDER.index(worker_rung(OPUS, likelihood)) - position for likelihood in range(1, 5)], [-2, -1, 0, 1])
self.assertEqual([LADDER.index(worker_rung(OPUS, likelihood)) - position for likelihood in range(1, 5)], [-1, -1, 0, 1])
def test_steps_a_review_up_by_its_e_plus_i_from_the_projects_rung_and_never_down(self):
position = LADDER.index(OPUS)
@@ -33,8 +36,8 @@ class Ladder(unittest.TestCase):
self.assertEqual(review_floor(OPUS, 0), OPUS)
def test_a_step_past_either_end_stops_there(self):
self.assertEqual(worker_rung(OPUS, 1), Rung("claude-haiku-5-5", "max"))
self.assertEqual(worker_rung(LADDER[1], 1), LADDER[0])
self.assertEqual(worker_rung(OPUS, 1), Rung("claude-sonnet-5-5", "high"))
self.assertEqual(worker_rung(LADDER[0], 1), LADDER[0])
self.assertEqual(review_floor(Rung("claude-opus-5-5", "xhigh"), 8), LADDER[-1])
self.assertEqual(stepped_up(LADDER[-1]), LADDER[-1])
self.assertEqual(stepped_up(OPUS), Rung("claude-opus-5-5", "high"))
@@ -43,7 +46,7 @@ class Ladder(unittest.TestCase):
self.assertEqual(set(WORKER_STEPS), set(range(1, LEVELS["L"] + 1)))
def test_names_the_lowest_rung_any_l_routes_a_worker_to(self):
self.assertEqual(lowest_worker_rung(OPUS), Rung("claude-haiku-5-5", "max"))
self.assertEqual(lowest_worker_rung(OPUS), Rung("claude-sonnet-5-5", "high"))
def test_plans_on_the_rung_l_picks_but_never_below_the_projects(self):
self.assertEqual(planning_rung(OPUS, 1), OPUS)
@@ -94,20 +97,32 @@ class Ladder(unittest.TestCase):
def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
haiku, fable = LADDER[4], LADDER[-1]
self.assertEqual(review_rungs(OPUS, haiku, 4)["reviewer"], OPUS)
self.assertEqual(review_rungs(OPUS, haiku, 5)["reviewer"], Rung("claude-opus-5-5", "high"))
self.assertEqual(review_rungs(OPUS, fable, 5)["reviewer"], fable)
self.assertEqual(review_rungs(OPUS, Rung("claude-opus-5-5", "high"), 7)["reviewer"], Rung("claude-opus-5-5", "max"))
self.assertEqual(review_rungs(OPUS, haiku, 4)["stability"], OPUS)
self.assertEqual(review_rungs(OPUS, haiku, 5)["stability"], Rung("claude-opus-5-5", "high"))
self.assertEqual(review_rungs(OPUS, fable, 5)["stability"], fable)
self.assertEqual(review_rungs(OPUS, Rung("claude-opus-5-5", "high"), 7)["stability"], Rung("claude-opus-5-5", "max"))
def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
self.assertEqual(review_rungs(OPUS, LADDER[-1], 8), {"reviewer": LADDER[-1], "seat": OPUS, "security": OPUS})
self.assertEqual(review_rungs(OPUS, LADDER[-1], 8), {**dict.fromkeys(REVIEWERS, LADDER[-1]), "seat": OPUS, "security": OPUS})
def test_holds_a_reviewer_to_the_reviewers_rung_and_anything_else_to_the_projects(self):
fable = LADDER[-1]
self.assertEqual(review_rung("reviewer", OPUS, fable), fable)
for kind in ("seat", "security"):
with self.subTest(kind=kind):
self.assertEqual(review_rung(kind, OPUS, fable), OPUS)
def test_runs_a_replayed_pass_on_its_replays_rung_below_the_workers_where_the_e_plus_i_steps_no_review_up_and_the_worker_runs_no_higher_than_the_project(self):
sonnet, haiku, opus_high = Rung("claude-sonnet-5-5", "high"), LADDER[0], Rung("claude-opus-5-5", "high")
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): haiku, ("stability", "claude-sonnet-5-5"): haiku}):
self.assertEqual(review_rungs(OPUS, LADDER[4], 4), {**dict.fromkeys(REVIEWERS, OPUS), "prose": haiku, "seat": OPUS, "security": OPUS})
self.assertEqual(review_rungs(OPUS, OPUS, 4)["prose"], haiku)
self.assertEqual(review_rungs(OPUS, opus_high, 4)["prose"], opus_high)
self.assertEqual(review_rungs(OPUS, sonnet, 5)["prose"], opus_high)
self.assertEqual(review_rungs(OPUS, LADDER[-1], 5)["prose"], LADDER[-1])
self.assertEqual((review_rungs(sonnet, sonnet, 4)["prose"], review_rungs(sonnet, sonnet, 4)["stability"]), (sonnet, haiku))
def test_holds_each_replayed_rung_below_its_models_project_rung_on_the_ladder(self):
for (kind, model), rung in ladder.REPLAYED.items():
with self.subTest(kind=kind, model=model):
project = project_rung(model)
self.assertIn(kind, REVIEWERS)
self.assertIsNotNone(project)
self.assertLess(position(rung), position(project) if project else 0)
self.assertIn(rung, LADDER)
if __name__ == "__main__":
unittest.main()
+15 -13
View File
@@ -9,20 +9,22 @@ class Environment(unittest.TestCase):
PROJECT = Rung("claude-opus-5-5", "medium")
WORKER = Rung("claude-haiku-5-5", "max")
def test_the_project_the_worker_and_the_reviewers_rungs_are_named_in_the_environment(self):
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_REVIEWER_RUNG": "claude-opus-5-5 at high effort"})
self.assertEqual(environment(self.PROJECT, Route(self.WORKER))["LOOP_CLAUDE_REVIEWER_RUNG"], "claude-opus-5-5 at medium effort")
self.assertEqual(environment(self.PROJECT, Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 2))["LOOP_CLAUDE_REVIEWER_RUNG"], "claude-opus-5-5 at xhigh effort")
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["LOOP_CLAUDE_REVIEWER_RUNG"], "claude-opus-5-5 at xhigh effort")
def test_the_project_and_the_workers_rungs_and_the_e_plus_i_reviews_take_are_named_in_the_environment(self):
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"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(environment(self.PROJECT, Route(self.WORKER))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "0")
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "6")
def test_a_project_off_the_ladder_is_handed_empty_rungs_so_none_is_inherited(self):
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_REVIEWER_RUNG": ""})
def test_a_project_off_the_ladder_is_handed_an_empty_rung_so_none_is_inherited(self):
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "0"})
def test_handed_reads_back_what_environment_named(self):
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5))), (self.PROJECT, self.WORKER, Rung("claude-opus-5-5", "high")))
self.assertEqual(handed(environment(None, Route(self.WORKER))), (None, self.WORKER, None))
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5))), (self.PROJECT, self.WORKER, 5))
self.assertEqual(handed(environment(None, Route(self.WORKER))), (None, self.WORKER, 0))
def test_a_missing_or_unknown_rung_reads_as_none(self):
self.assertEqual(handed({}), (None, None, None))
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}), (None, None, None))
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}), (None, None, None))
def test_a_missing_or_unknown_rung_reads_as_none_and_a_missing_or_unknown_e_plus_i_as_0(self):
self.assertEqual(handed({}), (None, None, 0))
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}), (None, None, 0))
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}), (None, None, 0))
for bogus in ("", "five", "-1", "5.0", "²"):
with self.subTest(bogus=bogus):
self.assertEqual(handed({"LOOP_CLAUDE_ESCAPE_AND_IMPACT": bogus})[2], 0)
+10 -9
View File
@@ -1,25 +1,26 @@
"""The rungs loop-claude hands a worker's claude in its environment, so rule-hook holds each review launch to them: docs/decisions.md → `routing:`.
"""The rungs and the E + I loop-claude hands a worker's claude in its environment, from which rule-hook works out the rung of each review launch: docs/decisions.md → `routing:`.
loop-claude sets these variables for its worker and for the claude an interrupt resumes; a human's shell does not, and rule-hook then checks no review launch."""
import typing
from model_routing.ladder import LADDER, review_rungs, Rung
from model_routing.ladder import LADDER, Rung
from model_routing.route import Route
PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG"
WORKER_RUNG = "LOOP_CLAUDE_WORKER_RUNG"
REVIEWER_RUNG = "LOOP_CLAUDE_REVIEWER_RUNG"
# The E + I the chunk's reviews are routed on, from which review_rungs works out each review's rung.
ESCAPE_AND_IMPACT = "LOOP_CLAUDE_ESCAPE_AND_IMPACT"
def environment(project: Rung | None, route: Route) -> dict[str, str]:
"""The variables a worker's claude on route starts with. A project off the ladder gets empty project and reviewer rungs, so none is inherited from the environment."""
reviewers = review_rungs(project, route.rung, route.reviewed_on())["reviewer"] if project else None
return {PROJECT_RUNG: str(project) if project else "", WORKER_RUNG: str(route.rung), REVIEWER_RUNG: str(reviewers) if reviewers else ""}
"""The variables a worker's claude on route starts with. A project off the ladder gets an empty project rung, so none is inherited from the environment."""
return {PROJECT_RUNG: str(project) if project else "", WORKER_RUNG: str(route.rung), ESCAPE_AND_IMPACT: str(route.reviewed_on())}
def handed(environ: typing.Mapping[str, str]) -> tuple[Rung | None, Rung | None, Rung | None]:
"""The project's, the worker's and the reviewers' rungs, each None when unset or not on the ladder."""
return on_the_ladder(environ.get(PROJECT_RUNG)), on_the_ladder(environ.get(WORKER_RUNG)), on_the_ladder(environ.get(REVIEWER_RUNG))
def handed(environ: typing.Mapping[str, str]) -> tuple[Rung | None, Rung | None, int]:
"""The project's and the worker's rungs, each None when unset or not on the ladder, and the reviews' E + I, 0 when unset or not a whole number. An older loop-claude hands no E + I, and 0 steps no review up."""
escape_and_impact = environ.get(ESCAPE_AND_IMPACT, "")
return on_the_ladder(environ.get(PROJECT_RUNG)), on_the_ladder(environ.get(WORKER_RUNG)), int(escape_and_impact) if escape_and_impact.isdecimal() else 0
def on_the_ladder(value: str | None) -> Rung | None:
+111 -51
View File
@@ -1,15 +1,15 @@
#!/usr/bin/env python3
"""Score todo.md's items by the formula it states, weighing each achieve goal by its position in README.md, and hold them to its bar.
"""Score todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar.
usage: rank_todo.py [--check] [todo.md]
Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md when there is
one. Rewrites each item's Score from the formula and sorts the items by release; within a release,
question rows come first, then security rows, then the rest, each group by score from highest, then
by ID. Then it moves each blocker, an item another's Blocked by cell names, that ranks below an item
it blocks to just above the first such item. Orders the details to match. Writes each item's R, and
adds the Blocked by and R columns to a table without them. --check writes nothing and fails when the
file is not ranked as it would be.
Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md and
docs/comprehension-history.md where they exist. Rewrites each item's Score from the formula and
sorts the items by release; within a release, question rows come first, then security rows, then
the rest, each group by score from highest, then by ID. Then it moves each blocker, an item
another's Blocked by cell names, that ranks below an item it blocks to just above the first such
item. Orders the details to match. Writes each item's R, and adds the Blocked by and R columns to a
table without them. --check writes nothing and fails when the file is not ranked as it would be.
A valid todo.md; ## Details and each item's detail are optional:
@@ -37,10 +37,17 @@ A valid todo.md; ## Details and each item's detail are optional:
- The formula holds numbers, + - * / ** and parentheses over L, E, I, R, S and V.
- V sums, over the goals in an item's Moves cell, each goal's weight times how far the item moves it.
README.md marks each goal **Maintain:** or **Achieve:**. The one ranked k of n achieve goals, in
reading order, a sub-goal such as 1.1 included, weighs (1/k) / (1 + 1/2 + ... + 1/n). Only an item
marked defect may name a maintain goal, the one it restores, which weighs as the heaviest achieve
goal.
README.md marks each goal **Maintain:** or **Achieve:**. Code health, the achieve goal every
project shares, ranks first; a Moves cell names it as in `code health by 6`. README.md's achieve
goals follow in reading order, a sub-goal such as 1.1 included. Each weighs 0.97 times the one
before, and the weights sum to 1. With 5 achieve goals the first weighs 0.212 and the last 0.188.
With 15 they weigh 0.082 and 0.053. The overall is the mean of the overall means of every scoring
run on docs/comprehension-history.md's newest scored commit. While it is under 7.0, or the history
holds no scoring run, code health weighs 4 times its weight by position, and the other goals keep
theirs. A line `**Void:** code health, since <reason>.` in README.md's ## Goals drops code health,
and an item may not name it. A project must void it where its docs/decisions.md has a
`## review opt-out:` title naming the comprehension check. Only an item marked defect may name a
maintain goal, the one it restores, which weighs as the heaviest achieve goal.
- The bar is judged on the Score as shown, to one decimal.
- A new item takes Next ID, and Next ID then goes up by one; every ID stays below it.
- An item's L, E and I are levels that ~/.claude/rules/todo-items.md defines: L from 1 to 4, E from 1
@@ -70,22 +77,33 @@ A valid todo.md; ## Details and each item's detail are optional:
release is cut. A release whose items all moved elsewhere without a line reads as finished.
Exit 1, saying why, on bad arguments, a file that cannot be read or written, a todo.md, README.md or
docs/decisions.md that breaks the rules above, an item that is not exempt scoring under the bar, or
--check finding the file unranked.
docs/decisions.md that breaks the rules above, a scoring run on docs/comprehension-history.md's
newest scored commit with no Mean row ending in its overall, an item that is not exempt scoring
under the bar, or --check finding the file unranked.
"""
import ast
import dataclasses
import decimal
import math
import pathlib
import re
import sys
import typing
from todo_table import BLOCKED_BY, cells, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows, version
from todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows, version
from failure import Failure
from comprehension_history import FLOOR, HISTORY, latest_overall
from markdown_text import listed, sections
from file_writes import replace_file
# What each achieve goal weighs of the one above it; docs/decisions.md records the choice.
GOAL_STEP = 0.97
# Code health weighs this many times its weight by position while the comprehension panel's overall is under FLOOR, or unmeasured; lilleman's choice, which docs/decisions.md records.
UNDER_FLOOR = 4
# Any **Void:** line of README.md's ## Goals; ranked_goals accepts only `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → "Shared goal" spells it.
VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M)
# A docs/decisions.md title opting the project out of the comprehension check, as larv-review's SKILL.md → "Opt-out" spells it.
OPTED_OUT = re.compile(r"^## review opt-out:.*\bcomprehension check\b", re.M)
LARGEST_FORMULA = 200
LONGEST_FORMULA = 4 * LARGEST_FORMULA
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
@@ -103,9 +121,9 @@ class Scoring:
formula: ast.Expression
bar: float
next_id: int
# README.md's goals in reading order, each with its mark.
# Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. In OLD_SHAPE an item may name only the goals weights holds.
goals: dict[str, Mark]
# The weight of each goal an item may name: in OLD_SHAPE every goal, at the weight todo.md states; else each goal goal_weights weighs.
# The weight of each goal an item may name: in OLD_SHAPE each of README.md's goals, at the weight todo.md states; else each goal goal_weights weighs.
weights: dict[str, float]
@@ -113,7 +131,7 @@ class Scoring:
class Ranked:
text: str
under_bar: list[str]
# What ranking prints and --check does not: an old-shape table's call to reshape, a README with no achieve goal, and each dropped blocker ID, since a mistyped ID drops the same way.
# What ranking prints and --check does not: an old-shape table's call to reshape, a README that voids code health and marks no goal **Achieve:**, and each dropped blocker ID, since a mistyped ID drops the same way.
notes: list[str]
@@ -130,19 +148,25 @@ def main(argv: list[str]) -> int:
for line in failures:
print(line, file=sys.stderr)
return 1 if failures else 0
texts = read_all(todo)
if isinstance(texts, Failure):
return fail(texts)
ranked = rank(*texts)
ranked = rank_file(todo)
if isinstance(ranked, Failure):
return fail(ranked)
if ranked.text != texts[0]:
unwritten = write(todo, ranked.text)
if unwritten:
return fail(unwritten)
return 1 if ranked.under_bar else 0
def rank_file(todo: pathlib.Path) -> Ranked | Failure:
"""Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr."""
texts = read_all(todo)
if isinstance(texts, Failure):
return texts
ranked = rank(*texts)
if isinstance(ranked, Failure):
return ranked
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
return unwritten
for line in ranked.notes + ranked.under_bar:
print(f"{todo}: {line}", file=sys.stderr)
return 1 if ranked.under_bar else 0
return ranked
def check_failures(todo: pathlib.Path) -> list[str]:
@@ -169,10 +193,10 @@ def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure:
return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md")
def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure:
"""todo.md, the README.md beside it, and its docs/decisions.md, empty when there is none."""
def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure:
"""todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md, each empty when there is none."""
texts = []
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None)):
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)):
try:
texts.append(path.read_text(encoding="utf-8"))
except FileNotFoundError:
@@ -183,7 +207,7 @@ def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
return texts[0], texts[1], texts[2]
return texts[0], texts[1], texts[2], texts[3]
def write(path: pathlib.Path, text: str) -> Failure | None:
@@ -191,13 +215,13 @@ def write(path: pathlib.Path, text: str) -> Failure | None:
return Failure(f"{path}: {unwritten.reason}") if unwritten else None
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
def rank(text: str, readme: str, decisions: str, history: str) -> Ranked | Failure:
lines = text.split("\n")
table = read_table(lines)
if isinstance(table, Failure):
return table
shape = shape_of(table.columns)
scoring = read_scoring(text, lines, readme, shape)
scoring = read_scoring(text, lines, readme, decisions, history, shape)
if isinstance(scoring, Failure):
return scoring
items = read_items(table, scoring)
@@ -237,7 +261,7 @@ def notes(items: list[Item], scoring: Scoring) -> list[str]:
if scoring.shape is OLD_SHAPE:
return [RESHAPE] + dropped
# Printed so the under-bar lines it causes do not read as items of low value.
unweighed = [] if any(scoring.weights.values()) else ["README.md marks no goal **Achieve:**, so every item scores V 0"]
unweighed = [] if any(scoring.weights.values()) else ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"]
return unweighed + dropped
@@ -269,8 +293,8 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
return f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it{blocked}, or mark it with a reason the bar does not apply"
def read_scoring(text: str, lines: list[str], readme: str, shape: Shape) -> Scoring | Failure:
goals = readme_goals(readme)
def read_scoring(text: str, lines: list[str], readme: str, decisions: str, history: str, shape: Shape) -> Scoring | Failure:
goals = ranked_goals(readme, decisions)
if isinstance(goals, Failure):
return goals
formula = parse_formula(stated(text, "Score"), variables(shape))
@@ -282,18 +306,41 @@ def read_scoring(text: str, lines: list[str], readme: str, shape: Shape) -> Scor
next_id = stated(text, "Next ID")
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
numbers = [number for number, _ in goals]
if shape is OLD_SHAPE:
weights = parse_weights(lines, numbers)
elif WEIGHTS_HEADER in lines:
weights = Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs each achieve goal by its position in README.md")
else:
weights = goal_weights(goals)
weights = weigh(lines, history, goals, shape)
if isinstance(weights, Failure):
return weights
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
def ranked_goals(readme: str, decisions: str) -> list[tuple[str, Mark]] | Failure:
"""Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. A **Void:** line other than `**Void:** code health, since <reason>.` fails, and so does a docs/decisions.md that opts out of the comprehension check where README.md keeps code health, since the goal then has no signal."""
goals = readme_goals(readme)
if isinstance(goals, Failure):
return goals
voids = VOID.findall("".join(sections(readme).get("Goals", [])))
if other := [void for void in voids if not void.startswith(f"{CODE_HEALTH}, since ")]:
if other[0].lower().startswith(CODE_HEALTH):
return Failure(f"README.md's ## Goals voids code health as `{other[0]}`; spell the void exactly `**Void:** {CODE_HEALTH}, since <reason>.`")
return Failure(f"README.md's ## Goals voids `{other[0]}`; only code health may be voided, as `**Void:** {CODE_HEALTH}, since <reason>.`")
if voids:
return goals
if OPTED_OUT.search(decisions):
return Failure(f"docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** {CODE_HEALTH}, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says")
return [(CODE_HEALTH, "Achieve"), *goals]
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape) -> dict[str, float] | Failure:
"""Each goal's weight. In OLD_SHAPE, README.md's goals weigh what todo.md states, and code health has no weight, so no item may name it. Otherwise goal_weights gives each its weight, at the overall latest_overall reads where the goals hold code health."""
if shape is OLD_SHAPE:
return parse_weights(lines, [number for number, _ in goals if number != CODE_HEALTH])
if WEIGHTS_HEADER in lines:
return Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs the goals itself, as its --help says")
overall = latest_overall(history) if CODE_HEALTH in dict(goals) else None
if isinstance(overall, Failure):
return overall
return goal_weights(goals, overall)
def read_table(lines: list[str]) -> Table | Failure:
"""The items table, held to its shape's columns and alone under ## Items."""
if "## Items" not in lines:
@@ -429,13 +476,15 @@ def readme_goals(readme: str) -> list[tuple[str, Mark]] | Failure:
return goals
def goal_weights(goals: list[tuple[str, Mark]]) -> dict[str, float] | Failure:
"""Each achieve goal's sum-reciprocal weight: the one ranked k of n in reading order weighs (1/k) / (1 + 1/2 + ... + 1/n). Each maintain goal weighs as the heaviest achieve goal, since a broken one outranks any achieve goal; only a defect that restores it may name it. Every weight is 0 where README.md marks no goal **Achieve:**, so every item scores V 0 and only an exempt one passes the bar."""
def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None) -> dict[str, float] | Failure:
"""Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is under FLOOR or None, and the other goals keep their weights. Each maintain goal weighs as the heaviest achieve goal, since a broken one outranks any achieve goal; only a defect that restores it may name it. Every weight is 0 where goals holds no achieve goal, as where README.md voids code health and marks no goal **Achieve:**, so every item scores V 0 and only an exempt one passes the bar."""
if unmarked := [number for number, mark in goals if mark is None]:
return Failure(f"README.md's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score")
achieve = [number for number, mark in goals if mark == "Achieve"]
harmonic = sum(1 / rank for rank in range(1, len(achieve) + 1))
weights = {number: 1 / rank / harmonic for rank, number in enumerate(achieve, 1)}
total = sum(GOAL_STEP**rank for rank in range(len(achieve)))
weights = {number: GOAL_STEP**rank / total for rank, number in enumerate(achieve)}
if CODE_HEALTH in weights and (overall is None or overall < FLOOR):
weights[CODE_HEALTH] *= UNDER_FLOOR
heaviest = max(weights.values(), default=0.0)
return weights | {number: heaviest for number, mark in goals if mark == "Maintain"}
@@ -559,20 +608,31 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail
def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
"""The row as an item, refused where it names a goal it may not; in SHAPE, with the R its L, E and I give."""
item = parse_row(row, table)
if isinstance(item, Failure):
return item
if broken := cited_goals_failure(item, scoring):
return broken
if scoring.shape is OLD_SHAPE:
if unknown := [goal for goal, _ in item.moves if goal not in scoring.weights]:
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list")
return item
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None:
"""Why the item may not name one of the goals it names, such as one README.md voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
if scoring.shape is OLD_SHAPE:
unknown = [goal for goal, _ in item.moves if goal not in scoring.weights]
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
for goal, _ in item.moves:
if goal == CODE_HEALTH and goal not in scoring.goals:
return Failure(f"item {item.id} names {CODE_HEALTH}, which README.md voids; drop it from the item's {MOVES}, or the void from README.md")
if goal not in scoring.goals:
return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number")
if scoring.goals[goal] == "Maintain" and item.exempt != "defect":
return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves")
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
return None
def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...]) -> str:
+11 -12
View File
@@ -25,7 +25,6 @@ archive or the record cannot be read or written, or a figure in the record canno
import dataclasses
import os
import pathlib
import subprocess
import sys
import time
@@ -33,6 +32,7 @@ from reading_cost.measure import Checkout, measure, Reading
from failure import Failure
from reading_cost.figures import figure, merged, readings_of, RECORD, RESET, trend, unheld
from transcript_archive.read import finished_chunks, read_threads
from git_repo import git
from transcript_archive.location import project_archive
from file_writes import replace_file
from utc_stamp import utc
@@ -112,18 +112,17 @@ def failed(failure: Failure) -> int:
def located() -> Checkout | Failure:
try:
found = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"], capture_output=True, text=True)
if found.returncode != 0:
return Failure(found.stderr.strip())
top, common = found.stdout.splitlines()
listed = subprocess.run(["git", "ls-files", "-z"], capture_output=True, cwd=top, text=True)
except (OSError, ValueError) as failure:
return Failure(f"could not find the checkout: {failure}")
if listed.returncode != 0:
return Failure(listed.stderr.strip())
found = git("rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir")
if isinstance(found, Failure):
return found
if len(lines := found.splitlines()) != 2:
return Failure(f"git rev-parse printed {found!r}, not a checkout's top folder and git directory on two lines")
top, common = lines
listed = git("ls-files", "-z", cwd=top)
if isinstance(listed, Failure):
return listed
# The common dir is the main checkout's .git, whichever worktree runs this.
return Checkout(top, str(pathlib.Path(common).parent), frozenset(filter(None, listed.stdout.split("\0"))))
return Checkout(top, str(pathlib.Path(common).parent), frozenset(filter(None, listed.split("\0"))))
def read_record(record: pathlib.Path) -> str | Failure:
+25 -1
View File
@@ -15,7 +15,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from transcript_archive.write import archive
from reading_cost.measure import Checkout, Reading
from failure import Failure
from reading_cost import figures, measure
from reading_cost import figures, main, measure
from transcript_archive.read import finished_chunks, FinishedChunk
from test_env import isolated_env
from transcript_archive import outcomes
@@ -160,5 +160,29 @@ class ReadingCostTool(unittest.TestCase):
self.assertIn("not a git repository", ran.stderr)
class Located(unittest.TestCase):
def test_lists_the_whole_checkout_from_a_folder_inside_it(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
root = pathlib.Path(temp.name).resolve()
(root / "sub").mkdir()
(root / "a.txt").write_text("a")
(root / "sub" / "b.txt").write_text("b")
for args in (("init", "--quiet"), ("add", ".")):
subprocess.run(["git", *args], check=True, cwd=root, env=isolated_env())
with contextlib.chdir(root / "sub"):
found = main.located()
self.assertEqual(found, Checkout(str(root), str(root), frozenset({"a.txt", "sub/b.txt"})))
def test_fails_in_a_checkout_whose_path_holds_a_newline(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
root = pathlib.Path(temp.name, "a\nb")
root.mkdir()
subprocess.run(["git", "init", "--quiet"], check=True, cwd=root, env=isolated_env())
with contextlib.chdir(root):
self.assertIsInstance(main.located(), Failure)
if __name__ == "__main__":
unittest.main()
+11 -6
View File
@@ -5,20 +5,25 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from rule_hook.reviewer_rung import REVIEWERS, SEAT, SECURITY_OPENER
from review_passes import PASS_AGENTS, PASSES
from repo_checks.test_python_floor import ROOT
from rule_hook.reviewer_rung import SEAT, SECURITY_OPENER
OPENING = re.compile(r"^## Opening\n+```\n([^\n]+?\.)(?: |\n)", re.MULTILINE)
REVIEWER_NAME = re.compile(r"\b[a-z]+(?:-[a-z]+)*-(?:reviewer|architect|auditor)\b")
# An agent's name, as opposed to the skill or plugin that reviews a pass.
AGENT_NAME = re.compile(r"[a-z]+(?:-[a-z]+)*")
# A row of the pass table: its pass and its reviewer cell.
PASS_ROW = re.compile(r"^\| (?!Pass \|)([A-Z][a-z -]+?) \| ([^|]+?) \|", re.MULTILINE)
LARV_REVIEW = (ROOT / "skills" / "larv-review" / "SKILL.md").read_text(encoding="utf-8")
PASS_TABLE = LARV_REVIEW.split("## 3. Passes", 1)[1].split("A comment is prose", 1)[0]
class ReviewerLaunches(unittest.TestCase):
"""rule-hook holds a review launch to its rung by recognising it; these fail when what it recognises drifts from what the skills launch."""
"""rule-hook holds a review launch to its rung by recognising it, and `larv-review round-count` counts the passes by name; these fail when what they recognise drifts from what the skills launch."""
def test_the_reviewers_are_the_ones_larv_review_s_pass_table_names(self):
passes = LARV_REVIEW.split("## 3. Passes", 1)[1].split("A comment is prose", 1)[0]
self.assertEqual(set(REVIEWER_NAME.findall(passes)), REVIEWERS)
def test_the_passes_and_their_agents_are_the_ones_larv_review_s_pass_table_names_in_its_order(self):
rows = [(name.lower(), reviewer if AGENT_NAME.fullmatch(reviewer) else None) for name, reviewer in PASS_ROW.findall(PASS_TABLE)]
self.assertEqual(rows, list(PASS_AGENTS.items()))
def test_the_seat_opening_is_the_sentence_that_opens_every_seat_prompt(self):
opening = OPENING.search((ROOT / "skills" / "comprehension-panel" / "seat-prompts.md").read_text(encoding="utf-8"))
+26
View File
@@ -0,0 +1,26 @@
import json
import pathlib
import sys
import unittest
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
INSTALL = "git config filter.settings.clean bin/settings_filter.py"
class Settings(unittest.TestCase):
def test_the_stored_settings_hold_no_model_and_sorted_keys(self):
# The index, not the working file: the working file holds this machine's model in Claude Code's key order.
stored = git("show", ":settings.json", cwd=str(ROOT))
self.assertIsInstance(stored, str, stored)
fix = f"commit settings.json with the filter on: {INSTALL}"
self.assertNotIn("model", json.loads(stored), fix)
self.assertEqual(stored, cleaned(json.loads(stored)), fix)
def test_the_readme_installs_the_filter_git_attributes_names_for_the_root_settings_only(self):
self.assertEqual("/settings.json filter=settings\n", (ROOT / ".gitattributes").read_text(encoding="utf-8"))
self.assertIn(f"{INSTALL}\n", (ROOT / "README.md").read_text(encoding="utf-8"))
+1 -1
View File
@@ -15,5 +15,5 @@ class Types(unittest.TestCase):
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line")
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "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", "-m", "round_titles", "-p", "reading_cost", "-p", "rule_hook", "-p", "rung_replay", "-p", "score_outcomes", "-p", "stability_replay", "-p", "subagent_rung", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "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)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+1 -1
View File
@@ -5,7 +5,7 @@ import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from stability_replay import main
from review_replay import main
from loop_claude.effects import system_effects
sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects()))
+16
View File
@@ -0,0 +1,16 @@
"""The passes of larv-review, as skills/larv-review/SKILL.md → "Passes" lists them."""
import typing
# A pass an agent under agents/ reviews, in lower case. A Literal cannot be built from `PASS_AGENTS`, so test_review_passes holds the two together.
ReviewedPass = typing.Literal["architecture", "principles", "overrides", "stability", "product-owner", "prose"]
# Each pass in the order of SKILL.md's pass table, and the agent under agents/ that reviews it; None where a skill or plugin does. The auto-reviewer is left out: larv-review counts its rounds from its reviews on the PR, not from commit titles.
PASS_AGENTS: dict[str, str | None] = {"architecture": "systems-architect", "principles": "principles-auditor", "full scan": None, "security": None, "overrides": "override-reviewer", "stability": "stability-reviewer", "product-owner": "product-owner-reviewer", "prose": "prose-reviewer"}
PASSES = tuple(PASS_AGENTS)
def _reviewed(name: str) -> typing.TypeGuard[ReviewedPass]:
return name in typing.get_args(ReviewedPass)
# The passes that have an agent. A pass missing from `ReviewedPass` drops out of it, which test_review_passes fails on.
REVIEWERS: dict[ReviewedPass, str] = {name: agent for name, agent in PASS_AGENTS.items() if agent and _reviewed(name)}
@@ -1,10 +1,11 @@
"""Replay archived stability rounds on the rungs below the project's, to find which rungs may run the stability reviewer: docs/decisions.md → `routing: the stability reviewer runs no lower than the project's rung`.
"""Replay a review pass's archived rounds on the rungs below the project's, to find which rungs may run its reviewer: docs/decisions.md → `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`.
usage: stability-replay <model>
usage: review-replay <pass> <model>
<pass> is one of architecture, principles, overrides, stability, product-owner or prose.
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
latest 10 archived stability rounds whose report holds a 🔴 or 🟡 finding, from the projects that
~/.claude/loop-claude-models.json runs on the model. It replays each round on the code it
latest 10 archived rounds of the pass whose report holds a 🔴 or 🟡 finding, from the projects
that ~/.claude/loop-claude-models.json runs on the model. It replays each round on the code it
reviewed: in a throwaway clone of the project's checkout, at the newest commit of origin/HEAD
authored by the time the round began, on the branch the reviewer started on. The clone's default
branch stands at the newest commit authored before the round's chunk began, so a diff against it
@@ -12,18 +13,17 @@ shows the chunk's change. The prompt names the clone in place of the worktree it
chunk has since removed. A round whose code it cannot find in this way is not replayed; stderr
names it and why. The prompt also names a copy of the chunk's review folder in place of that
folder, holding only the reports written after the chunk began and before the round did. A replay
whose prompt still names the review folder finds nothing.
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
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 lowest rung a worker routes to, 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, 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 stability reviewer on the worker's rung whenever the worker runs at
or above it; docs/decisions.md → `routing: the stability reviewer runs no lower than the project's rung`
records the run.
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,
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.
Like the loop, it tries claude three times running before it counts a reply as failed. A failed
review or match finds nothing. Exit 1, saying why, on bad arguments, an unreadable archive or
@@ -39,21 +39,22 @@ import tempfile
import typing
from transcript_archive.location import archive_root
from stability_replay.rounds import authored_by, report, reviewed_path, Round, round_from, sample, stamp_seconds
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
from review_replay.rounds import authored_by, lost_inputs, report, reviewed_path, Round, round_from, sample, stamp_seconds
from project_key import checkout_of
from claude_code.reply import claude_reply, Limited
from rung_replay.command import down_from, failed, limited_exit, project_rung_or_exit, projects_on
from loop_claude.effects import Effects
from failure import Failure
from rung_replay.search import first_reply, replayed
from claude_code.transcript import first_timestamped_line, read_transcript
from model_routing.ladder import LADDER, project_rung, Rung
from claude_code.entries import parse_entry, structured_output
from review_folder import REPORTS, review_folder
from model_routing.ladder import Rung
from review_passes import ReviewedPass, REVIEWERS
TOOL = "stability-replay"
TOOL = "review-replay"
USAGE = f"{TOOL} <pass> <model>, <pass> one of {', '.join(REVIEWERS)} and <model> a model on the routing ladder"
LATEST = 10
REVIEWER = "stability-reviewer"
MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False}
@@ -67,30 +68,56 @@ class Code:
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
anchor = project_rung_or_exit(TOOL, argv, __doc__)
if isinstance(anchor, int):
return anchor
rounds = archived_rounds(anchor.model, archive_root(home, env), home)
read = arguments_or_exit(TOOL, argv, __doc__, USAGE, pass_and_model)
if isinstance(read, int):
return read
reviewed, anchor = read
rounds = archived_rounds(REVIEWERS[reviewed], anchor.model, archive_root(home, env), home)
if isinstance(rounds, Failure):
return failed(TOOL, rounds.reason)
codes = codes_found(rounds, effects)
if not codes:
return failed(TOOL, f"no archived {reviewed} round of projects on {anchor.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
chosen = sample(list(codes), LATEST)
# The project's rung is the reference, so the candidates start below it. They reach the ladder's lowest rung, below the lowest a worker routes to, since a pass may run below the worker's rung.
candidates = down_from(anchor, LADDER[0])[1:]
def found_on(found: Round, rung: Rung) -> set[int] | Limited:
return findings_found(found, codes[found], rung, anchor, home, effects)
replay = replayed(chosen, anchor, candidates, found_on, reproduced, f"{reviewed} rounds")
if isinstance(replay, Limited):
return limited_exit(TOOL, replay)
print(report(reviewed, anchor.model, anchor, chosen, replay))
return 0
def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung] | None:
"""The pass and the project's rung of the model argv names, as `<pass> <model>`; None for any other argv."""
if len(argv) != 2:
return None
reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None)
anchor = project_rung(argv[1])
return (reviewed, anchor) if reviewed and anchor else None
def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]:
"""The code each round reviewed, as code_of finds it; stderr names each round left out, and why."""
codes = {}
for found in rounds:
if isinstance(code := code_of(found, effects), Failure):
print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True)
else:
codes[found] = code
if not codes:
return failed(TOOL, f"no archived stability round of projects on {anchor.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
chosen = sample(list(codes), LATEST)
# The project's rung is the reference, so the candidates start below it.
replay = replayed(chosen, anchor, down_from(anchor)[1:], lambda found, rung: findings_found(found, codes[found], rung, anchor, home, effects), lambda _, found: sorted(found), "stability rounds")
if isinstance(replay, Limited):
return limited_exit(TOOL, replay)
print(report(anchor.model, anchor, chosen, replay))
return 0
return codes
def archived_rounds(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
def reproduced(_: Round, found: set[int]) -> list[int]:
"""The indexes of the round's findings that a replay on the reference reviewer found, which each lower rung is held to."""
return sorted(found)
def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
projects = projects_on(model, home)
if isinstance(projects, Failure):
return projects
@@ -98,13 +125,13 @@ def archived_rounds(model: str, root: pathlib.Path, home: pathlib.Path) -> list[
try:
for key in projects:
for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()):
found += chunk_rounds(checkout_of(key, home), chunk)
found += chunk_rounds(reviewer, checkout_of(key, home), chunk)
except (OSError, UnicodeDecodeError, ValueError) as failure:
return Failure(f"could not read the archive {root}: {failure}")
return found
def chunk_rounds(checkout: str, chunk: pathlib.Path) -> list[Round]:
def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]:
copies = sorted(chunk.glob("*.jsonl"))
began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None
if not began or not isinstance(began.get("timestamp"), str):
@@ -112,16 +139,16 @@ def chunk_rounds(checkout: str, chunk: pathlib.Path) -> list[Round]:
found = []
for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")):
described = json.loads(meta.read_text(encoding="utf-8"))
if not isinstance(described, dict) or described.get("agentType") != REVIEWER:
if not isinstance(described, dict) or described.get("agentType") != reviewer:
continue
entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl")))
if not isinstance(entries, Failure) and (one := round_from(checkout, stamp_seconds(began["timestamp"]), entries)):
if not isinstance(entries, Failure) and (one := round_from(reviewer, checkout, stamp_seconds(began["timestamp"]), entries)):
found.append(one)
return found
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 prompt's removed worktree, and the commits authored by then.
"""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.
"""
@@ -130,12 +157,12 @@ def code_of(found: Round, effects: Effects) -> Code | Failure:
path = reviewed_path(found.prompt, found.root, os.path.exists)
if path is None:
return Failure("the prompt names neither one removed worktree nor the checkout")
default = git(effects, found.root, "symbolic-ref", "--short", "refs/remotes/origin/HEAD")
default = effects.git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=found.root)
if isinstance(default, Failure):
return default
default = default.strip().removeprefix("origin/")
log = git(effects, found.root, "log", "--format=%H %at", f"refs/remotes/origin/{default}")
main_line = git(effects, found.root, "log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}")
log = effects.git("log", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
main_line = effects.git("log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
if isinstance(log, Failure):
return log
if isinstance(main_line, Failure):
@@ -162,41 +189,69 @@ def findings_found(found: Round, code: Code, rung: Rung, anchor: Rung, home: pat
return matched
@dataclasses.dataclass(frozen=True)
class Copies:
"""The throwaway copies a replay hands its reviewer: clone, of the project's checkout, and reports, of the chunk's review folder."""
clone: str
reports: str
# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is; rounds.py's core takes the filesystem as an argument.
def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects) -> str | Failure | Limited:
try:
(home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="stability-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="stability-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports:
return reviewed_in(found, code, rung, home, effects, clone, reports)
with tempfile.TemporaryDirectory(prefix="review-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports:
return reviewed_in(found, code, rung, Copies(clone, reports), home, effects)
except OSError as failure:
return Failure(f"could not prepare the replay: {failure}")
def reviewed_in(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects, clone: str, reports: str) -> str | Failure | Limited:
"""The report of found's reviewer on rung, replayed on code cloned into clone, with its review folder copied into reports."""
# The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find.
def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, effects: Effects) -> str | Failure | Limited:
"""The report of found's reviewer on rung, replayed on code cloned into copies.clone, with its review folder copied into copies.reports."""
folder = pathlib.Path(review_folder(str(home), code.path))
copy_reports(found, folder, copies.reports)
prompt = redirected(found.prompt, home, folder, code.path, copies)
if isinstance(prompt, Failure):
return prompt
if lost := lost_inputs(prompt, copies.reports, lambda name: (pathlib.Path(copies.reports) / name).exists()):
return Failure(f"the prompt names {', '.join(lost)}, which the review folder did not hold from the chunk's start until the round's")
if isinstance(cloned := clone_reviewed(found, code, copies.clone, effects), Failure):
return cloned
reply = claude_reply(effects.claude, ["--agent", found.reviewer, *rung.flags()], copies.clone, prompt, "claude")
if isinstance(reply, Failure | Limited):
return reply
return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report")
def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None:
"""Copies into reports each report written to folder after found's chunk began and before its round did."""
# The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find.
for written in folder.iterdir() if folder.is_dir() else ():
if written.is_file() and found.began <= written.stat().st_mtime < found.seconds:
shutil.copy2(written, reports)
# Replace the folder's path first: outside home it contains the worktree's path, which replacing code.path would otherwise turn into the clone's.
prompt = found.prompt.replace(str(folder), reports).replace(f"~/{folder.relative_to(home)}", reports).replace(code.path, clone)
def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure:
"""prompt naming copies.reports in place of the review folder, in either spelling, and copies.clone in place of the worktree; a Failure where it still names the review folder."""
# Replace the folder's path first: outside home it contains the worktree's path, which replacing the worktree's would otherwise turn into the clone's.
prompt = prompt.replace(str(folder), copies.reports).replace(f"~/{folder.relative_to(home)}", copies.reports).replace(worktree, copies.clone)
# A spelling the rewrite misses, such as $HOME/, would leave the reviewer the live folder and the findings in it.
if REPORTS in prompt.replace(reports, ""):
if REPORTS in prompt.replace(copies.reports, ""):
return Failure("the prompt names the review folder in a spelling the replay does not redirect")
return prompt
def clone_reviewed(found: Round, code: Code, clone: str, effects: Effects) -> Failure | None:
"""Clones found's checkout into clone, on the commit its reviewer read, with the default branch where it stood as the chunk began."""
for command in (
("clone", "--quiet", "--shared", "--no-checkout", found.root, clone),
("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base),
("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base),
("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed),
):
if isinstance(ran := git(effects, found.root, *command), Failure):
if isinstance(ran := effects.git(*command, cwd=found.root), Failure):
return ran
args = ["--agent", REVIEWER, *rung.flags()]
reply = claude_reply(effects.claude, args, clone, prompt, "claude")
if isinstance(reply, Failure | Limited):
return reply
return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report")
return None
def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited:
@@ -216,11 +271,3 @@ def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung,
if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers):
return Failure(f"the match replied: {json.dumps(reply)}")
return {n - 1 for n in numbers if 1 <= n <= len(findings)}
def git(effects: Effects, cwd: str, *args: str) -> str | Failure:
try:
ran = effects.git(list(args), cwd)
except OSError as failure:
return Failure(f"git {' '.join(args)} could not start in {cwd}: {failure.strerror}")
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
@@ -1,4 +1,4 @@
"""Which archived stability rounds to replay, the code each reviewed, and the report: docs/decisions.md → `routing: the stability reviewer runs no lower than the project's rung`."""
"""Which archived rounds of a review pass to replay, the code each reviewed, and the report: docs/decisions.md → `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`."""
import dataclasses
import datetime
import pathlib
@@ -14,11 +14,14 @@ 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.
ROUND_REPORT = re.compile(r"-round-\d+(?:-rerun)?\.md$")
@dataclasses.dataclass(frozen=True)
class Round:
"""One archived stability review of the checkout at root, at the UTC stamp at, in a chunk that began at began: its prompt, and the 🔴 and 🟡 findings its report holds, each with its lines up to the next blank line or finding."""
"""One archived review by the agent reviewer of the checkout at root, at the UTC stamp at, in a chunk that began at began: its prompt, and the 🔴 and 🟡 findings its report holds, each with its lines up to the next blank line or finding."""
reviewer: str
root: str
branch: str
at: str
@@ -31,15 +34,15 @@ class Round:
return stamp_seconds(self.at)
def round_from(root: str, began: float, entries: list[dict]) -> Round | None:
"""The round a stability reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to."""
def round_from(reviewer: str, root: str, began: float, entries: list[dict]) -> Round | None:
"""The round a reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to."""
reports = [text for found in entries for part in assistant_parts(found) if (text := part_text(part))]
first = entries[0] if entries else {}
if not stamped(first) or not reports or not (findings := recorded_findings(reports[-1])):
return None
prompt = content(first)
prompt = prompt if isinstance(prompt, str) else "".join(part_text(part) or "" for part in parts(first))
return Round(root, first.get("gitBranch", ""), first["timestamp"], began, prompt, tuple(findings))
return Round(reviewer, root, first.get("gitBranch", ""), first["timestamp"], began, prompt, tuple(findings))
def stamped(entry: dict) -> bool:
@@ -84,6 +87,12 @@ def reviewed_path(prompt: str, root: str, exists: typing.Callable[[str], bool])
return root if not gone and root in named else None
def lost_inputs(prompt: str, reports: str, held: typing.Callable[[str], bool]) -> list[str]:
"""The files the prompt names in reports, the copy of a round's review folder, that the copy does not hold, other than round reports. A report the copy lacks is the round's own or a later one, left out on purpose; any other file it lacks, such as a branch diff written again after the round began, would leave the replay without an input the round had."""
named = [LINE_OR_STOP.sub("", path).removeprefix(reports + "/") for path in PATH.findall(prompt) if path.startswith(reports + "/")]
return sorted({name for name in named if not ROUND_REPORT.search(name) and not held(name)})
def authored_by(log: list[tuple[str, float]], seconds: float) -> str | None:
"""The newest commit in log, which lists newest first, authored at or before seconds. A rebase keeps author times, so a merged branch's commits still say what it held."""
return next((commit for commit, authored in log if authored <= seconds), None)
@@ -94,10 +103,10 @@ def sample(rounds: list[Round], latest: int) -> list[Round]:
return sorted(rounds, key=lambda found: (found.seconds, found.root))[-latest:]
def report(model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> str:
def report(reviewed: str, model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> str:
total = sum(len(found_round.findings) for found_round in rounds)
lines = [
f"Replayed {len(rounds)} stability rounds of {model} projects, holding {total} 🔴 and 🟡 findings.",
f"Replayed {len(rounds)} {reviewed} rounds of {model} projects, holding {total} 🔴 and 🟡 findings.",
f"The reference reviewer, {reference}, found {sum(len(found) for found in replay.on_reference)} of them.",
]
for tried in replay.tried:
@@ -14,14 +14,15 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from stability_replay.rounds import authored_by, recorded_findings, report, reviewed_path, Round, round_from, sample, stamp_seconds
from review_replay.rounds import authored_by, lost_inputs, recorded_findings, report, reviewed_path, Round, round_from, sample, stamp_seconds
from loop_claude.effects import Effects, system_effects
from failure import Failure
from stability_replay import main
from review_replay import main
from rung_replay.search import Miss, Replay, Tried
from review_passes import REVIEWERS
from model_routing.ladder import Rung
TOOL = pathlib.Path(__file__).resolve().parents[1] / "stability-replay"
TOOL = pathlib.Path(__file__).resolve().parents[1] / "review-replay"
REFERENCE = Rung("claude-opus-5-5", "medium")
MIDDLE = Rung("claude-sonnet-5-5", "high")
CHEAP = Rung("claude-haiku-5-5", "max")
@@ -32,7 +33,7 @@ def entry(kind, text, **fields):
def a_round(at, findings=("🔴 a",)):
return Round("/code/p", "x", f"2026-10-14T10:00:0{at}Z", 0, "Review it.", tuple(findings))
return Round("stability-reviewer", "/code/p", "x", f"2026-10-14T10:00:0{at}Z", 0, "Review it.", tuple(findings))
class RecordedFindings(unittest.TestCase):
@@ -51,19 +52,19 @@ class RoundFrom(unittest.TestCase):
entry("assistant", "Reading."),
entry("assistant", "BLOCK\n\n🔴 a.py:1 breaks"),
]
self.assertEqual(round_from("/code/p", 5.0, entries), Round("/code/p", "x", "2026-10-14T10:00:00.500Z", 5.0, "Review branch x in /code/p-x.", ("🔴 a.py:1 breaks",)))
self.assertEqual(round_from("/code/p", 5.0, entries).seconds, 1791972000.5)
self.assertEqual(round_from("stability-reviewer", "/code/p", 5.0, entries), Round("stability-reviewer", "/code/p", "x", "2026-10-14T10:00:00.500Z", 5.0, "Review branch x in /code/p-x.", ("🔴 a.py:1 breaks",)))
self.assertEqual(round_from("stability-reviewer", "/code/p", 5.0, entries).seconds, 1791972000.5)
def test_reads_a_prompt_given_as_a_string(self):
start = {"type": "user", "message": {"content": "Review branch x in /code/p-x."}, "timestamp": "2026-10-14T10:00:00Z", "gitBranch": "x"}
self.assertEqual(round_from("/code/p", 5.0, [start, entry("assistant", "🔴 a")]).prompt, "Review branch x in /code/p-x.")
self.assertEqual(round_from("stability-reviewer", "/code/p", 5.0, [start, entry("assistant", "🔴 a")]).prompt, "Review branch x in /code/p-x.")
def test_skips_a_round_with_no_red_or_yellow_finding_or_no_report(self):
start = entry("user", "Review.", timestamp="2026-10-14T10:00:00Z", cwd="/code/p", gitBranch="x")
self.assertIsNone(round_from("/code/p", 5.0, [start, entry("assistant", "APPROVE\n\n🟢 nit")]))
self.assertIsNone(round_from("/code/p", 5.0, [start]))
self.assertIsNone(round_from("/code/p", 5.0, []))
self.assertIsNone(round_from("/code/p", 5.0, [{**start, "timestamp": "yesterday"}, entry("assistant", "🔴 a")]))
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, [start, entry("assistant", "APPROVE\n\n🟢 nit")]))
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, [start]))
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, []))
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, [{**start, "timestamp": "yesterday"}, entry("assistant", "🔴 a")]))
class ReviewedPath(unittest.TestCase):
@@ -79,6 +80,13 @@ class ReviewedPath(unittest.TestCase):
self.assertIsNone(reviewed_path("Review /code/p-x and /code/p-43.", "/code/p", exists))
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."
self.assertEqual(lost_inputs(prompt, "/c", {"ls-files.txt"}.__contains__), ["branch.diff"])
self.assertEqual(lost_inputs(prompt, "/c", {"branch.diff", "ls-files.txt"}.__contains__), [])
class AuthoredBy(unittest.TestCase):
def test_takes_the_newest_commit_authored_by_then(self):
log = [("c3", 30), ("c2", 20), ("c1", 10)]
@@ -96,7 +104,7 @@ class Sample(unittest.TestCase):
class Report(unittest.TestCase):
def test_counts_the_findings_and_names_each_miss_and_the_lowest_rung_that_missed_none(self):
rounds = [a_round(1, ("🔴 a\nmore", "🟡 b")), a_round(2)]
lines = report("claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(rounds[0], 0, {1})])], MIDDLE)).splitlines()
lines = report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(rounds[0], 0, {1})])], MIDDLE)).splitlines()
self.assertEqual(lines, [
"Replayed 2 stability rounds of claude-opus-5-5 projects, holding 3 🔴 and 🟡 findings.",
"The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.",
@@ -105,8 +113,8 @@ class Report(unittest.TestCase):
" /code/p 2026-10-14T10:00:01Z: 🔴 a",
"Lowest rung that finds every finding the reference reviewer finds: claude-sonnet-5-5 at high effort",
])
self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, {0}], [Tried(MIDDLE, [Miss(rounds[1], 0, set())])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung")
self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
self.assertEqual(report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, {0}], [Tried(MIDDLE, [Miss(rounds[1], 0, set())])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung")
self.assertEqual(report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
class Match(unittest.TestCase):
@@ -135,15 +143,6 @@ class Match(unittest.TestCase):
self.assertIsInstance(self.run_match(json.dumps({"type": "result", "structured_output": output})), Failure)
class Git(unittest.TestCase):
def test_says_why_git_cannot_start_in_a_directory_that_is_gone(self):
def gone(args, cwd):
raise FileNotFoundError(2, "No such file or directory")
ran = main.git(dataclasses.replace(system_effects(), git=gone), "/code/gone", "log")
self.assertEqual(ran, Failure("git log could not start in /code/gone: No such file or directory"))
def unused(*_):
raise AssertionError("not called")
@@ -174,6 +173,7 @@ class Main(unittest.TestCase):
for key in ("proj", "other"):
self.write_chunk(key, "c1", "2026-10-14T10:00:00Z")
self.reviews = []
self.agents = set()
def write_chunk(self, key, chunk, at, began="2026-10-14T09:15:00Z"):
"""A chunk that began at began, whose stability round began at at."""
@@ -207,6 +207,7 @@ class Main(unittest.TestCase):
if "--agent" in args:
shown = [subprocess.run(["git", *command], cwd=cwd, capture_output=True, text=True).stdout for command in (["show", "HEAD:a.txt"], ["branch", "--show-current"], ["show", "origin/main:a.txt"])]
self.reviews.append((rung, *shown, prompt, cwd))
self.agents.add(args[args.index("--agent") + 1])
result = review(rung)
else:
reviewed = Rung(*re.search(r"review on (\S+) (\S+)", prompt).groups())
@@ -221,7 +222,7 @@ class Main(unittest.TestCase):
return code, out.getvalue(), err.getvalue()
def test_replays_the_models_rounds_on_the_commit_reviewed_from_the_project_rung_down(self):
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0] if rung.model == "claude-haiku-5-5" else [0, 1]})
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0] if rung.model == "claude-haiku-5-5" else [0, 1]})
self.assertEqual(code, 0, err)
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP])
_, reviewed, branch, base, prompt, cwd = self.reviews[0]
@@ -233,6 +234,18 @@ class Main(unittest.TestCase):
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z: 🟡 slow", out)
self.assertTrue(out.endswith("finds: claude-sonnet-5-5 at high effort\n"))
def test_replays_the_prose_pass_with_the_prose_reviewer(self):
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
self.assertEqual(code, 0, err)
self.assertEqual(self.agents, {"prose-reviewer"})
self.assertTrue(out.startswith("Replayed 1 prose rounds"), out)
def test_tries_each_rung_down_to_the_ladders_lowest_below_the_lowest_a_worker_routes_to(self):
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
self.assertEqual(code, 0, err)
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP, *(Rung("claude-haiku-5-5", effort) for effort in ("xhigh", "high", "medium", "low"))])
self.assertTrue(out.endswith("finds: claude-haiku-5-5 at low effort\n"), out)
def review_folder_with_round_1(self):
"""The chunk's review folder, holding round 1's report from before the replayed round began at 10:00, that round's own and a later pass's reports, written after, and an earlier attempt's report, from before the chunk began at 09:15."""
folder = self.home / ".local" / "state" / "larv-review" / "code" / "proj-x"
@@ -258,7 +271,7 @@ class Main(unittest.TestCase):
(named / "stability-round-2.md").write_text("replayed\n")
return {"type": "result", "result": f"review on {rung.model} {rung.effort}"}
code, _, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0, 1]}, review)
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}, review)
self.assertEqual(code, 0, err)
named, copied, earlier = seen[0]
self.assertEqual(named.parent, folder.parents[1], "the copy sits in the reports folder, where rule-hook lets the reviewer write")
@@ -272,28 +285,47 @@ class Main(unittest.TestCase):
def test_points_the_review_folders_absolute_path_at_the_copy(self):
folder = self.review_folder_with_round_1()
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to {folder}/stability-round-2.md.")
code, _, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0, 1]})
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
self.assertEqual(code, 0, err)
prompt = self.reviews[0][4]
self.assertNotIn(str(folder), prompt)
self.assertRegex(prompt, rf"report to {folder.parents[1]}/stability-replay-\w+/stability-round-2\.md\.$")
self.assertRegex(prompt, rf"report to {folder.parents[1]}/review-replay-\w+/stability-round-2\.md\.$")
def test_replays_no_round_whose_prompt_still_names_the_review_folder_after_the_rewrite(self):
self.review_folder_with_round_1()
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to $HOME/.local/state/larv-review/code/proj-x/stability-round-2.md.")
code, out, err = self.run_main(["claude-opus-5-5"], unused)
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
self.assertEqual(code, 0, err)
self.assertEqual(self.reviews, [])
self.assertIn(f"on {REFERENCE} found nothing: the prompt names the review folder in a spelling the replay does not redirect", err)
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
def test_replays_a_round_whose_prompt_names_an_input_written_before_it_began_naming_the_copy(self):
folder = self.review_folder_with_round_1()
(folder / "branch.diff").write_text("the diff\n")
before = stamp_seconds("2026-10-14T09:50:00Z")
os.utime(folder / "branch.diff", (before, before))
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
self.assertEqual(code, 0, err)
self.assertRegex(self.reviews[0][4], rf"The diff is {folder.parents[1]}/review-replay-\w+/branch\.diff\.")
def test_replays_no_round_whose_prompt_names_an_input_the_folder_holds_only_as_rewritten_after_the_round_began(self):
folder = self.review_folder_with_round_1()
(folder / "branch.diff").write_text("a later diff\n")
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
self.assertEqual(code, 0, err)
self.assertEqual(self.reviews, [])
self.assertIn(f"on {REFERENCE} found nothing: the prompt names branch.diff, which the review folder did not hold from the chunk's start until the round's", err)
def test_finds_nothing_and_leaves_no_folder_behind_when_it_cannot_copy_the_reports(self):
folder = self.review_folder_with_round_1()
(folder / "stability-round-1.md").chmod(0)
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
scratch = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
self.enterContext(unittest.mock.patch.object(tempfile, "tempdir", str(scratch)))
code, _, err = self.run_main(["claude-opus-5-5"], unused)
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
self.assertEqual(code, 0, err)
self.assertEqual(self.reviews, [])
self.assertIn(f"on {REFERENCE} found nothing: could not prepare the replay: ", err)
@@ -302,13 +334,13 @@ class Main(unittest.TestCase):
def test_replays_the_rounds_of_every_chunk(self):
self.write_chunk("proj", "c2", "2026-10-14T10:30:00Z")
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0, 1]})
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
self.assertEqual(code, 0, err)
self.assertTrue(out.startswith("Replayed 2 stability rounds"), out)
def test_checks_out_the_commit_detached_when_the_reviewer_started_on_the_default_branch(self):
self.set_branch("main")
self.assertEqual(self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
self.assertEqual(self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
self.assertEqual(self.reviews[0][1:3], ("1\n", ""))
def test_sets_the_default_branch_to_its_own_line_and_not_to_a_branch_merged_after_the_chunk_began(self):
@@ -320,20 +352,20 @@ class Main(unittest.TestCase):
run_git(self.checkout, "checkout", "-q", "main")
run_git(self.checkout, "merge", "-q", "--no-ff", "-m", "m", "side", at="2026-10-14T09:40:00Z")
run_git(self.checkout, "push", "-qf", "origin", "main")
self.assertEqual(self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
self.assertEqual(self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
self.assertEqual(self.reviews[0][1:4], ("s\n", "x\n", "0\n"))
def test_finds_nothing_in_a_round_whose_review_has_no_report(self):
code, out, err = self.run_main(["claude-opus-5-5"], unused, review=lambda rung: {"type": "result"})
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused, review=lambda rung: {"type": "result"})
self.assertEqual(code, 0, err)
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE] * 3)
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z on {REFERENCE} found nothing: the reviewer replied with no report", err)
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
def assert_no_round(self):
code, _, err = self.run_main(["claude-opus-5-5"], unused)
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
self.assertEqual(code, 1)
self.assertEqual(err.splitlines(), [f"stability-replay: no archived stability round of projects on claude-opus-5-5 in {self.archive} holds a 🔴 or 🟡 on code it can find"])
self.assertEqual(err.splitlines(), [f"review-replay: no archived stability round of projects on claude-opus-5-5 in {self.archive} holds a 🔴 or 🟡 on code it can find"])
def test_skips_a_chunk_with_no_transcript_copy(self):
(self.archive / "proj" / "c1" / "t0.jsonl").unlink()
@@ -344,7 +376,7 @@ class Main(unittest.TestCase):
self.assert_no_round()
def assert_left_out(self, reason, root=None):
code, _, err = self.run_main(["claude-opus-5-5"], unused)
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
self.assertEqual(code, 1)
self.assertIn(f"{root or self.checkout} 2026-10-14T10:00:00Z is left out: {reason}", err)
@@ -366,23 +398,25 @@ class Main(unittest.TestCase):
self.assert_left_out("no commit was authored by then")
def test_exits_1_on_a_usage_limit_bad_arguments_or_no_round_to_replay(self):
code, _, err = self.run_main(["claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
self.assertEqual(code, 1)
self.assertIn("usage limit: You've hit your limit", err)
for argv in ([], ["off-ladder"], ["claude-opus-5-5", "x"]):
self.assertEqual(self.run_main(argv, unused)[0], 1)
code, _, err = self.run_main(["claude-haiku-5-5"], unused)
for argv in ([], ["claude-opus-5-5"], ["full scan", "claude-opus-5-5"], ["stability", "off-ladder"], ["stability", "claude-opus-5-5", "x"]):
with self.subTest(argv=argv):
self.assertEqual(self.run_main(argv, unused)[0], 1)
code, _, err = self.run_main(["stability", "claude-haiku-5-5"], unused)
self.assertEqual(code, 1)
self.assertIn("no archived stability round of projects on claude-haiku-5-5", err)
def test_prints_the_help(self):
code, out, _ = self.run_main(["-h"], unused)
self.assertEqual((code, out.splitlines()[2]), (0, "usage: stability-replay <model>"))
self.assertEqual((code, out.splitlines()[2]), (0, "usage: review-replay <pass> <model>"))
self.assertIn(f"{', '.join(list(REVIEWERS)[:-1])} or {list(REVIEWERS)[-1]}.", " ".join(out.split()))
def test_the_launcher_prints_the_help(self):
ran = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True)
self.assertEqual(ran.returncode, 0)
self.assertIn("usage: stability-replay <model>", ran.stdout)
self.assertIn("usage: review-replay <pass> <model>", ran.stdout)
if __name__ == "__main__":
+2 -1
View File
@@ -1,8 +1,9 @@
"""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."""
import re
from review_passes import PASSES
CAP = 3
PASSES = ("architecture", "principles", "full scan", "security", "overrides", "stability", "product-owner", "prose")
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]+) 🟡(?:;|$)")
+5 -5
View File
@@ -5,9 +5,9 @@ import re
import statistics
import typing
from model_routing.route import archived_worker, ESCALATION_MARKER
from claude_code.entries import assistant_parts, parts, tool_call, usage_count
from git_command import commits
from model_routing.route import ESCALATION_MARKER, route_from
from model_routing.ladder import position, Rung
from round_titles import round_counts
from shell_command import simple_commands
@@ -91,7 +91,7 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
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)
start = archived_worker(cycles[0][1]) if cycles else None
start = route_from(cycles[0][1]) if cycles else None
return ChunkFigures(
tokens=tokens,
start=start.rung if start and start.item else None,
@@ -130,11 +130,11 @@ def add(tokens: dict[str, collections.Counter[str]], project: str, kind: str, ru
def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str:
"""The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker off the ladder is returned as its text."""
"""The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker."""
second = timestamp[:19] + "Z"
found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted")
archived = archived_worker(found)
return archived.rung if archived else found
route = route_from(found)
return route.rung if route else found
def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung:
+8 -7
View File
@@ -15,10 +15,11 @@ from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, r
from failure import Failure
from model_routing.ladder import LADDER, Rung
from transcript_archive import outcomes, write
from model_routing.route import Route
LOW = Rung("claude-opus-5-5", "medium")
HIGH = Rung("claude-opus-5-5", "high")
LOW_ROUTE = f"{LOW}, routed by item 7's L of 3 and E + I of 4"
LOW_ROUTE = Route(LOW, 7, 3, 4).record()
def message(id_, at, *parts, model="claude-opus-5-5", tokens=(1, 10, 100)):
@@ -49,7 +50,7 @@ class Measured(unittest.TestCase):
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(str(HIGH))) + stamped("2026-10-14T12:00:00Z", outcomes.finished(str(HIGH), "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).record())) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).record(), "merged", "j"))
found = measured(Chunk("log", [kept], worker, []), "/h")
self.assertEqual(found.tokens["project"], {"log": 333})
self.assertEqual(found.tokens["subagent type"], {"worker": 333})
@@ -84,22 +85,22 @@ class Measured(unittest.TestCase):
worker = [commit("m1", "Answer stability round 1: 1 🔴, 0 🟡"), commit("m2", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m3", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m4", "Answer prose round 1: 0 🔴, 1 🟡")]
self.assertEqual(measured(Chunk("log", [], worker, []), "/h").rounds_past_first, 1)
def test_reads_the_rung_of_a_route_an_older_loop_claude_archived_by_r_plus_c(self):
older = f"{LOW}, routed by item 7's R + C of 9"
def test_reads_the_route_of_a_line_loop_claude_wrote_before_it_archived_json(self):
older = f"{LOW}, routed by item 7's L of 3 and E + I of 4"
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})
def test_starts_no_route_for_a_chunk_no_item_routed(self):
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(str(LOW), "m", "j"))
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).record(), "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})
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(str(HIGH), "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).record(), "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")),
@@ -211,7 +212,7 @@ 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(str(HIGH), "m", "j"), 4070908800))
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).record(), "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})
+4 -11
View File
@@ -1,20 +1,13 @@
import os
import pathlib
import subprocess
from failure import Failure
# A -c given here outranks the checkout's own config, which may allow one transport by name; GIT_NO_LAZY_FETCH needs git 2.44.
GUARDS = [option for setting in ["core.fsmonitor=false", "log.showSignature=false", "protocol.allow=never", *(f"protocol.{name}.allow=never" for name in ("ext", "file", "git", "http", "https", "ssh"))] for option in ("-c", setting)]
import git_repo
def git(directory: str, *args: str) -> str | Failure:
# The hook runs git in a checkout the call has not yet been allowed to touch, whose config could name a program: no fsmonitor, no signature check, and no fetch of a partial clone's missing objects through its transport.
try:
ran = subprocess.run(["git", *GUARDS, "-C", directory, *args], capture_output=True, env={**os.environ, "GIT_NO_LAZY_FETCH": "1"}, text=True)
except OSError as failure:
return Failure(f"git could not start: {failure}")
return ran.stdout.strip() if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
"""What git printed in directory, stripped, run guarded: the hook runs git in a checkout the call has not yet been allowed to touch."""
ran = git_repo.git(*args, cwd=directory, guarded=True)
return ran if isinstance(ran, Failure) else ran.strip()
def existing(directory: str) -> str:
+6 -2
View File
@@ -34,10 +34,14 @@ def parsed_entry(line: str) -> LogLine | None:
def this_chunks(entry: LogLine, reflog: set[str], branch: str, on_default: typing.Callable[[str], bool]) -> bool:
"""Whether the override is the current branch's: its commit is in the branch's reflog, which keeps a commit an amend or a rebase replaced, follows `git branch -m`, and holds no other branch's commit."""
"""Whether the override is the current branch's: its commit is in the branch's reflog, which holds every commit the branch has had. So:
- an override logged at c1 still counts after an amend or a rebase replaced c1 with c2;
- one logged under the branch's old name counts after `git branch -m`, which carries the reflog over;
- one logged on another branch, at a commit this reflog lacks, doesn't count;
- one logged at a default-branch commit, such as the one the branch started from, sits in the reflogs of other branches too, so it counts only under this branch's own name;
- one logged before any commit existed, with an empty commit, counts on every branch."""
if entry.commit == "":
return True
# The default branch's commits are in every branch's reflog, so such a line counts only under the branch's own name: one logged before the branch's first commit.
return entry.commit in reflog and (entry.branch == branch or not on_default(entry.commit))
+4 -1
View File
@@ -1,10 +1,13 @@
"""Refuse a reviewer's file call other than a Write of its report into the reports folder: skills/larv-review/review-findings.md → "Report"."""
import os
import pathlib
from rule_hook.rules import Breach
from rule_hook.call import Call
from review_folder import REPORTS
from rule_hook.reviewer_rung import REVIEWERS
# Each agent under agents/, read from the folder, so an agent the routing tables miss is still confined.
REVIEWERS = frozenset(path.stem for path in (pathlib.Path(__file__).resolve().parents[2] / "agents").glob("*.md"))
def report_breaches(call: Call, path: str, home: str) -> list[Breach]:
+11 -12
View File
@@ -1,14 +1,14 @@
"""Refuse an Agent call that launches a review below the rung it needs, worked out from the rungs loop-claude hands its worker: docs/decisions.md → `routing:`."""
import pathlib
"""Refuse an Agent call that launches a review below the rung it needs, worked out from the rungs and the E + I loop-claude hands its worker: docs/decisions.md → `routing:`."""
import typing
from rule_hook.rules import Breach
from rule_hook.call import Call, text
from model_routing.worker_rungs import handed
from model_routing.ladder import highest, position, review_rung, ReviewKind, Rung
from model_routing.ladder import position, review_rungs, ReviewKind, Rung
from review_passes import REVIEWERS
# A reviewer is an agent under agents/, as CLAUDE.md → "Vocabulary" defines it.
REVIEWERS = frozenset(path.stem for path in (pathlib.Path(__file__).resolve().parents[2] / "agents").glob("*.md"))
# The pass each agent under agents/ reviews.
PASS_OF = {agent: kind for kind, agent in REVIEWERS.items()}
# The opening of every comprehension seat's prompt: skills/comprehension-panel/seat-prompts.md → "Opening".
SEAT = "You are one seat of a comprehension panel."
# The opening of the security pass's prompt: skills/larv-review/SKILL.md → "Security".
@@ -18,23 +18,22 @@ SUBJECTS: dict[ReviewKind, str] = {"seat": "a comprehension seat", "security": "
def reviewer_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Breach]:
"""The breach of an Agent call that launches a review below its rung; none where loop-claude handed no rungs."""
project, worker, reviewers = handed(environ)
project, worker, escape_and_impact = handed(environ)
kind = review_kind(call.given)
if kind is None or project is None or worker is None:
return []
# A worker an older loop-claude started was handed no reviewers' rung; its reviewers are held to the rung that loop-claude gave them.
required = review_rung(kind, project, reviewers or highest(project, worker))
required = review_rungs(project, worker, escape_and_impact)[kind]
named = named_rung(call.given, worker)
if position(named) >= position(required):
return []
subject = text(call.given, "subagent_type") if kind == "reviewer" else SUBJECTS[kind]
subject = SUBJECTS.get(kind) or text(call.given, "subagent_type")
return [Breach("reviewer-rung", f"{subject} would run on {named}, below {required}: launch it with {required.agent_args()}", call.cwd)]
def review_kind(given: dict[str, typing.Any]) -> ReviewKind | None:
"""What a launch reviews, a reviewer, a comprehension seat or the security pass; None for any other subagent."""
if text(given, "subagent_type") in REVIEWERS:
return "reviewer"
"""What a launch reviews, a reviewer's pass, a comprehension seat or the security pass; None for any other subagent."""
if pass_reviewed := PASS_OF.get(text(given, "subagent_type")):
return pass_reviewed
opening = text(given, "prompt").lstrip()
if opening.startswith(SEAT):
return "seat"
+2
View File
@@ -61,6 +61,8 @@ RULES: dict[RuleName, Rule] = {
"a git commit in a checkout whose todo.md has changes",
),
}
# The lookahead ends each reason at the next marker on its line, or at the line's end. The reason is lazy, so it stops at the next marker instead of running on and swallowing the markers after it.
# An HTML marker's closing `-->` stays in its reason; `overrides` strips it.
OVERRIDE = re.compile(r"(?:#|<!--)\s*rule-override ([a-z-]+):([^\n]*?)(?=[ \t]*(?:#|<!--)\s*rule-override |$)", re.MULTILINE)
# [-] keeps this file from matching itself.
ATTRIBUTION = re.compile(r"co-authored[-]by:[^\n]*\b(?:claude|anthropic)\b|generated with \[?claude code", re.IGNORECASE)
+43 -12
View File
@@ -5,6 +5,7 @@ import subprocess
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
@@ -14,9 +15,12 @@ from rule_hook.call import Call
from git_command import Commit, commit_message, commits
from test_rank_todo import DECISIONS, README, TODO
from test_env import isolated_env
from model_routing import ladder
from rule_hook.override_log import LogLine, parsed_entry, this_chunks
from rule_hook.reviewer_rung import reviewer_breaches
from shell_command import simple_commands
from rule_hook.git import git as rule_hook_git
from model_routing.ladder import Rung
from shell_command import segments, simple_commands
HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook"
# Built from parts, so this file carries no attribution of its own.
@@ -71,6 +75,20 @@ class Commits(unittest.TestCase):
def test_a_line_that_does_not_parse_hides_only_itself(self):
self.assertEqual(len(committed("echo 'open\ngit commit -m a")), 1)
def test_a_redirect_keeps_its_command_s_words_together(self):
self.assertEqual(segments("echo hi > f arg"), [["echo", "hi", "arg"]])
for redirect in [">", ">>", "<", "<<<", "<>", ">&", "<&", ">|", "&>", "&>>"]:
with self.subTest(redirect):
self.assertEqual(committed(f"git {redirect} /tmp/x commit -m hi"), [Commit("/r", ["hi"], False)])
self.assertEqual(committed("git commit >&2 -m hi 2>&1"), [Commit("/r", ["hi"], False)])
self.assertEqual(committed("> out git commit -m hi"), [Commit("/r", ["hi"], False)])
def test_a_separator_glued_to_a_redirect_still_ends_the_command(self):
self.assertEqual(segments("echo a > f; echo b | cat &> g\nls"), [["echo", "a"], ["echo", "b"], ["cat"], ["ls"]])
for command in ["echo a &</dev/null git commit -m hi", "echo a;>f git commit -m hi"]:
with self.subTest(command):
self.assertEqual(committed(command), [Commit("/r", ["hi"], False)])
class CommandBreaches(unittest.TestCase):
def test_one_line_passes(self):
@@ -166,19 +184,19 @@ class OverrideLog(unittest.TestCase):
class ReviewerRung(unittest.TestCase):
# A worker routed to Haiku 5.5 at max, on a project whose rung is Opus 5.5 at medium, with its reviewers on the project's rung.
ENVIRON = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_REVIEWER_RUNG": "claude-opus-5-5 at medium effort"}
# The same project, with a worker and its reviewers routed above it to Fable 5.1 at max.
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-1 at max effort", "LOOP_CLAUDE_REVIEWER_RUNG": "claude-fable-5-1 at max effort"}
# A worker routed to Sonnet 5.5 at high, on a project whose rung is Opus 5.5 at medium, with its reviewers on the project's rung.
ENVIRON = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
# The same project, with a worker, and so its reviewers, routed above it to Fable 5.1 at max.
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-1 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
def refused(self, given: dict, environ: dict[str, str] = ENVIRON) -> list[str]:
return rules(reviewer_breaches(Call("Agent", given, "/r"), environ))
def test_a_reviewer_below_the_project_rung_is_refused_naming_the_arguments_to_pass(self):
breaches = reviewer_breaches(Call("Agent", {"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high", "prompt": "Review."}, "/r"), self.ENVIRON)
breaches = reviewer_breaches(Call("Agent", {"subagent_type": "stability-reviewer", "model": "haiku", "effort": "max", "prompt": "Review."}, "/r"), self.ENVIRON)
self.assertEqual(rules(breaches), ["reviewer-rung"])
self.assertIn("stability-reviewer", breaches[0].detail)
self.assertIn("claude-sonnet-5-5 at high effort", breaches[0].detail)
self.assertIn("claude-haiku-5-5 at max effort", breaches[0].detail)
self.assertIn("model opus, effort medium", breaches[0].detail)
def test_a_reviewer_on_the_project_rung_or_a_rerun_above_it_passes(self):
@@ -200,20 +218,29 @@ class ReviewerRung(unittest.TestCase):
def test_an_effort_off_the_ladder_for_its_model_is_refused(self):
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus", "effort": "low"}), ["reviewer-rung"])
def test_a_reviewer_is_held_to_the_reviewers_rung_where_that_is_higher(self):
def test_a_reviewer_is_held_to_the_rung_its_e_plus_i_picks_where_that_is_higher(self):
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}, self.ABOVE), ["reviewer-rung"])
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "fable", "effort": "max"}, self.ABOVE), [])
lifted = self.ENVIRON | {"LOOP_CLAUDE_REVIEWER_RUNG": "claude-opus-5-5 at high effort"}
lifted = self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}, lifted), ["reviewer-rung"])
self.assertEqual(self.refused({"prompt": "You are one seat of a comprehension panel.", "model": "opus", "effort": "medium"}, lifted), [])
def test_holds_a_reviewer_to_the_higher_of_the_workers_and_the_projects_rung_where_loop_claude_handed_no_reviewers_rung(self):
without = {name: rung for name, rung in self.ABOVE.items() if name != "LOOP_CLAUDE_REVIEWER_RUNG"}
def test_holds_a_reviewer_to_the_higher_of_the_workers_and_the_projects_rung_where_loop_claude_handed_no_e_plus_i(self):
without = {name: rung for name, rung in self.ABOVE.items() if name != "LOOP_CLAUDE_ESCAPE_AND_IMPACT"}
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}, without), ["reviewer-rung"])
below = {name: rung for name, rung in self.ENVIRON.items() if name != "LOOP_CLAUDE_REVIEWER_RUNG"}
below = {name: rung for name, rung in self.ENVIRON.items() if name != "LOOP_CLAUDE_ESCAPE_AND_IMPACT"}
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high"}, below), ["reviewer-rung"])
self.assertEqual(self.refused({"prompt": "You are one seat of a comprehension panel.", "model": "sonnet", "effort": "high"}, without), ["reviewer-rung"])
def test_a_replayed_passs_reviewer_is_held_to_its_replays_rung_below_the_workers_unless_the_e_plus_i_steps_reviews_up_or_the_worker_climbed(self):
lowered = {"subagent_type": "prose-reviewer", "model": "haiku", "effort": "medium"}
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): Rung("claude-haiku-5-5", "medium")}):
self.assertEqual(self.refused(lowered), [])
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "haiku", "effort": "low"}), ["reviewer-rung"])
self.assertEqual(self.refused({**lowered, "subagent_type": "stability-reviewer"}), ["reviewer-rung"])
self.assertEqual(self.refused(lowered, self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}), ["reviewer-rung"])
self.assertEqual(self.refused(lowered, self.ABOVE), ["reviewer-rung"])
def test_a_seat_or_a_security_launch_is_held_to_the_project_rung_alone(self):
seat = {"prompt": "You are one seat of a comprehension panel. Tools: Read, Grep, Glob.", "model": "opus", "effort": "medium"}
self.assertEqual(self.refused(seat, self.ABOVE), [])
@@ -276,6 +303,10 @@ class Hook(unittest.TestCase):
git(self.repo, "commit", "-q", "--allow-empty", "-m", "base")
git(self.repo, "checkout", "-q", "-b", "chunk")
def test_runs_git_guarded(self):
git(self.repo, "config", "core.fsmonitor", "/bin/false")
self.assertEqual(rule_hook_git(self.repo, "config", "core.fsmonitor"), "false")
def listed(self) -> str:
return subprocess.run([str(HOOK), "overrides"], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout
+16 -11
View File
@@ -1,22 +1,27 @@
"""What judge-replay's and stability-replay's commands share: the argument, the projects on its model, the candidate rungs and the exits."""
"""What judge-replay's and review-replay's commands share: reading the arguments, the projects on a model, the candidate rungs and the exits."""
import pathlib
import sys
import typing
from failure import Failure
from model_routing.ladder import LADDER, lowest_worker_rung, position, project_rung, Rung
from model_routing.ladder import LADDER, position, Rung
from claude_code.reply import Limited
from loop_claude.project.model_choice import read_models_file
from loop_claude.stop import Stop
def project_rung_or_exit(tool: str, argv: list[str], help_text: str) -> Rung | int:
"""The project's rung of the model argv names, or the exit code: 0 after printing help_text for -h or --help, 1 after saying why argv cannot be read."""
# What a tool reads from its arguments, such as the project's rung of the model they name.
Parsed = typing.TypeVar("Parsed")
def arguments_or_exit(tool: str, argv: list[str], help_text: str, usage: str, read: typing.Callable[[list[str]], Parsed | None]) -> Parsed | int:
"""What read makes of argv, or the exit code: 0 after printing help_text for -h or --help, 1 after saying, with usage, that argv cannot be read, where read gives None."""
if argv[:1] in (["-h"], ["--help"]):
print(help_text.strip())
return 0
anchor = project_rung(argv[0]) if len(argv) == 1 else None
if anchor is None:
return failed(tool, f"cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; usage: {tool} <model>, a model on the routing ladder")
return anchor
arguments = read(argv)
if arguments is None:
return failed(tool, f"cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; usage: {usage}")
return arguments
def projects_on(model: str, home: pathlib.Path) -> list[str] | Failure:
@@ -27,9 +32,9 @@ def projects_on(model: str, home: pathlib.Path) -> list[str] | Failure:
return sorted(key for key, on in models.items() if on == model)
def down_from(top: Rung) -> list[Rung]:
"""top, the project's rung, and each rung below it, highest first, down to the lowest rung a worker routes to: no route uses a rung below it, so a replay there could change no routing."""
return list(LADDER[position(lowest_worker_rung(top)):position(top) + 1])[::-1]
def down_from(top: Rung, floor: Rung) -> list[Rung]:
"""top, the project's rung, and each rung below it, highest first, down to floor."""
return list(LADDER[position(floor):position(top) + 1])[::-1]
def limited_exit(tool: str, limited: Limited) -> int:
+1 -1
View File
@@ -1,4 +1,4 @@
"""The rung search judge-replay and stability-replay share: replay archived cases on a reference rung, then hold each candidate rung to what the reference reproduced."""
"""The rung search judge-replay and review-replay share: replay archived cases on a reference rung, then hold each candidate rung to what the reference reproduced."""
import concurrent.futures
import dataclasses
import sys
+3 -2
View File
@@ -63,8 +63,9 @@ class FirstReply(unittest.TestCase):
class DownFrom(unittest.TestCase):
def test_runs_from_the_projects_rung_down_to_the_lowest_rung_a_worker_routes_to(self):
self.assertEqual(down_from(REFERENCE), [REFERENCE, MIDDLE, CHEAP])
def test_runs_from_the_projects_rung_down_to_the_floor_highest_first(self):
self.assertEqual(down_from(REFERENCE, CHEAP), [REFERENCE, MIDDLE, CHEAP])
self.assertEqual(down_from(REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
if __name__ == "__main__":
+1 -1
View File
@@ -39,5 +39,5 @@ def anchor_lines(found: Anchors | Failure, outcomes: list[Outcome]) -> list[str]
lines = []
for level, ids in found:
lines.append(f"{level}:")
lines += [render(by_id[id_]) if id_ in by_id else f"- Item {id_}: no merge commit on the default branch shipped it." for id_ in ids]
lines += [render(by_id[id_]) if id_ in by_id else f"- Item {id_}: no chunk shipped it." for id_ in ids]
return lines
+78 -32
View File
@@ -6,11 +6,12 @@ Run it inside a project checkout or one of its worktrees. It fetches origin, whe
that remote, and reads origin's default branch, or else the local main or master; a failed fetch
reads origin as last fetched and says so on stderr.
Git history is the record. A chunk is a merge commit on the default branch's first-parent line
whose change removed items from todo.md, and changed more than todo.md and the records below; it
shipped those items. Each item's guess is the scores it held in the todo.md of the merge's first
parent: L, E, I, R and S. An item scored before L, E and I replaced C holds R and S, and C too where
its table also had A, G and Goals. The chunk measures:
Git history is the record. The default branch's first-parent line is cut into chunks by one rule: a
merge commit is a chunk of its own, and any other commit joins the run of the newer commit above it when
both share a commit time, else starts a chunk. A chunk whose change removed items from todo.md, and changed more
than todo.md and the records below, shipped those items. Each item's guess is the scores it held in
the todo.md the chunk started from: L, E, I, R and S. An item scored before L, E and I replaced C
holds R and S, and C too where its table also had A, G and Goals. The chunk measures:
- lines changed: lines added plus lines deleted against the first parent, leaving out todo.md and
the records tools append to, docs/comprehension-history.md and docs/reading-cost.md;
@@ -21,7 +22,12 @@ its table also had A, G and Goals. The chunk measures:
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.
A project that merges without merge commits, by fast-forward or squash, has no chunk to measure.
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
a pushed or fast-forwarded commit may be part of a pull request. A merge's titles are its branch's
commits'; any other chunk's are its own. Two pull requests merged in the same second read as one
chunk. Rebase drops a round's commit that changed no file, so a rebase or push chunk gives its
rounds and findings as lower bounds, `at least`, and the report ends saying all this.
Given L, E and I, on the levels ~/.claude/rules/todo-items.md defines, and S, it works out R from
L, E and I, as rank_todo.py does, and lists the 5 finished items whose guesses sit closest, closest
@@ -30,16 +36,17 @@ scored before L, E and I, the newest first among equals. Each line gives what th
measured, which items shipped with it, and its tagline.
Then the project's anchors, the shipped items its docs/score-anchors.md names for each level of L,
E and I, read from the checkout's working tree, each line as above, or that no merge shipped it. A
E and I, read from the checkout's working tree, each line as above, or that no chunk shipped it. A
file that cannot be read, a row that does not hold a level on its scale and a list of IDs, or a
level named twice leaves the anchors out, saying why.
Then the median of the outcome R and S each predict at each value they were guessed at: R against
🔴 findings, S against lines changed. And how well L, E and I each order chunks by review rounds
past each pass's first and by 🔴 findings: Spearman's rank correlation, from -1 to +1, where +1
orders them exactly; none where every chunk held the same level, or the same outcome. It counts only chunks that shipped one
item, since a chunk measures all its items at once, and reports a score only once 10 such chunks
hold it and its outcomes.
Then the median of the outcome R and S each predict at each value they were guessed at: R against 🔴
findings, S against lines changed. And how well L, E and I each order chunks by review rounds past
each pass's first and by 🔴 findings: Spearman's rank correlation, from -1 to +1, where +1 orders
them exactly; none where every chunk held the same level, or the same outcome. It counts only chunks
that shipped one item, since a chunk measures all its items at once. It leaves out the chunks never
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.
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
@@ -50,15 +57,24 @@ 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 git_repo import default_branch, file_at, full_history, git, top
from failure import Failure
from todo_table import LEVELS, risk, TOP_SCORE
from markdown_text import listed
from score_outcomes.outcomes import nearest, Outcome, outcomes_of, render, report, shipped
from utc_stamp import utc
# The scores score-outcomes takes, in order.
GIVEN = ("L", "E", "I", "S")
# How the report reads the chunks that left no merge commit, which history bounds only by their shared commit time.
UNMERGED = [
"Chunks that left no merge commit:",
"",
"- Each is the run of commits on the default branch that share one commit time, since a rebase merge replays a pull request's commits at once. Its guesses come from the todo.md before its first commit.",
"- Two pull requests merged in the same second read as one chunk, so a pull request that shipped nothing adds its lines, files and rounds to the chunk it shares a time with.",
"- A run whose commits all kept their author time was never replayed: it was pushed or fast-forwarded as committed. It may hold only part of its pull request, so the medians and the rank correlations leave it out.",
"- Rebase drops a round's commit that changed no file, so their rounds and findings are at least what history shows, and the medians count the rebased ones as shown.",
]
def main(argv: list[str]) -> int:
@@ -88,10 +104,12 @@ def report_text(outcomes: list[Outcome], anchored: Anchors | Failure, given: dic
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 merge commit on the default branch shipped an item from todo.md. A project that merges by squash or fast-forward has none."]
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."]
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:", "", *report(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(UNMERGED)
return "\n\n".join("\n".join(section) for section in sections)
@@ -114,36 +132,64 @@ def read_anchors() -> Anchors | Failure:
def read_outcomes(default: str) -> list[Outcome] | Failure:
"""What each chunk on the default branch's first-parent line measured."""
if partial := full_history():
return partial
merges = git("log", "--first-parent", "--merges", "--format=%H %h %ct", default, "--", "todo.md")
if isinstance(merges, Failure):
return merges
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]
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] = []
for line in merges.splitlines():
merge, short, time = line.split()
measured = measure(merge, short, utc(int(time)))
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]):
continue
label = first if first == last else f"{first}^..{last}"
titled = f"{first}^1..{first}^2" if landed == "merge" else f"{first}^1..{last}"
measured = measure(f"{first}^1", last, label, utc(committed), titled, landed)
if isinstance(measured, Failure):
return measured
outcomes += measured
return outcomes
def measure(merge: str, short: str, merged: str) -> list[Outcome] | Failure:
"""What one merge measured for each item it shipped."""
before = file_at(f"{merge}^1", "todo.md")
if isinstance(before, Failure):
return before
after = file_at(merge, "todo.md")
def chunk_log(lines: list[str]) -> list[Chunk]:
"""The chunks `git log --first-parent --format=%h %ct %at %p` lines cut, newest first: each chunk's first and last commit as short hashes, its commit time, and how it reached the branch. A merge commit is a chunk of its own; any other commit joins the run of the newer commit above it when both share a commit time."""
chunks: list[Chunk] = []
joinable = False
for line in lines:
short, committed, authored, *parents = line.split()
if len(parents) > 1:
chunks.append((short, short, int(committed), "merge"))
joinable = False
elif joinable and chunks[-1][2] == int(committed):
_, newest, time, landed = chunks[-1]
chunks[-1] = (short, newest, time, "rebase" if landed == "rebase" or committed != authored else "push")
else:
chunks.append((short, short, int(committed), "rebase" if committed != authored else "push"))
joinable = True
return chunks
def measure(before: str, tip: str, label: str, merged: str, titled: str, landed: Landing) -> list[Outcome] | 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):
return planned
after = file_at(tip, "todo.md")
if isinstance(after, Failure):
return after
items = shipped(before, after)
items = shipped(planned, after)
if not items:
return []
numstat = git("diff", "--numstat", f"{merge}^1", merge)
numstat = git("diff", "--numstat", before, tip)
if isinstance(numstat, Failure):
return numstat
titles = git("log", "--format=%s", f"{merge}^1..{merge}^2")
titles = git("log", "--format=%s", titled)
if isinstance(titles, Failure):
return titles
return outcomes_of(items, short, merged, numstat, titles.splitlines())
return outcomes_of(items, label, merged, numstat, titles.splitlines(), landed)
+18 -9
View File
@@ -13,10 +13,15 @@ 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 merge that shipped an item measured. findings holds the 🔴 and 🟡 counts, None where a round title lacks them or the branch has no round."""
"""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
@@ -25,6 +30,7 @@ class Outcome:
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.
@@ -46,8 +52,8 @@ def shipped(before: str, after: str) -> list[Item]:
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]) -> list[Outcome]:
"""What one merge measured for each item it shipped, from `git diff --numstat` against its first parent and its branch's commit titles; none where it changed nothing but the plan and the records."""
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:
@@ -56,7 +62,7 @@ def outcomes_of(shipped: list[Item], merge: str, merged: str, numstat: str, titl
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)) 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]:
@@ -69,8 +75,8 @@ def nearest(outcomes: list[Outcome], given: dict[str, int], count: int = 5) -> l
def report(outcomes: list[Outcome]) -> list[str]:
"""Among chunks that shipped one item, since a chunk measures all its items at once: 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]
"""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]
@@ -94,7 +100,7 @@ def report(outcomes: list[Outcome]) -> list[str]:
def too_few(held: int, name: str, what: str) -> str:
chunks = "chunk that shipped one item records" if held == 1 else "chunks that shipped one item record"
chunks = "such chunk records" if held == 1 else "such chunks record"
return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}."
@@ -113,10 +119,13 @@ def ranks(values: list[int]) -> list[float]:
def render(outcome: Outcome) -> str:
scores = ", ".join(f"{name} {outcome.item.scores[name]}" for name in SHOWN if name in outcome.item.scores)
findings = f"{outcome.findings[0]} 🔴, {outcome.findings[1]} 🟡" if outcome.findings else "findings unknown"
# 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')}, {plural(outcome.rounds_past_first, 'round')} past each pass's first, {findings}; merged {outcome.merged} in {outcome.merge}{together}. {outcome.item.tagline}"
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:
+167 -14
View File
@@ -8,11 +8,11 @@ import unittest
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 test_env import isolated_env
from todo_table import Item
from score_outcomes.outcomes import nearest, Outcome, outcomes_of, rank_correlation, render, report, shipped
from score_outcomes.main import report_text
from score_outcomes.outcomes import Landing, nearest, Outcome, outcomes_of, rank_correlation, render, report, 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 +29,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) -> Outcome:
return Outcome(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), "aaaaaaa", merged, shipped_with, lines, 1, rounds, findings)
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)
class Shipped(unittest.TestCase):
@@ -50,16 +50,38 @@ class Shipped(unittest.TestCase):
self.assertEqual(shipped(todo(FIRST, "| x | 0.1.0 | | **Bad.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"), todo()), [])
class ChunkLog(unittest.TestCase):
# Lines are `%h %ct %at %p`, newest first: short hash, commit time, author time, parents.
def test_a_merge_is_a_chunk_of_its_own_and_joins_no_run_below_it(self):
self.assertEqual(chunk_log(["m 100 100 a b", "c 100 100 a"]), [("m", "m", 100, "merge"), ("c", "c", 100, "push")])
def test_commits_sharing_a_commit_time_form_one_run_labelled_rebase_when_any_differs(self):
self.assertEqual(chunk_log(["c2 200 150 c1", "c1 200 100 r"]), [("c1", "c2", 200, "rebase")])
def test_a_run_of_commits_that_all_kept_their_author_time_is_labelled_push(self):
self.assertEqual(chunk_log(["c2 200 200 c1", "c1 200 200 r"]), [("c1", "c2", 200, "push")])
def test_a_run_is_rebase_when_only_its_older_commit_was_replayed(self):
self.assertEqual(chunk_log(["c2 200 200 c1", "c1 200 100 r"]), [("c1", "c2", 200, "rebase")])
def test_a_run_is_rebase_when_only_its_newer_commit_was_replayed(self):
self.assertEqual(chunk_log(["c2 200 100 c1", "c1 200 200 r"]), [("c1", "c2", 200, "rebase")])
def test_a_commit_at_another_time_starts_a_new_chunk(self):
self.assertEqual(chunk_log(["c2 300 300 c1", "c1 200 200 r"]), [("c2", "c2", 300, "push"), ("c1", "c1", 200, "push")])
class OutcomesOf(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)
self.assertEqual(found[0], Outcome(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, (1, 6)))
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"))
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", []), [])
self.assertEqual(outcomes_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", [], "merge"), [])
class Nearest(unittest.TestCase):
@@ -89,11 +111,11 @@ class Report(unittest.TestCase):
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 chunk that shipped one item records S and its outcome; the report needs 10.", report([outcome(1, 2, 2, 4), outcome(2, 2, 2, None, shipped_with=(1,))]))
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)])
for name in "LEI":
with self.subTest(name=name):
self.assertIn(f"- {name}, by review rounds past each pass's first and 🔴 findings: 1 chunk that shipped one item records {name} and both outcomes; the report needs 10.", too_few)
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)
def test_ranks_ties_by_their_mean_rank(self):
self.assertAlmostEqual(rank_correlation([1, 1, 2, 2, 2], [1, 2, 3, 4, 5]), 0.866, places=3)
@@ -121,6 +143,13 @@ class Render(unittest.TestCase):
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,))))
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")))
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.**")
ANCHORS_TEXT = "# Score anchors\n\nWhy these.\n\n| Level | Items |\n|---|---|\n| L 1 | 4, 9 |\n| I 3 | 5 |\n"
@@ -145,7 +174,7 @@ class Anchors(unittest.TestCase):
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))])
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 merge commit on the default branch shipped it."])
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):
self.assertIn("docs/score-anchors.md", anchor_lines([], [])[0])
@@ -158,7 +187,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")]
too_few = "chunks that shipped one item record"
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:
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
@@ -169,7 +198,7 @@ Anchors in docs/score-anchors.md, each level's shipped items:
L 1:
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
Median outcome at each guessed score, among chunks that shipped one item:
Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:
- R, 🔴 findings: 2 {too_few} R and its outcome; the report needs 10.
- S, lines changed: 2 {too_few} S and its outcome; the report needs 10.
@@ -177,6 +206,37 @@ Median outcome at each guessed score, among chunks that shipped one item:
- 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.""")
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)
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))
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))
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")
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)
self.assertIn("- I, by review rounds past each pass's first and 🔴 findings: rank correlation +1.00 and -1.00 (10 chunks)", text)
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")
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)
self.assertIn("never replayed", nearest_section)
self.assertIn("- Item 9, R 2, S 3:", anchors_section)
self.assertIn("never replayed", anchors_section.split("Median outcome")[0])
def test_lists_no_nearest_items_where_no_scores_are_given(self):
self.assertTrue(report_text([], [], None).startswith("Anchors in docs/score-anchors.md"))
@@ -195,12 +255,24 @@ class ScoreOutcomesTool(unittest.TestCase):
def git(self, *args):
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout
def commit(self, title, files):
def commit(self, title, files, at=None, authored=None):
for name, text in files.items():
(self.checkout / name).parent.mkdir(parents=True, exist_ok=True)
(self.checkout / name).write_text(text)
self.git("add", name)
dates = {"GIT_COMMITTER_DATE": at, "GIT_AUTHOR_DATE": authored}
self.env.update({name: date for name, date in dates.items() if date})
self.git("commit", "-q", "-m", title)
for name in dates:
self.env.pop(name, None)
return self.git("rev-parse", "--short", "HEAD").strip()
def merge_branch(self, branch, at):
self.env.update({"GIT_COMMITTER_DATE": at, "GIT_AUTHOR_DATE": at})
self.git("merge", "-q", "--no-ff", "-m", f"Merge {branch}", branch)
for name in ("GIT_COMMITTER_DATE", "GIT_AUTHOR_DATE"):
self.env.pop(name, None)
return self.git("rev-parse", "--short", "HEAD").strip()
def run_tool(self, *args):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
@@ -217,6 +289,87 @@ class ScoreOutcomesTool(unittest.TestCase):
self.assertIn("- Item 4, R 2, S 3, C 10: 3 lines in 1 file, 0 rounds past each pass's first, 1 🔴, 2 🟡; merged ", ran.stdout)
self.assertNotIn("Item 5", ran.stdout)
def run_on_rebased_history(self):
self.commit("Re-score item 4", {"todo.md": todo(FIRST.replace("| 2 | 3 |", "| 1 | 3 |"), SECOND)}, at="2026-10-13T08:00:00Z")
first = self.commit("Score item 4 higher", {"todo.md": todo(FIRST, SECOND)}, at="2026-10-13T09:00:00Z")
self.commit("Do it", {"a.py": "1\n2\n3\n", "todo.md": todo(SECOND)}, at="2026-10-13T09:00:00Z")
self.commit("Record the reading cost", {"docs/reading-cost.md": "9\n"}, at="2026-10-13T09:00:00Z")
last = self.commit("Answer stability round 1: 1 🔴, 2 🟡; fix", {"a.py": "1\n2\n4\n"}, at="2026-10-13T09:00:00Z")
self.commit("Change more", {"a.py": "1\n2\n4\n5\n6\n"}, at="2026-10-13T10:00:00Z")
pushed = self.commit("Do that", {"b.py": "1\n", "todo.md": todo()}, at="2026-10-13T11:00:00Z", authored="2026-10-13T11:00:00Z")
ran = self.run_tool("1", "2", "1", "3")
self.assertEqual(ran.returncode, 0, ran.stderr)
item_4 = [line for line in ran.stdout.splitlines() if line.startswith("- Item 4,")]
return ran.stdout, item_4[0], first, last, pushed
def test_guesses_a_rebase_chunk_from_the_todo_md_before_its_first_commit(self):
_, item_4, _, _, _ = self.run_on_rebased_history()
self.assertTrue(item_4.startswith("- Item 4, R 1, S 3, C 10: "), item_4)
def test_leaves_the_reading_cost_record_out_of_a_rebase_chunks_lines(self):
_, item_4, _, _, _ = self.run_on_rebased_history()
self.assertIn(": 3 lines in 1 file, ", item_4)
def test_labels_a_run_of_commits_that_kept_their_author_time_never_replayed(self):
stdout, _, _, _, pushed = self.run_on_rebased_history()
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown; committed 2026-10-13T11:00:00Z in {pushed}, never replayed, so perhaps part of a pull request. **Then this.**", stdout)
def test_measures_a_rebase_run_at_one_commit_time_as_one_chunk_whose_rounds_read_at_least(self):
_, item_4, first, last, _ = self.run_on_rebased_history()
self.assertIn(f"at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", item_4)
def test_explains_the_chunks_that_left_no_merge_commit_after_a_rebase(self):
stdout, _, _, _, _ = self.run_on_rebased_history()
self.assertIn("Chunks that left no merge commit:", stdout)
def test_counts_a_direct_commit_behind_the_newest_merge_as_a_push_chunk(self):
drop = self.commit("Drop item 5 on main", {"b.py": "1\n", "todo.md": todo(FIRST)}, at="2026-10-12T09:00:00Z", authored="2026-10-12T09:00:00Z")
self.git("switch", "-q", "-c", "chunk")
self.commit("Do it", {"a.py": "1\n", "todo.md": todo()})
self.git("switch", "-q", "main")
self.git("merge", "-q", "--no-ff", "-m", "Merge chunk", "chunk")
ran = self.run_tool("1", "2", "1", "3")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertRegex(ran.stdout, r"- Item 4, R 2, S 3, C 10: 1 line in 1 file, 0 rounds past each pass's first, findings unknown; merged \S+ in [0-9a-f]{7,}\. ")
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown; committed 2026-10-12T09:00:00Z in {drop}, never replayed, so perhaps part of a pull request. **Then this.**", ran.stdout)
self.assertNotIn("by rebase", ran.stdout)
def test_labels_a_merge_merge_even_when_its_author_and_commit_times_are_equal(self):
self.git("switch", "-q", "-c", "chunk")
self.commit("Do it", {"a.py": "1\n", "todo.md": todo(SECOND)}, at="2026-10-13T09:00:00Z", authored="2026-10-13T09:00:00Z")
self.git("switch", "-q", "main")
merged = self.merge_branch("chunk", "2026-10-13T10:00:00Z")
ran = self.run_tool("1", "2", "1", "3")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn(f"merged 2026-10-13T10:00:00Z in {merged}. **Do it.**", ran.stdout)
self.assertNotIn("by rebase", ran.stdout)
self.assertNotIn("never replayed", ran.stdout)
def test_counts_each_merge_at_one_commit_time_as_its_own_chunk(self):
self.git("switch", "-q", "-c", "one")
self.commit("Do four", {"a.py": "1\n", "todo.md": todo(SECOND)}, at="2026-10-13T10:00:00Z", authored="2026-10-13T10:00:00Z")
self.git("switch", "-q", "main")
first = self.merge_branch("one", "2026-10-13T10:00:00Z")
self.git("switch", "-q", "-c", "two")
self.commit("Do five", {"b.py": "1\n", "todo.md": todo()}, at="2026-10-13T10:00:00Z", authored="2026-10-13T10:00:00Z")
self.git("switch", "-q", "main")
second = self.merge_branch("two", "2026-10-13T10:00:00Z")
ran = self.run_tool("1", "2", "1", "3")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn(f"merged 2026-10-13T10:00:00Z in {first}. **Do it.**", ran.stdout)
self.assertIn(f"merged 2026-10-13T10:00:00Z in {second}. **Then this.**", ran.stdout)
def test_counts_a_rebase_run_behind_a_merge_as_one_chunk_labelled_rebase(self):
self.git("switch", "-q", "-c", "other")
self.commit("Other work", {"z.py": "1\n"})
self.git("switch", "-q", "main")
first = self.commit("Do it", {"a.py": "1\n2\n3\n", "todo.md": todo(SECOND)}, at="2026-10-13T09:00:00Z", authored="2026-10-13T08:00:00Z")
last = self.commit("Answer stability round 1: 1 🔴, 2 🟡; fix", {"a.py": "1\n2\n4\n"}, at="2026-10-13T09:00:00Z", authored="2026-10-13T08:00:00Z")
self.merge_branch("other", "2026-10-13T10:00:00Z")
ran = self.run_tool("1", "2", "1", "3")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn(f"- Item 4, R 2, S 3, C 10: 3 lines in 1 file, at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", ran.stdout)
def test_lists_the_projects_anchors_with_what_their_chunks_measured(self):
self.git("switch", "-q", "-c", "chunk")
self.commit("Do it", {"a.py": "1\n", "todo.md": todo(SECOND)})
@@ -227,7 +380,7 @@ class ScoreOutcomesTool(unittest.TestCase):
ran = self.run_tool("1", "2", "1", "3")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("Anchors in docs/score-anchors.md, each level's shipped items:\n\nL 1:\n- Item 4, R 2, S 3, C 10: 1 line in 1 file", ran.stdout)
self.assertIn("I 3:\n- Item 5: no merge commit on the default branch shipped it.", ran.stdout)
self.assertIn("I 3:\n- Item 5: no chunk shipped it.", ran.stdout)
def test_refuses_anchors_it_cannot_read(self):
(self.checkout / "docs").mkdir()
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Git's clean filter for settings.json: drop "model" and sort every key.
Claude Code rewrites settings.json, in its own key order, whenever a model is
picked or a plugin installed. Each machine owns its model, so neither the
model nor Claude Code's key order reaches a commit.
"""
import json
import sys
def cleaned(settings: dict[str, object]) -> str:
"""settings.json as git stores it: without "model", every key sorted."""
kept = {key: value for key, value in settings.items() if key != "model"}
return json.dumps(kept, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
def main() -> int:
# On a non-zero exit git warns and stores the file as written.
try:
settings = json.loads(sys.stdin.read())
except ValueError as error:
print(f"settings_filter.py: {error}", file=sys.stderr)
return 1
if not isinstance(settings, dict):
print("settings_filter.py: settings.json holds no JSON object", file=sys.stderr)
return 1
sys.stdout.write(cleaned(settings))
return 0
if __name__ == "__main__":
sys.exit(main())
+15 -1
View File
@@ -7,6 +7,8 @@ import shlex
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
OPERATOR = set("\n();&|<>")
# A token that is only a redirect: the command's words go on after its target. `&<` is not one: it is a `&` that ends the command, then a `<`.
REDIRECT = re.compile(r"&>>?|[<>]+[&|]?")
# A quoted string or an escape is taken whole, so a # inside one starts no comment; a comment starts a word.
PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<![^\s;&|()])#[^\n]*""", re.DOTALL)
@@ -29,6 +31,15 @@ def simple_commands(command: str, cwd: str, home: str) -> list[Simple]:
def segments(command: str) -> list[list[str]]:
"""The command's simple commands as lists of words, split at ; & | ( ) and line breaks, without redirect targets. Shell forms it does not parse:
- a quoted string is one word, so `bash -c "git commit"` and `echo "$(git commit)"` hide the inner command;
- a backtick substitution stays inside its words, while `$(git commit)` outside quotes splits into the `$` and a command of its own;
- a keyword or a brace opens its command's words, so `then git commit` reads as the command `then`;
- `<(...)` and `>(...)` end the command, and the first word inside them is dropped as a redirect target, so `tee >(git commit)` hides the commit;
- a file descriptor before a redirect, as in `2>&1`, stays a word;
- a heredoc's body is dropped;
- variables, aliases and functions are not expanded;
- a line with an unbalanced quote yields nothing."""
text = uncommented(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command))
tokens = lexed(text)
if tokens is None:
@@ -39,8 +50,11 @@ def segments(command: str) -> list[list[str]]:
for token in tokens:
if target:
target = False
elif set(token) <= OPERATOR and token:
elif REDIRECT.fullmatch(token):
# A redirect's target is not an operand.
target = True
elif set(token) <= OPERATOR and token:
# A separator, or a redirect glued to one as in `;>f`, `&<f` or `<(`: the word after the redirect is its target.
target = "<" in token or ">" in token
found.append([])
elif found[-1] or not ASSIGNMENT.match(token):
+5 -6
View File
@@ -4,9 +4,11 @@ import datetime
import json
import math
import os
import subprocess
import sys
from failure import Failure
import git_repo
CYAN = "\033[36m"
DIM = "\033[2m"
GREEN = "\033[32m"
@@ -141,11 +143,8 @@ def render(status: Status, branch: str, home: str, now: datetime.datetime) -> st
def current_branch(where: str) -> str:
if not where:
return ""
try:
found = subprocess.run(["git", "-C", where, "branch", "--show-current"], errors="replace", stderr=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True)
except OSError:
return ""
return found.stdout.strip() if found.returncode == 0 else ""
found = git_repo.git("branch", "--show-current", cwd=where)
return "" if isinstance(found, Failure) else found.strip()
def main() -> str:
+1 -1
View File
@@ -40,7 +40,7 @@ class SubagentRung(unittest.TestCase):
off = self.run_tool("claude-opus-5", "4")
self.assertEqual((off.returncode, off.stdout), (0, ""))
self.assertEqual(off.stderr, "subagent-rung: claude-opus-5 is not on the routing ladder; pass the Agent tool no model or effort\n")
for bound, rung in (("1", "model haiku, effort max\n"), ("4", "model opus, effort high\n")):
for bound, rung in (("1", "model sonnet, effort high\n"), ("4", "model opus, effort high\n")):
self.assertEqual(self.run_tool("claude-opus-5-5", bound).stdout, rung)
for flag in ("-h", "--help"):
self.assertIn("usage: subagent-rung [--plan] <model> <L>", self.run_tool(flag).stdout)
+64 -29
View File
@@ -9,39 +9,78 @@ from failure import Failure
import todo_table
class Standing(unittest.TestCase):
def test_takes_the_earliest_release_where_it_is_the_earliest_named_since_the_last_cut_and_names_the_next_release(self):
HEADER = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
ROW = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
def naming(named: set[tuple[int, int, int]] | Failure) -> list[str] | Failure:
"""LastCut.todos_since holding one todo.md text that files an item under each release in named."""
if isinstance(named, Failure):
return named
return [HEADER + "".join(ROW.format(id=id_, release=todo_table.version(release)) for id_, release in enumerate(sorted(named), 1))]
def one(release: tuple[int, int, int]) -> todo_table.Item:
"""The plan's only item, filed under release."""
return todo_table.Item(1, release, "", "**Do 1.**", {}, (), ())
def plan_under(earliest: tuple[int, int, int] | None) -> list[todo_table.Item]:
"""A plan holding one item under earliest, or none where earliest is None."""
return [] if earliest is None else [one(earliest)]
class NextRelease(unittest.TestCase):
def test_names_the_earliest_release_after_the_last_cut_that_todo_md_named_since_it_or_the_plan_holds(self):
cases = (
("v1.2.3", 4, (1, 2, 4), set(), chunk_pick.Next((1, 2, 4), None)),
("v1.2.3", 4, (1, 3, 0), {(1, 3, 0)}, chunk_pick.Next((1, 3, 0), None)),
("v1.2.3", 4, (1, 2, 4), {(1, 3, 0)}, chunk_pick.Next((1, 2, 4), None)),
("v1.2.3", 4, (1, 3, 0), {(1, 2, 3), (1, 3, 0)}, chunk_pick.Next((1, 3, 0), None)),
("v0.2.0", 4, (0, 4, 0), set(), chunk_pick.Next((0, 4, 0), None)),
(None, 4, (0, 2, 0), set(), chunk_pick.Next((0, 2, 0), None)),
("v1.2.3", (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, chunk_pick.Upcoming((1, 2, 4), False, True)),
("v1.2.3", (1, 2, 4), {(1, 3, 0)}, chunk_pick.Upcoming((1, 2, 4), True, True)),
("v1.2.3", None, {(1, 2, 2), (1, 3, 0)}, chunk_pick.Upcoming((1, 3, 0), False, True)),
("v1.2.3", None, set(), chunk_pick.Upcoming(None, False, True)),
(None, (0, 2, 0), set(), chunk_pick.Upcoming((0, 2, 0), True, True)),
(None, None, set(), chunk_pick.Upcoming(None, True, True)),
("v1.2.3-rc.1", (1, 2, 3), set(), chunk_pick.Upcoming((1, 2, 3), True, True)),
)
for tag, earliest, named, upcoming in cases:
with self.subTest(tag=tag, earliest=earliest, named=named):
self.assertEqual(chunk_pick.next_release(plan_under(earliest), chunk_pick.LastCut(tag, "", 4, naming(named))), upcoming)
def test_says_work_has_landed_towards_it_where_a_change_is_unreleased(self):
cut = lambda changes: chunk_pick.LastCut("v1.2.3", "", changes, naming({(1, 3, 0)}))
self.assertEqual(chunk_pick.next_release([one((1, 3, 0))], cut(4)), chunk_pick.Upcoming((1, 3, 0), True, True))
self.assertEqual(chunk_pick.next_release([one((1, 3, 0))], cut(0)), chunk_pick.Upcoming((1, 3, 0), True, False))
self.assertEqual(chunk_pick.next_release([one((1, 3, 0))], cut(Failure("count unreadable"))), chunk_pick.Upcoming((1, 3, 0), True, Failure("count unreadable")))
class ChunkItem(unittest.TestCase):
def test_takes_the_earliest_release_where_it_is_the_next_and_else_says_whether_the_next_is_ready_to_cut_or_to_plan(self):
cases = (
("v1.2.3", 4, (1, 2, 4), set(), chunk_pick.Next((1, 2, 4), one((1, 2, 4)))),
("v1.2.3", 4, (1, 3, 0), {(1, 3, 0)}, chunk_pick.Next((1, 3, 0), one((1, 3, 0)))),
("v1.2.3", 4, (1, 2, 4), {(1, 3, 0)}, chunk_pick.Next((1, 2, 4), one((1, 2, 4)))),
("v1.2.3", 4, (1, 3, 0), {(1, 2, 3), (1, 3, 0)}, chunk_pick.Next((1, 3, 0), one((1, 3, 0)))),
("v0.2.0", 4, (0, 4, 0), set(), chunk_pick.Next((0, 4, 0), one((0, 4, 0)))),
(None, 4, (0, 2, 0), set(), chunk_pick.Next((0, 2, 0), one((0, 2, 0)))),
(None, 4, None, set(), chunk_pick.Next(None, None)),
("v1.2.3-rc.1", 4, (1, 2, 3), set(), chunk_pick.Next((1, 2, 3), None)),
(Failure("tags unreadable"), 4, (0, 2, 0), set(), chunk_pick.Next((0, 2, 0), None)),
("v1.2.3-rc.1", 4, (1, 2, 3), set(), chunk_pick.Next((1, 2, 3), one((1, 2, 3)))),
(Failure("tags unreadable"), 4, (0, 2, 0), set(), chunk_pick.Next((0, 2, 0), one((0, 2, 0)))),
("v1.2.3", 4, (1, 2, 3), set(), chunk_pick.Cut((1, 2, 3))),
("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, chunk_pick.Cut((1, 2, 2))),
("v1.2.3", 4, (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, chunk_pick.Finished((1, 2, 4))),
("v0.9.2", 4, (1, 0, 0), {(0, 9, 3)}, chunk_pick.Finished((0, 9, 3))),
("v1.2.3", 4, (1, 4, 0), {(1, 2, 2), (1, 3, 0)}, chunk_pick.Finished((1, 3, 0))),
("v1.2.3", 4, None, {(1, 3, 0)}, chunk_pick.Finished((1, 3, 0))),
("v1.2.3", 4, None, set(), chunk_pick.Finished(None)),
("v1.2.3", 4, (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, chunk_pick.ReadyToCut((1, 2, 4))),
("v0.9.2", 4, (1, 0, 0), {(0, 9, 3)}, chunk_pick.ReadyToCut((0, 9, 3))),
("v1.2.3", 4, (1, 4, 0), {(1, 2, 2), (1, 3, 0)}, chunk_pick.ReadyToCut((1, 3, 0))),
("v1.2.3", 4, None, {(1, 3, 0)}, chunk_pick.ReadyToCut((1, 3, 0))),
("v1.2.3", 4, None, set(), chunk_pick.ReadyToCut(None)),
("v1.2.3", 0, (1, 3, 0), {(1, 2, 4)}, chunk_pick.Unplanned((1, 2, 4))),
("v1.2.3", 0, None, set(), chunk_pick.Unplanned(None)),
("v1.2.3", Failure("count unreadable"), None, set(), chunk_pick.Unknown()),
("v1.2.3", Failure("count unreadable"), (1, 3, 0), {(1, 3, 0)}, chunk_pick.Next((1, 3, 0), one((1, 3, 0)))),
("v1.2.3", 4, (1, 3, 0), Failure("log unreadable"), chunk_pick.Unknown()),
("v1.2.3", 4, (1, 2, 3), Failure("log unreadable"), chunk_pick.Cut((1, 2, 3))),
)
for tag, landed, earliest, named, stands in cases:
with self.subTest(tag=tag, landed=landed, earliest=earliest, named=named):
self.assertEqual(chunk_pick.standing(tag, landed, earliest, None, named), stands)
def test_takes_the_first_item_only_where_the_earliest_release_is_next(self):
first = todo_table.Item(1, (1, 2, 4), "", "**Do 1.**", {}, (), ())
self.assertEqual(chunk_pick.standing("v1.2.3", 4, (1, 2, 4), first, set()), chunk_pick.Next((1, 2, 4), first))
self.assertEqual(chunk_pick.standing("v1.2.3", 4, (1, 2, 3), first, set()), chunk_pick.Cut((1, 2, 3)))
for tag, changes, earliest, named, stands in cases:
with self.subTest(tag=tag, changes=changes, earliest=earliest, named=named):
self.assertEqual(chunk_pick.chunk_item(plan_under(earliest), chunk_pick.LastCut(tag, "", changes, naming(named))), stands)
def test_counts_the_changes_unreleased_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self):
changelog = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
@@ -56,16 +95,12 @@ class Standing(unittest.TestCase):
self.assertIsNone(chunk_pick.unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n"))
def test_names_each_release_a_todo_md_since_the_last_cut_filed_items_under(self):
row = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
header = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
texts = [header + row.format(id=1, release="0.2.0"), "", "not a table | x |", header + row.format(id=2, release="0.3.0")]
texts = [HEADER + ROW.format(id=1, release="0.2.0"), "", "not a table | x |", HEADER + ROW.format(id=2, release="0.3.0")]
self.assertEqual(chunk_pick.named_releases(texts), {(0, 2, 0), (0, 3, 0)})
self.assertEqual(chunk_pick.named_releases(Failure("log unreadable")), Failure("log unreadable"))
def test_leaves_out_a_release_the_plan_marks_renamed_and_keeps_one_whose_items_moved_unmarked(self):
row = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
header = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
plan = lambda *rows, renamed=(): header + "".join(row.format(id=id_, release=release) for id_, release in rows) + ("\n## Renamed\n\n" + "".join(f"- {old} renamed to {new}\n" for old, new in renamed) if renamed else "")
plan = lambda *rows, renamed=(): HEADER + "".join(ROW.format(id=id_, release=release) for id_, release in rows) + ("\n## Renamed\n\n" + "".join(f"- {old} renamed to {new}\n" for old, new in renamed) if renamed else "")
cases = (
("renamed", [plan((1, "0.2.1")), plan((1, "0.3.0"), renamed=[("0.2.1", "0.3.0")])], {(0, 3, 0)}),
("deferred: its items moved without a mark", [plan((1, "0.2.1"), (2, "0.3.0")), plan((1, "0.3.0"), (2, "0.3.0"))], {(0, 2, 1), (0, 3, 0)}),
+45
View File
@@ -26,6 +26,51 @@ class Git(unittest.TestCase):
self.assertIn("latin", done.reason)
self.assertIn("UTF-8", done.reason)
def test_says_which_command_could_not_start_in_a_directory_that_is_gone(self):
done = git_repo.git("log", cwd="/code/gone")
self.assertIsInstance(done, Failure)
self.assertTrue(done.reason.startswith("git log could not start: "), done.reason)
self.assertIn("/code/gone", done.reason)
class Guarded(unittest.TestCase):
"""A checkout whose own config may name a program for git to run."""
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = temp.name
self.config("init", "--quiet")
def config(self, *args):
subprocess.run(["git", *args], capture_output=True, check=True, cwd=self.root)
def test_runs_a_command_that_needs_no_transport(self):
self.assertEqual(git_repo.git("rev-parse", "--is-inside-work-tree", cwd=self.root, guarded=True), "true\n")
def test_refuses_each_transport_the_checkout_allows_by_name(self):
# Port 1 refuses a connection, so a transport let through fails without the refusal named.
for name, url in (("ext", "ext::true"), ("file", f"file://{self.root}"), ("git", "git://127.0.0.1:1/x"), ("http", "http://127.0.0.1:1/x"), ("https", "https://127.0.0.1:1/x"), ("ssh", "ssh://127.0.0.1:1/x")):
with self.subTest(name):
self.config("config", f"protocol.{name}.allow", "always")
done = git_repo.git("ls-remote", url, cwd=self.root, guarded=True)
self.assertIsInstance(done, Failure)
self.assertIn(f"transport '{name}' not allowed", done.reason)
def test_refuses_a_transport_it_does_not_name(self):
done = git_repo.git("ls-remote", "ftp://127.0.0.1:1/x", cwd=self.root, guarded=True)
self.assertIsInstance(done, Failure)
self.assertIn("transport 'ftp' not allowed", done.reason)
def test_turns_off_the_fsmonitor_and_signature_check_the_checkout_turns_on(self):
self.config("config", "core.fsmonitor", "/bin/false")
self.config("config", "log.showSignature", "true")
self.assertEqual(git_repo.git("config", "core.fsmonitor", cwd=self.root, guarded=True), "false\n")
self.assertEqual(git_repo.git("config", "log.showSignature", cwd=self.root, guarded=True), "false\n")
def test_stops_a_partial_clone_fetching_its_missing_objects(self):
self.assertEqual(git_repo.git("-c", "alias.lazy=!printenv GIT_NO_LAZY_FETCH", "lazy", cwd=self.root, guarded=True), "1\n")
class StalledOrigin(unittest.TestCase):
"""A checkout whose origin, run through git's ext transport, answers nothing for 10 s, and which records no default branch for it."""
+188 -43
View File
@@ -13,7 +13,10 @@ import rank_todo
from repo_checks.test_python_floor import ROOT
import todo_table
README = "# P\n\n## Goals\n\n1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n 1. **Achieve:** Tested.\n\n## Audience\n\nMe.\n"
# Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it.
VOID = "**Void:** code health, since a test project has no code to read.\n\n"
README = "# P\n\n## Goals\n\n" + VOID + "1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n 1. **Achieve:** Tested.\n\n## Audience\n\nMe.\n"
DECISIONS = "## A choice\n\nStands until `todo.md` item 5 ends it.\n"
@@ -33,7 +36,7 @@ TODO = """# todo
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 0 |
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 |
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 8 | 2.1 by 8, 1 by 6 | 0 |
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 0 |
| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 0 |
@@ -96,15 +99,15 @@ Kept as written.
class Rank(unittest.TestCase):
def ranked(self, todo=TODO, readme=README, decisions=DECISIONS):
return rank_todo.rank(todo, readme, decisions)
return rank_todo.rank(todo, readme, decisions, "")
def test_scores_and_sorts_by_release_then_security_then_score_and_orders_the_details_to_match(self):
ranked = self.ranked()
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 8.3 |
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 8 | 2.1 by 8, 1 by 6 | 2.6 |
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 2.1 |
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.0 |
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 300.0 |
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 |
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 |
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 |
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 |
""", ranked.text)
self.assertTrue(ranked.text.endswith("## Details\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n## Notes\n\nKept as written.\n"))
self.assertEqual(ranked.under_bar, [])
@@ -115,12 +118,24 @@ class Rank(unittest.TestCase):
quoting = TODO.replace("Fast detail.", " ## Goals\n\nFast detail.")
self.assertIn("### 3. Make it fast, `a | b`.\n\n ## Goals\n\nFast detail.\n", self.ranked(quoting).text)
def test_weighs_each_achieve_goal_by_its_sum_reciprocal_rank(self):
def test_weighs_each_achieve_goal_97_percent_of_the_one_above_and_a_defects_maintain_goal_as_the_first(self):
readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
self.assertEqual({goal: round(weight, 4) for goal, weight in rank_todo.goal_weights(rank_todo.readme_goals(readme)).items()}, {"1": 0.5455, "1.1": 0.5455, "1.2": 0.2727, "2": 0.1818})
self.assertEqual({goal: round(weight, 4) for goal, weight in rank_todo.goal_weights(rank_todo.readme_goals(readme), None).items()}, {"1": 0.3435, "1.1": 0.3435, "1.2": 0.3332, "2": 0.3232})
def test_weighs_5_achieve_goals_from_0212_to_0188_and_15_from_0082_to_0053_as_the_help_says(self):
for count, first, last in ((5, 0.212, 0.188), (15, 0.082, 0.053)):
with self.subTest(count=count):
goals = rank_todo.readme_goals("## Goals\n\n" + "".join(f"{number}. **Achieve:** G.\n" for number in range(1, count + 1)))
weights = list(rank_todo.goal_weights(goals, None).values())
self.assertEqual((round(weights[0], 3), round(weights[-1], 3), round(sum(weights), 6)), (first, last, 1))
for figure in (rank_todo.GOAL_STEP, first, last):
self.assertIn(str(figure), rank_todo.__doc__)
self.assertIn(f"While it is under {rank_todo.FLOOR}, or the history holds no scoring run, code health weighs {rank_todo.UNDER_FLOOR} times its weight by position, and the other goals keep theirs.", " ".join(rank_todo.__doc__.split()))
def test_scores_an_item_by_the_weights_of_the_goals_it_moves(self):
readme = "## Goals\n\n" + VOID + "1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
todo = TODO.replace("2.1 by 8, 1 by 6", "1.2 by 2, 2 by 3").replace("| 2.1 by 1 |", "| 1 by 1 |")
ranked = self.ranked(todo, readme)
self.assertIn("| **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 8 | 1.2 by 2, 2 by 3 | 0.4 |", ranked.text)
self.assertIn("| **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 1.2 by 2, 2 by 3 | 1.3 |", self.ranked(todo, readme).text)
def test_scores_an_item_that_moves_no_goal_zero(self):
ranked = self.ranked(TODO.replace("| 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |", "| 1 | 2 | 1 | 2 | 4 | |"))
@@ -133,11 +148,11 @@ class Rank(unittest.TestCase):
self.assertEqual(gone.reason, "docs/decisions.md cites \"`todo.md` item 5\", which todo.md no longer holds; revise that decision to say what holds now")
def test_names_each_item_under_the_bar_that_is_not_exempt(self):
ranked = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 2.5`"))
self.assertEqual(ranked.under_bar, ["item 2 scores 2.1, under the bar 2.5; delete it, or mark it with a reason the bar does not apply"])
self.assertEqual(self.ranked(TODO.replace("`Bar = 2`", "`Bar = 2.1`")).under_bar, [])
blocking = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 2.5`").replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |"))
self.assertEqual(blocking.under_bar, ["item 2 scores 2.1, under the bar 2.5; delete it and the items it blocks, directly or through another (3, 5), or mark it with a reason the bar does not apply"])
ranked = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.5`"))
self.assertEqual(ranked.under_bar, ["item 2 scores 3.1, under the bar 3.5; delete it, or mark it with a reason the bar does not apply"])
self.assertEqual(self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.1`")).under_bar, [])
blocking = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.5`").replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |"))
self.assertEqual(blocking.under_bar, ["item 2 scores 3.1, under the bar 3.5; delete it and the items it blocks, directly or through another (3, 5), or mark it with a reason the bar does not apply"])
self.assertEqual(self.ranked(ranked.text.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | principle |")).under_bar, [])
self.assertEqual(self.ranked(ranked.text.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | owner |")).under_bar, [])
@@ -166,10 +181,10 @@ class Rank(unittest.TestCase):
def test_weighs_the_maintain_goal_a_defect_restores_as_the_heaviest_achieve_goal(self):
ranked = self.ranked(TODO.replace("| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |", "| 2 | 0.1.0 | | defect | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 |"))
self.assertIn("| **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 | 12.5 |", ranked.text)
self.assertIn("| **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 | 9.5 |", ranked.text)
def test_refuses_a_goal_named_beside_its_own_sub_goal(self):
readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
readme = "## Goals\n\n" + VOID + "1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
todo = TODO.replace("2.1 by 8, 1 by 6", "1.2 by 2, 1 by 3").replace("| 2.1 by 1 |", "| 2 by 1 |")
self.assertEqual(self.ranked(todo, readme), Failure("item 3 names goal 1 and its sub-goal 1.2; name one, never both: the sub-goal where the move serves it, else the parent"))
self.assertIsInstance(self.ranked(todo.replace("1.2 by 2, 1 by 3", "1.2 by 2, 2 by 3"), readme), rank_todo.Ranked)
@@ -177,15 +192,15 @@ class Rank(unittest.TestCase):
def test_scores_every_item_zero_where_readme_marks_no_goal_achieve(self):
ranked = self.ranked(TODO.replace("2.1 by 8, 1 by 6", "").replace("| 2.1 by 1 |", "| |").replace("| 1 by 9 |", "| |"), README.replace("**Achieve:**", "**Maintain:**"))
self.assertEqual([line.split(" scores ")[0] for line in ranked.under_bar], ["item 2", "item 3", "item 1"])
self.assertEqual(ranked.notes, ["README.md marks no goal **Achieve:**, so every item scores V 0"])
self.assertEqual(ranked.notes, ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"])
def test_accepts_a_move_of_ten_and_a_variable_base(self):
ranked = self.ranked(TODO.replace("| 1 by 9 |", "| 1 by 10 |").replace("100 * V / 2**S", "V * S ** 2"))
self.assertIn("| **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 10 | 6.7 |", ranked.text)
self.assertIn("| **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 10 | 5.1 |", ranked.text)
def test_asks_to_drop_a_goal_weights_table_from_a_table_with_moves(self):
weighted = TODO.replace("## Items\n", "| Goal | W |\n|---|---|\n| 1 | 1.00 |\n\n## Items\n")
self.assertEqual(self.ranked(weighted), Failure("todo.md holds a goal weights table beside a Moves column; drop the table, since rank_todo.py weighs each achieve goal by its position in README.md"))
self.assertEqual(self.ranked(weighted), Failure("todo.md holds a goal weights table beside a Moves column; drop the table, since rank_todo.py weighs the goals itself, as its --help says"))
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"):
@@ -195,7 +210,7 @@ class Rank(unittest.TestCase):
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "1 ** (1 / (S - S))")), Failure("the formula gives item 1 no finite score"))
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "(1 / (S - S)) ** 0")), Failure("the formula gives item 1 no finite score"))
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "W")), Failure("the formula 'W' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses"))
self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, 1.2 by 5`, each moved by a whole number from 1 to 10"))
self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, code health by 5`, each moved by a whole number from 1 to 10"))
def test_refuses_a_file_off_the_format(self):
row = "| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 |"
@@ -210,7 +225,7 @@ class Rank(unittest.TestCase):
"Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1": "Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 0",
"2.1 by 8, 1 by 6": "2.1: 8, 1: 6",
"2.1 by 8, 1 by 6 ": "2.1 by 8,1 by 6 ",
"| 2 | 1 | 2 | 3 | 8 | 2.1 by 8, 1 by 6 |": "| 2 | 1 | 2 | 3 | 8 | 2.1, 1 |",
"| 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 |": "| 2 | 1 | 2 | 3 | 7 | 2.1, 1 |",
row + "\n": row.replace("2 | 4 |", "2 | ² |") + "\n",
"| 2.1 by 1 | 0 |\n\n## Details": "| 2.1 by 1 | 0 |\n\n| 9 | 0.1.0 | | | **Stray.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n\n## Details",
"| 4 | 0.1.0 | | security |": "| 4 | 0.1.0 | | later |",
@@ -229,28 +244,134 @@ class Rank(unittest.TestCase):
self.assertIsInstance(self.ranked(TODO.replace(old, new)), Failure)
# A scoring run of the project whose overall mean is {overall}.
SCORED = "# Comprehension history\n\n## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mid A | 6 |\n| Mean | {overall} |\n"
class CodeHealth(unittest.TestCase):
readme = "## Goals\n\n1. **Achieve:** A.\n"
todo = TODO.split("| 1 | 0.2.0", 1)[0].replace("`Bar = 2`", "`Bar = 0.1`") + "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 0 |\n| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n"
def scores(self, history, readme=readme):
ranked = rank_todo.rank(self.todo, readme, "", history)
return ranked if isinstance(ranked, Failure) else {line.split(" | ")[0]: line.rsplit(" | ", 1)[1].rstrip(" |") for line in ranked.text.splitlines() if line.startswith("| ") and " 0.1.0 " in line}
def entry(self, overall, at="2026-10-08T12", read="PR #1 at aaaaaaa"):
"""A scoring run's entry, without the history's title."""
return SCORED.format(overall=overall).removeprefix("# Comprehension history\n\n").replace("2026-10-08T12", at).replace("PR #1 at aaaaaaa", read)
def test_ranks_code_health_first_among_the_achieve_goals_at_an_overall_of_7_or_above(self):
# Code health, then goal 1: weights 1 / 1.97 and 0.97 / 1.97, an item moving one by 1 at S 1 scoring 50 times its weight.
self.assertEqual(self.scores(SCORED.format(overall="7.00")), {"| 1": "25.4", "| 2": "24.6"})
def test_weighs_code_health_four_times_as_much_under_an_overall_of_7_and_before_any_scoring_run(self):
for history in (SCORED.format(overall="6.99"), "", "# Comprehension history\n\n## 2026-10-09T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nRuling: better\n"):
with self.subTest(history=history):
self.assertEqual(self.scores(history), {"| 1": "101.5", "| 2": "24.6"})
def test_weighs_by_the_newest_scored_commit_wherever_the_file_holds_it(self):
older = self.entry("6.50")
newer = self.entry("7.25", "2026-10-10T12", "PR #1 at bbbbbbb")
for history in (f"{older}\n{newer}", f"{newer}\n{older}"):
with self.subTest(history=history):
self.assertEqual(self.scores(history)["| 1"], "25.4")
def test_weighs_by_the_mean_overall_of_every_run_on_the_newest_scored_commit(self):
# 7.13 and 6.88 average 7.005, at the floor or above; 7.10 and 6.80 average 6.95, under it.
for first, rerun, value in (("7.13", "6.88", "25.4"), ("7.10", "6.80", "101.5")):
with self.subTest(first=first, rerun=rerun):
self.assertEqual(self.scores(f"{self.entry(first)}\n{self.entry(rerun, '2026-10-08T13', 'PR #1 rerun at aaaaaaa')}")["| 1"], value)
later = self.entry("6.50", "2026-10-09T12", "PR #2 at bbbbbbb")
self.assertEqual(self.scores(f"{self.entry('7.13')}\n{self.entry('6.88', '2026-10-08T13', 'PR #1 rerun at aaaaaaa')}\n{later}")["| 1"], "101.5")
def test_matches_a_commit_whichever_length_a_heading_writes_it_at(self):
full = "aaaaaaa" + "0" * 33
# As runs of one commit, 7.13 and 6.88 average 7.005; the newer alone is under the floor.
for first, rerun in (("aaaaaaa", full), (full, "aaaaaaa")):
with self.subTest(first=first, rerun=rerun):
self.assertEqual(self.scores(f"{self.entry('7.13', read=f'PR #1 at {first}')}\n{self.entry('6.88', '2026-10-08T13', f'PR #1 rerun at {rerun}')}")["| 1"], "25.4")
def test_weighs_by_a_ruling_that_holds_scoring_seats_places(self):
# A ruling recorded before PR #255 scored the project too: below its votes, a scores table with a Mean row, and each scoring seat's places.
ruling = "## 2026-10-10T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nRuling: better\n\n| Seat | Overall |\n|---|---|\n| Mid A | better |\n\n| Seat | Overall |\n|---|---|\n| Mid A | 7.5 |\n| Mean | 7.25 |\n\nJunior A, hardest first:\n\n- `bin/a.py:1` `f`: long\n"
self.assertEqual(self.scores(f"{self.entry('6.50')}\n{ruling}")["| 1"], "25.4")
def test_refuses_a_newest_scoring_run_with_no_overall_mean(self):
for history in (SCORED.format(overall="high"), SCORED.split("| Mean")[0]):
with self.subTest(history=history):
self.assertEqual(self.scores(history), Failure("docs/comprehension-history.md's scoring run 2026-10-08T12:00:00Z, PR #1 at aaaaaaa has no Mean row ending in its overall, which sets code health's weight"))
def test_drops_code_health_where_readme_voids_it(self):
voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n"
self.assertEqual(self.scores("", voided), Failure("item 1 names code health, which README.md voids; drop it from the item's Moves, or the void from README.md"))
ranked = rank_todo.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", "")
self.assertIn("| **Read easier.** | 1 | 1 | 1 | 1 | 1 | 1 by 2 | 100.0 |", ranked.text)
def test_weighs_a_defects_maintain_goal_as_code_health_four_times_over_under_an_overall_of_7(self):
readme = "## Goals\n\n1. **Achieve:** A.\n2. **Maintain:** B.\n"
todo = self.todo.replace("| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 |", "| 2 | 0.1.0 | | defect | **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 |")
for history, value in (("", "101.5"), (SCORED.format(overall="7.00"), "25.4")):
with self.subTest(history=history):
self.assertIn(f"| **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 | {value} |", rank_todo.rank(todo, readme, "", history).text)
def test_refuses_a_plan_whose_project_opts_out_of_the_comprehension_check_yet_keeps_code_health(self):
opted_out = "## review opt-out: the architect and the comprehension check\n\nCosts rounds.\n"
self.assertEqual(rank_todo.rank(self.todo, self.readme, opted_out, ""), Failure("docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says"))
self.assertIsInstance(rank_todo.rank(self.todo, self.readme, opted_out.replace(" and the comprehension check", ""), ""), rank_todo.Ranked)
voided = "## Goals\n\n**Void:** code health, since nobody reads the probes.\n\n1. **Achieve:** A.\n"
self.assertIsInstance(rank_todo.rank(self.todo.replace("code health by 1", "1 by 2"), voided, opted_out, ""), rank_todo.Ranked)
def test_ranks_a_project_that_voids_code_health_whatever_its_history_holds(self):
voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n"
self.assertIsInstance(rank_todo.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", SCORED.format(overall="high")), rank_todo.Ranked)
def test_refuses_a_void_of_anything_but_code_health(self):
self.assertEqual(self.scores("", "## Goals\n\n**Void:** speed, since nobody waits.\n\n1. **Achieve:** A.\n"), Failure("README.md's ## Goals voids `speed, since nobody waits.`; only code health may be voided, as `**Void:** code health, since <reason>.`"))
def test_shows_the_spelling_of_a_void_of_code_health_that_misses_it(self):
for void in ("code health.", "Code health, since it is a one-off script.", "code health since it is a one-off script."):
with self.subTest(void=void):
self.assertEqual(self.scores("", f"## Goals\n\n**Void:** {void}\n\n1. **Achieve:** A.\n"), Failure(f"README.md's ## Goals voids code health as `{void}`; spell the void exactly `**Void:** code health, since <reason>.`"))
def test_parses_code_health_in_a_moves_cell(self):
self.assertEqual(todo_table.parse_moves("1", "code health by 4, 1.1 by 2"), (("code health", 4), ("1.1", 2)))
self.assertIsInstance(todo_table.parse_moves("1", "code health by 11"), Failure)
self.assertIsInstance(todo_table.parse_moves("1", "health by 4"), Failure)
def test_reads_the_history_beside_todo_md(self):
with tempfile.TemporaryDirectory() as temp:
todo = pathlib.Path(temp, "todo.md")
todo.write_text(self.todo)
pathlib.Path(temp, "README.md").write_text(self.readme)
pathlib.Path(temp, "docs").mkdir()
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00"))
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(rank_todo.main([str(todo)]), 0)
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
class Risk(unittest.TestCase):
"""R is L + E + I - 2, which rank_todo.py writes, at least 7 when I is 5 and at least 5 when I is 4."""
def ranked(self, todo):
return rank_todo.rank(todo, README, DECISIONS)
return rank_todo.rank(todo, README, DECISIONS, "")
def test_writes_r_from_l_e_and_i_over_a_stale_or_missing_r(self):
ranked = self.ranked(TODO).text
for levels, risk in (("| 1 | 1 | 1 |", 1), ("| 2 | 1 | 2 |", 3), ("| 1 | 2 | 1 |", 2)):
with self.subTest(levels=levels):
self.assertIn(f"{levels} {risk} |", ranked)
stale = TODO.replace("| 2 | 1 | 2 | 3 | 8 |", "| 2 | 1 | 2 | 10 | 8 |")
stale = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 10 | 7 |")
self.assertEqual(self.ranked(stale).text, ranked)
without_r = TODO.replace("| I | R | S |", "| I | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|")
without_r = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+) \| \d+ \|", r"\1 |", without_r)
self.assertEqual(self.ranked(without_r).text, ranked)
def test_writes_r_into_a_blank_r_cell(self):
blank = TODO.replace("| 2 | 1 | 2 | 3 | 8 |", "| 2 | 1 | 2 | | 8 |")
blank = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | | 7 |")
self.assertEqual(self.ranked(blank).text, self.ranked(TODO).text)
def test_leaves_a_stale_r_to_ranking_so_a_reader_keeps_the_r_the_table_stored(self):
stale = TODO.replace("| 2 | 1 | 2 | 3 | 8 |", "| 2 | 1 | 2 | 10 | 8 |")
stale = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 10 | 7 |")
self.assertEqual(next(item for item in todo_table.items(stale) if item.id == 3).scores["R"], 10)
self.assertNotEqual(self.ranked(stale).text, stale)
@@ -281,7 +402,7 @@ class Risk(unittest.TestCase):
class OldShape(unittest.TestCase):
"""A table with A, G and Goals, from before the Moves column, ranks by the formula and goal weights it states until its project reshapes it."""
def ranked(self, todo=OLD_SHAPE, readme=README):
return rank_todo.rank(todo, readme, DECISIONS)
return rank_todo.rank(todo, readme, DECISIONS, "")
def test_scores_by_the_stated_weights_and_says_to_reshape(self):
ranked = self.ranked()
@@ -308,7 +429,7 @@ class OldShape(unittest.TestCase):
def test_ranks_a_table_from_before_c_joined_and_says_to_reshape_it(self):
legacy = OLD_SHAPE.split("## Items")[0] + "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |\n"
self.assertEqual(rank_todo.rank(legacy, README, "").notes, [rank_todo.RESHAPE])
self.assertEqual(rank_todo.rank(legacy, README, "", "").notes, [rank_todo.RESHAPE])
def test_refuses_a_table_with_both_moves_and_goals(self):
both = OLD_SHAPE.replace("| Goals | Score |\n|---|", "| Goals | Moves | Score |\n|---|---|").replace(" | 0 |\n", " | 1 by 1 | 0 |\n")
@@ -318,22 +439,22 @@ class OldShape(unittest.TestCase):
def test_names_the_goals_column_a_table_misspells_by_its_shape(self):
misspelt = TODO.replace("| S | Moves |", "| S | Move |")
self.assertEqual(rank_todo.rank(misspelt, README, DECISIONS), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
self.assertEqual(rank_todo.rank(misspelt, README, DECISIONS, ""), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
self.assertEqual(todo_table.items(misspelt), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
self.assertEqual(self.ranked(OLD_SHAPE.replace("| G | Goals |", "| G | Goal |")), Failure("todo.md's items table has no Goals column; rank_todo.py --help shows a valid one"))
class Blockers(unittest.TestCase):
def ranked(self, todo):
return rank_todo.rank(todo, README, DECISIONS)
return rank_todo.rank(todo, README, DECISIONS, "")
def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self):
ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |"))
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 8.3 |
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 2.1 |
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.0 |
| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 8 | 2.1 by 8, 1 by 6 | 2.6 |
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 300.0 |
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 |
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 |
| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 |
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 |
""", ranked.text)
self.assertEqual(self.ranked(ranked.text), ranked)
@@ -351,7 +472,20 @@ class Blockers(unittest.TestCase):
waits = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |"))
self.assertEqual(todo_table.bundle_candidates(waits, todo_table.next_item(waits)), [])
answered = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |"))
self.assertEqual([item.id for item in todo_table.bundle_candidates(answered, todo_table.next_item(answered))], [3, 4, 5])
self.assertEqual([item.id for item in todo_table.bundle_candidates(answered, todo_table.next_item(answered))], [3, 5])
def test_ships_an_item_above_r_5_alone(self):
# Item 4 has R 9: it joins no chunk, and none joins it. Item 5, at R 5, still joins.
found = todo_table.items(TODO)
self.assertNotIn(4, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
self.assertIn(5, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
self.assertEqual(todo_table.bundle_candidates(found, next(item for item in found if item.id == 4)), [])
# At R 6, item 3 ships alone too.
riskier = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | 6 | 7 |"))
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(riskier, todo_table.next_item(riskier))])
# Before rank_todo.py fills its R cell, item 3's L 3, E 2 and I 3 still make R 6.
unranked = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | | 7 |"))
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(unranked, todo_table.next_item(unranked))])
def test_drops_a_blocker_the_table_no_longer_holds_as_finished(self):
finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |")
@@ -425,15 +559,15 @@ class Renamed(unittest.TestCase):
self.assertIsInstance(todo_table.renames(f"## Renamed\n\n{bad}\n"), Failure)
def test_fails_on_a_renamed_section_that_does_not_parse(self):
failed = rank_todo.rank(TODO + "\n## Renamed\n\nsoon\n", README, DECISIONS)
failed = rank_todo.rank(TODO + "\n## Renamed\n\nsoon\n", README, DECISIONS, "")
self.assertIsInstance(failed, Failure)
self.assertIn("## Renamed", failed.reason)
def test_ranks_a_plan_with_a_valid_renamed_section(self):
self.assertIsInstance(rank_todo.rank(TODO + "\n## Renamed\n\n- 0.3.0 renamed to 0.4.0\n", README, DECISIONS), rank_todo.Ranked)
self.assertIsInstance(rank_todo.rank(TODO + "\n## Renamed\n\n- 0.3.0 renamed to 0.4.0\n", README, DECISIONS, ""), rank_todo.Ranked)
def test_fails_on_an_item_filed_under_a_release_the_plan_marks_renamed(self):
live = rank_todo.rank(TODO + "\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", README, DECISIONS)
live = rank_todo.rank(TODO + "\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", README, DECISIONS, "")
self.assertIsInstance(live, Failure)
self.assertIn("marks release 0.2.0 renamed but files item 1 under it", live.reason)
@@ -461,6 +595,17 @@ class Main(unittest.TestCase):
pathlib.Path(temp, "README.md").unlink()
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not found; rank_todo.py weighs goals from the README.md beside todo.md\n"))
def test_writes_the_ranked_file_yet_fails_on_an_item_under_the_bar(self):
under = "item 2 scores 3.1, under the bar 4; delete it, or mark it with a reason the bar does not apply"
with tempfile.TemporaryDirectory() as temp:
todo = pathlib.Path(temp, "todo.md")
todo.write_text(TODO.replace("`Bar = 2`", "`Bar = 4`"))
pathlib.Path(temp, "README.md").write_text(README)
pathlib.Path(temp, "docs").mkdir()
pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS)
self.assertEqual(self.run_main(str(todo)), (1, f"{todo}: {under}\n"))
self.assertEqual(self.run_main("--check", str(todo)), (1, f"{todo}: {under}\n"))
def test_says_to_reshape_an_old_shape_table_but_passes_the_check(self):
with tempfile.TemporaryDirectory() as temp:
todo = pathlib.Path(temp, "todo.md")
@@ -474,7 +619,7 @@ class Main(unittest.TestCase):
def test_shows_a_valid_file_in_help_and_names_arguments_it_cannot_read(self):
self.assertEqual(self.run_main("--help")[0], 0)
skeleton = "\n".join(line[4:] for line in rank_todo.__doc__.split("\n") if line.startswith(" "))
ranked = rank_todo.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "")
ranked = rank_todo.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "")
self.assertIsInstance(ranked, rank_todo.Ranked)
self.assertEqual((ranked.under_bar, ranked.notes), ([], []))
self.assertEqual(self.run_main("--fix"), (1, "rank_todo.py: cannot read the arguments --fix; usage: rank_todo.py [--check] [todo.md]\n"))
@@ -483,5 +628,5 @@ class Main(unittest.TestCase):
class ThisRepo(unittest.TestCase):
def test_todo_md_is_ranked_with_nothing_under_the_bar(self):
text = (ROOT / "todo.md").read_text(encoding="utf-8")
ranked = rank_todo.rank(text, (ROOT / "README.md").read_text(encoding="utf-8"), (ROOT / "docs" / "decisions.md").read_text(encoding="utf-8"))
ranked = rank_todo.rank(text, *((ROOT / name).read_text(encoding="utf-8") for name in ("README.md", "docs/decisions.md", "docs/comprehension-history.md")))
self.assertEqual(ranked, rank_todo.Ranked(text, [], []))
+18
View File
@@ -0,0 +1,18 @@
import pathlib
import sys
import typing
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from review_passes import PASS_AGENTS, PASSES, ReviewedPass, REVIEWERS
class ReviewPasses(unittest.TestCase):
def test_names_each_pass_that_has_an_agent_once_in_the_literal_and_in_the_list(self):
self.assertEqual(list(REVIEWERS), list(typing.get_args(ReviewedPass)))
self.assertEqual(list(REVIEWERS), [name for name in PASSES if PASS_AGENTS[name]])
def test_names_each_agent_under_agents(self):
agents = pathlib.Path(__file__).resolve().parents[1] / "agents"
self.assertEqual(sorted(REVIEWERS.values()), sorted(path.stem for path in agents.glob("*.md")))
+81
View File
@@ -0,0 +1,81 @@
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from settings_filter import cleaned
from test_env import isolated_env
FILTER = pathlib.Path(__file__).resolve().parent / "settings_filter.py"
ROOT = FILTER.parents[1]
PICKED = json.dumps({"theme": "dark", "model": "opus[1m]", "env": {}}, indent=2)
class Clean(unittest.TestCase):
def test_drops_the_model_and_sorts_every_key(self):
written = {"theme": "dark", "model": "opus[1m]", "env": {"B": "1", "A": "2"}}
self.assertEqual(cleaned(written), '{\n "env": {\n "A": "2",\n "B": "1"\n },\n "theme": "dark"\n}\n')
def test_keeps_text_outside_ascii(self):
self.assertEqual(cleaned({"name": "Lilleman på Larv"}), '{\n "name": "Lilleman på Larv"\n}\n')
def test_a_file_that_holds_no_json_object_exits_1_naming_the_tool(self):
for written in ("{", "[]"):
ran = subprocess.run([sys.executable, FILTER], input=written, capture_output=True, text=True)
self.assertEqual((ran.returncode, ran.stdout), (1, ""), written)
self.assertIn("settings_filter.py: ", ran.stderr)
class Checkout(unittest.TestCase):
"""A repo as README → Install leaves it, checked out at tag v1; tag v2 doesn't change settings.json."""
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.repo = pathlib.Path(temp.name)
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
self.git("init", "-q")
(self.repo / "bin").mkdir()
(self.repo / "bin" / "settings_filter.py").symlink_to(FILTER)
(self.repo / ".gitattributes").write_text((ROOT / ".gitattributes").read_text())
self.git("config", "filter.settings.clean", "bin/settings_filter.py")
self.settings = self.repo / "settings.json"
self.settings.write_text(cleaned({"env": {}, "theme": "dark"}))
(self.repo / ".claude").mkdir()
(self.repo / ".claude" / "settings.json").write_text('{\n "model": "claude-opus-5-5"\n}\n')
self.git("add", ".")
self.git("commit", "-qm", "settings")
self.git("tag", "v1")
(self.repo / "other").write_text("")
self.git("add", "other")
self.git("commit", "-qm", "a tag that leaves settings.json alone")
self.git("tag", "v2")
self.git("checkout", "-q", "v1")
def git(self, *args):
return subprocess.run(["git", "-C", self.repo, "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, env=self.env, text=True).stdout
def test_a_model_pick_in_claude_codes_key_order_leaves_nothing_to_commit(self):
self.settings.write_text(PICKED)
self.assertEqual(self.git("diff"), "")
# git status lists a file whose size changed until it is staged; staging adds no change.
self.git("add", "settings.json")
self.assertEqual(self.git("status", "--porcelain"), "")
def test_a_staged_pick_outlasts_an_update_to_a_tag_that_leaves_settings_json_alone(self):
self.settings.write_text(PICKED)
self.git("add", "settings.json")
self.git("checkout", "-q", "-f", "v2")
self.assertEqual(self.settings.read_text(), PICKED)
def test_the_repos_own_harness_settings_keep_their_model(self):
self.assertEqual(self.git("show", ":.claude/settings.json"), '{\n "model": "claude-opus-5-5"\n}\n')
if __name__ == "__main__":
unittest.main()
+13 -6
View File
@@ -103,9 +103,16 @@ class Script(unittest.TestCase):
ran = self.run_script(stdin)
self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, f"{RED}warning: statusline.py's input is not a JSON object{RESET}", ""))
def test_shows_a_branch_name_that_is_not_utf_8(self):
for branch, shown in ((b"trunk", "trunk"), (b"f\xe5", "f\ufffd")):
with tempfile.TemporaryDirectory() as checkout:
subprocess.run([b"git", b"init", b"-q", b"-b", branch, checkout.encode()], check=True)
ran = self.run_script(json.dumps({"cwd": checkout}))
self.assertEqual((ran.stdout, ran.stderr), (SEP.join([f"{CYAN}{checkout}{RESET}", f"{DIM}{shown}{RESET}"]), ""))
def run_on_branch(self, branch):
with tempfile.TemporaryDirectory() as checkout:
subprocess.run([b"git", b"init", b"-q", b"-b", branch, checkout.encode()], check=True)
ran = self.run_script(json.dumps({"cwd": checkout}))
return ran, checkout
def test_shows_the_branch(self):
ran, checkout = self.run_on_branch(b"trunk")
self.assertEqual((ran.stdout, ran.stderr), (SEP.join([f"{CYAN}{checkout}{RESET}", f"{DIM}trunk{RESET}"]), ""))
def test_shows_no_branch_where_git_fails_on_a_name_that_is_not_utf_8(self):
ran, checkout = self.run_on_branch(b"f\xe5")
self.assertEqual((ran.stdout, ran.stderr), (f"{CYAN}{checkout}{RESET}", ""))
+27 -8
View File
@@ -10,11 +10,15 @@ TOP_SCORE = 10
LEVELS = {"L": 4, "E": 3, "I": 5}
# The least R each impact level I allows, since a severe enough consequence outranks how unlikely it is.
RISK_FLOOR = {4: 5, 5: 7}
# The highest R an item may have and still share a chunk; `docs/decisions.md` → `chunks:` says why 5.
BUNDLE_MAX_R = 5
EXEMPTIONS = ("", "decision", "defect", "owner", "principle", "question", "security")
# The column naming the items that block an item: each must be done before the item starts.
BLOCKED_BY = "Blocked by"
# The column naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`.
MOVES = "Moves"
# The achieve goal every project shares, which ~/.claude/CLAUDE.md → "Shared goal" states, and a Moves cell names by these words, since it has no number in any README.
CODE_HEALTH = "code health"
# How the items table's header opens, which tells it from any other table in todo.md.
HEADER_START = "| ID | Release |"
# todo.md's ## Details section, its body the first group.
@@ -55,11 +59,11 @@ class Shape:
def parse_moves(id_: str, cell: str) -> Moves | Failure:
"""A Moves cell: empty, or each goal the item moves, named once, and how far."""
matches = [re.fullmatch(r"([0-9]+(?:\.[0-9]+)*) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
"""A Moves cell: empty, or each goal the item moves, named once, and how far. rank_todo.py's cited_goals_failure holds the rules that need README.md."""
matches = [re.fullmatch(rf"([0-9]+(?:\.[0-9]+)*|{CODE_HEALTH}) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
moves = tuple((match.group(1), int(match.group(2))) for match in matches if match)
if len(moves) < len(matches) or any(not 1 <= by <= TOP_SCORE for _, by in moves):
return Failure(f"item {id_}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, 1.2 by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
return Failure(f"item {id_}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
goals = [goal for goal, _ in moves]
if repeated := [goal for goal in goals if goals.count(goal) > 1]:
return Failure(f"item {id_} cites goal {repeated[0]} twice; name each goal once")
@@ -131,10 +135,17 @@ def shape_of(columns: tuple[str, ...]) -> Shape:
return OLD_SHAPE if MOVES not in columns and {"A", "G", OLD_SHAPE.goals_column}.intersection(columns) else SHAPE
def items(todo: str) -> list[Item] | None | Failure:
"""Each row of a todo.md's items table; None where todo.md holds no items table."""
@dataclasses.dataclass(frozen=True)
class NoItemsTable(Failure):
"""todo.md holds no items table. A table with no rows is not a NoItemsTable: items returns an empty list for it."""
def items(todo: str) -> list[Item] | Failure:
"""Each row of a todo.md's items table; a NoItemsTable where todo.md holds none."""
table = items_table(todo.splitlines())
if table is None or isinstance(table, Failure):
if table is None:
return NoItemsTable("todo.md holds no items table")
if isinstance(table, Failure):
return table
found = []
for row in table.rows:
@@ -191,9 +202,17 @@ def renames(todo: str) -> set[tuple[int, int, int]] | Failure:
return marked
def ships_alone(item: Item) -> bool:
"""An item above BUNDLE_MAX_R joins no chunk, and none joins it. R is worked out from L, E and I, so a row whose R cell rank_todo.py has not filled yet still counts. An old-shape table has no L, E or I, so none of its items ships alone."""
scores = item.scores
return all(level in scores for level in ("L", "E", "I")) and risk(scores["L"], scores["E"], scores["I"]) > BUNDLE_MAX_R
def bundle_candidates(found: list[Item], first: Item) -> list[Item]:
"""The items of first's release, in the table's order, that a chunk taking first may take too: those that do not wait once the chunk's own items count as done."""
chunk = {item.id for item in found if item.release == first.release}
"""The items of first's release, in the table's order, that a chunk taking first may take too: those that do not ship alone, and do not wait once the chunk's own items count as done."""
if ships_alone(first):
return []
chunk = {item.id for item in found if item.release == first.release and not ships_alone(item)}
# Dropping an item that waits may make another wait on it, so drop until none waits.
while waits := waiting(found, chunk) & chunk:
chunk -= waits
+22
View File
@@ -0,0 +1,22 @@
"""The archive of loop-claude's transcripts: where each file lives, what it holds, and when a copy is replaced.
<archive root>/<project key>/<chunk>/<sha256>.jsonl
<archive root>/<project key>/<chunk>/<sha256>.outcomes.md
<archive root>/<project key>/<chunk>/session/...
- The archive root is $LOOP_CLAUDE_TRANSCRIPTS, or ~/.claude/loop-claude-transcripts (location.archive_root).
- The project key is the checkout's path relative to ~/code, or to / outside it (project_key.project_key).
- <chunk> is the hash of the transcript's first line with a timestamp (location.chunk_folder). It is the
same for every cycle of a chunk, and differs between chunks, since a finished chunk's session is deleted
and the next chunk's transcript starts afresh.
- <sha256>.jsonl is a copy of the session's transcript, named by the hash of its bytes, so each distinct
transcript is kept once.
- <sha256>.outcomes.md sits beside the copy and holds the task, then each outcome opened by its UTC time (outcomes.py).
- session/ holds every other file of the session, such as the subagents' transcripts, which Claude
Code keeps in a folder named after the session, beside the transcript. A file there is replaced only by a version that
grew from it. A file Claude Code rewrote whole lands beside its copy as <name>.<hash of its content>
(write.copy_for).
write.archive writes the layout, at every interrupt and as every cycle ends. read.py and the tools that
measure finished chunks read it.
"""
+8 -7
View File
@@ -1,6 +1,7 @@
import re
from markdown_text import quoted
from model_routing.route import Record
from utc_stamp import STAMPED
TASK = "Task: "
@@ -28,23 +29,23 @@ def escalation_block(escalation: str) -> str:
return f"Escalation:\n{quoted(escalation)}\n\n" if escalation else ""
def finished(worker: str, evidence: str, judge: str) -> str:
def finished(worker: Record, evidence: str, judge: str) -> str:
return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{JUDGE}{judge}\n{WORKER}{worker}"
def unfinished(worker: str, evidence: str, judge: str, escalation: str) -> str:
def unfinished(worker: Record, 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: str) -> str:
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none. worker is the rung the worker ran on until the interrupt."""
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."""
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: str) -> str:
def answered(question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: Record) -> 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}"
@@ -55,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: str) -> str:
def stepped_up(worker: Record) -> 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: str, why: str) -> str:
def stopped(worker: Record, why: str) -> str:
return f"Stopped: {why}\n\n{WORKER}{worker}"
+1
View File
@@ -12,6 +12,7 @@ from utc_stamp import utc
def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, at: float) -> Failure | None:
"""Keeps the transcript at path, its outcomes file and its session's files in project_archive, in the layout this package's docstring gives; the failure that stopped it, or None. The outcome is stamped and appended to the outcomes file, which opens with the task only when the copy is new."""
try:
with open(path, "rb") as handle:
raw = handle.read()
+338
View File
@@ -2207,3 +2207,341 @@ Inherited architect, decided by:
- Locality, Shape: `bin/chunk_preflight/choices.py:24` `planned`: each pick variant carries its release, so the messages read straight off it, where 6e0fda4 paired a recomputed `earliest` with a string by hand
- Shape: `bin/chunk_preflight/gathered.py:1` `gathered`: data only, with the choices in `choices.py`, though `facts.py` imports `PULLS_LIST` from the decision module
- Shape: `bin/chunk_pick.py:118` `unreleased_changes`: with `committed_since_release` and one `version`, the names say what they count
## 2026-10-18T12:16:18Z, PR #321 at 862137b, against 0462980
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | worse | better | better | same |
| Inherited architect | same | worse | better | better | better |
| Maintainability senior | same | better | better | better | better |
| Junior A | same | worse | same | better | same |
Mid A, decided by:
- Locality: `bin/loop_claude/cycle/judge.py:153` `escalation_mark`: "one trigger buys one step" was one flag and one function in `run.py`'s `unspent`; now a mark across cycles read through `Route.escalated_at`, `entries_read` stamped late by `judge_once`, None versus 0, `STEP_LINE`, `Grounds.since_step` and the routing steps, over three modules
- Locality: `bin/loop_claude/cycle/judge.py:216` `quotes_checked`: turns a `QuotedAnswer` into an `Interrupt` without `entries_read`, correct only because `judge_once` stamps after `run_judge`, which nothing here says
- Locality: `bin/model_routing/route.py:12` `ROUTED`: the mark survives only by round-tripping through `Route.__str__`, so rewording one fragment resets it to 0 at a distance
- Shape, Self-sufficiency: `bin/model_routing/route.py:13` `ROUTED`: a verbose regex with each group naming the `__str__` fragment it reads, in place of one dense line
- Shape: `bin/loop_claude/cycle/judge.py:143` `Grounds`: one named tuple whose fields document their own checks, in place of loose strings and a docstring list
- Shape: `bin/loop_claude/routing.py:84` `one_rung_up`: no longer shares its name with `Cycle.stepped_from`, which means the route before the step
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:87` `escalation`: the docstring shows the full sentences it renders for a concrete rung
Inherited architect, decided by:
- Locality: `bin/loop_claude/cycle/judge.py:185` `judge_once`: "one trigger buys one step" runs through five units in four modules and outlives the run via the archive line, with three "nothing" values for one idea: 0 for no mark, None for no escalation, None for never stamped
- Locality: `bin/loop_claude/cycle/judge.py:219` `quotes_checked`: builds an `Interrupt` without `entries_read`, safe only because the stamp comes later; swapped, the escalation is silently dropped
- Shape, Self-sufficiency: `bin/loop_claude/cycle/judge.py:143` `Grounds`: each checked text is a named field with its rule and penalty beside it, so the judge-rejection path reads easier
- Shape: `bin/loop_claude/routing.py:84` `one_rung_up`: the name says what it does, and its `escalated_at` parameter shows it moves the mark, where `stepped_from` clashed with `Cycle.stepped_from`
- Locality, Shape: `bin/loop_claude/cycle/run.py:69` `escalated`: `Cycle` lost the cycle-scoped `escalation_spent` and `rule` no longer filters through `unspent`, so `run.py` reads on its own
- Self-sufficiency: `bin/model_routing/route.py:13` `ROUTED`: each group labelled by the fragment it reads, with a warning that a reword resets the mark
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:88` `escalation`: the docstring shows the rendered text for one concrete route
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:61` `STEP_LINE`: defined beside the slicing that inserts it, with the entries-only-grow assumption written on `Route.escalated_at`
Maintainability senior, decided by:
- Locality: `bin/model_routing/route.py:66` `Route.escalated_at`: one persisted mark that holds across cycles replaces a cycle-scoped flag and a filter in `rule` that rewrote the judge's verdict outside the judge
- Locality: `bin/loop_claude/routing.py:76` `stepped_by_ruling`: "no escalation, no step" now lives in routing, so `run.py`'s `escalated` reads straighter; offset in part by `judge_once` stamping `entries_read` after `quotes_checked` rebuilds an `Interrupt`, an order that matters
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:143` `Grounds`: each checked text a named field with its own comment, in place of two positional strings and a docstring list
- Self-sufficiency: `bin/model_routing/route.py:13` `ROUTED`: each group commented with the `Route.__str__` fragment it reads back
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:87` `escalation`: the docstring quotes the sentences it produces, and the body joins whole parts in place of space-led fragments
- Shape: `bin/loop_claude/routing.py:84` `one_rung_up`: renamed from `stepped_from`, which meant the opposite of `Cycle.stepped_from` beside it
Junior A, decided by:
- Locality: `bin/model_routing/route.py:66` `Route.escalated_at`: "one trigger buys one step" moved from one file's cycle-local flag and `unspent` filter to a mark threaded through six files
- Locality: `bin/loop_claude/cycle/judge.py:189` `judge_once`: stamps `entries_read` after the run, an unstamped None silently steps nothing, and "none" is 0 on the route but None in `stepped` and `stepped_by_ruling`
- Self-sufficiency: `bin/model_routing/route.py:13` `ROUTED`: a verbose pattern whose groups name the fragments they read, in place of one dense line
- Self-sufficiency, Shape: `bin/loop_claude/cycle/judge.py:143` `Grounds`: each field documents what must quote it and what a misquote does, though `judge` and `judge_once` grow to nine positional parameters
- Shape: `bin/loop_claude/routing.py:84` `one_rung_up`: removes the name it shared with `Cycle.stepped_from`, which meant the opposite
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:87` `escalation`: a worked example of the exact sentences, as its neighbours already had
## 2026-10-18T16:57:38Z, PR #322 at 49e86fd, against 2911d3f
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | same | better | same | better |
| Inherited architect | same | worse | better | same | same |
| Maintainability senior | same | better | worse | same | same |
| Junior A | better | better | same | same | better |
Mid A, decided by:
- Navigation, Shape: `bin/review_replay/main.py:1` `review_replay`: the tool takes any pass and its name says so, with `REVIEWERS` listing the passes and the usage printing them, where the old name pointed at stability alone
- Shape: `bin/review_replay/main.py:208` `reviewed_in`: copy, rewrite, clone and run are each a named step with a docstring, where `bin/stability_replay/main.py:175` did all four in one body; `codes_found` takes the left-out loop out of `main`
- Locality: `bin/rule_hook/reviewer_rung.py:18` `reviewer_breaches`: asks `review_rungs(...)[kind]` directly, without the older loop-claude fallback or the filesystem glob
- Locality: `bin/loop_claude/cycle/prompts.py:72` `taken_in_launches`: compares whole `review_rungs` dicts, right only because of a condition inside `ladder.review_rungs` that a comment states
- Locality: `bin/model_routing/ladder.py:71` `REPLAYED`: an empty table that `review_rungs`, `lowered`, `shared_launches` and `reruns` all branch on, so a reader follows a path no data drives
- Shape: `bin/rule_hook/reviewer_report.py:10` `REVIEWERS`: a frozenset of agent files, while `ladder.py`'s `REVIEWERS` is a dict from pass to agent; one name for two shapes
- Shape: `bin/loop_claude/cycle/prompts.py:43` `review_launches`: fan-out grows by four units and "each reviewer" becomes a magic key, but stays bounded with docstring examples
Inherited architect, decided by:
- Locality: `bin/loop_claude/cycle/prompts.py:43` `review_launches`: one launch sentence now needs `REVIEWS`' per-pass rows, `shared_launches` skipping them for an `"each reviewer"` key, and `lowered` putting them back, where the base was one loop over three rows
- Locality: `bin/loop_claude/cycle/prompts.py:78` `taken_in_launches`: compares the whole `review_rungs` dict, correct only by a rule enforced in `ladder.review_rungs`
- Locality: `bin/model_routing/ladder.py:71` `REPLAYED`: a hand-edited table, empty today, that overrides a pass's rung below the worker's under a combined E + I and worker condition; a second source of truth
- Shape: `bin/review_replay/main.py:208` `reviewed_in`: split into `copy_reports`, `redirected` and `clone_reviewed`, each with a docstring; `codes_found` and `pass_and_model` take inline loops and lambdas out of `main`
- Shape: `bin/rung_replay/command.py:16` `arguments_or_exit`: argument parsing is no longer hard-wired to one model, and `down_from(top, floor)` makes judge-replay's floor show at its call site
- Shape: `bin/rule_hook/reviewer_report.py:10` `REVIEWERS`: shares its name with `ladder.py`'s hand-kept dict of a different shape
Maintainability senior, decided by:
- Shape: `bin/loop_claude/cycle/prompts.py:14` `REVIEWS`: six rows built from `REVIEWERS`, a separate `"each reviewer"` entry, a `kind not in REVIEWERS` filter and a `lowered` list re-joined in two places, all serving an empty `REPLAYED`
- Shape: `bin/model_routing/ladder.py:69` `REVIEWERS`: two modules on one rule-hook call path each hold a `REVIEWERS` of a different type and meaning, where the base had one
- Shape: `bin/model_routing/ladder.py:104` `review_rungs`: fans out to every pass then overlays `REPLAYED` under a condition only a dense docstring paragraph explains; `taken_in_launches` compares whole dicts
- Locality: `bin/review_replay/main.py:208` `reviewed_in`: copy, rewrite and clone are named units, and the lambdas passed to `replayed` are named functions
- Locality: `bin/rung_replay/command.py:35` `down_from`: takes the floor as an argument, so each caller states its own floor where the base hid judge-replay's policy in the shared helper
Junior A, decided by:
- Locality: `bin/rule_hook/reviewer_rung.py:24` `reviewer_breaches`: the required rung comes straight from `review_rungs`, the function the prompts use, where the base passed it through an environment variable and a fallback
- Locality: `bin/rule_hook/reviewer_report.py:10` `REVIEWERS`: report confinement reads `agents/` itself, no longer importing its set from a module about rungs
- Locality, Shape: `bin/review_replay/main.py:208` `reviewed_in`: four jobs and seven arguments became named units with docstrings, and `main`'s loop and lambdas are named
- Navigation: `README.md:113`: the import map now names every reader of `model_routing/` and what `rung_replay/` holds, and the tool's name leads to it for any pass
- Shape: `bin/loop_claude/cycle/prompts.py:57` `shared_launches`: five helpers, a made-up `"each reviewer"` key and paths an empty `REPLAYED` never runs, against `ReviewKind` naming the real passes
## 2026-10-18T19:59:26Z, PR #324 at c713910, against e6223f7
Ruling: same
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | worse | better | same | same |
| Inherited architect | same | worse | better | same | same |
Mid A, decided by:
- Locality: `bin/larv_review/record.py:56` `rerank`: recording a scoring run now also rewrites the checkout's todo.md and can exit 1 on items under the bar, so changing record-scoring needs rank_todo.rank_file's whole contract, where the base only appended to the history
- Locality: `bin/rank_todo.py:338` `weigh`: an item's score now depends on docs/comprehension-history.md's newest scored commit and on a `## review opt-out:` title in docs/decisions.md, so scores and --check can change without anyone editing todo.md or README.md
- Shape: `bin/rank_todo.py:315` `ranked_goals`: the base's inline three-way weights branch in read_scoring is a named weigh, with the code-health and void rules in ranked_goals, each easier alone, at the cost of three similar names weigh, goal_weights and parse_weights
- Shape: `bin/rank_todo.py:623` `cited_goals_failure`: the base's parse_item mixed goal checks with writing R, and main inlined read, rank, write and print; each is now a unit with one purpose, and rank_file is reusable
- Shape: `bin/comprehension_history.py:130` `newest_scored`: the base's index arithmetic in latest_places is a named helper latest_overall shares, and overall_cells and FLOOR moved to the module that parses the table they read
Inherited architect, decided by:
- Locality: `bin/rank_todo.py:196` `read_all`: ranking now also depends on the newest scoring run in docs/comprehension-history.md, so a passing --check can fail with nobody touching todo.md, and nothing at the call site shows that a history append moves code health's weight
- Locality: `bin/larv_review/record.py:56` `rerank`: recording a scoring run now writes todo.md through rank_todo.rank_file, which prints its notes to stderr, and the message pointing at "the lines above" reads right only if rank_file printed first
- Locality: `bin/rank_todo.py:106` `OPTED_OUT`: ranking now matches a docs/decisions.md title spelled in larv-review's SKILL.md → "Opt-out", so rewording that heading silently changes whether rank_todo refuses a plan
- Locality: `bin/loop_claude/cycle/prompts.py:17` `AFTER_CODE_HEALTH`: the caveat that code health ranks first unless the README voids it is repeated in prose across about eight files, so one change to the shared goal edits all of them
- Shape: `bin/comprehension_history.py:130` `newest_scored`: replaces the base's index juggling in latest_places with two truthfully named predicates serving latest_places and latest_overall
- Shape: `bin/comprehension_history.py:145` `overall_cells`: FLOOR and overall_cells now have one home next to DIMENSIONS, and agreement's inline sort became the named scoring_runs
- Shape: `bin/rank_todo.py:332` `weigh`: weigh, cited_goals_failure and rank_file are pulled out of read_scoring, parse_item and main, each doing one thing
## 2026-10-18T19:59:40Z, PR #324 at c713910
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 5.5 | 6 | 6.5 | 6 |
| Mid A | 7 | 5.5 | 6 | 6.5 | 6 |
| Maintainability senior | 7 | 6 | 6.5 | 6.5 | 6.5 |
| Inherited architect | 7 | 6 | 6 | 7 | 6.5 |
| Mean | 7.00 | 5.75 | 6.13 | 6.63 | 6.25 |
Junior A, hardest first:
- `bin/model_routing/route.py:66` `Route.escalated_at`: the escalation mark lives in six units across four files, with judge_once stamping entries_read, escalation_mark, stepped and judge_prompt's STEP_LINE held at once
- `bin/loop_claude/loop/main.py:1` "loop-claude --help": a 164-line docstring is the loop's real spec, its routing paragraphs packing every rule into one block that routed and after_verdict need open
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: prompt sentences assembled from rung comparisons over replay-lowered passes, the project's rung, the top rung and higher E + I
- `bin/model_routing/route.py:13` `ROUTED`: stored state persisted as prose and parsed back by regexes in four places, so rewording one string silently changes routing
- `bin/rank_todo.py:568` `score`: a 660-line file carrying two table shapes, with OLD_SHAPE forks in scoring, weights, goal parsing and column checks
- `bin/chunk_pick.py:97` `standing`: five inputs become five outcomes, and chunk_pick.Finished shares its name with judge.Finished
- `bin/review_replay/rounds.py:73` `reviewed_path`: rebuilds the code a past reviewer read from prompt text and author times, a heuristic
- `bin/comprehension_history.py:159` `scored`: legacy formats from before PR #255 and #232 leak into the reading
Mid A, hardest first:
- `bin/loop_claude/routing.py:64` `stepped`: seven small functions, each defined through another, with six inputs held at once to predict one rung, and an import cycle shaping the signature
- `bin/loop_claude/loop/main.py:259` `after_verdict`: the 164-line docstring is the only full map of routing, and after_verdict chains it all in one expression
- `bin/loop_claude/cycle/run.py:45` `Cycle.stepped_from`: the route changes outside the state machine, cleared on every event but HumanTyped, so it outlives exactly one hop
- `bin/loop_claude/cycle/judge.py:216` `quotes_checked`: three bodies of text to check quotes against, fuzzy matching, and three ways a failed check is handled
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: fragments that each start with a space, so no whole prompt is visible without running it in your head
- `bin/model_routing/route.py:13` `ROUTED`: a saved string format parsed back by a verbose regex that still accepts an older format
- `bin/rank_todo.py:568` `score`: two table shapes share every path, the goal term W in one and V in the other
- `bin/loop_claude/loop/reload.py:43` `decoded_as`: a generic decoder with two sentinels and a duck-typed fits hook defined on Route
Maintainability senior, hardest first:
- `bin/loop_claude/routing.py:64` `stepped`: four things held at once, the unfinished count, the taken-in L, the escalation cap from item_rung and the mark threaded through judge.py's escalation_mark, STEP_LINE and Grounds.since_step
- `bin/model_routing/route.py:86` `Route.__str__`: the route written as English and parsed back by ROUTED and outcomes.workers, so a sentence's wording is a storage schema shared by four tools
- `bin/loop_claude/loop/main.py:1` "loop-claude --help": a 160-line spec whose routing paragraph carries about 15 rules, re-describing what routing.py, ladder.py and retry.py enforce
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: each sentence built conditionally with a leading-space convention, and taken_in_launches scanning every higher E + I
- `bin/loop_claude/cycle/judge.py:216` `quotes_checked`: three grounds with three failure consequences, and the demotion to an interrupt loses release_ready
- `bin/review_replay/rounds.py:73` `reviewed_path`: guesses which removed worktree a reviewer read, and redirected depends on the order of its replacements
- `bin/comprehension_history.py:150` `scoring_runs`: near-synonyms scored and scoring_runs differ only on a ruling from before PR #255
- `bin/rank_todo.py:332` `weigh`: the goal term is W or V by shape, so every scoring path asks which shape
Inherited architect, would restructure first:
- `bin/round_titles.py:4` `CAP`: no program loops the reviewers; the cap lives in SKILL.md prose and the code only counts rounds and prints a note
- `bin/git_command.py:16` `commits`: parses git commit messages for rule-hook while git_repo.py, rule_hook/git.py, larv_review/git.py and Effects.git each run git, and git_repo bypasses Effects
- `bin/transcript_archive/outcomes.py:39` `outcomes`: shares its name with score_outcomes/outcomes.py, which measures finished chunks instead
- `bin/loop_claude/routing.py:64` `stepped`: routing has four homes, ladder.py, route.py, routing.py and routing_check with routing_figures, and prompts.py restates the ladder as sentences
- `bin/rank_todo.py:196` `read_all`: a 658-line library as well as a tool, imported by rule_hook and larv_review, and now reading four documents, so a todo.md commit in any project depends on its comprehension history
- `bin/loop_claude/cycle/judge.py:68` `Reply.bundled`: the taken-in L is also called bundled, and the project's rung is also called anchor
- `bin/chunk_pick.py:97` `standing`: "next release" is computed two ways, here and in larv_review/plan.py's scoring_run_due, which may diverge after a rename
## 2026-10-18T19:59:40Z, PR #324 rerun at c713910
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 5.5 | 6.5 | 6 | 6 |
| Mid A | 7.5 | 6 | 6.5 | 7 | 6.5 |
| Maintainability senior | 7.5 | 6 | 6.5 | 6.5 | 6.5 |
| Inherited architect | 6.5 | 6 | 5.5 | 6.5 | 6 |
| Mean | 7.13 | 5.88 | 6.25 | 6.50 | 6.25 |
Junior A, hardest first:
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: the worker's English instructions built from how the worker's, the project's, the reviewers' and any replay-lowered rung relate, with ladder.review_rungs, REPLAYED and escalation_rungs open at once
- `bin/loop_claude/routing.py:64` `stepped`: seven small functions defined through each other, bundled learned only from judge.Reply, and escalated_at both an argument and a Route field with different meanings
- `bin/model_routing/route.py:13` `ROUTED`: routing state lives as English sentences in outcomes.md, read back by a regex, with the newest file by mtime deciding
- `bin/loop_claude/loop/main.py:1` "loop-claude --help": about 160 lines and the only full account of routing, step-ups, the archive layout, reloads and the routing figures in one unbroken paragraph
- `bin/loop_claude/cycle/run.py:69` `escalated`: stepped_from must survive a HumanTyped event and reset on every other, and archive_stepped writes one outcome or two depending on it
- `bin/loop_claude/cycle/judge.py:216` `quotes_checked`: three quote checks follow different rules, and an escalation that fails is silently dropped
- `bin/chunk_pick.py:97` `standing`: two separate notions of the next release and of work having landed, here and in larv_review/plan.py's scoring_run_due
- `bin/rank_todo.py:332` `weigh`: old-shape support forks behaviour throughout a 659-line file
Mid A, hardest first:
- `bin/model_routing/route.py:66` `Route.escalated_at`: the escalation mark is one concept spread over five files, the entry count, the injected step line, a double quote check and the cap from item_rung held at once
- `bin/loop_claude/cycle/run.py:69` `escalated`: state outside the state machine, cleared on every event but HumanTyped and read by ask, keep_answer and archive_stepped, depending on its order before transition
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: routing policy and English wording interleaved, much of the branching serving an empty REPLAYED
- `bin/loop_claude/loop/main.py:210` `run_loop`: the route passed as lazy thunks and re-derived every cycle, with an anchor-is-None branch in three places
- `bin/model_routing/route.py:86` `Route.__str__`: the archive's human-readable lines are what reruns, the routing figures and the replays parse back
- `bin/comprehension_history.py:150` `scoring_runs`: two near-identical predicates differing only for a ruling from before PR #255
- `bin/rank_todo.py:568` `score`: every rule exists twice for the old table shape
- `bin/review_replay/main.py:149` `code_of`: rebuilds which worktree a reviewer read by the first missing directory among its prompt's paths
Maintainability senior, hardest first:
- `bin/loop_claude/routing.py:64` `stepped`: seven one-line rung functions each defined by the others, four inputs held together, and an import cycle steering the interface
- `bin/loop_claude/cycle/judge.py:153` `escalation_mark`: the escalation mark spread over route.py, judge.py's Grounds and judge_prompt and run.py's escalated, and no single place states that one trigger buys one step
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: which conditional sentences reach which prompt means tracing fresh, routed_by, resumed, rungs_held and stepped_to
- `bin/loop_claude/loop/main.py:1` "loop-claude --help": the routing paragraph is one block covering the ladder, the judge, replays, rule-hook's variables, step rules, archive lines and legacy R + C
- `bin/model_routing/route.py:13` `ROUTED`: routing state survives restarts as English sentences parsed back by regex, a hidden contract across three packages
- `bin/rank_todo.py:218` `rank`: every stage branches on the old table shape, about half a 660-line file read and then discarded
- `bin/comprehension_history.py:130` `newest_scored`: four near-identical names over two concepts, split by a legacy case only the docstrings explain
- `bin/chunk_pick.py:97` `standing`: five inputs, three of which may be Failure, produce five outcomes, the order of the Failure checks carrying meaning
Inherited architect, would restructure first:
- `bin/round_titles.py:5` `PASSES`: the pass list lives in four places, PASSES, ladder.ReviewedPass, REVIEWERS and SKILL.md's table, kept in sync by hand
- `bin/rule_hook/rules.py:55` `round-title-counts`: no program blocks a fourth review round; rule-hook checks only the counts inside a round's title
- `bin/git_repo.py:8` `git`: bin/'s root holds about 43 entries, with 13 loose modules such as git_repo, git_command, chunk_pick and todo_table not grouped by purpose
- `bin/loop_claude/cycle/judge.py:68` `Reply.bundled`: the taken-in L and E + I are bundled in the judge's reply and taken in on Route and in routing.taken_in
- `bin/model_routing/route.py:86` `Route.__str__`: the archive's text format is written in two modules and parsed back by ROUTED, routing_figures, reading_cost, score_outcomes and judge_replay
- `bin/todo_table.py:89` `OLD_SHAPE`: the old todo.md shape is the largest dead weight in rank_todo.py
## 2026-10-21T18:16:09Z, PR #333 at 7c7a398, against fda48ac
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | same | better | better | better | better |
| Inherited architect | better | better | better | better | better |
Mid A, decided by:
- Locality, Shape: `bin/git_repo.py:22` `git`: now the one git runner, with a guarded flag and GUARD_SETTINGS giving each transport its own line and saying why, where four more wrappers each had their own failure text and decoding
- Shape, Locality: `bin/loop_claude/effects.py:16` `Git`: the effect returns str | Failure like everywhere else, removing checkout.py's try/except OSError and returncode handling
- Shape: `bin/rule_hook/git.py:7` `git`: a dense one-line GUARDS comprehension became a thin call with guarded=True whose docstring says why
- Self-sufficiency: `bin/rule_hook/rules.py:64` `OVERRIDE`: the new comment explains the lazy reason, the lookahead and the stripped -->
- Self-sufficiency: `CLAUDE.md:108` "Vocabulary": now defines judge's records, paired ruling, place, scoring run and seat
- Self-sufficiency: `bin/metric_bench/main.py:114` `run_scores`: a small pull the other way, the comment cites plan item 204
Inherited architect, decided by:
- Navigation, Shape, Overall: `bin/git_repo.py:22` `git`: four places that started git with differently worded errors now go through one function, and the hardening is one named list instead of a one-line comprehension
- Locality, Shape: `bin/loop_claude/effects.py:16` `Git`: Effects.git returns str | Failure, so checkout.py and review_replay drop their own exception and returncode conventions
- Locality: `bin/metric_bench/main.py:112` `run_scores`: what the tool does on bad input is stated in its help, not hidden in a private wrapper's errors="replace"
- Self-sufficiency: `CLAUDE.md:105` "Vocabulary": defines the comprehension terms the charter used without defining, and rules.py's OVERRIDE gains its explanation
- Self-sufficiency: `bin/metric_bench/main.py:114` `run_scores`: a small cost, "item 204's" points to a plan item a code reader can't resolve
- Locality: `bin/rule_hook/git.py:7` `git`: a small cost, the guards no longer sit beside the hook that needs them, though both docstrings say why
## 2026-10-21T20:20:12Z, PR #335 at 33645b0, against dec19c5
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | same | better | same | better |
| Inherited architect | better | same | better | same | better |
Mid A, decided by:
- Navigation, Shape: `skills/larv-review/SKILL.md:73` "Re-entry": one table now answers which passes a fix reruns, where five Trigger cells and three bullets did, with a worked example under it
- Shape: `skills/larv-review/SKILL.md:86` "What a round reviews": the round-2 scope left "Round cap", which now holds only counting and capping, as its name promises
- Locality: `bin/settings_filter.py:12` `cleaned`: hidden state, since the stored and the working file differ and a per-clone git setting turns the filter on, with an ordering rule for Update; it balances the Re-entry table's gain
- Self-sufficiency: `bin/settings_filter.py:2` module docstring: the tool explains itself, but the steps to run it live in README and AGENTS.md
Inherited architect, decided by:
- Navigation, Shape: `skills/larv-review/SKILL.md:73` "Re-entry": "which passes does this fix rerun" is answered in one table where it was split between Trigger-cell clauses and a Rerun bullet
- Shape: `skills/larv-review/SKILL.md:31` pass table's Trigger column: each cell now says only when the pass first runs
- Navigation: `skills/larv-review/SKILL.md:86` "What a round reviews": a named paragraph beside Re-entry, where a reader asking what round 2 looked at searches
- Locality: `.gitattributes:1` the settings filter: committed behaviour depends on an untracked per-machine git setting, and README's Install and Update steps work only in order
- Self-sufficiency: `bin/settings_filter.py:2` module docstring: the script stands alone, but cannot say it is inert unless Install's git config line ran
## 2026-10-22T18:56:17Z, PR #354 at 7042a75, against 6f58a0e5c25f37026c50b1dde77612464be26803
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | better | same | better | better |
| Inherited architect | better | better | same | better | better |
Mid A, decided by:
- Navigation, Locality: `bin/review_passes.py:7` `PASS_AGENTS`: the pass names lived in two files, one of them the routing ladder where nobody would look; one module named for its contents holds both now
- Navigation, Self-sufficiency: `bin/loop_claude/loop/main.py:53` `Routing: the worker's rung`: the 70-line routing paragraph is now headed parts a reader jumps to
- Navigation, Self-sufficiency: `bin/transcript_archive/__init__.py:1` "transcript_archive": the archive's file layout sits with the code that writes it, in place of loop-claude's help
- Locality: `bin/larv_review/plan.py:32` `landed_towards`: the next release is asked of `chunk_pick`, so the rule is written once
- Self-sufficiency: `bin/shell_command.py:33` `segments`: the new docstring lists each shell form it does not parse
- Self-sufficiency: `bin/git_repo.py:3` "git_repo": the module docstring says every tool starts git through it
Inherited architect, decided by:
- Navigation, Locality: `bin/review_passes.py:7` `PASS_AGENTS`: two unlinked pass lists became one table in a module named for it, so adding a pass is a single edit
- Locality: `bin/larv_review/plan.py:32` `landed_towards`: it reuses `chunk_pick`'s rule in place of its own, so the scoring-run trigger and chunk-preflight cannot disagree about the next release
- Locality: `bin/larv_review/ruling.py:38` `surplus`: the surplus-seat check is a named predicate called where the ruling is recorded, not hidden in `votes`
- Navigation: `bin/loop_claude/loop/main.py:53` `Routing: the worker's rung`: seven headed sections replace one 50-line routing paragraph
- Self-sufficiency: `bin/shell_command.py:33` `segments`: the docstring answers why rule-hook missed a git call
- Self-sufficiency: `bin/rule_hook/override_log.py:36` `this_chunks`: the case list maps each commit shape to its one-line return
- Self-sufficiency: `bin/larv_review/main.py:34` "larv-review --help": the help no longer states when work has landed, and points to `plan.py` instead
- Locality: `bin/score_outcomes/main.py:134` `read_outcomes`: whether a commit joins the chunk above depends on the previous iteration's state, with a positional `Chunk` tuple
- Locality: `bin/todo_table.py:137` `NoItemsTable`: every caller must test it before `Failure`, and swapping the checks silently changes the message
## 2026-10-22T20:32:06Z, PR #357 at 3f8e175, against 64023b5
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | better | better | same | better |
| Inherited architect | better | better | better | better | better |
Mid A, decided by:
- Locality, Shape: `bin/loop_claude/routing.py:67` `after_unfinished`: takes the verdict itself and owns the whole route after an unfinished verdict, where `stepped` took loose ints, explained an import-cycle workaround and left `taking_in` to the caller
- Locality, Navigation: `bin/loop_claude/loop/main.py:251` `run_loop`: `routed` returns a Route and `after_verdict` takes `Concluded`, so the off-ladder None and the `ended`/`before` juggling are gone and `archive_step` compares two records in one pass
- Navigation, Shape: `bin/loop_claude/verdicts.py:1` "verdicts": the verdict types left the long `cycle/judge.py` for a small module whose docstring says why it sits outside cycle/
- Shape: `bin/loop_claude/cycle/judge.py:69` `Reply.highest_likelihood_taken_in`: `bundled` gave no hint it carries an L; the new name does, and the verdicts are built by keyword
- Navigation, Shape: `bin/chunk_pick.py:50` `ReadyToCut`: no longer clashes with the judge's `Finished`
- Shape: `bin/chunk_pick.py:109` `next_release`: replaces the five-argument `standing` and is shared with larv_review's `landed_towards`; `Upcoming.is_earliest` needs its comment
- Locality: `bin/model_routing/route.py:74` `Route.record`: a typed JSON record replaces the prose that `ROUTED` parsed back, at the cost of a second, labelled read path
Inherited architect, decided by:
- Locality, Shape: `bin/loop_claude/routing.py:67` `after_unfinished`: takes the Unfinished verdict and does all the next route's work, the E + I intake included, where `stepped` took loose ints because of an import cycle
- Locality: `bin/loop_claude/loop/main.py:274` `after_verdict`: one call replaces the base's order-sensitive `ended` copy and `before` unpacking, and `archive_step` names both routes outright
- Shape: `bin/loop_claude/cycle/judge.py:122` `verdict_from`: verdicts built by keyword where positional calls met differing field orders, and `bundled` renamed to what it holds
- Navigation, Shape: `bin/chunk_pick.py:50` `ReadyToCut`: ends the two-`Finished` clash, and `next_release` splits the five-argument `standing`
- 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
+77 -29
View File
@@ -1,12 +1,10 @@
# Decisions
## larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension
## 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: an item that lifts the lowest dimension scores G 9, since the lowest dimension caps the overall and lifting it is worth the most to the floor. PR #257's scoring run found Shape lowest, at 6.25. The Shape items are `todo.md` items 114, 124 and 125. When PR #283 replaces G, the chunk that ships it carries this rule into the new score.
2026-10-16, PR #283: such an item moves each goal it cites by 9, in place of G 9. lilleman, answering that PR's review: such items compete with the others like any item, so they no longer rank first.
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.
## 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
@@ -72,12 +70,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 trigger names fixes like it; 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 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, 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.
@@ -90,9 +90,9 @@ Valid while the ladder orders its rungs by competence.
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
## 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. 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.
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
@@ -132,18 +132,32 @@ Valid while the ladder orders its rungs by competence.
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, each README achieve goal weighed by its position, the first heaviest, held to its bar, ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; the table's order is the plan's only order
## 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. An item under the bar is not kept; this repo's bar started at 10 and was set to 9 the same day, purging the 17 items under it. An Exempt cell keeps a row past the bar where a rule needs it kept. lilleman retired the two decisions whose plans the purge removed: the stats line in the transcript archive, and three benches before a workflow change merges. A finding under the bar is recorded nowhere, so a later review may raise it again, and the run rescores it. That costs one scoring; a ledger of dropped findings would regrow the list the bar caps. larv-review's "Round cap" → "Done" counts a finding named under the bar as settled, so one raised again holds no pass open. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale. The format is mandatory in every project, as the premises are (goal 1.3); the formula 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. A 🟡 against a technical principle is exempt as `principle`, because its audience value scores low and the bar would drop every one. A 🟢 against a principle is scored like any other finding. 2026-10-08, lilleman: the goal weights in `todo.md` depart from an even spread by position, which would weigh goal 4, leaking nothing, at 0.11. Valid while one human sets the bar and reads the ranking, and while the items marked `principle` stay few enough to rank.
2026-10-02, lilleman. Serves goal 1: findings were filed faster than chunks closed them, so the plan grew without telling what mattered. Each item is scored as `~/.claude/rules/todo-items.md` says; this repo's formula counts value highest and size least. 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-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 sum-reciprocal 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-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-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. The goal ranked k of n achieve goals in reading order weighs (1/k) / (1 + 1/2 + … + 1/n), the sum-reciprocal weight. 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-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-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 goal 1.4 as well as 1.1, since reading cost is measured in tokens per chunk; a goal of its own for readability is left for later. 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-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.
@@ -158,6 +172,10 @@ Three places carry the rule. `rules/todo-items.md` states it and loads with `tod
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.
@@ -226,13 +244,13 @@ Valid while the worker writes the tests that larv-review's reviewers hold to the
Each reviewer holds Write for its report. Claude Code passes a subagent's type to a PreToolUse hook as `agent_type`. So `bin/rule_hook/reviewer_report.py` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`; no marker overrides it. A reviewer's Bash, as stability-reviewer holds, is not confined.
The folder is fixed, since loop-claude's headless sessions have no scratchpad. It sits outside every checkout, so no project sees a report. It survives a reboot, unlike `/tmp`, so a resumed chunk still reads its earlier rounds. It is in the user's home, so no other local user plants a symlink that widens it. A report may quote a secret, so `larv-review review-folder`, which makes the chunk's folder, leaves `~/.local/state/larv-review` readable by the user alone.
The folder is fixed, since loop-claude's headless sessions have no scratchpad, and it also holds any other file a session parks outside its checkout, such as the comprehension panel's base worktree or a build probe's output. It sits outside every checkout, so no project sees a report. It survives a reboot, unlike `/tmp`, so a resumed chunk still reads its earlier rounds. It is in the user's home, so no other local user plants a symlink that widens it. A report may quote a secret, so `larv-review review-folder`, which makes the chunk's folder, leaves `~/.local/state/larv-review` readable by the user alone.
A chunk keeps its folder after the merge. `stability-replay` hands a replayed reviewer a copy holding only the reports written after the chunk began and before the round did. So the replay reads the earlier rounds its prompt names, never the findings it is to find. The chunk's own reports stay as they were.
A chunk keeps its folder after the merge. `review-replay` hands a replayed reviewer a copy holding only the reports written after the chunk began and before the round did. So the replay reads the earlier rounds its prompt names, never the findings it is to find. The chunk's own reports stay as they were.
Claude Code's own subagent prompt tells a subagent to return findings rather than write report files. `review-findings.md` → "Report" overrides that, since the file is the worker's input; a prose-reviewer probed on 2026-10-18 wrote the file its prompt named. A general-purpose wrapper that launches the reviewer was not tried: Claude Code's documentation says a subagent cannot start another.
Before this change, reports took a median 19k tokens per chunk, 8% of the worker's peak context, and lines carrying a severity mark were 9–24% of a report (2026-10-08, over 68 archived transcripts). `stability-replay` still counts each 🔴 and 🟡 by its line in the reviewer's reply, now a one-line summary. todo.md item 187 is to measure what the worker reads of the reports instead.
Before this change, reports took a median 19k tokens per chunk, 8% of the worker's peak context, and lines carrying a severity mark were 9–24% of a report (2026-10-08, over 68 archived transcripts). `review-replay` still counts each 🔴 and 🟡 by its line in the reviewer's reply, now a one-line summary. todo.md item 187 is to measure what the worker reads of the reports instead.
Valid while Claude Code passes `agent_type` to hooks inside a subagent. Without it, the rule refuses nothing, and a reviewer may write anywhere.
@@ -256,19 +274,21 @@ Valid while a mutation run on a chunk's changed lines stays cheap beside the rev
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 two rungs down, 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 these steps on 2026-10-16 as a first 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 them. A change to the ladder or the steps is lilleman's.
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, the seats and the security pass always on the project's
## 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.
Only chunks run below the project's rung can prove that a cheaper worker holds quality (goal 1.1). So on 2026-10-14 lilleman chose a trial on real chunks: a replay of past chunks would spend on work that never ships (goal 1.4). Review holds quality meanwhile. While the worker runs below the project's rung, loop-claude's prompt has it launch each comprehension seat and the security pass's subagent on the project's rung, and each reviewer there too unless the highest E + I among its items picks a higher rung, through the Agent tool's model and effort. The worker runs a full scan only from such a subagent, because the `claude-security` plugin's researchers and verifiers inherit the model that starts them. A subagent that cannot run the scan leaves it unavailable, so larv-review runs `/security-review` in its place. lilleman chose the project's rung, medium, knowing `settings.json` runs Opus 5.5 at xhigh, so a routed worker runs below the effort an interactive session takes.
Only chunks run below the project's rung can prove that a cheaper worker holds quality (goal 1.1). So on 2026-10-14 lilleman chose a trial on real chunks: a replay of past chunks would spend on work that never ships (goal 1.4). Review holds quality meanwhile. While the worker runs below the project's rung, loop-claude's prompt has it launch each comprehension seat and the security pass's subagent on the project's rung, and each reviewer there too unless the highest E + I among its items picks a higher rung or a replay lowered its pass, through the Agent tool's model and effort. The worker runs a full scan only from such a subagent, because the `claude-security` plugin's researchers and verifiers inherit the model that starts them. A subagent that cannot run the scan leaves it unavailable, so larv-review runs `/security-review` in its place. lilleman chose the project's rung, medium, knowing `settings.json` then ran every interactive session on Opus 5.5 at xhigh, so a routed worker ran below the effort an interactive session took.
While the worker runs above the project's rung, loop-claude's prompt has it launch the comprehension seats and the security pass's subagent on the project's rung too. So the seats score every chunk on one rung, and the security pass spends no more than the project chose. The prompt after each unfinished verdict repeats this, since a step-up may have taken the worker above the project's rung. The other reviewers never run below the worker's rung: a worker climbs because its chunk proved harder than its score said, which is when a cheaper reviewer is the bigger risk. A reviewer or seat that rules the work below standard may rerun one rung up: `review: a reviewer or comprehension seat that rules the work below standard`.
While the worker runs above the project's rung, loop-claude's prompt has it launch the comprehension seats and the security pass's subagent on the project's rung too. So the seats score every chunk on one rung, and the security pass spends no more than the project chose. The prompt after each unfinished verdict repeats this, since a step-up may have taken the worker above the project's rung. The other reviewers never run below the worker's rung while it runs above the project's: a worker climbs because its chunk proved harder than its score said, which is when a cheaper reviewer is the bigger risk. A reviewer or seat that rules the work below standard may rerun one rung up: `review: a reviewer or comprehension seat that rules the work below standard`.
On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on either side of the project's rung, which may lift them above both the worker's rung and the project's: how far a defect would escape, and what it would break, set how hard review must look (goal 1.1). loop-claude names that rung in the worker's prompt, and hands it to the worker's claude beside the project's and the worker's, so rule-hook holds each reviewer launch to it. A low E + I never steps a reviewer below the project's rung: lilleman chose to lower a pass only where a replay shows a lower rung finding every 🔴 and 🟡 the project's rung finds, which `todo.md` item 159 measures for each pass. An item the worker takes in beyond the routed one counts too, since its E + I scores its defects as the routed item's scores theirs. The worker's prompt names the reviewers' rung each higher E + I picks, so the worker reviews a taken-in item on it in the same run. The judge reports the highest E + I the worker states for a taken-in item. From the next cycle loop-claude routes on that E + I, and archives it with the route so a rerun keeps it.
On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on either side of the project's rung, which may lift them above both the worker's rung and the project's: how far a defect would escape, and what it would break, set how hard review must look (goal 1.1). loop-claude names that rung in the worker's prompt. It hands the E + I to the worker's claude beside the project's rung and the worker's, so rule-hook works out each review's rung as the prompt does and holds each launch to it. A low E + I never steps a reviewer below the project's rung: only a replay lowers a pass, as `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…` records. An item the worker takes in beyond the routed one counts too, since its E + I scores its defects as the routed item's scores theirs. The worker's prompt names the reviewers' rung each higher E + I picks, so the worker reviews a taken-in item on it in the same run. The judge reports the highest E + I the worker states for a taken-in item. From the next cycle loop-claude routes on that E + I, and archives it with the route so a rerun keeps it.
Valid until the trial on real chunks shows whether a worker below the project's rung holds quality.
@@ -310,15 +330,17 @@ Valid while the ladder orders its rungs by competence.
2026-10-15, lilleman asked for it. Serves goals 1.1 and 1.4: when the hard part is the rest of the chunk, handing it to subagents piece by piece leaves the worker, which reads and checks each of their diffs, on a rung that proved too low. The worker climbs only once its run records a trigger.
loop-claude's prompt offers the step beside the escalated subagent of `routing: a worker hands a task one rung up`, as long as the limit leaves a rung that subagent may take without the human's yes. The worker then ends its run asking loop-claude for a higher rung and naming the trigger. The judge quotes an earlier passage that shows the trigger fired, such as a review round's commit title or the worker's report of the failing test, never the request itself. The trigger must have fired since any earlier such request, so one trigger buys one step. The judge sees the worker's text and tool calls but no tool results, so the quote shows that the run recorded the trigger, not that a tool's output bears it out. loop-claude checks the quote word for word, as it checks a quoted answer, since stitched fragments can make up a trigger. Without such a quote, the rung holds. A misquote is no failure, since holding the rung is safe and three failures stop an unattended loop. The next cycle's prompt names the worker's rung, so the worker learns whether the step went through. When a quoted answer, or an interrupt the human answers on loop-claude's terminal, steps the worker up, the prompt that resumes it with the answer names the new rung, so the worker learns of the step sooner.
loop-claude's prompt offers the step beside the escalated subagent of `routing: a worker hands a task one rung up`, as long as the limit leaves a rung that subagent may take without the human's yes. The worker then ends its run asking loop-claude for a higher rung and naming the trigger. The judge quotes the earlier passage where the trigger fired, such as a review round's commit title or the worker's report of the failing test, never a later mention of it and never the request itself. The quoted passage must sit after the worker's last step-up, which loop-claude checks, so one passage buys one step. The judge sees the worker's text and tool calls but no tool results, so the quote shows that the run recorded the trigger, not that a tool's output bears it out. loop-claude checks the quote word for word, as it checks a quoted answer, since stitched fragments can make up a trigger. Without such a quote, the rung holds. A misquote is no failure, since holding the rung is safe and three failures stop an unattended loop. The next cycle's prompt names the worker's rung, so the worker learns whether the step went through. When a quoted answer, or an interrupt the human answers on loop-claude's terminal, steps the worker up, the prompt that resumes it with the answer names the new rung, so the worker learns of the step sooner.
A run that asks for a higher rung may also ask a question. The judge then interrupts, or quotes the answer from README.md or the records, and either ruling carries the escalation quote too, checked the same way. loop-claude steps the rung as the ruling comes in, before the human is asked or the worker resumes with the quoted answer, since the work after the answer is work the stepped rung should do. An interrupt or a quoted answer is no unfinished verdict, so it adds to no count. The judge may quote a different passage for the trigger that already stepped the rung, and loop-claude cannot tell that from a new trigger. So once an interrupt or a quoted answer has taken an escalation, no later ruling of that cycle carries one. A trigger that fires after the answer steps nothing in that cycle.
A run that asks for a higher rung may also ask a question. The judge then interrupts, or quotes the answer from README.md or the records, and either ruling carries the escalation quote too, checked the same way. loop-claude steps the rung as the ruling comes in, before the human is asked or the worker resumes with the quoted answer, since the work after the answer is work the stepped rung should do. An interrupt or a quoted answer is no unfinished verdict, so it adds to no count.
The judge may quote a different passage for the trigger that already stepped the rung, and loop-claude cannot tell from the quote alone whether the trigger is new. So it goes by where the quoted passage sits in the transcript. When an escalation steps the worker, the route marks how many transcript entries the session held: the mark. loop-claude then accepts an escalation quote only from the worker's own lines after the mark, never from its own prompts or the human's lines, which repeat earlier passages. The judge reads a `[step]` line at the mark saying the triggers before it are spent, so it quotes a passage the check accepts. The session's transcript only grows, so the mark holds across cycles. The trigger that bought a step, and any rewording of it before the mark, cannot buy another. A trigger that fires after the step steps the worker again, in the same cycle or a later one. One risk remains: a worker on the stepped rung may restate an old trigger after the mark, and the judge may quote that. The cap two rungs above the rung the item picks limits what this costs. Before the mark, once an interrupt or a quoted answer had taken an escalation, no later ruling of that cycle carried one, so a trigger that fired after the answer was lost. lilleman chose the mark on 2026-10-18 over two alternatives: lifting that rule when a worker run ended would have let one trigger buy two steps, and telling the worker its request was dropped would still have lost the step.
The step is one rung up from the rung the worker would otherwise hold: its own, or the rung an item the judge saw it take in picks, whichever is higher. It resets the count of unfinished verdicts, so the step every second one takes counts afresh; when both steps fall on one verdict, the worker steps once. It stops at the limit escalated subagents stop at, two rungs above the rung the chunk started on. Past that limit the rung holds: loop-claude takes no yes from the human between cycles, so a worker there asks the human for an escalated subagent instead. The judge keeps its rung, as `routing: on a model judge-replay covered` says.
The archive quotes the judge's passage under `Escalation:` in the unfinished verdict, the interrupt or the quoted answer. The step an unfinished verdict causes is archived after it. The step an interrupt or a quoted answer causes is archived with it, at once: the interrupt or answer names the rung the worker ran on until then, and a step-up archived beside it names the rung it runs on from then. So the routing figures charge each stretch to its own rung, and a loop that dies while the human answers resumes on the stepped rung. `bin/routing_figures/` counts none of these steps as an escalation by trigger, which it counts only from subagent prompts.
The archive quotes the judge's passage under `Escalation:` in the unfinished verdict, the interrupt or the quoted answer. The step an unfinished verdict causes is archived after it. The step an interrupt or a quoted answer causes is archived with it, at once: the interrupt or answer names the rung the worker ran on until then, and a step-up archived beside it names the rung it runs on from then. So the routing figures charge each stretch to its own rung, and a loop that dies while the human answers resumes on the stepped rung. Each archived worker line names the mark once there is one, so a resumed loop keeps it. `bin/routing_figures/` counts none of these steps as an escalation by trigger, which it counts only from subagent prompts.
Valid while the worker reports in its transcript the triggers that fired.
Valid while the worker reports in its transcript the triggers that fired, and while a chunk's session transcript only grows.
## 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
@@ -332,12 +354,38 @@ 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: the stability reviewer runs no lower than the project's rung while the worker runs below it, until `stability-replay` shows a lower rung finding every 🔴 and 🟡 the project's rung finds
## 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-15, lilleman proposed running the stability reviewer on the worker's rung; the replay that gates it is the agent's proposal. Serves goals 1.1 and 1.4: the stability pass is the only one that mutation-tests the changed lines, so a defect it misses may merge, and a cheaper reviewer saves money only where it misses nothing.
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.
`bin/stability-replay <model>` replays archived stability rounds on the code each reviewed, first on the project's rung, then on each rung below it, highest first, and stops at the first that misses a finding the project's rung found again. A rung qualifies only where it finds every such 🔴 and 🟡.
`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 🟡.
On 2026-10-15, `bin/stability-replay claude-opus-5-5` replayed the latest 10 rounds holding a 🔴 or 🟡, 40 findings in all, 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 🔴, so no rung below the project's rung qualifies, and Haiku 5.5, below Sonnet on the ladder, was not tried. So the stability reviewer runs where `routing: a chunk's worker runs on the rung its item's L picks` puts every reviewer: never below the project's rung while the worker runs below it.
`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.
Valid until a new model joins the ladder, or the archive holds rounds a new reviewer prompt produced: replay then.
The runs, each on the latest 10 rounds of Opus 5.5 projects that hold a 🔴 or 🟡:
- 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 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 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.
## 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.
## 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.
+138
View File
@@ -657,3 +657,141 @@ Read most (opens and searches):
## Reading cost, chunk d905b642140f, finished 2026-10-18T08:20:12Z
187066 new input tokens before the first commit.
## Reading cost, chunk e7a12c46be6e, finished 2026-10-18T09:10:49Z
115559 new input tokens before the first commit.
## Reading cost, chunk b897b24d5e70, finished 2026-10-18T11:15:04Z
87043 new input tokens before the first commit.
## Reading cost, chunk 9f9579dd30bb, finished 2026-10-18T12:17:04Z
163028 new input tokens before the first commit.
## Reading cost, chunk 9fdabb34de02, finished 2026-10-18T17:00:58Z
416077 new input tokens before the first commit.
Read most (opens and searches):
- `rules/decisions.md` 1
## Reading cost, chunk 299b4aa74f32, finished 2026-10-21T16:53:41Z
250555 new input tokens before the first commit.
## Reading cost, chunk 5a330b55cc88, finished 2026-10-21T17:22:55Z
230039 new input tokens before the first commit.
## Reading cost, chunk a346f6f10ff4, finished 2026-10-21T18:16:55Z
92718 new input tokens before the first commit.
Read most (opens and searches):
- `rules/todo-items.md` 1
## Reading cost, chunk dd5ad8ab4fdf, finished 2026-10-21T18:27:48Z
58208 new input tokens before the first commit.
## Reading cost, chunk 14bbaa6d288c, finished 2026-10-21T20:23:13Z
78001 new input tokens before the first commit.
Read most (opens and searches):
- `rules/decisions.md` 1
## Reading cost, chunk 14a854b3a90e, finished 2026-10-21T20:29:57Z
54018 new input tokens before the first commit.
Read most (opens and searches):
- `CLAUDE.md` 1
## Reading cost, chunk b1320916dd31, finished 2026-10-21T20:42:34Z
50910 new input tokens before the first commit.
Read most (opens and searches):
- `rules/todo-items.md` 1
## Reading cost, chunk b4afdc174f9a, finished 2026-10-21T22:28:38Z
151079 new input tokens before the first commit.
Read most (opens and searches):
- `bin/model_routing/ladder.py` 2
- `bin/score_outcomes/main.py` 2
- `todo.md` 2
- `bin/routing_figures/measure.py` 1
- `bin/score_outcomes/outcomes.py` 1
- `docs/decisions.md` 1
## Reading cost, chunk 4527b73a80f1, finished 2026-10-21T22:42:41Z
63554 new input tokens before the first commit.
## Reading cost, chunk 4ac79cd68d51, finished 2026-10-21T22:53:11Z
53393 new input tokens before the first commit.
Read most (opens and searches):
- `skills/larv-review/SKILL.md` 1
## Reading cost, chunk 6a3cc045298a, finished 2026-10-21T23:12:09Z
96259 new input tokens before the first commit.
Read most (opens and searches):
- `rules/decisions.md` 1
## Reading cost, chunk d69472f986e3, finished 2026-10-21T23:32:33Z
73910 new input tokens before the first commit.
## Reading cost, chunk e78792eec4a6, finished 2026-10-22T00:08:00Z
71637 new input tokens before the first commit.
## Reading cost, chunk 6b16b3b2e832, finished 2026-10-22T00:24:58Z
61875 new input tokens before the first commit.
## Reading cost, chunk c4c29834104a, finished 2026-10-22T11:03:14Z
81812 new input tokens before the first commit.
## Reading cost, chunk d8a7f2b6f64c, finished 2026-10-22T11:13:16Z
76260 new input tokens before the first commit.
## Reading cost, chunk 796f17403d2e, finished 2026-10-22T17:58:21Z
122986 new input tokens before the first commit.
## Reading cost, chunk a91c10247935, finished 2026-10-22T18:13:46Z
183925 new input tokens before the first commit.
Read most (opens and searches):
- `skills/larv-review/SKILL.md` 3
- `rules/todo-items.md` 2
## Reading cost, chunk fc21489c7990, finished 2026-10-22T18:57:09Z
55808 new input tokens before the first commit.
## Reading cost, chunk 1034c157d8d2, finished 2026-10-22T19:29:13Z
100386 new input tokens before the first commit.
+7 -1
View File
@@ -73,8 +73,14 @@
* Deterministic order wherever order carries no meaning.
- Sort such a list, on a key that does not move: the name a line introduces, never where it came from. Exception: `id` goes first. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to.
- An import sorts on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group.
* About seven things per level, so a reader new to the project can take in each level at once.
- A level is what a reader looks at together: the parameters of a function and its branches (cyclomatic complexity), the methods of a class, the files in a folder and the folders beside them, the sections of a document, the components of a system, the hops of a call chain. Past about seven, group the things under names a reader can follow; each group then counts as one.
- Parameters, branches and the values a function tracks act on each other, so a reader holds them in mind together, and a mind holds about four. Aim for four or five of them, and treat seven as the ceiling. Keep a function to one screen, about 24 lines of 80 characters.
- Things a reader finds by name may run far past seven: 100 files named by locale, the cases of an enum, a reference list. A predictable name and a sorted order serve them better than a group would.
- Each added level makes a reader open one more folder, file or function to find a thing, so a split must save more than it costs. Keep eight, nine or ten things in one level when splitting them would add more names, files or jumps than it removes. Say why where the level is declared: a comment, the folder's README.
- Group by what a reader would name: a feature, a step, what changes together. BANNED: `misc/`, `part2()` or a parameter object that exists only to bring a count down. GOOD: `invoices/`, `payments/`, `reports/`, each holding what changes together; `locales/` holding `de.json` to `zh.json`, flat.
- Crossing a limit asks for one of two answers, never a split at any cost: group the things, or record why they stay. Keep a limit only while the comprehension panel's readers (`~/.claude/skills/comprehension-panel/`) find the code it flags hard.
* Keep It Simple, Stupid (KISS): keep solutions simple, so a reader new to the project understands each part on one read.
- Keep a size or complexity limit only while the comprehension panel's readers (`~/.claude/skills/comprehension-panel/`) find the code it flags hard.
* Don't Repeat Yourself (DRY) is a guide, not an absolute rule. It aims at one authoritative home per piece of knowledge, one obvious way per need. Before applying it, ask whether the code would be easier to understand, easier to reason about, or easier to maintain if DRY were broken; if so, break it, so long as the spellings cannot disagree (below). A surface people write — a template, data, an API — may accept a second spelling where that makes it easier to use.
- A value, rule, definition or concept lives in one place, and everywhere else derives it from there or points at it. A copy that can drift is a second spelling: derive it from its owner, or, for config a human writes, reject it where it is read and name the owner.
- Before adding a way to do something, find the existing one and use it. The same goes for tests: extend an existing test with an assertion before writing a new one. Where two spellings serve the same caller for the same need, keep one and reject the other as early as possible — at load, parse or compile — with an error naming the one to use: `token {p} renders a level that {p.first} reads a path into; name the fields you want instead`. A second spelling that makes a surface people write easier to use stays (above).
+2
View File
@@ -7,4 +7,6 @@ paths:
- **Goals** state the project's aim and intent, not promises: one numbered line each, like slogans, in priority order; a sub-goal is indented under its goal — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal names no step of the work, such as a check to run first, and rarely an implementation. How a goal is met goes in a method section further down the README and names the goal it serves. BANNED as a goal: `Kill weak candidates early, with the cheap checks first.` GOOD: the goal `Keep research on a budget, so it scales in both time and cost.`, with the cheap checks moved to the method section, naming that goal.
- **Mark each goal `**Maintain:**` or `**Achieve:**`.** A maintain goal is a state to hold: a change that breaks it is redesigned or dropped, whatever its value to other goals. An achieve goal is a direction to pursue, weighed against the other achieve goals. Under each achieve goal, three indented bullets: `Signal:` what moving towards it looks like, `Counter-signal:` what shows it is bought at a wrong price, and `Why:` one line on how the two connect. A goal with sub-goals states its own signal. A maintain goal has no bullets. BANNED: an unmarked goal; an achieve goal with no signal; `**Achieve:** Delivery speed.` with the signal `faster`. GOOD: `**Achieve:** Delivery speed.` with `Signal: hours from a chunk's start to its merge fall.`, `Counter-signal: 🔴 findings per chunk rise.` and `Why: speed bought by skipping review shows up as defects.`
- **Leave code health out of the README.** `~/.claude/CLAUDE.md` → "Shared goal" states it for every project, ranked first, and says when and how a README voids it. File an item to drop a README goal that restates it: the goals after it renumber, and every Moves cell and decision citing them must follow.
- **Audience** names who depends on the project and what they may rely on.
- **Every project's audience includes the contributor**: the person who reads the code to change it. The README doesn't list them, and drops them only with the `**Void:** code health` line (`~/.claude/CLAUDE.md` → "Shared goal").
+1 -1
View File
@@ -20,7 +20,7 @@ paths:
| 5 | — | — | irreversible: data lost for good, or a one-way door |
- **I's reach counts every project and session that runs the change.** A change to a hook or a tool that every session runs is I level 3, every consumer affected, even where one person uses it.
- **Name in Moves each achieve goal in `README.md` → `## Goals` the item moves, and how far,** from 1 to 10, judged by its value to the audience in `## Audience`: `1.1 by 8, 1.2 by 5`. Name the most specific goal it moves, and a parent goal only for a move none of its sub-goals covers, never beside its own sub-goal. Leave out every maintain goal, which vetoes, except on an item marked `defect` that restores it: name that goal, and how much of it is broken. `rank_todo.py --help` says how it weighs each goal.
- **Name in Moves each achieve goal in `README.md` → `## Goals` the item moves, and how far,** from 1 to 10, judged by its value to the audience in `## Audience`: `1.1 by 8, 1.2 by 5`. Where the item moves code health, the goal in `CLAUDE.md` → "Shared goal", name it as in `code health by 6`, unless the README voids it. Name the most specific goal it moves, and a parent goal only for a move none of its sub-goals covers, never beside its own sub-goal. Leave out every maintain goal, which vetoes, except on an item marked `defect` that restores it: name that goal, and how much of it is broken. `rank_todo.py --help` says how it weighs each goal.
- **A table with C, A, G and Goals in place of L, E, I and Moves is in the old shape.** Reshaping it is the project's only work until done, as `CLAUDE.md` → "Working loop" says, and `rank_todo.py` says how. Until then, A is the item's value to the audience and G its value to the goals it cites.
- **Score L, E and I against the project's anchors, and check every score against finished chunks.** Guess the scores, then run `~/.claude/bin/score-outcomes <L> <E> <I> <S>` in the project. It lists the finished items guessed nearest and the project's anchors, the shipped items its `docs/score-anchors.md` names for each level, 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. Compare the item with each anchor in turn: is it more or less likely to hold a defect, to let one escape, or to do damage? Give it the level whose anchors it matches; where a level has no anchor, judge by the level's words in the table above. Set S to the value guessed for the finished items whose outcome matches what you expect of this one. Keep your guess when no listed item resembles the one you are scoring.
- **Anchor each level of L, E and I with two or three items the project shipped,** in `docs/score-anchors.md`: a table whose Level column names a level, such as `L 1`, and whose Items column lists the anchors' IDs, such as `12, 14`. Choose an L anchor whose chunk, as `score-outcomes` measured it, fits the level's words: its lines changed and the components it touched. Choose an E or I anchor by the level's words and what followed its release, since no tool measures either yet. Leave out a level no shipped item shows. Replace a level's anchors when the items scored at it turn out about ten times more likely, or ten times less likely, than its words say: to hold a defect, to let one escape, or to do damage.
+28 -29
View File
@@ -1,63 +1,62 @@
{
"env": {
"CLAUDE_SECURITY_SCAN_TIP": "off"
},
"attribution": {
"sessionUrl": false
},
"includeCoAuthoredBy": false,
"permissions": {
"defaultMode": "auto",
"additionalDirectories": [
"~/.local/state/larv-review",
"~/code"
]
},
"model": "opus",
"awaySummaryEnabled": false,
"disableClaudeAiConnectors": true,
"statusLine": {
"type": "command",
"command": "~/.claude/bin/statusline.py",
"refreshInterval": 30
},
"effortLevel": "xhigh",
"enabledPlugins": {
"claude-security@claude-plugins-official": true,
"code-review@claude-plugins-official": true,
"frontend-design@claude-plugins-official": false,
"rust-analyzer-lsp@claude-plugins-official": true,
"code-review@claude-plugins-official": true
"rust-analyzer-lsp@claude-plugins-official": true
},
"env": {
"CLAUDE_SECURITY_SCAN_TIP": "off"
},
"extraKnownMarketplaces": {
"claude-plugins-official": {
"source": {
"source": "github",
"repo": "anthropics/claude-plugins-official"
"repo": "anthropics/claude-plugins-official",
"source": "github"
}
}
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Edit|MultiEdit|Write|Agent",
"hooks": [
{
"type": "command",
"command": "~/.claude/bin/rule-hook",
"timeout": 30
"timeout": 30,
"type": "command"
}
]
],
"matcher": "Bash|Edit|MultiEdit|Write|Agent"
}
]
},
"effortLevel": "xhigh",
"includeCoAuthoredBy": false,
"mcpServers": {},
"modelSettings": {
"claude-fable-5-1": {
"effortLevel": "high"
}
},
"awaySummaryEnabled": false,
"tui": "fullscreen",
"permissions": {
"additionalDirectories": [
"~/.local/state/larv-review",
"~/code"
],
"defaultMode": "auto"
},
"skipDangerousModePermissionPrompt": true,
"skipWorkflowUsageWarning": true,
"statusLine": {
"command": "~/.claude/bin/statusline.py",
"refreshInterval": 30,
"type": "command"
},
"theme": "dark",
"mcpServers": {}
"tui": "fullscreen"
}
+3 -1
View File
@@ -103,7 +103,9 @@ section gets it at its first scoring run or paired ruling.
A paired ruling asks whether a change makes a project read better, the same or worse. Each seat
reads both versions, so what the two versions share cannot move the ruling. Check out the older
version as a detached worktree in your scratchpad, and remove it afterwards. Build each seat's
version as a detached worktree in a folder you make under the chunk's review folder
(`~/.claude/bin/larv-review review-folder` prints it), and remove the worktree and that folder
afterwards. Build each seat's
prompt from `seat-prompts.md` → "Paired ruling"; the seats and the rule for adding one are the
caller's.

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