Compare commits

...

415 Commits

Author SHA1 Message Date
lilleman c2d72c97c6 Record the comprehension check: paired ruling better 2026-10-28 18:54:30 +01:00
lilleman f1d749e0f5 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); the round 1 answers stand 2026-10-28 18:49:39 +01:00
lilleman b1f89a9952 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); the round 1 answers stand 2026-10-28 18:49:39 +01:00
lilleman 382ebde51e Answer principles round 2: 0 🔴, 0 🟡 (0 misread); the round 1 answers stand 2026-10-28 18:47:46 +01:00
lilleman 29e055584c Answer prose round 1: 0 🔴, 4 🟡 (0 misread); reword the time comments, the docstring and the changelog sentence 2026-10-28 18:47:39 +01:00
lilleman 9fc1392bc8 Answer stability round 1: 0 🔴, 3 🟡 (0 misread); test the flush and a leading indent, and the stamped transcript line 2026-10-28 18:47:39 +01:00
lilleman c583900199 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); stamp the transcript and trust lines through say 2026-10-28 18:47:39 +01:00
lilleman 6e171fe2c0 Answer principles round 1: 0 🔴, 2 🟡 (0 misread); move say beside Effects and drop a clock comparison from the black-box test 2026-10-28 18:40:24 +01:00
lilleman 4d40cc81bc Answer architecture round 2: 0 🔴, 1 🟡 (0 misread); expect the usage-limit time with seconds in the black-box test 2026-10-28 18:35:09 +01:00
lilleman 08855e8055 Answer architecture round 1: 1 🔴, 2 🟡 (0 misread); render the stamp through Effects.local_time 2026-10-28 18:33:31 +01:00
lilleman 43e7e96b41 Open every line loop-claude prints with the machine's local time 2026-10-28 18:30:24 +01:00
lilleman 9014fd0a2c Merge pull request 'Give each review pass at most two rounds per chunk, with no third round and no ask for one' (#390) from item-246 into main 2026-10-28 18:22:16 +01:00
lilleman 3927dc280c Record the comprehension check: paired ruling better 2026-10-28 18:22:06 +01:00
lilleman 3ef47907d0 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); say none found where the branch lists no round commits 2026-10-28 18:17:04 +01:00
lilleman d3fd16d4ed Answer stability round 2: 0 🔴, 0 🟡 (0 misread); approved 2026-10-28 18:17:04 +01:00
lilleman f7b448ccbf Answer principles round 3: 0 🔴, 1 🟡 (0 misread); offer --amend only where the round commit is the newest 2026-10-28 18:13:46 +01:00
lilleman cd7926b5ad Answer prose round 1: 0 🔴, 7 🟡 (0 misread); fix the CAP comment, help, decision and AGENTS.md wording 2026-10-28 18:10:57 +01:00
lilleman 18d0bb6b6d Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); file security findings from late auto-reviews, and say how to commit fixes the cap refuses 2026-10-28 18:10:57 +01:00
lilleman 365b0f82a6 Answer stability round 1: 0 🔴, 3 🟡 (0 misread); pin the guarded default-branch reads and which commit an amend drops, and name the pass and its counted commits in the refusal 2026-10-28 18:10:57 +01:00
lilleman 720ffd58b6 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-10-28 17:55:00 +01:00
lilleman 9240cd68ea Answer principles round 2: 0 🔴, 0 🟡 (0 misread); approved 2026-10-28 17:55:00 +01:00
lilleman 4f831316d2 Answer principles round 1: 1 🔴, 1 🟡 (0 misread); count a fixed finding at the cap as done, and keep the Stage 0 rerun in its round 2026-10-28 17:54:03 +01:00
lilleman 865f5b0306 Answer architecture round 2: 0 🔴, 0 🟡 (0 misread); approved 2026-10-28 17:48:42 +01:00
lilleman fe975488ec Answer architecture round 1: 1 🔴, 2 🟡 (0 misread); read the branch's round titles and default branch one way for rule-hook and round-count 2026-10-28 17:47:41 +01:00
lilleman 0254e427f2 Give each review pass at most two rounds per chunk, with no third round and no ask for one 2026-10-28 17:37:09 +01:00
lilleman 47a40757c3 Merge pull request 'Block a read of file lines already in the agent's context, unless a compaction dropped them or the file changed' (#387) from item-239 into main 2026-10-28 17:31:31 +01:00
lilleman fc5e463594 Record the comprehension check: paired ruling same against cde7720; file item 250 for the repeat-read seam the seats found hard 2026-10-28 17:24:54 +01:00
lilleman 0447f2e07a Record lilleman's no to a fourth principles round in item 246 2026-10-28 17:14:41 +01:00
lilleman 155dedcf5c Merge remote-tracking branch 'origin/main' into item-239
# Conflicts:
#	todo.md
2026-10-28 14:58:17 +01:00
lilleman 312a8b590d Answer product-owner round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-28 14:57:47 +01:00
lilleman e9e130cb77 Answer stability round 3: 0 🔴, 0 🟡 (0 misread); keep the Edit-refusal comment above the tests it explains 2026-10-28 14:57:43 +01:00
lilleman f4a2ea823d Answer stability round 2: 0 🔴, 2 🟡 (0 misread); test calls that neither read nor write, a change in the read's millisecond, and the change stamp's format 2026-10-28 14:55:19 +01:00
lilleman dd90d109fd Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); say that a Read goes through until the agent read the file with Read 2026-10-28 14:41:52 +01:00
lilleman e68100b35e Answer principles round 3: 0 🔴, 0 🟡 (0 misread); drop the test's pin on the block's wording 2026-10-28 14:17:59 +01:00
lilleman 53459014a4 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); reword repeat-read's docstrings, changelog and test names 2026-10-28 14:14:55 +01:00
lilleman 5ea156a67b Answer product-owner round 1: 1 🔴, 1 🟡 (0 misread); let a Read through once the file changed after the last Read or write, and reword the changelog 2026-10-28 14:14:54 +01:00
lilleman b1a90abff4 Answer stability round 1: 1 🔴, 8 🟡 (0 misread); read only a regular file, only as far as the shown lines, skip cut-short output, and test the surviving mutants 2026-10-28 14:14:53 +01:00
lilleman e41f4e0979 Answer principles round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-28 13:06:52 +01:00
lilleman 71e2e0f893 Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-28 13:05:01 +01:00
lilleman 488d9b0eee Answer principles round 1: 0 🔴, 2 🟡 (0 misread); kill the surviving mutants and split repeat-read's tests to one behaviour each 2026-10-28 13:05:00 +01:00
lilleman 8602b8a7ee Answer architecture round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:53:26 +01:00
lilleman 248e46f616 Answer architecture round 1: 2 🔴, 2 🟡 (0 misread); move transcript parsing into claude_code and keep repeat_read pure 2026-10-28 12:52:34 +01:00
lilleman d583f8d48c Merge pull request 'Reword the note that prose findings stay' (#389) from item-246-prose into main 2026-10-28 12:47:46 +01:00
lilleman f5afc7f6d3 Reword the note that prose findings stay 2026-10-28 12:47:43 +01:00
lilleman 058804bb13 Merge pull request 'File items 246 and 247: cap review at two rounds, count escaped defects; record that prose findings stay' (#388) from item-246 into main 2026-10-28 12:47:36 +01:00
lilleman 592a6052fe File items 246 and 247: cap review at two rounds, count escaped defects; record that prose findings stay 2026-10-28 12:47:33 +01:00
lilleman 1d2f3d14d2 Sort repeat_read's imports and keep its sed range's names apart 2026-10-28 12:44:18 +01:00
lilleman 2d3ec3a636 Block a read of file lines already in the agent's context, unless a compaction dropped them or the file changed 2026-10-28 12:43:46 +01:00
lilleman 37df9b7805 Append the reading-cost figure 2026-10-28 12:43:46 +01:00
lilleman cde7720750 Merge pull request 'Run the tests once, on the latest stable Python, in one heavy slot's four workers' (#386) from item-245 into main 2026-10-28 12:36:56 +01:00
lilleman b2aa02eb22 Record the comprehension check: paired ruling same 2026-10-28 12:36:47 +01:00
lilleman 722dd5e451 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:33:34 +01:00
lilleman d371869f4a Answer stability round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:33:34 +01:00
lilleman 4193165c5d Answer prose round 1: 0 🔴, 2 🟡 (0 misread); put the Test command first, rewrite the changelog entry 2026-10-28 12:33:34 +01:00
lilleman 17fb0ac247 Answer principles round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:29:32 +01:00
lilleman 6ca9b4a2e7 Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:28:57 +01:00
lilleman dd4bcbd1c4 Answer principles round 1: 0 🔴, 3 🟡 (0 misread); type-check every tool for README's Python, check the worker count, pin pytest 2026-10-28 12:28:57 +01:00
lilleman 084d763412 Answer architecture round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-28 12:21:34 +01:00
lilleman d57727ec39 Answer architecture round 1: 0 🔴, 2 🟡 (0 misread); run the tests in one heavy slot's four workers, pin pytest 2026-10-28 12:21:08 +01:00
lilleman 53e663c8f8 Run the tests once, on the latest stable Python, across the CPUs 2026-10-28 12:17:05 +01:00
lilleman d7806d0b16 Merge pull request 'Report the routing figures in dollars, cache reads included, from the cost each archived run records' (#382) from item-234 into main 2026-10-28 12:10:30 +01:00
lilleman b086e7bf2a Say the routing figures now count the compaction dollars in item 235's detail 2026-10-28 12:07:03 +01:00
lilleman b6548d32e6 Merge remote-tracking branch 'origin/main' into item-234
# Conflicts:
#	todo.md
2026-10-28 12:06:47 +01:00
lilleman 6c059e0545 Answer principles round 4: 0 🔴, 0 🟡 (0 misread); drop a no-op slice in a test, keep the local defaultdicts 2026-10-28 12:06:23 +01:00
lilleman f6f21fc38c Merge pull request 'File item 245: run the tests once, on the latest stable Python, across the CPUs' (#385) from item-245 into main 2026-10-28 12:05:08 +01:00
lilleman b7cadb328e File item 245: run the tests once, on the latest stable Python, across the CPUs 2026-10-28 12:05:06 +01:00
lilleman 14ed4f9cdc Type the dollars as floats so mypy passes 2026-10-28 12:01:30 +01:00
lilleman 7daa3268da Merge pull request 'File item 244: stamp each line loop-claude prints with local time' (#384) from item-244 into main 2026-10-28 11:47:50 +01:00
lilleman 83171df2ce File item 244: stamp each line loop-claude prints with local time 2026-10-28 11:47:45 +01:00
lilleman 9b089d3c30 Merge remote-tracking branch 'origin/main' into item-234 2026-10-28 11:44:37 +01:00
lilleman 9d888c9e47 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 11:44:37 +01:00
lilleman 12e3d4ffa6 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 11:44:37 +01:00
lilleman 67e4b36dfd Answer prose round 1: 0 🔴, 7 🟡 (0 misread); reworded the comments, the intro and the changelog entry, fixed in the stability answer 2026-10-28 11:43:46 +01:00
lilleman c37c80297e Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); the intro says where a missing transcript's cost lands, fixed in the stability answer 2026-10-28 11:43:46 +01:00
lilleman 69f05a8c3c Answer stability round 1: 1 🔴, 2 🟡 (0 misread); keep f-strings 3.11-valid, count Agent calls without a transcript across subagents, pin the undated message's rung 2026-10-28 11:43:46 +01:00
lilleman bb3eb4fac6 Answer principles round 3: 0 🔴, 2 🟡 (0 misread); count lacking subagents by launches less transcripts and say the cost lands mostly on the worker 2026-10-28 11:29:01 +01:00
lilleman 7c5af45aaf Answer principles round 2: 0 🔴, 1 🟡 (0 misread); count the launched subagents the archive has no transcript of 2026-10-28 11:27:58 +01:00
lilleman 0c1e92943a Answer principles round 1: 0 🔴, 3 🟡 (0 misread); name Spent, derive cache-write prices, say a missing subagent's cost lands on the held messages 2026-10-28 11:26:12 +01:00
lilleman 6917092fd7 Merge pull request 'File item 243: answer every waiting loop-claude from one terminal app' (#383) from item-243 into main 2026-10-28 11:24:52 +01:00
lilleman 499b111071 File item 243: answer every waiting loop-claude from one terminal app 2026-10-28 11:24:40 +01:00
lilleman e83ed096c4 Report the routing figures in dollars, cache reads included, from the cost each archived run records 2026-10-28 11:21:15 +01:00
lilleman dac60ccf7b Merge pull request 'Record lilleman's choice to try one principles auditor despite the trial's two misses' (#381) from item-233 into main 2026-10-28 11:14:28 +01:00
lilleman d6ff9e26b5 Answer prose round 2: 0 🔴, 2 🟡 (0 misread); split the sentence and stop implying code health had its own auditor 2026-10-28 11:14:24 +01:00
lilleman 64a7242139 Record lilleman's choice to try one principles auditor despite the trial's two misses 2026-10-28 11:13:07 +01:00
lilleman 22265be7fd Merge pull request 'Run one principles-auditor per round for the goals and every principles file that applies' (#380) from item-233 into main 2026-10-28 10:16:32 +01:00
lilleman 31edfe0c37 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 10:16:25 +01:00
lilleman efa98dae4a Answer stability round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 10:16:25 +01:00
lilleman c31f367771 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); define a yardstick in the auditor, name the one auditor plainly in the decision's title, split and correct the trial paragraph, explain the old pass in the changelog, and name the split in item 242's tagline 2026-10-28 10:16:21 +01:00
lilleman 3af346ef75 Answer principles round 2: 0 🔴, 0 🟡 (0 misread); have item 242 also split the tests that check several behaviours 2026-10-28 10:10:10 +01:00
lilleman 9bb27ce493 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 10:08:57 +01:00
lilleman 3833c91bc0 Answer principles round 1: 0 🔴, 2 🟡 (0 misread); make the decision's validity checkable by a replay, name one auditor in its title, file item 242 for loops without subTest 2026-10-28 10:08:57 +01:00
lilleman d9b4939b99 Refresh item 155 with the latest reading-cost figures 2026-10-28 10:04:04 +01:00
lilleman 27e61c4c9d Run one principles-auditor per round for the goals and every principles file that applies 2026-10-28 10:03:54 +01:00
lilleman ba5fc55539 Record the reading cost of the last chunk 2026-10-28 10:03:53 +01:00
lilleman 31e363a469 Merge pull request 'Have the worker enter the chunk's worktree before the security pass, so the skill scans the branch's diff' (#379) from item-238 into main 2026-10-28 09:48:01 +01:00
lilleman debabc40fd Answer prose round 1: 0 🔴, 1 🟡 (0 misread); enter the worktree in §2, before the first pass 2026-10-28 09:46:06 +01:00
lilleman 44974bcd02 Have the worker enter the chunk's worktree before the security pass, so the skill scans the branch's diff 2026-10-28 09:43:39 +01:00
lilleman ecff799cb6 Merge pull request 'Record in the comment at UNFINISHED_LIMIT that the human confirmed 6' (#378) from item-59 into main 2026-10-28 09:42:21 +01:00
lilleman 15e22a79f3 Answer prose round 1: 0 🔴, 1 🟡 (0 misread); end the comment with what the human confirmed 2026-10-28 09:42:07 +01:00
lilleman 48f795b1a3 Record in the comment at UNFINISHED_LIMIT that the human confirmed 6, counting every unfinished verdict 2026-10-28 09:40:31 +01:00
lilleman 243a9d872d Merge pull request 'Stop loop-claude and ask the human after six unfinished verdicts running' (#371) from item-59 into main 2026-10-28 02:48:42 +01:00
lilleman 946815a495 Record the comprehension check: PR #371 ruled the same 2026-10-28 02:47:14 +01:00
lilleman 51faf71ecc Answer stability round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-28 02:45:15 +01:00
lilleman c64b3f362d Answer principles round 2: 0 🔴, 1 🟡 (0 misread); record at LoopRun why its three fields stay apart 2026-10-28 02:45:15 +01:00
lilleman 7a7528fba8 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); reword the exit-2 heading and bullet, drop the false claim of six runs, say the stop needs the human, and record at LoopRun why its fields stay apart 2026-10-28 02:45:15 +01:00
lilleman 8caf92dfbe Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); say in the comment at UNFINISHED_LIMIT that it counts every unfinished verdict 2026-10-28 02:40:46 +01:00
lilleman 4bcead0b89 Answer principles round 1: 1 🔴, 3 🟡 (0 misread); the stability round's commit fixes the import order and the untested stepped route, and folds the help test into HelpLimits; LoopRun keeps three fields since renaming one stops a running loop at its next reload 2026-10-28 02:40:46 +01:00
lilleman 2815b89589 Answer stability round 1: 1 🔴, 4 🟡 (1 misread); sort the imports, test the stop's stepped route on the ladder, fix the false archive claim, and assert the stop's facts, not its sentence 2026-10-28 02:40:46 +01:00
lilleman f41b549ff7 Merge origin/main into item-59 2026-10-28 02:24:52 +01:00
lilleman ca6bce76ce Say in the comment at UNFINISHED_LIMIT that it counts every unfinished verdict 2026-10-28 02:24:41 +01:00
lilleman 0d706c7240 Merge pull request 'Launch a round's reviewers in up to three waves, each in one message' (#377) from item-232 into main 2026-10-28 02:22:56 +01:00
lilleman 83cf3897a7 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); state the waves in the imperative, cite Done, skip a wave none of whose passes runs, narrow the claim to Agent calls, and fix the changelog's timing 2026-10-28 02:19:40 +01:00
lilleman 9accc68ec3 Launch a round's reviewers in up to three waves, each in one message, in place of one at a time 2026-10-28 02:17:15 +01:00
lilleman b23bf4f9c3 Merge pull request 'Give the worker's claude a 200k auto-compact window, from item 231's evaluation of context cost, and file items 235 to 241' (#376) from item-231 into main 2026-10-27 09:16:09 +01:00
lilleman c36d7a2f9c Answer prose round 3: 0 🔴, 8 🟡 (0 misread); put the reading rule in the worker's prompt, quote it, mark the items the decision cites, name the whole-project reading in the audit decision's title, and state each answer once 2026-10-27 09:13:00 +01:00
lilleman b46d5374ff Record lilleman's answers: merge the window, trial the reading rule as item 240, no scout for reviewers, and the audit keeps reading the project whole 2026-10-27 09:08:18 +01:00
lilleman 172e72ae07 Answer prose round 2: 0 🔴, 12 🟡 (0 misread); pair each option with its trial and put the conclusion first, tell the two read measures apart, move the security workaround into the skill, and restate items 238 to 241 2026-10-27 02:17:30 +01:00
lilleman d96e5c35ef Record the read pricing, precision and tool trials in item 231's decision, and file questions 240 and 241 2026-10-27 02:11:05 +01:00
lilleman 34a623e261 File item 239, lilleman's call: block a re-read of a file range already in context while the file is unchanged 2026-10-27 01:30:34 +01:00
lilleman b569f638ac Answer prose round 1: 0 🔴, 12 🟡 (0 misread); put the decision first in its entry, list the compact instructions, write the changelog for the public, and restate items 52, 102, 233, 235, 236 and 238 2026-10-27 01:06:24 +01:00
lilleman 34c13f97cd Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); say subagents inherit the window and how many compact, keep a reviewer's drafted findings through a compaction, move item 238 into 0.4.0 2026-10-27 00:57:56 +01:00
lilleman 2b2e18ec6d Answer stability round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-27 00:51:39 +01:00
lilleman 9abc5f4781 Answer principles round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-27 00:46:53 +01:00
lilleman 56b9077e4c Answer stability round 1: 0 🔴, 2 🟡 (0 misread); cut the help paragraph to one sentence and tie its 200k to COMPACT_WINDOW 2026-10-27 00:45:38 +01:00
lilleman 78837aabc6 Answer security round 1: 0 🔴, 0 🟡 (0 misread); file item 238, since the skill scans nothing when a subagent runs it outside the worktree 2026-10-27 00:38:12 +01:00
lilleman 23fbf853d8 Answer principles round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-27 00:35:37 +01:00
lilleman 14736e8e6e Answer principles round 1: 0 🔴, 9 🟡 (0 misread); name the 200k window's compaction point, read a compaction summary as Claude Code's, remove item 231, refresh items 234, 235, 52 and 102, file item 237 2026-10-27 00:32:10 +01:00
lilleman f2e239d111 Compact the worker's context above 200k tokens, from item 231's evaluation of context cost, and file items 235 and 236 2026-10-27 00:13:08 +01:00
lilleman aa020f15f7 Merge pull request 'Move each release forward one, and file items 231 to 234 into 0.4.0' (#375) from item-231 into main 2026-10-26 23:35:19 +01:00
lilleman a0458e0a2c Answer prose round 1: 0 🔴, 5 🟡 (0 misread); restate items 231 to 233's taglines and details 2026-10-26 23:35:12 +01:00
lilleman ea6300a432 Move each release forward one, and file items 231 to 234 into 0.4.0: context cost, parallel reviews, one principles auditor, dollar figures 2026-10-26 23:32:03 +01:00
lilleman 5a0c3f47b9 Merge pull request 'File item 230: an ambitious refactor whenever a scoring run is under 7.0' (#374) from item-230 into main 2026-10-26 22:01:34 +01:00
lilleman d66c0bb317 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); restate item 230's tagline and detail 2026-10-26 21:57:45 +01:00
lilleman cd76c1f511 Wrap item 230's detail 2026-10-26 21:55:31 +01:00
lilleman 4aa8eb9467 File item 230: an ambitious refactor whenever a scoring run is under 7.0 2026-10-26 21:47:22 +01:00
lilleman 3bde9cd6dd Merge pull request 'Cap the memory of each container a heavy command makes under run-heavy at its slot's share' (#373) from item-227 into main 2026-10-24 11:54:30 +02:00
lilleman cf961b55f0 Record the comprehension check: paired ruling same against eb7b506 2026-10-24 11:54:21 +02:00
lilleman 3ac8c79694 Answer stability round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-24 11:46:56 +02:00
lilleman 3617498f33 Answer principles round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-24 11:46:56 +02:00
lilleman ed22a48a61 Answer product-owner round 3: 0 🔴, 1 🟡 (0 misread); a call with a --memory of 0 anywhere passes through unchanged, so neither docker's -m 0 nor a container's grep -m 0 is dropped or overridden 2026-10-24 11:46:56 +02:00
lilleman 6a2f29635e Answer stability round 2: 1 🔴, 2 🟡 (0 misread); drop a --memory of 0 so the added limit stands, pin the 6m floor's edge, test env --unset, env --ignore-environment and doas, and say on Linux in the rule text 2026-10-24 11:42:53 +02:00
lilleman 594b28ff68 Answer principles round 2: 0 🔴, 1 🟡 (0 misread); the -m 1.2.3 crash was answered in the product-owner round 2 commit, which also refuses the exemption to env -i and env -u 2026-10-24 11:39:12 +02:00
lilleman 055c2d2df0 Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); a size has at most one point, so -m 1.2.3 in a container's command is no size and crashes nothing 2026-10-24 11:39:12 +02:00
lilleman c87e9f19d6 Answer stability round 1: 1 🔴, 5 🟡 (0 misread); the 🔴, the rule text and the PATH half of the exemption were answered in the principles round 1 commit; exempt no docker under sudo or doas, test unknown memory and the shim without a share, keep helped beside unlimited, drop a dead fallback 2026-10-24 11:37:08 +02:00
lilleman e551a2b5a9 Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-24 11:31:10 +02:00
lilleman 487adc2091 Answer prose round 1: 0 🔴, 10 🟡 (0 misread); answered in the principles round 1 commit: the decision title says where the rule passes, the help lists the cap's cases, the rule text names the run-heavy exemption, and the docstrings, CLAUDE.md, reviewer step, README and changelog say what a reader does 2026-10-24 11:31:10 +02:00
lilleman a12e68fa61 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); answered in the principles round 1 commit: a memory option below docker's 6m floor, such as grep -m 1, belongs to the container's command, and run-heavy adds its docker only where PATH finds a real one 2026-10-24 11:31:10 +02:00
lilleman 2fa328a406 Answer principles round 1: 0 🔴, 4 🟡 (0 misread); exempt only a bare docker under run-heavy with no PATH of its own, drop the stale item citation, unit-test the slot share in MiB, place the limits by the subcommand's index; also a named Option, exit 126, clearer names and the launcher's import order 2026-10-24 11:31:10 +02:00
lilleman 2eb6fc828f Answer architecture round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-24 11:26:42 +02:00
lilleman 5649331a5e Answer architecture round 2: 0 🔴, 1 🟡 (0 misread); capped adds only the limit a container lacks and removes only an unset or unlimited swap, so a size in the container's own command stays 2026-10-24 11:25:58 +02:00
lilleman 52641079b7 Answer architecture round 1: 0 🔴, 3 🟡 (0 misread); keep the slot's share beside ROOM_SHARE in machine_load, move the rule's predicate into rule_hook, and have capped set both limits itself instead of leaning on docker taking the last option 2026-10-24 11:24:21 +02:00
lilleman 4c1ab3f185 Cap the memory of each container a heavy command makes under run-heavy at its slot's share, and have stability-reviewer size a mutation run's concurrency to fit it 2026-10-24 01:06:56 +02:00
lilleman eb7b50698c Merge pull request 'Block a docker run or docker create that sets no memory limit, and read docker's TLS and buildx --builder options as taking a value' (#372) from item-228 into main 2026-10-24 01:00:41 +02:00
lilleman 7fb8c61c5e Say in README why docker_command.py sits at bin's root 2026-10-24 01:00:35 +02:00
lilleman f4d25691d6 Record the comprehension check: paired ruling better against d1733a2 2026-10-24 01:00:31 +02:00
lilleman 899e8ed55c Answer principles round 3: 0 🔴, 0 🟡 (0 misread) 2026-10-24 00:47:57 +02:00
lilleman a622d19280 Answer stability round 3: 0 🔴, 1 🟡 (0 misread); test that a size after the image's command is no limit; name given's regex parameter pattern 2026-10-24 00:47:57 +02:00
lilleman e17ed74fc2 Answer stability round 2: 0 🔴, 2 🟡 (0 misread); --memory-swap -1 was answered in the principles round 2 commit, and requiring a swap limit stays, as the decision says docker's default swaps as much again as the limit; test a --help past the image 2026-10-24 00:45:13 +02:00
lilleman e1a67eff2a Answer principles round 2: 0 🔴, 1 🟡 (0 misread); a swap limit is a size other than 0, so --memory-swap -1 is no limit, read like the memory limit and not from any word; the docstrings and changelog name both limits 2026-10-24 00:44:13 +02:00
lilleman 1ae4018101 Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-10-24 00:42:39 +02:00
lilleman 951f166c79 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); answered in the product-owner round 1 commit: -m and --memory count only with a size 2026-10-24 00:42:39 +02:00
lilleman e2606b8dab Answer prose round 1: 0 🔴, 6 🟡 (0 misread); answered in the principles round 1 commit: the shipped items leave the plan, the decision names Bash commands, compose and its scripts, splits the cgroup-parent sentence, item 227 names each machine load decision in full, and the docstrings say what -m and --help do 2026-10-24 00:42:39 +02:00
lilleman 196abe18a9 Answer principles round 1: 0 🔴, 5 🟡 (0 misread); require a swap limit beside the memory limit, ask in CLAUDE.md for both where rule-hook can't see the container, remove items 225 and 228 with a changelog entry; the -m finding was answered in the product-owner round 1 commit 2026-10-24 00:42:39 +02:00
lilleman 2d219ff6c8 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); read -m and --memory as a limit only with a size, so python -m pytest in the container is no limit, and read timeout as a launcher; also take the technical principles' nits: --help counts only beside docker's subcommand, sort STARTS_CONTAINER, print the example limit once, and name item 227 in the decision 2026-10-24 00:36:19 +02:00
lilleman 500e2c2947 Answer architecture round 2: 0 🔴, 0 🟡 (0 misread) 2026-10-24 00:32:30 +02:00
lilleman f7ad418b20 Name the launcher reading in shell_command's docstring 2026-10-24 00:32:30 +02:00
lilleman a292ec4cae Answer architecture round 1: 0 🔴, 3 🟡 (0 misread); move docker's parsing to bin/ for item 227's shim, read launchers once in shell_command.launched, and give the memory limit its own decision, sized to what the work needs 2026-10-24 00:31:41 +02:00
lilleman 7b61fd5b4b Sort rule_hook's imports by their first binding 2026-10-24 00:18:50 +02:00
lilleman b6d8fe48af Record the reading cost of the chunks before item 228, and refresh item 155 with its rise 2026-10-24 00:16:05 +02:00
lilleman fbaa3075c4 Block a docker run or docker create that sets no memory limit, and read docker's TLS and buildx --builder options as taking a value 2026-10-24 00:15:44 +02:00
lilleman b6954e5aa7 File items 227 and 228: cap a heavy command's containers at its slot's memory share, and block a docker run without a memory limit 2026-10-24 00:13:26 +02:00
lilleman 2135afe8d7 Answer architecture round 1: 1 🔴, 4 🟡 (0 misread); share the stop archiving, fix the limit at 6, reword the exit-2 contract, close the cycle in one step 2026-10-23 15:09:46 +02:00
lilleman 008c187192 Stop loop-claude and ask the human after six unfinished verdicts running 2026-10-23 15:06:10 +02:00
lilleman 4fa114905a Record reading cost for PR #370 2026-10-23 15:06:10 +02:00
lilleman d1733a2d8d Merge pull request 'Move the run-heavy rule's command parsing into its own module' (#370) from item-223 into main 2026-10-23 14:50:23 +02:00
lilleman 2249655796 Record the comprehension check: PR #370 ruled better 2026-10-23 14:49:23 +02:00
lilleman 686c1dc7a4 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:46:30 +02:00
lilleman c70dda6bd9 Answer principles round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:46:30 +02:00
lilleman bd00eee3ca Answer prose round 1: 0 🔴, 1 🟡 (0 misread); reword two comments, rename docker_at, file the DOCKER_VALUED gap as item 225 2026-10-23 14:45:45 +02:00
lilleman fc38e80591 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:45:45 +02:00
lilleman f94f23a3d7 Answer stability round 1: 1 🔴, 0 🟡 (0 misread); the import sort of the principles round answers it 2026-10-23 14:45:45 +02:00
lilleman 6ea148bdf4 Answer principles round 1: 1 🔴, 0 🟡 (0 misread); sort the heavy_command import before review_folder 2026-10-23 14:45:45 +02:00
lilleman ff3babef74 Answer architecture round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:36:16 +02:00
lilleman 578de9231f Move the run-heavy rule's command parsing into its own module and pick docker's position without a nested conditional 2026-10-23 14:35:06 +02:00
lilleman 2558a6ad7e Record the last chunk's reading cost 2026-10-23 14:35:06 +02:00
lilleman eb1c302553 Merge pull request 'Renumber the decision-paragraph split from item 222 to 224, which item-222's chunk had also used' (#369) from item-224 into main 2026-10-23 14:33:32 +02:00
lilleman 1895bbbad5 Answer prose round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 14:33:25 +02:00
lilleman 620590cf24 Renumber the decision-paragraph split from item 222 to 224, which item-222's chunk had also used 2026-10-23 14:32:54 +02:00
lilleman 64d438681e Merge pull request 'Hold each heavy command for one of a heavy slot per 4 CPUs, and each worker until a quarter of memory is available' (#366) from item-222 into main 2026-10-23 11:56:55 +02:00
lilleman 5f54116696 Merge remote-tracking branch 'origin/main' into item-222
# Conflicts:
#	CHANGELOG.md
#	README.md
#	docs/comprehension-history.md
#	todo.md
2026-10-23 11:53:36 +02:00
lilleman 065a0d2d3f File item 223: move the run-heavy rule's command parsing into its own module 2026-10-23 11:52:41 +02:00
lilleman 83c0f268d4 Record the comprehension check: paired ruling same against 4a0ba59 2026-10-23 11:52:41 +02:00
lilleman fd60b6da97 Merge pull request 'Count, per finished chunk, the findings that arose from misreading code that had already shipped' (#368) from item-198 into main 2026-10-23 11:51:22 +02:00
lilleman 91f328e8de Record the comprehension check: paired ruling better against 4a0ba59 2026-10-23 11:51:12 +02:00
lilleman 5e7e3649c6 Answer overrides round 3: 0 🔴, 0 🟡 (0 misread); all four overrides accepted, later round 3 commits ruled on ahead 2026-10-23 11:49:30 +02:00
lilleman 2bbfb90936 Answer product-owner round 3: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 11:49:30 +02:00
lilleman 29715fcd2a Answer stability round 3: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 11:49:30 +02:00
lilleman ff08f496cb Answer principles round 3: 0 🔴, 0 🟡 (0 misread); rename two tests to what they check 2026-10-23 11:49:30 +02:00
lilleman e05c54aad0 Merge remote-tracking branch 'origin/main' into item-222 2026-10-23 11:45:57 +02:00
lilleman 203049f4c3 Answer prose round 1: 0 🔴, 9 🟡; reword the decision, the rule's help, run-heavy's help and the reviewer's step 4, and drop -h from the light flags 2026-10-23 11:45:53 +02:00
lilleman ef392502ba Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); all six overrides accepted 2026-10-23 11:45:40 +02:00
lilleman 222ee12e09 Answer stability round 2: 0 🔴, 2 🟡 (0 misread); both answered in the principles and product-owner answers 2026-10-23 11:45:40 +02:00
lilleman 73b9eec07c Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); head the list as findings with their misread count 2026-10-23 11:45:40 +02:00
lilleman 9aa174d511 Answer principles round 2: 0 🔴, 1 🟡 (0 misread); say in rule-hook's refusal that the misread count is at most the findings, and move a stray assertion back 2026-10-23 11:45:40 +02:00
lilleman 2d2371766d Answer product-owner round 1: 0 🔴, 0 🟡; name the slot folder and fuser in the wait message, keep help calls light, and give the reviewer's suite the long timeout 2026-10-23 11:43:10 +02:00
lilleman 477772d7a5 Answer prose round 1: 0 🔴, 12 🟡 (0 misread); reword the decision, the Misread section and the comments, mark item 110 decision, file item 222 2026-10-23 11:40:38 +02:00
lilleman 9d4d6ee401 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); spell each chunk's line as round titles do, and say where the list sits 2026-10-23 11:40:38 +02:00
lilleman bac9dd54bc Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); both overrides accepted 2026-10-23 11:40:38 +02:00
lilleman 13447388a2 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 11:40:38 +02:00
lilleman 779d05886b Answer stability round 1: 0 🔴, 1 🟡 (0 misread); the three repeated tests went in the principles answer 2026-10-23 11:40:38 +02:00
lilleman 1e225c4397 Answer principles round 1: 0 🔴, 3 🟡 (0 misread); refuse a misread count above the findings, share the lower-bound rule, name score-outcomes' new list in the README 2026-10-23 11:40:38 +02:00
lilleman a68f6a781d Answer overrides round 1: 0 🔴, 0 🟡 2026-10-23 11:39:51 +02:00
lilleman ef33efd2e4 Answer stability round 3: 0 🔴, 0 🟡 2026-10-23 11:39:14 +02:00
lilleman 44305e6f8d Answer principles round 4: 0 🔴, 0 🟡 2026-10-23 11:38:24 +02:00
lilleman 1d3b928bdb Answer architecture round 2: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-10-23 11:30:54 +02:00
lilleman 80cc36e904 Answer architecture round 1: 0 🔴, 2 🟡 (0 misread); read a round title's counts once, into one Counts value 2026-10-23 11:30:17 +02:00
lilleman 4d18b8e125 Count, per finished chunk, the findings that arose from misreading code that had already shipped 2026-10-23 11:23:44 +02:00
lilleman e00eb558c2 Append the reading-cost figure 2026-10-23 11:23:44 +02:00
lilleman 4a0ba59210 Merge pull request 'Give "record", "outcome" and "places" one meaning each across bin/, and rename larv_review/git.py by what it holds' (#367) from item-125 into main 2026-10-23 11:16:34 +02:00
lilleman 447668865d Record the comprehension check: paired ruling better against dcbdc97 2026-10-23 11:16:21 +02:00
lilleman 27d778ed81 Answer stability round 2: 0 🔴, 2 🟡; the docker fix and the echo and bare env cases landed with principles round 3 2026-10-23 11:14:03 +02:00
lilleman 1d00bfd1ef Answer principles round 3: 0 🔴, 2 🟡; find docker past a launcher's own options, as for a mutation tool 2026-10-23 11:14:03 +02:00
lilleman 5a56fff040 Answer principles round 2: 0 🔴, 0 🟡; call the loop index index, clear of the imported position 2026-10-23 11:10:51 +02:00
lilleman bd64bd59c2 Answer stability round 1: 0 🔴, 2 🟡; the two hard places it touches change by one word, settled in the PR summary 2026-10-23 11:09:51 +02:00
lilleman dd9dda8f69 Answer security round 1: 0 🔴, 0 🟡; nothing to change 2026-10-23 11:09:51 +02:00
lilleman e3566f694a Answer prose round 1: 0 🔴, 4 🟡; correct the decision's counts and wording, and call the archived route a worker line in item 218 2026-10-23 11:09:51 +02:00
lilleman 21d507f0c5 Answer principles round 1: 0 🔴, 1 🟡; give the true reason score-outcomes keeps its name, name archived_kind and three locals by what they hold 2026-10-23 11:09:51 +02:00
lilleman 792fa2b8b0 Answer stability round 1: 0 🔴, 5 🟡; test the lock-error and slot-folder exits and the default folder, and return a Failure from held_slot 2026-10-23 11:06:55 +02:00
lilleman dde9caa172 Answer principles round 2: 0 🔴, 2 🟡; have rule-hook read docker's subcommand and the tool inside docker run or exec, and pass a run-heavy behind a launcher 2026-10-23 11:06:55 +02:00
lilleman c7dbd56f39 Answer principles round 1: 0 🔴, 5 🟡; enforce run-heavy in rule-hook, take slots through one tested function, exit 125 on lock errors, fake meminfo in black-box tests 2026-10-23 10:55:55 +02:00
lilleman 504aa31bdb Answer architecture round 2: 0 🔴, 0 🟡; nothing to change 2026-10-23 10:55:05 +02:00
lilleman 387a5ce506 Answer architecture round 1: 0 🔴, 2 🟡; finish "record", record the three meanings as a decision, name rule-hook's check once 2026-10-23 10:54:24 +02:00
lilleman 6725ee4c9d Answer security round 1: 0 🔴, 0 🟡 2026-10-23 10:48:39 +02:00
lilleman 6ff77f7049 Answer architecture round 2: 0 🔴, 0 🟡 2026-10-23 10:47:49 +02:00
lilleman 66af309e71 Answer architecture round 1: 0 🔴, 3 🟡; keep the slots and the memory share in machine_load, exit 125/126/127 as GNU wrappers do, point --help at the module 2026-10-23 10:47:01 +02:00
lilleman 8d2a1cf9fd Give "record", "outcome" and "places" one meaning each across bin/, and rename larv_review/git.py by what it holds 2026-10-23 10:42:06 +02:00
lilleman 7c05bf414c Append the reading-cost figure 2026-10-23 10:41:12 +02:00
lilleman 6c823de29c Hold each heavy command for one of a heavy slot per 4 CPUs, and each worker until a quarter of memory is available 2026-10-23 10:40:57 +02:00
lilleman 9df08bd41e Merge pull request 'Keep item 218 blocked on item 170 whether or not 170 changes the routing steps' (#365) from item-218 into main 2026-10-23 10:28:39 +02:00
lilleman f20d1799c3 Answer prose round 1: 0 🔴, 1 🟡; say item 218 waits for item 170 whether or not 170 changes the steps 2026-10-23 10:28:35 +02:00
lilleman 1b7d5244b1 Keep item 218 blocked on item 170 whether or not 170 changes the routing steps 2026-10-23 10:27:09 +02:00
lilleman e923534fc9 Merge pull request 'Keep the routing steps as they are, and re-tune them once 50 chunks have shipped under them' (#364) from item-170 into main 2026-10-23 10:25:15 +02:00
lilleman c8d97fb516 Answer prose round 1: 0 🔴, 4 🟡; state the 15 chunks and the 50-chunk threshold once, and drop the worker's move of the item 2026-10-23 10:24:44 +02:00
lilleman e92bde2bd3 Keep the routing steps as they are, and re-tune them once 50 chunks have shipped under them 2026-10-23 10:22:12 +02:00
lilleman 7a4ac91597 Merge pull request 'Say in larv-review's skill that the auto-reviewer's round commit takes no round title' (#363) from item-216 into main 2026-10-23 05:39:16 +02:00
lilleman b68b1b60ac Answer prose round 1: 0 🔴, 2 🟡; move the auto-reviewer's commit rule into its bullet and say what title it takes 2026-10-23 05:36:05 +02:00
lilleman 2317ed4c90 Say in larv-review's skill that the auto-reviewer's round commit takes no round title 2026-10-23 05:34:08 +02:00
lilleman 65a0433deb Record the reading cost of the last finished chunk 2026-10-23 05:34:08 +02:00
lilleman ad6e6898c2 Merge pull request 'Sort the decision log by title, and rewrite its six amendment-log entries as the current state' (#362) from item-82 into main 2026-10-23 05:33:11 +02:00
lilleman 22e2c22b8f Answer prose round 1: 1 🔴, 6 🟡; restore the lost reasons, mark the unbuilt scoring parts, and name who ruled 2026-10-23 05:33:02 +02:00
lilleman e452b0c55e Sort the decision log by title, and rewrite its six amendment-log entries as the current state 2026-10-23 05:29:51 +02:00
lilleman dcbdc970a6 Merge pull request 'Hold the escalation mark in one module, and carry a ruling's step-up through the cycle's states' (#361) from item-210 into main 2026-10-23 05:24:55 +02:00
lilleman 0b1289cb33 Record the comprehension check: paired ruling better against 39dd51b 2026-10-23 05:24:46 +02:00
lilleman 6f98a1855b Answer prose round 1: 0 🔴, 5 🟡; tighten the escalation mark's comments, item 221's detail, and fold three decision entries into item 190 2026-10-23 05:22:15 +02:00
lilleman d70cbca594 Answer stability round 2: 0 🔴, 0 🟡; approved 2026-10-23 05:09:15 +02:00
lilleman 6733615e1c Answer principles round 2: 0 🔴, 0 🟡; approved, file item 221 and fix two blank-line nits 2026-10-23 05:09:15 +02:00
lilleman 92afe2ac08 Answer stability round 1: 0 🔴, 2 🟡; assert the mark-0 transcript and underscore emphasis, in f781ac6 2026-10-23 05:07:36 +02:00
lilleman fa2024c09f Answer security round 1: 0 🔴, 0 🟡; no findings 2026-10-23 05:07:30 +02:00
lilleman f781ac611b Answer principles round 1: 0 🔴, 1 🟡; rename the module escalation_mark.py so it no longer shares the escalation field's name 2026-10-23 05:07:30 +02:00
lilleman aebd92de43 Answer architecture round 2: 0 🔴, 0 🟡; approved 2026-10-23 04:55:50 +02:00
lilleman bf8b642ead Answer architecture round 1: 0 🔴, 2 🟡; rename Step to StepUp and let escalation.py own the judge's step-line sentence 2026-10-23 04:54:45 +02:00
lilleman f0e14f3fdf Hold the escalation mark in one module, and carry a ruling's step through the cycle's states 2026-10-23 04:45:03 +02:00
lilleman 4764d3d522 Merge pull request 'Have rule-hook refuse a round commit past round 3 unless an override quotes the human answer' (#360) from item-214 into main 2026-10-23 04:32:34 +02:00
lilleman ef12b17d8b Answer prose round 1: 0 🔴, 0 🟡; tighten the changelog, decision and item 220 wording 2026-10-23 04:29:37 +02:00
lilleman 9f044044ab Answer stability round 2: 0 🔴, 0 🟡; approved 2026-10-23 04:27:25 +02:00
lilleman a85b0a44d5 Answer principles round 2: 0 🔴, 0 🟡; approved 2026-10-23 04:27:25 +02:00
lilleman a99a98c504 Answer stability round 1: 0 🔴, 1 🟡; test the checkout a round-cap breach names 2026-10-23 04:23:52 +02:00
lilleman dceff3c985 Answer principles round 1: 1 🔴, 0 🟡; file the title-only count as item 220 and cite it in the decision 2026-10-23 04:23:52 +02:00
lilleman 1a83c13eb9 Have rule-hook refuse a round commit past round 3 unless an override quotes the human answer 2026-10-23 04:15:52 +02:00
lilleman 39dd51bb44 Merge pull request 'Split review_launches into model_routing's choice of each review's rung and whole prompt sentences that render it' (#359) from item-212 into main 2026-10-23 04:06:02 +02:00
lilleman 66a12bd806 Record the comprehension check: ruling better for PR #359 2026-10-23 04:05:52 +02:00
lilleman 72a63c5ade Answer product-owner round 1: 0 🔴, 0 🟡; approved 2026-10-23 04:03:31 +02:00
lilleman a0780ca0bd Answer stability round 3: 0 🔴, 0 🟡; approved 2026-10-23 04:03:31 +02:00
lilleman 5732b898a6 Answer principles round 3: 0 🔴, 0 🟡; approved 2026-10-23 04:03:31 +02:00
lilleman a225166956 Answer principles round 2: 0 🔴, 1 🟡; the 🟡 is answered by the stability round 2 fix 2026-10-23 03:53:14 +02:00
lilleman 7c42f038ac Answer prose round 1: 0 🔴, 4 🟡; reword the docstrings and comments the pass found false or hard to read, and add a changelog line 2026-10-23 03:53:14 +02:00
lilleman f58fe5a9db Answer stability round 2: 0 🔴, 1 🟡; name when a replay applies in ladder.py and have chosen find the higher E + I that end it, so a top-rung project keeps them 2026-10-23 03:53:14 +02:00
lilleman 28b64042ba Answer stability round 1: 0 🔴, 2 🟡; find the higher E + I that move the reviewers by their rung alone, and keep the choice's tests the prompt tests do not repeat 2026-10-23 03:46:01 +02:00
lilleman 061b32dd66 Answer principles round 1: 0 🔴, 2 🟡; drop the stale clause from item 174, point --help at review_choice.py, and tidy the new module's docstring, imports and comments 2026-10-23 03:45:46 +02:00
lilleman 061118be0b Answer architecture round 1: 0 🔴, 1 🟡; give a chunk no item routed the same rung sentences as its resumed prompt, and sort the new modules' imports 2026-10-23 03:37:12 +02:00
lilleman 28da11dd8d Split review_launches into model_routing's choice of each review's rung and whole prompt sentences that render it 2026-10-23 03:32:47 +02:00
lilleman a351ba8a33 Merge pull request 'State each routing rule once in the docstring of the code that enforces it, cut loop-claude --help's routing paragraph, and name the project's rung project in bin/loop_claude' (#358) from item-211 into main 2026-10-23 03:21:06 +02:00
lilleman a4071f59ce Answer prose round 1: 0 🔴, 1 🟡; state the help's step-up rule as the code holds it, and reword the docstrings and the changelog entry 2026-10-23 03:20:54 +02:00
lilleman 372cfa7535 File item 219 to name the project's rung project in the three tools outside bin/loop_claude 2026-10-23 03:12:39 +02:00
lilleman 2f03ba1a77 Answer product-owner round 2: 0 🔴, 0 🟡; approved 2026-10-23 03:11:41 +02:00
lilleman 5b615ef46e Answer stability round 2: 0 🔴, 0 🟡; approved 2026-10-23 03:11:41 +02:00
lilleman 058ec1da4f Answer principles round 2: 0 🔴, 0 🟡; approved 2026-10-23 03:11:41 +02:00
lilleman 038ef6e732 Answer stability round 1: 0 🔴, 4 🟡; test the escalation sentence on the second-highest rung, and the docstring and judge_rung fixes came in the principles round 2026-10-23 03:10:31 +02:00
lilleman a81f878f92 Answer principles round 1: 0 🔴, 5 🟡; make the routing.py and prompts.py module docstrings true and short, drop the routing_check copy of the figures, rename judge_rung's local, and keep the help's 20 2026-10-23 03:10:31 +02:00
lilleman aa9a4cb78b Answer product-owner round 1: 0 🔴, 1 🟡; keep the help's rung definition and the routing qualifier 2026-10-23 03:10:31 +02:00
lilleman 3b69ced357 State each routing rule once in the docstring of the code that enforces it, cut loop-claude --help's routing paragraph, and name the project's rung project in bin/loop_claude 2026-10-22 22:42:01 +02:00
lilleman 545ab3ab37 Merge pull request 'Archive the route as a JSON record loop-claude reads back field by field, and name the stepping functions and the judge's taken-in levels by what they do' (#357) from item-137 into main 2026-10-22 22:32:32 +02:00
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
123 changed files with 4771 additions and 1831 deletions
+9
View File
@@ -25,6 +25,7 @@
!bin/claude_code/
!bin/claude_code/*.py
!bin/comprehension_history.py
!bin/docker_command.py
!bin/failure.py
!bin/file_writes.py
!bin/git_command.py
@@ -39,6 +40,8 @@
!bin/loop_claude/
!bin/loop_claude/**/
!bin/loop_claude/**/*.py
!bin/machine_load/
!bin/machine_load/*.py
!bin/markdown_text.py
!bin/metric-bench
!bin/metric_bench/
@@ -54,6 +57,7 @@
!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
@@ -64,6 +68,11 @@
!bin/rule_hook/*.py
!bin/rung_replay/
!bin/rung_replay/*.py
!bin/run-heavy
!bin/run_heavy/
!bin/run_heavy/*.py
!bin/run_heavy/path_entry/
!bin/run_heavy/path_entry/docker
!bin/score-outcomes
!bin/score_outcomes/
!bin/score_outcomes/*.py
+42 -35
View File
@@ -2,53 +2,60 @@
Decisions live in `docs/decisions.md`:
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
- bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
- bin/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names
- bin/: the tools and their tests run on the host's Python, with no container
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
- chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
- review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human
- review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge
- review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
- review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
- review: a project decision may suspend the comprehension check for the plan items it names
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
- review: the principles audit runs on every chunk that changes code, config or tests, and on no other chunk
- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
- loop-claude: a `claude` that cannot start is a failed worker run, retried
- review: an ask no user answers leaves the PR unmerged
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
- loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
- loop-claude: every claude it starts bypasses permissions inside its sandbox
- review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
- review: the premises chunk's whole review is the human's approval
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
- settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
- loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` → "Compact instructions" says what the summary keeps
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
- machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
- reading cost and `score-outcomes`: each waits for 10 finished chunks before it shows a median
- rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides one, and larv-review's overrides pass rules on each override before merge
- rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR
- review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
- review: a fix for a 🔴 or 🟡 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
- review: a pass gets at most two rounds per chunk, with no third and no ask for one; the fixes answering round 2 merge once the gate passes
- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
- review: a project decision may suspend the comprehension check for the plan items it names
- review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge
- review: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
- review: an ask no user answers leaves the PR unmerged
- review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`
- review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose
- review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
- review: the premises chunk's whole review is the human's approval
- review: the principles audit runs on every chunk that changes code, config or tests, reads the project whole with one auditor checking the goals and every principles file that applies, and runs on no other chunk
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
- routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
- routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass; the seats and the security pass always on the project's
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
- routing: loop-claude measures review rounds and unfinished verdicts per rung every 20 cycles, and calls for a routing change when, of two rungs with 5 or more chunks each, the lower took more of either than the one above, or when 5 or more subagents of one type had reports longer than the tool results they read
- routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
- routing: a worker delegates a task only where it needs just the task's conclusion, and each subagent runs on the rung its task's L picks from the project's rung, never below the project's rung when it files or scores todo.md items
- routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it
- routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, steps one rung up as the judge interrupts or quotes an answer, or next cycle, up to two rungs above the rung its item picks
- routing: loop-claude measures review rounds and unfinished verdicts per rung every 20 cycles, and calls for a routing change when, of two rungs with 5 or more chunks each, the lower took more of either than the one above, or when 5 or more subagents of one type had reports longer than the tool results they read
- routing: on a model judge-replay covered, the judge runs on the rung a review would get from the highest E + I among its chunk's items, never below the project's rung
- routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
- routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
- rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides one, and larv-review's overrides pass rules on each override before merge
- rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
- settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
## Working rules
@@ -63,4 +70,4 @@ The project values for `skills/comprehension-panel/seat-prompts.md`:
- `{kind}`: a Claude Code configuration with an agent loop and review skills
- `{domain}`: driving headless Claude Code sessions, agent review workflows
- `{domain docs}`: the Claude Code documentation
- `{3am question}`: a loop-claude run exits 1 overnight after the judge returned a verdict the loop rejected, or a larv-review run looped a reviewer a fourth time
- `{3am question}`: a loop-claude run exits 1 overnight after the judge returned a verdict the loop rejected, or a larv-review run looped a reviewer a third time
+33
View File
@@ -1,5 +1,38 @@
# Changelog
## Unreleased
- `loop-claude` now opens every message it prints with the machine's local time, as in `2026-10-28 11:46:01`, so you can see when each happened, such as how long a question has waited. A message of several lines, such as a question, carries the time on its first line only. The `retrying at …` time of a usage-limit wait now also shows seconds, and no longer names the zone.
- larv-review now gives each review pass at most two rounds per chunk, where it gave three and then asked for more, and no longer asks: the fixes answering a pass's second round merge once the gate passes. rule-hook's new `round-cap` rule refuses a round commit that would take a pass past round 2, such as `Answer stability round 3: …`, and takes no override. It counts the pass's earlier round commits on the branch, so a third commit titled round 2 is refused too. `larv-review round-count` marks a pass at two rounds as at the cap.
- rule-hook has a new rule, `repeat-read`, and now runs before each Read call too. It blocks a Read, or a Bash `cat`, `head` or `sed -n '<A>,<B>p'` of one file, when every line it asks for is already in the agent's context, and the block names those lines. The rule takes no override.
- A line is in context when an earlier read's result in the agent's own transcript showed it since the last compaction, as the file holds it now. A subagent is judged on its own transcript, not its session's.
- A read goes through when it asks for a line no earlier read showed, or one that changed since. A Bash output that Claude Code cut short shows no lines.
- A Read also goes through until the agent has read the file with Read or written it with Edit, MultiEdit or Write, and again once the file changed after that. Edit, MultiEdit and Write refuse the file until then, and a Bash read does not count.
- Where the context lacks lines the transcript shows, as after Claude Code cleared old tool results, `grep -n '' <file> | sed -n '<A>,<B>p'` reads them.
- Install the latest stable Python, today 3.14, as `python3`: the tools and their tests no longer support 3.11 to 3.13. A full test run now takes about 29 s, where it took about 3.3 minutes. It runs once, on that Python, in four pytest-xdist workers, where it used to rerun the whole suite on 3.11.
- `routing-figures.md` now reports dollars by project, subagent type, rung and tool, in place of tokens. Cache reads are included; the tokens left them out, though they were about a quarter of the cost. The dollars are what each worker transcript's last `cost-state` entry records for each model, split across the messages of the worker and its subagents in proportion to their cost at list prices. The judge's runs are not counted, since the archive doesn't hold them.
- larv-review's principles pass now launches one auditor per round, which checks the README's goals, code health and every principles file that applies, so it reads the project once per round. It used to launch one auditor for the goals with code health and one for each principles file, each reading the whole project. Its report is `principles-round-<n>.md`, like every other pass's.
- A session running larv-review now enters the chunk's worktree with `EnterWorktree` before the first review pass, so `/security-review` and the full scan read the branch's diff. Run from the checkout root, they used to find it empty.
- `loop-claude` now stops with exit 2 when the judge rules one chunk unfinished 6 cycles running, so a worker and a judge that disagree can no longer cycle unattended without end. Rerunning resumes the chunk and gives it 6 more cycles.
- larv-review now launches a round's reviewers in up to three waves, each wave's reviewers in one message, in place of one reviewer at a time: first the architect, then the principles auditor with the security and overrides passes, then the stability, product-owner and prose passes. Each wave now lasts as long as its slowest reviewer, where a round used to last as long as all its reviewers one after another.
- loop-claude's worker, and every subagent it launches, now run with a 200k auto-compact window, handed as `CLAUDE_CODE_AUTO_COMPACT_WINDOW`: Claude Code compacts their context at about 170k tokens, where it used to let it grow to about 967k. loop-claude's judge no longer reads a compaction summary as words you typed. `CLAUDE.md` has a new section, "Compact instructions", saying what a summary keeps.
- On Linux, `run-heavy` now caps the memory of a container its command makes with `docker run` or `docker create`. A container that sets no limit gets a memory limit and a swap limit, both the slot's share: three quarters of the machine's memory, split across the heavy slots. A container that sets one of the two limits keeps it, and gets the other as large. This covers containers a project's own scripts start, which rule-hook can't see. A `docker compose` service, and a docker named by its full path, get no cap. rule-hook's `docker-run-memory` now lets a `docker run` under run-heavy pass.
- rule-hook has a new rule, `docker-run-memory`. It blocks a `docker run` or `docker create` that lacks a memory limit or a swap limit, such as `--memory 4g --memory-swap 4g`, sized to what the work needs. `--memory-swap -1`, unlimited swap, counts as none. `CLAUDE.md` asks for the same limits on a container a script or a compose file starts, which rule-hook can't see. rule-hook's `run-heavy` rule also now reads docker's `--tlscacert`, `--tlscert`, `--tlskey` and buildx's `--builder` as options that take a value, and reads `docker container run` as a run: `docker --tlscacert ca.pem build .` was not blocked outside run-heavy before.
- Reviewers now mark a 🔴 or 🟡 `[misread]` where it arose because the implementer misread code that had already shipped. A round's commit title now counts the marked findings, as in `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, and rule-hook's `round-title-counts` blocks a round title without that count. `score-outcomes` shows the count on each finished item, and lists it after the medians for each chunk whose round titles carry it, newest first. A chunk whose round titles predate this change reads as unknown.
- Sessions running at once no longer starve the machine. A new tool, `run-heavy <command>`, runs a heavy command, such as a full gate, mutation tests, an e2e run or a `docker build`, once it holds one of the machine's heavy slots: one per 4 CPUs, shared by every session. `CLAUDE.md` has every session run its heavy commands under it, and rule-hook blocks a `docker build` or a mutation run outside it. loop-claude now waits to start a worker while less than a quarter of the machine's memory is available.
- larv-review's skill now says a commit answering the external auto-reviewer takes no `Answer <pass> round` title, and that `larv-review round-count` doesn't list the auto-reviewer. A worker who followed the skill used to get a "not a pass" warning.
- loop-claude's first prompt for a chunk that no plan item routed now also names the rung on which the worker launches its reviews for an item it takes in, as the prompt after a step-up or an unfinished verdict already did.
- `loop-claude --help` now describes routing in two short paragraphs for the person running the loop. The rules it used to repeat are now stated once, in the code that enforces them.
- loop-claude now archives the route on each `Worker:` line as a JSON record, such as `{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 12}`, and reads it back field by field. The line used to be a sentence, such as `claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5`, which loop-claude parsed back word for word: rewording the sentence in the code would have made every archived line unreadable, and a rerun would have routed the open chunk afresh. A rerun and the routing figures still read the sentences archived since loop-claude routed on L. A rerun that finds a `Worker:` line it can't read now says so on stderr. The judge's reply now names the levels the worker took in `highest_likelihood_taken_in` and `highest_escape_and_impact_taken_in`, in place of `bundled` and `bundled_escape_and_impact`.
- A chunk now takes every unblocked item of its release that fires the same review passes, whatever its purpose: one PR title no longer has to state what the items achieve together. An item with R above 5 ships alone. `chunk-preflight` says so for such an item, and never lists one as an item that may join another.
- A branch whose name is not UTF-8 now shows no branch in the status line, in place of a name with replacement characters.
- 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.
+18 -3
View File
@@ -11,7 +11,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
- **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.
@@ -65,6 +65,8 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
- Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along.
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app <tool> …`.
- Tear down test containers after a run.
- Give every container you start a memory limit and a swap limit, as large as its work needs: `--memory 4g --memory-swap 4g` on `docker run`, or `mem_limit` and `memswap_limit` in a compose file, scripts included. rule-hook checks only the `docker run` and `docker create` in your Bash commands.
- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run it in the background, since the wait can outlast the Bash tool's timeout.
- Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's L as for a `todo.md` item; a task that changes no file, such as a search, is L 1. `<model>` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits:
1. A reviewer, a comprehension seat or the security pass: those loop-claude's prompt gives it. Given none, pass no model or effort, so it runs on your model.
2. An escalated task, below: the rung loop-claude's prompt names for escalation, or case 3's rung where the subagent files or scores `todo.md` items and that rung is higher.
@@ -73,11 +75,11 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
- Escalate a task that proves too hard for your rung. Four escalation triggers say so:
1. A re-score of the item's L, made on the project's rung or above, picks a rung above yours.
2. The same failing test or finding survives two fix attempts.
3. A pass reports a 🔴 in round 2 or later.
3. A pass reports a 🔴 in round 2.
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.
@@ -102,6 +104,19 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
- **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible.
- When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw <url> [options]` (see its README). Don't use claude-in-chrome for this.
## Compact instructions
Claude Code reads this section by its heading when it compacts a conversation. Keep in the summary:
- what remains before the chunk is finished;
- the task loop-claude gave, and each `todo.md` item the chunk takes with its L and E + I;
- the worktree, branch and PR;
- the rung loop-claude named for each review launch, rerun and escalated subagent;
- each review pass's rounds so far, each open 🔴 and 🟡, and how the answered ones were answered;
- every question the human answered, with the answer;
- each escalation trigger that fired;
- for a reviewer or comprehension seat, every finding and place it has drafted.
## Vocabulary
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
+13 -10
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
@@ -45,7 +47,7 @@ git remote add origin ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git
Then run Update's commands, skipping `git add settings.json`: the new repository tracks no file yet.
Have Python 3.11 or newer as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
Have the latest stable Python, today 3.14, as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
```sh
claude plugin marketplace add anthropics/claude-plugins-official
@@ -64,7 +66,7 @@ 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`. 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.
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
@@ -100,29 +102,30 @@ 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. Run it only in a sandbox, like loop-claude: 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.
- `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 Agent, Bash, Edit, MultiEdit, Read and Write call, and `rule-hook --help` states the rules and the override.
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; then each chunk's 🔴 and 🟡 findings with how many a reviewer marked `[misread]`, code health's counter-signal; `score-outcomes --help` states the measures.
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'`. Test the bench's git wrapper with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
Test on the host with `uvx --python "$(command -v python3)" --with pytest-xdist==3.8.0 pytest==9.2.0 -n 4 bin`. It needs `uv` on `PATH`, which fetches pytest, pytest-xdist and mypy. pytest-xdist runs the tests in four workers, one heavy slot's CPUs (`docs/decisions.md` → `bin/: the tools support only the latest stable Python, …`). `python3 -m unittest discover -s bin -p 'test_*.py'` runs the same tests one at a time. Test the bench's git wrapper with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/outcomes.py`. Leave out each test class that starts a tool's launcher through `subprocess`: a mutated module fails to load in a process mutmut did not start.
To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/results.py`. Leave out each test class that starts a tool's launcher through `subprocess`: a mutated module fails to load in a process mutmut did not start.
```ini
[mutmut]
source_paths=score_outcomes/outcomes.py
source_paths=score_outcomes/results.py
also_copy=.
pytest_add_cli_args_test_selection=score_outcomes/
pytest_add_cli_args=-k
not ScoreOutcomesTool
```
Then, in the copy: `uvx --with pytest 'mutmut>=3,<4' run && uvx --with pytest 'mutmut>=3,<4' results`, and `uvx --with pytest 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with pytest==9.2.0 'mutmut>=3,<4' results`, and `uvx --with pytest==9.2.0 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
## Tracking a new file
+4 -3
View File
@@ -1,13 +1,14 @@
---
name: principles-auditor
description: "Use this agent for larv-review's principles pass: one yardstick checked against the whole project."
description: "Use this agent for larv-review's principles pass: the project's goals and every principles file handed to it, checked against the whole project."
tools: Read, Grep, Glob, Write
---
You check one yardstick against the whole project: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`, with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it.
You check every yardstick you are handed against the whole project, which you read once for all of them. A yardstick is either the project's goals, every goal under its `README.md` → `## Goals` with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it, or one principles file, every principle in it.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardstick, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardsticks, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
- Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why.
- A departure a `todo.md` item plans away is named with that item, not raised.
- A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the `todo.md` item that ends it. Weigh it hard: that it was decided is no reason.
- Report under one heading per yardstick.
+2 -2
View File
@@ -12,8 +12,8 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
2. **Read every file under `~/.claude/principles/`**, the shared principles, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory org guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently.
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them.
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; delete nothing else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5. **Mutation-test the changed lines.** Run the project's documented mutation command, or else a widely deployed mutation tool for the language: cargo-mutants for Rust, Infection for PHP, mutmut for Python, Stryker for JavaScript and TypeScript. Limit it to the lines the change adds or modifies, through the tool's own option where it has one (cargo-mutants `--in-diff <diff file>`, Infection `--git-diff-lines`, Stryker `--mutate <file>:<lines>`); otherwise mutate only the changed files and keep only the mutants on changed lines. Run it through the project's tooling, as in step 4, on a scratch copy: the tools write files. Report its wall time and mutant count in Coverage & Verification, or why nothing was mutated. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch.
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; delete nothing else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5. **Mutation-test the changed lines.** Run the project's documented mutation command, or else a widely deployed mutation tool for the language: cargo-mutants for Rust, Infection for PHP, mutmut for Python, Stryker for JavaScript and TypeScript. Limit it to the lines the change adds or modifies, through the tool's own option where it has one (cargo-mutants `--in-diff <diff file>`, Infection `--git-diff-lines`, Stryker `--mutate <file>:<lines>`); otherwise mutate only the changed files and keep only the mutants on changed lines. Run it through the project's tooling and run-heavy, as in step 4, on a scratch copy: the tools write files. Under run-heavy, a container that sets neither memory limit gets the slot's share, in MiB in `RUN_HEAVY_MEMORY`. Set the tool's concurrency so that its parallel test runs together fit in that share. Report its wall time and mutant count in Coverage & Verification, or why nothing was mutated. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch.
6. **Two passes minimum, then hunt absences.**
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
- *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity).
+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
+12 -6
View File
@@ -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)
+29 -3
View File
@@ -1,5 +1,6 @@
"""Entries of Claude Code's transcripts and of its stream-json and json output."""
import json
import typing
def parse_entry(raw: str | bytes) -> dict | None:
@@ -36,8 +37,9 @@ def written_by_human(entry: dict) -> bool:
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
# {"type": "user", "isCompactSummary": true, "message": {"content": "This session is being continued from a previous conversation that ran out of context. ..."}}
def tagged_as_injected(entry: dict) -> bool:
return bool(entry.get("isMeta")) or entry.get("promptSource") in ("sdk", "system")
return bool(entry.get("isMeta")) or bool(entry.get("isCompactSummary")) or entry.get("promptSource") in ("sdk", "system")
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
@@ -67,7 +69,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
@@ -86,11 +88,35 @@ def part_text(part: object) -> str | None:
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
# {"type": "tool_use", "id": "toolu_01…", "name": "Bash", "input": {"command": "echo hi"}}
def tool_call(part: object) -> tuple[object, object] | None:
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
def tool_use_id(part: object) -> str | None:
return part["id"] if isinstance(part, dict) and part.get("type") == "tool_use" and isinstance(part.get("id"), str) else None
class ToolResult(typing.NamedTuple):
tool_use_id: str
text: str
failed: bool
# {"type": "tool_result", "tool_use_id": "toolu_01…", "content": "hi"}, its content also as [{"type": "text", "text": "hi"}], and with "is_error": true where the call failed
def tool_result(part: object) -> ToolResult | None:
if not isinstance(part, dict) or part.get("type") != "tool_result":
return None
return ToolResult(str(part.get("tool_use_id")), result_text(part.get("content")), bool(part.get("is_error")))
def result_text(content: object) -> str:
if isinstance(content, str):
return content
# Claude Code may split one text across blocks, even inside a line, so the blocks join with nothing between them.
return "".join(part_text(part) or "" for part in content) if isinstance(content, list) else ""
# stream-json's last line: {"type": "result", "subtype": "success", ...}
def ends_stream(event: dict) -> bool:
return event.get("type") == "result"
+5
View File
@@ -37,6 +37,11 @@ def session_files(transcript: str) -> list[str]:
return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*"))
# <session id>/subagents/agent-<agent id>.jsonl, beside <session id>.jsonl
def subagent_transcript(session_transcript: str, agent_id: str) -> str:
return os.path.join(session_transcript.removesuffix(".jsonl"), "subagents", f"agent-{agent_id}.jsonl")
def delete_session(session: Session) -> Failure | None:
path = transcript_file(session)
if path is None:
+23 -5
View File
@@ -39,6 +39,14 @@ class Render(unittest.TestCase):
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.\n\n[loop] Your question: A or B?\n\n[human] use B')
class Verbatim(unittest.TestCase):
def test_a_quote_holds_only_word_for_word_less_emphasis_and_whitespace(self):
self.assertTrue(transcript.verbatim("Merge **ff-only**.", "Merge ff-only.\nNever squash."))
self.assertTrue(transcript.verbatim("Merge _ff-only_.", "Merge ff-only.\nNever squash."))
self.assertFalse(transcript.verbatim("Merge ... squash.", "Merge ff-only.\nNever squash."))
self.assertFalse(transcript.verbatim("", "Merge ff-only."))
class FirstTimestampedLine(unittest.TestCase):
def test_skips_the_lines_every_chunk_shares_and_else_takes_the_first(self):
self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\nnot JSON\n{"timestamp": "t"}\n{"timestamp": "u"}\n'), b'{"timestamp": "t"}')
@@ -46,6 +54,15 @@ class FirstTimestampedLine(unittest.TestCase):
self.assertEqual(transcript.first_timestamped_line(b""), b"")
class CurrentThread(unittest.TestCase):
def test_a_parent_cycle_ends_the_thread(self):
looped = [{"uuid": "a", "parentUuid": "b"}, {"uuid": "b", "parentUuid": "a"}]
self.assertEqual([entry["uuid"] for entry in transcript.current_thread(looped)], ["a", "b"])
def test_entries_without_a_uuid_make_no_thread(self):
self.assertEqual(transcript.current_thread([{"type": "summary"}]), [])
class HumanTurns(unittest.TestCase):
def test_counts_typed_turns_and_not_tool_results(self):
self.assertEqual(transcript.human_turns([
@@ -58,6 +75,7 @@ class HumanTurns(unittest.TestCase):
{**human([{"type": "text", "text": "<task-notification>done</task-notification>"}]), "promptSource": "system"},
{**human("peer message"), "isMeta": True},
{**human("the loop's own prompt"), "promptSource": "sdk"},
{**human("This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation."), "isCompactSummary": True},
human([{"type": "text", "text": "[Request interrupted by user]"}]),
human([]),
queued("typed while claude worked", "human"),
@@ -85,12 +103,12 @@ class Parse(unittest.TestCase):
class ClaudeReply(unittest.TestCase):
@staticmethod
def claude(*outcomes):
def claude(*results):
def run(args, cwd, prompt):
outcome = outcomes[0]
if isinstance(outcome, OSError):
raise outcome
return subprocess.CompletedProcess(args, *outcome)
result = results[0]
if isinstance(result, OSError):
raise result
return subprocess.CompletedProcess(args, *result)
return run
def test_runs_claude_headless_with_the_args_in_cwd_on_the_prompt(self):
+26
View File
@@ -21,6 +21,21 @@ def read_transcript(path: str) -> list[dict] | Failure:
return Failure(f"could not read the transcript {path}: {failure.strerror}")
def current_thread(entries: list[dict]) -> list[dict]:
"""The entries of the transcript's current thread since its last compaction, oldest first: the newest entry with a uuid and its ancestors by parentUuid.
That leaves out a branch the session rewound, and the results of parallel tool calls that Claude Code chains on a side branch."""
chained = [entry for entry in entries if isinstance(entry.get("uuid"), str)]
by_uuid = {entry["uuid"]: entry for entry in chained}
found: list[dict] = []
entry = chained[-1] if chained else None
# A compaction writes {"type": "system", "subtype": "compact_boundary", "parentUuid": null, ...}, so the thread starts there; the length check stops a parent cycle.
while entry is not None and len(found) < len(chained):
found.append(entry)
entry = by_uuid.get(entry.get("parentUuid"))
return found[::-1]
# The lines before it, such as the session's title, are the same for every chunk of a project.
def first_timestamped_line(raw: bytes) -> bytes:
lines = raw.splitlines()
@@ -51,3 +66,14 @@ def part_line(part: object, tool_input_chars: int) -> str:
name, arguments = call
return f"[tool {name}] {json.dumps(arguments, ensure_ascii=False)[:tool_input_chars]}"
return ""
def verbatim(quote: str, text: str) -> bool:
"""Whether text holds the judge's quote word for word, once plain strips emphasis and reflows whitespace in both."""
quoted = plain(quote)
return quoted != "" and quoted in plain(text)
def plain(text: str) -> str:
# The judge drops markdown emphasis and reflows whitespace when it quotes.
return " ".join(text.replace("*", "").replace("_", "").split())
+7 -7
View File
@@ -1,37 +1,37 @@
import json
import pathlib
import sys
import typing
from failure import Failure
from file_writes import replace_json
# A failure only warns: claude still opens, and the human answers Claude Code's trust dialog.
def trust(config: pathlib.Path, roots: list[str]) -> None:
def trust(config: pathlib.Path, roots: list[str], note: typing.Callable[[str], None]) -> None:
try:
with open(config, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError) as failure:
print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr)
note(f"could not read {config}: {getattr(failure, 'strerror', failure)}")
return
marked = mark_trusted(data, roots)
if isinstance(marked, Failure):
print(f"could not read {config}: {marked.reason}", file=sys.stderr)
note(f"could not read {config}: {marked.reason}")
return
updated, untrusted = marked
if not untrusted:
return
if unwritten := replace_json(config, updated, indent=2):
print(f"could not write {config}: {unwritten.reason}", file=sys.stderr)
note(f"could not write {config}: {unwritten.reason}")
return
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
note("trusted for the interrupt: " + ", ".join(untrusted))
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict):
return Failure('not an object whose "projects" is an object')
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
if (wrong := next((path for path, settings in projects.items() if not isinstance(settings, dict)), None)) is not None:
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
+122
View File
@@ -0,0 +1,122 @@
"""What a docker command asks of docker: its subcommand, and whether a container it makes has a memory limit and a swap limit. capped adds the limits such a container lacks."""
import re
import typing
# The options of docker, docker buildx and docker compose that take a value, so the value is not read as a subcommand.
DOCKER_VALUED = frozenset({"--ansi", "--builder", "--config", "--context", "--env-file", "--file", "--host", "--log-level", "--parallel", "--profile", "--progress", "--project-directory", "--project-name", "--tlscacert", "--tlscert", "--tlskey", "-c", "-f", "-H", "-l", "-p"})
# The subcommands that make a container, whose memory limits docker reads from the same options.
STARTS_CONTAINER = (["container", "create"], ["container", "run"], ["create"], ["run"])
# A size as docker reads one, such as 4g, 512M or 1.5GiB, each unit a power of 1024: go-units' RAMInBytes pattern, less a number with two points, such as 1.2.3, which its float parse refuses.
SIZE = r"(\d+(?:\.\d+)?)([kKmMgGtTpP]?)[iI]?[bB]?"
# Docker's documented floor for --memory, 6m: a smaller value, such as grep -m 1's, belongs to the container's own command.
MEMORY_FLOOR = 6 * 1024**2
MEMORY_OPTIONS = ("-m", "--memory")
SWAP_OPTIONS = ("--memory-swap",)
class Option(typing.NamedTuple):
"""An option the arguments give: where it stands, how many words it takes, and its value."""
at: int
length: int
value: str
def size(value: str) -> float | None:
"""The bytes a docker size spells; None for a value that is no size."""
spelled = re.fullmatch(SIZE, value)
return float(spelled.group(1)) * 1024 ** " kmgtp".index(spelled.group(2).lower() or " ") if spelled else None
def memory_limit(value: str) -> bool:
return (size(value) or 0) >= MEMORY_FLOOR
def swap_limit(value: str) -> bool:
"""Whether a --memory-swap value limits swap: -1 leaves it unlimited, and 0 leaves it unset, which docker reads as twice the memory limit."""
return bool(size(value))
def unset_swap(value: str) -> bool:
return value == "-1" or size(value) == 0
def zero(value: str) -> bool:
return size(value) == 0
def docker_subcommand(arguments: list[str]) -> list[str]:
"""The subcommand docker's arguments name, past its options: such as ["build"], ["compose", "run"] or ["buildx", "build"]."""
return [arguments[at] for at in subcommand_at(arguments)]
def subcommand_at(arguments: list[str]) -> list[int]:
"""Where in docker's arguments each word of its subcommand stands, so a global option's value that spells it, as in --context run, is not taken for it."""
positional: list[int] = []
skip = False
for at, word in enumerate(arguments):
if skip:
skip = False
elif word.startswith("-"):
skip = word in DOCKER_VALUED
else:
positional.append(at)
if arguments[positional[0]] not in ("buildx", "compose", "container") or len(positional) == 2:
break
return positional
def unlimited(arguments: list[str]) -> bool:
"""Whether docker's arguments make a container, with docker run or docker create, and leave its memory or its swap without a limit.
The container's own arguments, past its image, are read too: telling them apart needs every value-taking option of docker run. So a -m 4g there reads as a limit, while python -m pytest and grep -m 1 do not, since neither is a size docker takes.
"""
subcommand = docker_subcommand(arguments)
limited = option_value(arguments, MEMORY_OPTIONS, memory_limit) and option_value(arguments, SWAP_OPTIONS, swap_limit)
return subcommand in STARTS_CONTAINER and not limited and not helped(arguments)
def helped(arguments: list[str]) -> bool:
"""Whether docker only prints its help: a --help before the subcommand or as the first word after it, not one the container's own command takes."""
after = subcommand_at(arguments)[-1] + 1
return "--help" in arguments[:after + 1]
def capped(arguments: list[str], share: str) -> list[str]:
"""docker's arguments, with each limit a container they make lacks added right after the subcommand.
A container that sets neither limit gets share for both. One that sets one limit gets the other at the same size, since docker refuses less swap than memory. A --memory-swap of -1 or 0 is dropped; every other word stays. Arguments with a --memory of 0 anywhere come back unchanged.
"""
# A -m 0 asks docker for unlimited memory, and would override an added limit; it may also be the container's own, as in grep -m 0, so it is neither dropped nor capped.
if not unlimited(arguments) or option_value(arguments, MEMORY_OPTIONS, zero):
return arguments
memory = option_value(arguments, MEMORY_OPTIONS, memory_limit)
swap = option_value(arguments, SWAP_OPTIONS, swap_limit)
rest = without(arguments, SWAP_OPTIONS, unset_swap)
limits = ([] if memory else ["--memory", swap or share]) + ([] if swap else ["--memory-swap", memory or share])
after = subcommand_at(rest)[-1] + 1
return [*rest[:after], *limits, *rest[after:]]
def option_value(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> str | None:
"""The value the arguments give one of the options, where it fits, as its next word or attached, as in -m4g or --memory=4g; None where they give none."""
found = option_at(arguments, options, fits)
return found.value if found else None
def without(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> list[str]:
"""The arguments with each of the options removed, with its value, where the value fits."""
while found := option_at(arguments, options, fits):
arguments = [*arguments[:found.at], *arguments[found.at + found.length:]]
return arguments
def option_at(arguments: list[str], options: tuple[str, ...], fits: typing.Callable[[str], bool]) -> Option | None:
"""Where the arguments first give one of the options, with a value that fits."""
for at, (word, following) in enumerate(zip(arguments, [*arguments[1:], ""])):
for option in options:
attached = word.removeprefix(option if len(option) == 2 else option + "=")
if attached != word and fits(attached):
return Option(at, 1, attached)
if word == option and fits(following):
return Option(at, 2, following)
return None
+6 -3
View File
@@ -11,6 +11,7 @@ class Commit:
directory: str
messages: list[str]
from_file: bool
amends: bool
def commits(simples: list[Simple], home: str) -> list[Commit]:
@@ -36,14 +37,16 @@ def git_subcommand(words: list[str], directory: str, home: str) -> tuple[str, li
return None
def commit_message(args: list[str]) -> tuple[list[str], bool]:
"""git commit's messages, and whether it reads one from a file."""
def commit_message(args: list[str]) -> tuple[list[str], bool, bool]:
"""git commit's messages, whether it reads one from a file, and whether it amends."""
messages = []
from_file = False
amends = False
words = iter(args)
for word in words:
if word == "--":
break
amends = amends or word == "--amend"
name, equals, value = word.partition("=")
if name in ("--message", "--file"):
given = value if equals else next(words, "")
@@ -55,4 +58,4 @@ def commit_message(args: list[str]) -> tuple[list[str], bool]:
continue
messages += [given] if name == "--message" else []
from_file = from_file or name == "--file"
return messages, from_file
return messages, from_file, amends
+21 -7
View File
@@ -1,4 +1,6 @@
"""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
@@ -58,20 +60,32 @@ def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, s
return ref if isinstance(ref, Failure) else (ref, note)
def default_ref(cwd: str | None = None, timeout: float | None = None) -> str | Failure:
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master. Asking origin, where the checkout records no default branch for it, fails after timeout seconds."""
remotes = git("remote", cwd=cwd)
def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> str | Failure:
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master.
Where the checkout records no default branch for origin, it asks origin, which fails after timeout seconds. Guarded, it runs git as `git` does with guarded, and fails there instead of asking origin."""
remotes = git("remote", cwd=cwd, guarded=guarded)
if isinstance(remotes, Failure):
return remotes
if "origin" in remotes.split():
recorded = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd)
return recorded.strip() if not isinstance(recorded, Failure) else origin_head(cwd, timeout)
recorded = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded)
if not isinstance(recorded, Failure):
return recorded.strip()
return Failure("origin records no default branch") if guarded else origin_head(cwd, timeout)
for branch in ("main", "master"):
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd), Failure):
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd, guarded=guarded), Failure):
return branch
return Failure("no origin remote, and no main or master branch to take as the default branch")
def branch_titles(default: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> list[str] | Failure:
"""The titles of the branch's own commits since default, newest first, read in cwd, else in the current directory.
--first-parent leaves out the commits a merge brought in, such as those of a default branch newer than the one the checkout last fetched."""
titles = git("log", "--first-parent", "--format=%s", f"{default}..HEAD", cwd=cwd, timeout=timeout, guarded=guarded)
return titles if isinstance(titles, Failure) else titles.splitlines()
def origin_head(cwd: str | None, timeout: float | None) -> str | Failure:
"""The default branch origin names, for a clone made by `git init` and `git remote add`, which records none."""
listed = git("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout)
+2 -1
View File
@@ -34,13 +34,14 @@ from project_key import checkout_of
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 loop_claude.stop import Stop
from loop_claude.verdicts import Verdict
TOOL = "judge-replay"
USAGE = f"{TOOL} <model>, a model on the routing ladder"
+9 -9
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
@@ -16,12 +16,12 @@ Kind = str
@dataclasses.dataclass(frozen=True)
class Case:
"""One archived verdict: on_record, judged at its UTC stamp."""
"""One archived verdict: the kind the archive gives it, judged at its UTC stamp."""
root: str
task: str
transcript: pathlib.Path
at: str
on_record: Kind
archived_kind: Kind
def case_from(root: str, outcomes: str, transcript: pathlib.Path) -> Case | None:
@@ -40,8 +40,8 @@ def sample(cases: list[Case], per_kind: int) -> list[Case]:
seen: collections.Counter[Kind] = collections.Counter()
kept = []
for found in sorted(cases, key=lambda found: (found.at, found.root, str(found.transcript)), reverse=True):
seen[found.on_record] += 1
if seen[found.on_record] <= per_kind:
seen[found.archived_kind] += 1
if seen[found.archived_kind] <= per_kind:
kept.append(found)
return kept[::-1]
@@ -63,12 +63,12 @@ def verdict_kind(verdict: Verdict | Failure) -> Kind:
def reproduced(case: Case, kind: Kind) -> list[Kind]:
"""The kind on record, where the reply returns it: a rung is held only to a verdict the reference judge reproduces."""
return [kind] if kind == case.on_record else []
"""The archived kind, where the reply returns it: a rung is held only to a verdict the reference judge reproduces."""
return [kind] if kind == case.archived_kind else []
def report(model: str, reference: Rung, cases: list[Case], replay: Replay[Case, Kind, Kind]) -> str:
kinds = collections.Counter(found.on_record for found in cases)
kinds = collections.Counter(found.archived_kind for found in cases)
unreproduced = [(found, kind) for found, kind in zip(cases, replay.on_reference) if not reproduced(found, kind)]
lines = [
f"Replayed {len(cases)} verdicts of {model} projects: {', '.join(f'{count} {kind}' for kind, count in sorted(kinds.items()))}.",
@@ -86,4 +86,4 @@ def report(model: str, reference: Rung, cases: list[Case], replay: Replay[Case,
def missed_lines(missed: list[tuple[Case, Kind]]) -> list[str]:
return [f" {found.root} {found.at}: on record {found.on_record}, replayed {kind}" for found, kind in missed]
return [f" {found.root} {found.at}: archived {found.archived_kind}, replayed {kind}" for found, kind in missed]
+10 -10
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
@@ -25,8 +25,8 @@ MIDDLE = Rung("claude-sonnet-5-5", "high")
REFERENCE = Rung("claude-opus-5-5", "xhigh")
def case(at, on_record):
return Case("/code/p", "Do the next chunk.", TRANSCRIPT, at, on_record)
def case(at, archived_kind):
return Case("/code/p", "Do the next chunk.", TRANSCRIPT, at, archived_kind)
class CaseFrom(unittest.TestCase):
@@ -37,7 +37,7 @@ class CaseFrom(unittest.TestCase):
def test_reads_each_kind_of_verdict(self):
for verdict in (FINISHED, UNFINISHED, INTERRUPTED, ANSWERED):
found = case_from("/code/p", f"Task: t\n\n2026-10-14T10:00:00Z {verdict}\n\nmore\n", TRANSCRIPT)
self.assertEqual(found.on_record, verdict)
self.assertEqual(found.archived_kind, verdict)
def test_skips_a_copy_with_no_verdict(self):
self.assertIsNone(case_from("/code/p", "Task: t\n\n2026-10-14T10:00:00Z Stepped up\n\nWorker: y\n", TRANSCRIPT))
@@ -60,7 +60,7 @@ class VerdictKind(unittest.TestCase):
class Reproduced(unittest.TestCase):
def test_holds_a_rung_to_a_verdict_only_where_the_reference_returned_the_kind_on_record(self):
def test_holds_a_rung_to_a_verdict_only_where_the_reference_returned_the_archived_kind(self):
self.assertEqual(reproduced(case("2026-10-14T10:00:00Z", FINISHED), FINISHED), [FINISHED])
self.assertEqual(reproduced(case("2026-10-14T10:00:00Z", FINISHED), INTERRUPTED), [])
@@ -72,10 +72,10 @@ class Report(unittest.TestCase):
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, replay).splitlines(), [
"Replayed 2 verdicts of claude-opus-5-5 projects: 1 Verdict: finished, 1 Verdict: interrupt.",
"The reference judge, claude-opus-5-5 at xhigh effort, reproduced 1. It returned another kind on:",
" /code/p 2026-10-14T10:00:00Z: on record Verdict: finished, replayed Verdict: unfinished",
" /code/p 2026-10-14T10:00:00Z: archived Verdict: finished, replayed Verdict: unfinished",
"claude-sonnet-5-5 at high effort missed 0.",
"claude-haiku-5-5 at xhigh effort missed 1:",
" /code/p 2026-10-14T10:00:01Z: on record Verdict: interrupt, replayed Verdict: finished",
" /code/p 2026-10-14T10:00:01Z: archived Verdict: interrupt, replayed Verdict: finished",
"Lowest rung that, like each rung above it, returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort",
])
missed_all = report("claude-opus-5-5", REFERENCE, cases, Replay([FINISHED, INTERRUPTED], [Tried(MIDDLE, [Miss(cases[1], INTERRUPTED, FINISHED)])], None)).splitlines()
@@ -114,7 +114,7 @@ class Main(unittest.TestCase):
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
@@ -122,7 +122,7 @@ 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):
@@ -136,7 +136,7 @@ class Main(unittest.TestCase):
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-opus-5-5 at medium effort\n"))
for said in ("The task an agent was given:\nDo it.", "1. Ship.", "From ~/.claude/CLAUDE.md:\nBe kind."):
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])
-31
View File
@@ -1,31 +0,0 @@
from git_repo import commits_since, file_at, full_history, git, newest_release_tag
from failure import Failure
from comprehension_history import HISTORY, HistoryChange
def history_changes(default: str) -> list[HistoryChange] | Failure:
"""Each merged change on the default branch that touched the history, newest first; a merge commit counts as one change against its first parent."""
if partial := full_history():
return partial
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
if isinstance(commits, Failure):
return commits
changes = []
for commit in commits.split():
before = file_at(f"{commit}^1", HISTORY)
if isinstance(before, Failure):
return before
after = file_at(commit, HISTORY)
if isinstance(after, Failure):
return after
changes.append(HistoryChange(commit, before, after))
return changes
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
+30
View File
@@ -0,0 +1,30 @@
from failure import Failure
from git_repo import file_at, full_history, git
from comprehension_history import HISTORY, HistoryChange
def history_changes(default: str) -> list[HistoryChange] | Failure:
"""Each merged change on the default branch that touched the history, newest first."""
if partial := full_history():
return partial
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
if isinstance(commits, Failure):
return commits
changes = []
for commit in commits.split():
change = history_change(commit)
if isinstance(change, Failure):
return change
changes.append(change)
return changes
def history_change(commit: str) -> HistoryChange | Failure:
"""The history before and after commit. A merge commit counts as one change, against its first parent."""
before = file_at(f"{commit}^1", HISTORY)
if isinstance(before, Failure):
return before
after = file_at(commit, HISTORY)
if isinstance(after, Failure):
return after
return HistoryChange(commit, before, after)
@@ -4,13 +4,13 @@ import time
from larv_review.agreement import agreement_report
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.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:
@@ -22,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
@@ -75,7 +77,7 @@ def scored_seats(given: SeatsFile) -> ScoringRun | Failure:
def read_seats(path: pathlib.Path, paired: bool) -> tuple[Heading, SeatsFile] | Failure:
"""The seats file and the heading its record goes under. Fails when the file names a commit the checkout lacks, or when the history already holds an entry on what it reads; it runs before anything is printed."""
"""The seats file and the heading its entry goes under. Fails when the file names a commit the checkout lacks, or when the history already holds an entry on what it reads; it runs before anything is printed."""
try:
given = seats_file(path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError) as failure:
+18 -18
View File
@@ -22,19 +22,18 @@ measured commit is the default branch's newest merged change that adds a paired
run to the history; a merge commit counts as one change against its first parent. With none, it is
the merge base of HEAD and the default branch.
round-count prints each pass's round count among the commits not yet on the default branch whose
titles open `Answer <pass> round <n>:`, ignoring case. The count is the highest <n>, or the number of
such commits when that is more. At or past the cap of {cap} rounds, it says to ask the human before
another round. It also lists each name in such a title that is not a pass.
round-count prints each pass's round count among the branch's commits since the default branch
whose titles open `Answer <pass> round <n>:`, ignoring case. It follows first parents, as
rule-hook's round-cap does. The count is the highest <n>, or the number of such commits when that
is more. At or past the cap of {cap} rounds, it says the pass takes no more rounds. 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.
@@ -88,7 +87,7 @@ and the inherited architect vote alike overall in a paired ruling more often tha
same way in a pair. It prints both counts. It opens `Unchecked:` until the history holds {pairs} such
pairs and one paired ruling, then `Assumption holds:` or `Assumption fails:`, and exits 0 each time.
Each record is appended to the history, created when missing, under a heading of the current UTC
Each entry is appended to the history, created when missing, under a heading of the current UTC
time and the seats file's first line. Each commit that line names must be in the checkout. It exits 1
when the history already holds an entry on what that line reads.
@@ -103,15 +102,16 @@ import re
import sys
import typing
from round_titles import CAP, PASSES, round_counts
from git_repo import default_branch, git, top
from git_repo import branch_titles, default_branch, git, top
from round_titles import CAP, round_counts
from failure import Failure
from comprehension_history import FLOOR
from larv_review.git import history_changes
from larv_review.history_changes import history_changes
from larv_review.ruling_base import measured_commit
from larv_review.agreement import MIN_PAIRS
from review_passes import PASSES
from larv_review.plan import plan_reasons
from larv_review.record import record_ruling, record_scoring, show_agreement, show_places
from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places
from review_folder import REPORTS, review_folder
USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement"
@@ -195,10 +195,10 @@ def show_ruling_base(default: str) -> Failure | None:
def round_count(default: str) -> Failure | None:
titles = git("log", "--format=%s", f"{default}..HEAD")
titles = branch_titles(default)
if isinstance(titles, Failure):
return titles
for name, count in round_counts(titles.splitlines()).items():
for name, count in round_counts(titles).items():
print(f"{name}: {count}{cap_note(count) if name in PASSES else ', not a pass: check the commit title'}")
return None
@@ -206,7 +206,7 @@ def round_count(default: str) -> Failure | None:
def cap_note(count: int) -> str:
if count < CAP:
return ""
return f", {'at' if count == CAP else 'past'} the cap: ask the human before another round"
return f", {'at' if count == CAP else 'past'} the cap: no more rounds"
def needs_scoring_run(default: str, ids: list[int]) -> Failure | None:
+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)
+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]
+91 -26
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"), [])]
@@ -260,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):
@@ -355,14 +388,21 @@ class LarvReviewTool(unittest.TestCase):
self.commit("Answer stability round 1: a")
self.commit("Answer stability round 2: b")
self.commit("Answer prose round 1: c")
self.commit("Answer stability round 3: d")
ran = self.run_tool("round-count")
self.assertIn("stability: 3, at the cap: ask the human before another round\n", ran.stdout)
self.commit("Answer stability round 4: e")
self.assertIn("stability: 4, past the cap: ask the human before another round\n", self.run_tool("round-count").stdout)
self.assertIn("stability: 2, at the cap: no more rounds\n", ran.stdout)
self.commit("Answer stability round 3: d")
self.assertIn("stability: 3, past the cap: no more rounds\n", self.run_tool("round-count").stdout)
self.assertIn("prose: 1\n", ran.stdout)
self.assertIn("architecture: 0\n", ran.stdout)
def test_leaves_out_the_round_commits_of_a_branch_merged_in_as_the_hook_does(self):
self.git("switch", "-q", "-c", "sibling")
self.commit("Answer stability round 1: a")
self.commit("Answer stability round 2: b")
self.git("switch", "-q", "chunk")
self.git("merge", "-q", "--no-ff", "-m", "Merge sibling", "sibling")
self.assertIn("stability: 0\n", self.run_tool("round-count").stdout)
def test_says_whether_a_scoring_run_is_due_and_refuses_an_unknown_item(self):
self.assertEqual(self.run_tool("needs-scoring-run", "1").stdout, "Scoring run due: the chunk leaves release 0.1.0 with no plan item.\n")
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
@@ -379,6 +419,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")
@@ -420,6 +478,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")
@@ -525,7 +590,7 @@ class LarvReviewTool(unittest.TestCase):
def test_states_its_rules_and_finds_origins_default_branch_where_the_clone_recorded_none(self):
helped = self.run_tool("--help")
self.assertEqual(helped.returncode, 0, helped.stderr)
self.assertIn("cap of 3 rounds", helped.stdout)
self.assertIn("cap of 2 rounds", helped.stdout)
self.git("remote", "set-head", "origin", "--delete")
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
+4 -4
View File
@@ -2,7 +2,7 @@ import dataclasses
import sys
import uuid
from loop_claude.effects import Effects
from loop_claude.effects import Effects, say
from failure import Failure
from claude_code.transcript import human_turns, read_transcript
from loop_claude.stop import needs_human, needs_terminal, Stop
@@ -24,7 +24,7 @@ class Talk:
def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop:
"""Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
print(f"\n{question}", file=sys.stderr)
say(f"\n{question}", effects)
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
return stop
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK.
@@ -34,7 +34,7 @@ def put_question(question: str, answer_here: bool, effects: Effects) -> str | Ta
try:
answer = effects.input(ASK_ANSWER).strip()
except EOFError:
print(file=sys.stderr)
print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time.
return needs_human(ANSWER_QUESTION, "the input ended")
if not answer:
return needs_human(ANSWER_QUESTION, "nothing was typed")
@@ -57,7 +57,7 @@ def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths
def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[str, str], effects: Effects) -> Failure | None:
"""Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start."""
trust(paths.claude_json, worktrees(root, effects))
trust(paths.claude_json, worktrees(root, effects), lambda text: say(text, effects))
try:
effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root, env)
except OSError as failure:
+46 -111
View File
@@ -6,13 +6,12 @@ import typing
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typed_answer
from claude_code.reply import claude_reply, Limited
from loop_claude.effects import Effects
from loop_claude import escalation_mark
from failure import Failure
from loop_claude.project.records import HUMAN_RULE_NAMES
from claude_code.entries import human_text, loop_text
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
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 claude_code.transcript import plain, verbatim
from loop_claude.cycle.retry import retried
from model_routing.ladder import Rung
from loop_claude.stop import Stop
@@ -22,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 "
@@ -32,48 +31,48 @@ 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 agent 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."})
# 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 the transcript passage where the trigger fired, such as a review round's commit title or the agent's report of the finding or failing test. Where a [step] line says loop-claude stepped the agent up a rung, quote only the agent'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 agent's question; else what shows the chunk finished or the work remaining."})
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: loop_claude/escalation_mark.py.
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. " + escalation_mark.QUOTE_AFTER_STEP + " Never a later mention of the trigger, and never the request itself."})
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."})
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
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."})
@@ -94,67 +93,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
# How many transcript entries the judge read, which judge_once stamps. An escalation the verdict carries moves the route's mark there; one on a verdict never stamped, None, steps nothing.
entries_read: int | None = None
@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
entries_read: int | None = None
@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
# As on Interrupt.
entries_read: int | None = None
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 agent'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 agent's question. An escalation must quote both this and shown: a misquote, or a quote of a passage before the mark, drops the escalation, so the worker's rung holds.
# escalation_mark.since_step's lines. An escalation must quote both these and shown: a misquote drops the escalation, as escalation_mark.checked says.
since_step: str
# README.md's premises and the records. A quoted answer must quote them: a misquote puts the question to the human.
quotable: str
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
def verdict_from(output: object) -> Verdict | Failure:
if not isinstance(output, dict):
return Failure("the judge returned no reply")
@@ -162,20 +110,20 @@ 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], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
@@ -183,10 +131,10 @@ def judge(root: str, task: str, premises: str, records: str, entries: list[dict]
def judge_once(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run on the transcript's entries, as judge retries it; judge-replay replays it. escalated_at is the route's mark: an escalation quote counts only from the entries after it."""
"""One judge run on the transcript's entries, as judge retries it; judge-replay replays it. escalated_at is the route's mark, as loop_claude/escalation_mark.py says."""
prompt, grounds = judge_prompt(task, premises, records, entries, escalated_at)
verdict = run_judge(root, judge_args(rung), prompt, grounds, effects)
return dataclasses.replace(verdict, entries_read=len(entries)) if isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) else verdict
return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, len(entries))
def judge_args(rung: Rung) -> list[str]:
@@ -200,7 +148,7 @@ def judge_args(rung: Rung) -> list[str]:
def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run, each quote in its verdict checked against grounds as Grounds says. quotes_checked checks the quoted answer and the escalation: neither misquote is a Failure, which would otherwise exit an unattended loop."""
"""One judge run, each quote in its verdict checked against grounds as Grounds says."""
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
if isinstance(reply, Failure | Limited):
return reply
@@ -214,28 +162,25 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict:
"""The verdict with its quoted answer and its escalation checked, as Grounds says; a quoted answer put to the human keeps the escalation it carried."""
"""The verdict with its quoted answer and its escalation checked. A quoted answer that neither README.md's premises nor the records hold goes to the human as an interrupt, which keeps the escalation the answer carried. Neither misquote is a Failure, which would otherwise exit an unattended loop."""
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable):
verdict = Interrupt(verdict.evidence, verdict.question, verdict.escalation, verdict.bundled)
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
verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, highest_likelihood_taken_in=verdict.highest_likelihood_taken_in)
return escalation_mark.checked(verdict, since=grounds.since_step, shown=grounds.shown)
def judge_prompt(task: str, premises: str, records: str, entries: list[dict], escalated_at: int) -> tuple[str, Grounds]:
"""The prompt, and what the judge's quotes are checked against. Where escalated_at, the route's mark, is above 0, the prompt shows STEP_LINE after that many entries."""
transcript = "\n\n".join(part for part in (render(entries[:escalated_at], typed_answer), STEP_LINE if escalated_at else "", render(entries[escalated_at:], typed_answer)) if part)
agents_own = [entry for entry in entries[escalated_at:] if human_text(entry) is None and loop_text(entry) is None]
"""The prompt, and what the judge's quotes are checked against."""
transcript = escalation_mark.transcript(entries, escalated_at, typed_answer)
head = (
f"From README.md:\n{premises}\n\n"
f"The records: the project's working rules and decisions, then the human's rules for every project:\n{records or 'none'}\n\n"
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 = transcript[max(0, len(transcript) - room):]
return f"{head}{shown}\n\n{JUDGE_RULES}", Grounds(shown, render(agents_own, typed_answer), f"{premises}\n\n{records}")
return f"{head}{shown}\n\n{JUDGE_RULES}", Grounds(shown, escalation_mark.since_step(entries, escalated_at), f"{premises}\n\n{records}")
def grounded(evidence: str, rendered_transcript: str) -> bool:
@@ -249,13 +194,3 @@ def grounded(evidence: str, rendered_transcript: str) -> bool:
return False
at = found + len(fragment)
return fragments != []
def verbatim(quote: str, text: str) -> bool:
quoted = plain(quote)
return quoted != "" and quoted in plain(text)
def plain(text: str) -> str:
# The judge drops markdown emphasis and reflows whitespace when it quotes.
return " ".join(text.replace("*", "").replace("_", "").split())
+89 -81
View File
@@ -1,8 +1,11 @@
from model_routing.ladder import climbed, LADDER, position, review_rungs, REVIEWERS, reviewers_rung, ReviewKind, Rung
from model_routing.route import ESCALATION_MARKER, HIGHEST_ESCAPE_AND_IMPACT, Route
"""What loop-claude says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. In a chunk's first prompt, routed_by places them after its routing sentences where an item routed the chunk, and fresh places them alone otherwise. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict."""
from model_routing.review_choice import chosen, ReviewChoice
from model_routing.ladder import climbed, LADDER, position, Rung
from model_routing.route import ESCALATION_MARKER, Route
from loop_claude.routing import escalation_rungs
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
from markdown_text import listed, quoted
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,27 +13,33 @@ QUOTE_SOURCES = listed(("README.md's Goals and Audience", *RECORD_FILES, *HUMAN_
# Where the worker may write an answer the human typed, so it counts as recorded.
ANSWER_DESTINATIONS = "README.md's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
# Each kind of review, as review_launches names those it launches: a row per pass, since a replay may lower one pass alone. "each reviewer" names every pass no replay lowered.
REVIEWS: tuple[tuple[str, ReviewKind], ...] = (*((f"each {agent}", kind) for kind, agent in REVIEWERS.items()), ("each comprehension seat", "seat"), ("the security pass's subagent", "security"))
# How review_launches names the reviews: "each reviewer" covers every pass with an agent that no replay lowered.
EACH_REVIEWER = "each reviewer"
EACH_SEAT = "each comprehension seat"
THE_SECURITY_PASS = "the security pass's subagent"
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it'
def fresh(task: str, premises: str, route: Route, anchor: Rung | None, facts: str) -> str:
def fresh(task: str, premises: str, route: Route, project: Rung | None, facts: str) -> str:
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
escalated = f"{escalation(route, anchor)}{reruns(route, anchor)}".lstrip()
routed = f"{routed_by(route, anchor)}{recount(route)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "")
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
routed = f"{routed_by(route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, project))
opening = f"{routed}\n\n" if routed else ""
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
def routed_by(route: Route, anchor: Rung | None) -> str:
return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
def routed_by(route: Route, project: Rung | None) -> str:
return " ".join((
f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.",
f"Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.",
*rung_sentences(route, project),
))
def recount(route: Route) -> str:
"""Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code."""
return f" After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
def preflight_facts(printed: str) -> str:
@@ -43,127 +52,126 @@ def preflight_failed(reason: str) -> str:
return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}"
def review_launches(route: Route, anchor: Rung | None) -> str:
"""Which reviews to launch on a rung other than the worker's, and on which, then the rung of each pass a replay lowered; below the project's rung, anchor, also where to launch a subagent that files or scores todo.md items; then taken_in_launches, the reviewers' rung each higher E + I picks. Empty off the ladder.
def review_launches(route: Route, project: Rung | None) -> list[str]:
"""The sentences naming where to launch reviews, in this order; none off the ladder:
- one for each rung, other than the worker's, that a reviewer, a seat or the security pass runs on;
- the rung of each pass a replay lowered;
- where the security pass runs on another rung than the worker's, that a full scan runs only from its subagent;
- where the worker runs below the project's rung, where to launch a subagent that files or scores todo.md items;
- the reviewers' rung each higher E + I picks.
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, it opens: ` Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks. Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Haiku 5.5 at low, and the E + I steps no review up, a sentence follows: ` Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose.`
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they open: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Haiku 5.5 at low, and the E + I steps no review up, a sentence follows: `Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose.`
"""
if anchor is None:
return ""
rungs, reviewers = review_rungs(anchor, route.rung, route.reviewed_on()), reviewers_rung(anchor, route.rung, route.reviewed_on())
lowered_launches = "".join(f" Launch {reviews} instead with the Agent tool set to {rung.agent_args()}, the rung the replay of its pass chose." for reviews, rung in lowered(rungs, reviewers))
scan = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them." if rungs["security"] != route.rung else ""
planning = f" Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {anchor.model} <L>` prints." if position(route.rung) < position(anchor) else ""
return f"{shared_launches(rungs, reviewers, route, anchor)}{lowered_launches}{scan}{planning}{taken_in_launches(route, anchor)}"
if project is None:
return []
choice = chosen(project, route)
lowered = [f"Launch each {REVIEWERS[kind]} instead with the Agent tool set to {rung.agent_args()}, the rung the replay of its pass chose." for kind, rung in choice.lowered.items()]
scan = ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else []
planning = [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if position(route.rung) < position(project) else []
return [*shared_launches(choice, route, project), *lowered, *scan, *planning, *taken_in_launches(choice)]
def shared_launches(rungs: dict[ReviewKind, Rung], reviewers: Rung, route: Route, anchor: Rung) -> str:
"""A sentence for each rung other than the worker's that a review runs on. "each reviewer" names every pass no replay lowered; those run on reviewers."""
together = {"each reviewer": reviewers} | {reviews: rungs[kind] for reviews, kind in REVIEWS if kind not in REVIEWERS}
def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[str]:
"""A sentence for each rung, other than the worker's, that the reviewers no replay lowered, the seats or the security pass run on."""
together = {EACH_REVIEWER: choice.reviewers, EACH_SEAT: choice.seat, THE_SECURITY_PASS: choice.security}
launched: dict[Rung, list[str]] = {}
for reviews, rung in together.items():
if rung != route.rung:
launched.setdefault(rung, []).append(reviews)
return "".join(f" Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, anchor)}." for rung, reviews in launched.items())
return [f"Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, project)}." for rung, reviews in launched.items()]
def lowered(rungs: dict[ReviewKind, Rung], reviewers: Rung) -> list[tuple[str, Rung]]:
"""Each pass a replay put below reviewers, the rung of every other pass, as REVIEWS names it, with the rung the replay chose."""
return [(reviews, rungs[kind]) for reviews, kind in REVIEWS if kind in REVIEWERS and rungs[kind] != reviewers]
def taken_in_launches(choice: ReviewChoice) -> list[str]:
"""The sentence naming the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run, since the judge reports a taken-in item's E + I only as the cycle ends, and loop-claude routes on it from the next cycle. None where no higher E + I picks a higher rung.
def taken_in_launches(route: Route, anchor: Rung) -> str:
"""The rung each higher E + I picks for the reviewers, so the worker reviews an item it takes in on that rung in the same run; the judge reports it as the cycle ends, so loop-claude routes on it only from the next cycle. Empty where no higher E + I picks a higher rung.
For a worker on Opus 5.5 at medium, routed by an item of E + I 6, it reads: ` Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.`
For a worker on Opus 5.5 at medium, on an Opus 5.5 project, routed by an item of E + I 6, it reads: `Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.`
"""
now = review_rungs(anchor, route.rung, route.reviewed_on())
higher: dict[Rung, int] = {}
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
# An E + I that lifts any pass puts every pass on reviewers_rung, since a replay lowers a pass only where the E + I steps no review up.
if review_rungs(anchor, route.rung, escape_and_impact) != now:
higher.setdefault(reviewers_rung(anchor, route.rung, escape_and_impact), escape_and_impact)
if not higher:
return ""
picks = [f"`{rung.agent_args()}` from {escape_and_impact}" for rung, escape_and_impact in higher.items()]
return f" Where an item you take into the chunk has an E + I of {min(higher.values())} or more, launch each reviewer with the Agent tool set to {listed(picks, 'and')}."
if not choice.higher:
return []
picks = [f"`{rung.agent_args()}` from {escape_and_impact}" for rung, escape_and_impact in choice.higher.items()]
return [f"Where an item you take into the chunk has an E + I of {min(choice.higher.values())} or more, launch {EACH_REVIEWER} with the Agent tool set to {listed(picks, 'and')}."]
def rung_named(rung: Rung, route: Route, anchor: Rung) -> str:
"""Why a review runs on rung: it is the project's, anchor, or the one the route's reviewed_on E + I picks, the item's or one taken in."""
if rung == anchor:
def rung_named(rung: Rung, route: Route, project: Rung) -> str:
"""Why a review runs on rung: it is the project's, or the one the route's reviewed_on E + I picks, the item's or one taken in."""
if rung == project:
return "the project's rung"
if route.escape_and_impact_taken_in:
return f"the rung picked by an item of E + I {route.escape_and_impact_taken_in} taken into the chunk"
return f"the rung item {route.item}'s E + I of {route.escape_and_impact} picks"
def escalation(route: Route, anchor: Rung | None) -> str:
"""The prompt's escalation sentences, the marker's among them, each led by a space. Empty off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
def escalation(route: Route, project: Rung | None) -> list[str]:
"""The prompt's escalation sentences, the marker's among them. None off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs.
For a worker on Opus 5.5 at high, on an Opus 5.5 project, routed by item 3 of L 4, they read: ` When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort max`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort max`.`
For a worker on Opus 5.5 at high, on an Opus 5.5 project, routed by item 3 of L 4, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort max`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort max`.`
"""
if anchor is None or route.rung not in LADDER[:-1]:
return ""
if project is None or route.rung not in LADDER[:-1]:
return []
marked = f"Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(anchor, route)]
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(project, route)]
if not rungs:
return " " + " ".join((
return [
f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.",
marked,
))
]
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
return " " + " ".join((
return [
f"When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to {rungs[0]}, one rung above yours{further}; above that, ask the human first.",
marked,
f"Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to {rungs[-1]}.",
))
]
def reruns(route: Route, anchor: Rung | None) -> str:
"""The prompt's sentences naming the rung one above a review's, on which it reruns when it asks: shared_reruns' for a reviewer and a seat, then one for each pass a replay lowered. Empty off the ladder.
def reruns(route: Route, project: Rung | None) -> list[str]:
"""The sentences naming the rung one above a review's, on which it reruns when it asks: shared_reruns' for a reviewer and a seat, then one for each pass a replay lowered. None off the ladder.
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Haiku 5.5 at low, routed by an item of E + I 4, they read: ` A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`. Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead.`
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Haiku 5.5 at low, routed by an item of E + I 4, they read: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.` and `Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead.`
"""
if anchor is None or route.rung not in LADDER:
return ""
rungs, reviewers = review_rungs(anchor, route.rung, route.reviewed_on()), reviewers_rung(anchor, route.rung, route.reviewed_on())
lowered_reruns = "".join(f" Rerun {reviews} that asks with the Agent tool set to `{climbed(rung, 1).agent_args()}` instead." for reviews, rung in lowered(rungs, reviewers))
return f"{shared_reruns(reviewers, rungs['seat'])}{lowered_reruns}"
if project is None or route.rung not in LADDER:
return []
choice = chosen(project, route)
lowered = [f"Rerun each {REVIEWERS[kind]} that asks with the Agent tool set to `{climbed(rung, 1).agent_args()}` instead." for kind, rung in choice.lowered.items()]
return [*shared_reruns(choice), *lowered]
def shared_reruns(reviewers: Rung, seats: Rung) -> str:
"""The sentence naming the rung one above reviewers, the rung of each pass no replay lowered, and one above seats, leaving out one already on the top rung."""
launched = (("reviewer", reviewers), ("comprehension seat", seats))
def shared_reruns(choice: ReviewChoice) -> list[str]:
"""The sentence naming the rung one above choice.reviewers and the one above choice.seat, leaving out either that is already on the top rung."""
launched = (("reviewer", choice.reviewers), ("comprehension seat", choice.seat))
rerun = {name: climbed(rung, 1) for name, rung in launched if rung != LADDER[-1]}
if not rerun:
return ""
return []
if len(set(rerun.values())) == 1:
return f" A {listed(list(rerun), 'or')} that asks for a rerun one rung up reruns with the Agent tool set to `{next(iter(rerun.values())).agent_args()}`."
return f" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."
return [f"A {listed(list(rerun), 'or')} that asks for a rerun one rung up reruns with the Agent tool set to `{next(iter(rerun.values())).agent_args()}`."]
return [f"A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."]
def resumed(unfinished_evidence: str, route: Route, anchor: Rung | None) -> str:
def resumed(unfinished_evidence: str, route: Route, project: Rung | None) -> str:
"""Names the worker's rung, so it learns whether its request for a higher rung went through, and the project's again, since a step-up between cycles may have taken the worker above it."""
on = f" loop-claude runs you on {route.rung}." if anchor else ""
on = f" loop-claude runs you on {route.rung}." if project else ""
ruled = f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{quoted(unfinished_evidence)}\n\n" if unfinished_evidence else " "
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}.{on}{rungs_held(route, anchor)}"
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}.{on}{rungs_held(route, project)}"
def rungs_held(route: Route, anchor: Rung | None) -> str:
def rung_sentences(route: Route, project: Rung | None) -> list[str]:
"""The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run."""
return f"{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
return [*review_launches(route, project), *escalation(route, project), *reruns(route, project)]
def answered(question: str, answer: str, route: Route, anchor: Rung | None, stepped: bool) -> str:
def rungs_held(route: Route, project: Rung | None) -> str:
"""rung_sentences, each after a space, to follow the sentence a prompt ends on."""
return "".join(f" {sentence}" for sentence in rung_sentences(route, project))
def answered(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
"""stepped is whether the answer's ruling stepped the worker up."""
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, anchor, stepped)}"
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, project, stepped)}"
def typed(question: str, answer: str, route: Route, anchor: Rung | None, stepped: bool) -> str:
def typed(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
"""The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it."""
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, anchor, stepped)}"
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, project, stepped)}"
# Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds.
@@ -179,9 +187,9 @@ def typed_answer(prompt: str) -> Typed | None:
return Typed(rest, answer)
def stepped_to(route: Route, anchor: Rung | None, stepped: bool) -> str:
def stepped_to(route: Route, project: Rung | None, stepped: bool) -> str:
"""The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise."""
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, anchor)}" if stepped else ""
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, project)}" if stepped else ""
def past_the_cap(question: str, answer: str, cap: int) -> str:
+3 -4
View File
@@ -1,7 +1,6 @@
import sys
import typing
from loop_claude.effects import Effects
from loop_claude.effects import Effects, say
from failure import Failure
from claude_code.reply import Limited
from loop_claude.stop import Stop
@@ -24,7 +23,7 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec
failures = 0
now = effects.now()
wait = limit_wait(result, now)
print(f"the {who} hit a usage limit ({result.said}); retrying at {effects.local_time(now + wait)}", file=sys.stderr, flush=True)
say(f"the {who} hit a usage limit ({result.said}); retrying at {effects.local_time(now + wait)}", effects)
effects.sleep(wait)
continue
if not isinstance(result, Failure):
@@ -34,7 +33,7 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec
failures += 1
if failures == FAILURES_RUNNING:
return Stop(1, f"the {who} failed three times running: {result.reason}")
print(f"retrying the {who} in a minute: {result.reason}", file=sys.stderr)
say(f"retrying the {who} in a minute: {result.reason}", effects)
effects.sleep(RETRY_DELAY)
+57 -50
View File
@@ -3,12 +3,14 @@ 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 loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
from claude_code.session import delete_session, Session, session_open, transcript_file
from loop_claude.effects import Effects
from loop_claude.cycle.judge import escalation_mark, Finished, Interrupt, judge, QuotedAnswer, Rejected, Unfinished
from loop_claude.effects import Effects, say
from failure import Failure
from loop_claude.routing import judge_rung, stepped_by_ruling
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.cycle.judge import judge, Rejected
from transcript_archive import outcomes
from loop_claude.paths import Paths
from loop_claude.cycle import prompts
@@ -16,8 +18,8 @@ from loop_claude.cycle.interrupt import put_question, talk, Talk
from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried
from model_routing.route import Route
from loop_claude.cycle.worker import run_worker, worker_args
from model_routing.ladder import Rung
from loop_claude.escalation_mark import StepUp
from loop_claude.stop import Stop
from model_routing import worker_rungs
@@ -37,12 +39,9 @@ class Cycle:
task: str
route: Route
# The project's rung; None for a model off the ladder.
anchor: Rung | None
project: Rung | None
# Empty when the previous cycle's verdict was not Unfinished.
unfinished_evidence: str
# Only an interrupt's or a quoted answer's escalation changes the route within a cycle. No transition reads the route or the fields below, so they stay out of the states.
# The route before that ruling stepped it up, for ask and keep_answer to archive and for worker_start to tell the worker; None unless the latest event is that ruling, or the answer the human typed to it.
stepped_from: Route | None = None
@dataclasses.dataclass(frozen=True)
@@ -59,28 +58,31 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
event = step(cycle, state)
if isinstance(event, Stop):
return stopped(cycle, event, event.reason)
cycle = escalated(cycle, event)
# Only a ruling's step-up changes the route within a cycle. No transition reads the current route, so Cycle holds it, not the states.
if isinstance(event, Ruled) and event.step_up:
cycle = dataclasses.replace(cycle, route=event.step_up.after)
state = transition(state, event)
except KeyboardInterrupt:
return stopped(cycle, Stop(130, ""), "Ctrl-C")
return Concluded(state.verdict, cycle.route)
def escalated(cycle: Cycle, event: Event) -> Cycle:
"""The cycle after event. Where the judge interrupted or quoted an answer with an escalation, its route steps up before the human is asked or the worker resumes, so the work after the answer runs on it. stepped_from holds through the answer the human types, so the worker resuming with it is told of the step; a copy on TypedAnswer would give the step a second owner."""
if isinstance(event, HumanTyped):
return cycle
cycle = dataclasses.replace(cycle, stepped_from=None)
if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and cycle.anchor):
return cycle
route = stepped_by_ruling(cycle.anchor, cycle.route, event.verdict.bundled, escalation_mark(event.verdict))
return dataclasses.replace(cycle, route=route, stepped_from=cycle.route if route != cycle.route else None)
def ruling_step_up(cycle: Cycle, verdict: Verdict) -> StepUp | None:
"""The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds."""
if not (isinstance(verdict, Interrupt | QuotedAnswer) and cycle.project):
return None
after = after_ruling(cycle.project, cycle.route, verdict)
return StepUp(cycle.route, after) if after != cycle.route else None
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
path = transcript_file(cycle.session)
failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(str(cycle.route), why), cycle.effects.now()) if path else None
# A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once.
return archived_stop(cycle.project_archive, cycle.session, cycle.task, cycle.route, stop, why, cycle.effects)
def archived_stop(project_archive: pathlib.Path, session: Session, task: str, route: Route, stop: Stop, why: str, effects: Effects) -> Stop:
"""stop, once archived with the route the worker holds. A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once."""
path = transcript_file(session)
failure = archive(project_archive, path, task, outcomes.stopped(route.worker_line(), why), effects.now(), lambda text: say(text, effects)) if path else None
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
@@ -91,12 +93,12 @@ def judge_of(cycle: Cycle) -> Rung:
def step(cycle: Cycle, state: Active) -> Event | Stop:
match state:
case Working(answered, _):
return work(cycle, answered)
case Working(answered, _, step_up):
return work(cycle, answered, step_up)
case Judging(transcript_path, _):
return rule(cycle, transcript_path)
case Interrupting(transcript_path, ruling, _):
return ask(cycle, transcript_path, ruling)
case Interrupting(transcript_path, ruling, _, step_up):
return ask(cycle, transcript_path, ruling, step_up)
case Talking(transcript_path, _):
return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked()
case Closing(transcript_path, verdict):
@@ -105,40 +107,40 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
typing.assert_never(state)
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> WorkerRan | Stop:
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> WorkerRan | Stop:
if isinstance(answered, QuotedAnswer):
print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
if stop := keep_answer(cycle, answered):
say(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", cycle.effects, stdout=True)
if stop := keep_answer(cycle, answered, step_up):
return stop
# worker_start runs inside the lambda: a failed attempt may have opened the session.
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered), worker_environment(cycle), cycle.effects), cycle.effects):
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, step_up), worker_environment(cycle), cycle.effects), cycle.effects):
return stop
path = transcript_file(cycle.session)
return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}")
def worker_environment(cycle: Cycle) -> dict[str, str]:
"""The rungs the worker's claude is handed, which rule-hook holds its review launches to."""
return worker_rungs.environment(cycle.anchor, cycle.route)
"""The rungs the worker's claude is handed, which rule-hook holds its review launches to, and the auto-compact window of its context."""
return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW)}
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> list[str]:
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> list[str]:
if isinstance(answered, QuotedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
if isinstance(answered, TypedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
if session_open(cycle.session):
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, cycle.facts), resume=False)
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False)
def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None:
def keep_answer(cycle: Cycle, answered: QuotedAnswer, step_up: StepUp | None) -> Stop | None:
path = transcript_file(cycle.session)
if not path:
return None
# As in ask: the answer names the rung the worker ran on until then, and a step-up archived after it names the rung it runs on from then.
quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), str(cycle.stepped_from or cycle.route))
if failure := archive_stepped(cycle, path, quoted):
quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), ran_on(cycle, step_up).worker_line())
if failure := archive_stepped(cycle, path, quoted, step_up):
return Stop(1, failure.reason)
return None
@@ -148,22 +150,22 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
if isinstance(entries, Failure):
return Stop(1, entries.reason)
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, entries, cycle.route.escalated_at, judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
return verdict if isinstance(verdict, Stop) else Ruled(verdict)
return verdict if isinstance(verdict, Stop) else Ruled(verdict, ruling_step_up(cycle, verdict))
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
"""Archives a judge reply loop-claude rejected, so the archive shows what the judge returned before a retry or an exit 1."""
if unkept := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle))), cycle.effects.now()):
if unkept := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle))), cycle.effects.now(), lambda text: say(text, cycle.effects)):
return Stop(1, unkept.reason)
return None
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | TalkChosen | Stop:
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | Stop:
question = question_for(ruling)
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, str(cycle.stepped_from or cycle.route))
if failure := archive_stepped(cycle, transcript_path, interrupted):
interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, ran_on(cycle, step_up).worker_line())
if failure := archive_stepped(cycle, transcript_path, interrupted, step_up):
return Stop(1, failure.reason)
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects)
@@ -173,10 +175,15 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer))
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str) -> Failure | None:
"""Archives the outcome of a ruling, then the step-up it caused when it stepped the route. The first failure is returned."""
for kept in (outcome, outcomes.stepped_up(str(cycle.route))) if cycle.stepped_from else (outcome,):
if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now()):
def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route:
"""The route the worker ran on until the ruling: the one before its step-up, if it made one."""
return step_up.before if step_up else cycle.route
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None) -> Failure | None:
"""Archives the outcome of a ruling, then the step-up it made, if it made one. The first failure is returned."""
for kept in (outcome, outcomes.stepped_up(step_up.after.worker_line())) if step_up else (outcome,):
if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now(), lambda text: say(text, cycle.effects)):
return failure
return None
@@ -188,8 +195,8 @@ 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)
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now()):
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation)
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now(), lambda text: say(text, cycle.effects)):
return Stop(1, failure.reason)
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
return Stop(1, failure.reason)
+16 -9
View File
@@ -1,6 +1,7 @@
import dataclasses
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.escalation_mark import StepUp
# A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records.
QUOTED_ANSWERS_PER_CYCLE = 3
@@ -18,6 +19,8 @@ class Working:
"""The worker runs, resumed with an answer quoted from README.md or the records, or typed by the human, when there is one."""
answered: QuotedAnswer | TypedAnswer | None = None
quoted_answers: int = 0
# The step-up made by the ruling that brought the answer, so the worker is told of it; None for none.
step_up: StepUp | None = None
@dataclasses.dataclass(frozen=True)
@@ -33,6 +36,8 @@ class Interrupting:
transcript_path: str
ruling: Interrupt | QuotedAnswer
quoted_answers: int = 0
# The step-up the ruling made. It holds through the answer the human types, and drops on /talk.
step_up: StepUp | None = None
@dataclasses.dataclass(frozen=True)
@@ -65,6 +70,8 @@ class WorkerRan:
@dataclasses.dataclass(frozen=True)
class Ruled:
verdict: Verdict
# None unless an interrupt's or a quoted answer's escalation stepped the route; always None for a finished or unfinished verdict.
step_up: StepUp | None = None
@dataclasses.dataclass(frozen=True)
@@ -94,16 +101,16 @@ def transition(state: State, event: Event) -> State:
match state, event:
case Working(_, quoted_answers), WorkerRan(transcript_path):
return Judging(transcript_path, quoted_answers)
case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE:
return Working(answered, quoted_answers + 1)
case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer() as ruling) if quoted_answers >= QUOTED_ANSWERS_PER_CYCLE:
return Interrupting(transcript_path, ruling, quoted_answers)
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() as ruling):
return Interrupting(transcript_path, ruling, quoted_answers)
case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered, step_up) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE:
return Working(answered, quoted_answers + 1, step_up)
case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer() as ruling, step_up) if quoted_answers >= QUOTED_ANSWERS_PER_CYCLE:
return Interrupting(transcript_path, ruling, quoted_answers, step_up)
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() as ruling, step_up):
return Interrupting(transcript_path, ruling, quoted_answers, step_up)
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
return Closing(transcript_path, verdict)
case Interrupting(_, _, quoted_answers), HumanTyped(typed):
return Working(typed, quoted_answers)
case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed):
return Working(typed, quoted_answers, step_up)
case Interrupting(transcript_path, _, quoted_answers), TalkChosen():
return Talking(transcript_path, quoted_answers)
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
+19 -2
View File
@@ -1,15 +1,22 @@
from claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
from loop_claude.effects import Effects
from loop_claude.effects import Effects, say
from failure import Failure
from claude_code.reply import Limited
from claude_code.transcript import part_line
from machine_load.memory import ROOM_SHARE
from model_routing.ladder import Rung
from claude_code.session import Session
PRINTED_TOOL_INPUT = 160
# Seconds between reads of the machine's memory while too little of it is available to start a worker.
MEMORY_POLL = 60
# The auto-compact window, in tokens, handed to the worker's claude in the environment variable AUTO_COMPACT_WINDOW names. Claude Code compacts before the window fills, at about 170k: docs/decisions.md → `loop-claude: the worker's claude compacts its context before it fills a 200k window`.
AUTO_COMPACT_WINDOW = "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
COMPACT_WINDOW = 200_000
def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects) -> Failure | Limited | None:
wait_for_memory(effects)
try:
proc = effects.stream_claude(args, root, env)
except OSError as failure:
@@ -24,10 +31,20 @@ def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects
resets.append(resets_at)
for part in assistant_parts(event):
if line := part_line(part, PRINTED_TOOL_INPUT):
print(line, flush=True)
say(line, effects, stdout=True)
return worker_outcome(proc.wait(), result, resets)
def wait_for_memory(effects: Effects) -> None:
"""Returns once the machine has room for a worker, or its memory cannot be read, so loops running at once do not push it into swap. While it waits, it says so once on stderr and reads the memory again each MEMORY_POLL seconds."""
said = False
while (memory := effects.memory()) is not None and not memory.has_room():
if not said:
say(f"waiting to start the worker until at least {ROOM_SHARE:.0%} of the machine's memory is available; {memory.available // 1024} MiB of {memory.total // 1024} MiB is available now", effects)
said = True
effects.sleep(MEMORY_POLL)
def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure | Limited | None:
if result is not None and hit_limit(result):
return Limited(max(resets, default=None), limit_said(result))
+13 -1
View File
@@ -8,6 +8,7 @@ import typing
from failure import Failure
import git_repo
from machine_load.memory import Memory, read_memory
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
PYTHON_TIMEOUT = 600
@@ -36,7 +37,10 @@ class Effects:
execv: typing.Callable[[str, list[str]], None]
git: Git
input: typing.Callable[[str], str]
# A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock.
local_time: typing.Callable[[float], str]
# The machine's memory; None where it cannot be read.
memory: typing.Callable[[], Memory | None]
now: typing.Callable[[], float]
on_terminal: typing.Callable[[], bool]
# Runs a Python script in a directory, as run_python does.
@@ -65,7 +69,8 @@ def system_effects() -> Effects:
execv=os.execv,
git=git_repo.git,
input=input,
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)),
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)),
memory=read_memory,
now=time.time,
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
@@ -83,3 +88,10 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
return subprocess.CompletedProcess(command, 1, "", f"could not start: {failure}")
except subprocess.TimeoutExpired:
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
def say(text: str, effects: Effects, *, stdout: bool = False) -> None:
"""Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time."""
body = text.lstrip("\n")
blanks = text[: len(text) - len(body)]
print(f"{blanks}{effects.local_time(effects.now())} {body}", file=sys.stdout if stdout else sys.stderr, flush=True)
+57
View File
@@ -0,0 +1,57 @@
"""The escalation mark makes one escalation trigger step the worker up one rung, never two (docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`).
A worker whose run ends asking loop-claude for a higher rung cites the trigger that fired, and the judge quotes the passage where it fired as the verdict's escalation. The mark, Route.escalated_at, is how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. The session's transcript only grows, so the mark holds across cycles, and the archive's Worker: lines keep it for a rerun.
- Stamp. stamped() writes on the judge's verdict how many entries the judge read.
- Step. routing.after_unfinished() and routing.after_ruling() step the worker up on an escalation and move the mark to moved_to(verdict). A ruling's StepUp travels through the cycle's states, so the archive and the worker's next prompt name it.
- Show. transcript() puts STEP_LINE after the mark, telling the judge that the triggers before that line are spent. QUOTE_AFTER_STEP, in the judge's schema, tells the judge to quote only the worker's words after that line.
- Check. checked() keeps an escalation only where it quotes both the transcript the judge was shown and the worker's own lines after the mark, which since_step() renders, so a passage that bought one step cannot buy another.
"""
import dataclasses
import typing
from loop_claude.verdicts import Escalating, Verdict
from claude_code.entries import human_text, loop_text
from claude_code.transcript import render, Typed, verbatim
from model_routing.route import Route
# Only the judge reads the step line, so it is not a [loop] line.
STEP_TAG = "[step]"
STEP_LINE = f"{STEP_TAG} loop-claude stepped the worker up a rung here, so the escalation triggers that fired before this line are spent."
# Reply.escalation's description in cycle/judge.py carries this sentence, so the judge reads STEP_LINE as the mark.
QUOTE_AFTER_STEP = f"Where a {STEP_TAG} line says loop-claude stepped the worker up a rung, quote only the worker's own words after it, and leave this empty where the trigger fired only before it."
@dataclasses.dataclass(frozen=True)
class StepUp:
"""An interrupt's or a quoted answer's escalation stepping the route within a cycle: the route the worker ran on until the ruling, and the one it runs on after."""
before: Route
after: Route
def stamped(verdict: Verdict, entries_read: int) -> Verdict:
"""The verdict with how many transcript entries the judge read, where it may carry an escalation."""
return dataclasses.replace(verdict, entries_read=entries_read) if isinstance(verdict, Escalating) else verdict
def moved_to(verdict: Escalating) -> int | None:
"""Where the verdict's escalation would move the mark, if the escalation steps the worker; None for a verdict without one."""
return verdict.entries_read if verdict.escalation else None
def transcript(entries: list[dict], at: int, typed_answer: typing.Callable[[str], Typed | None]) -> str:
"""The transcript as the judge sees it. Where the mark, at, is above 0, STEP_LINE comes after that many entries."""
return "\n\n".join(part for part in (render(entries[:at], typed_answer), STEP_LINE if at else "", render(entries[at:], typed_answer)) if part)
def since_step(entries: list[dict], at: int) -> str:
"""The worker's own lines after the mark, all of them, however much of the transcript the judge is shown. loop-claude's prompts and the human's lines are left out, since they repeat earlier passages, such as the judge's evidence or the worker's question."""
# No loop-claude prompt is left to carry an answer the human typed.
return render([entry for entry in entries[at:] if human_text(entry) is None and loop_text(entry) is None], lambda prompt: None)
def checked(verdict: Verdict, *, since: str, shown: str) -> Verdict:
"""The verdict without its escalation unless the escalation quotes both texts: since, the worker's lines after the mark as since_step renders them, and shown, the transcript the judge was shown. A misquote, or a quote of a passage before the mark, drops the escalation, so the worker's rung holds."""
if isinstance(verdict, Escalating) and verdict.escalation and not (verbatim(verdict.escalation, since) and verbatim(verdict.escalation, shown)):
return dataclasses.replace(verdict, escalation="")
return verdict
+105 -122
View File
@@ -39,93 +39,45 @@ 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.
Before each worker starts, loop-claude waits until at least a quarter of the machine's memory is available
(bin/machine_load/memory.py).
Each worker's claude, the session /talk opens and the subagents either launches run with a 200k
auto-compact window (CLAUDE_CODE_AUTO_COMPACT_WINDOW, bin/loop_claude/cycle/worker.py), so each
compacts its context at about 170k tokens.
Every claude loop-claude starts runs the project's model, saved per <key> in
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
the session /talk opens and the judge on another rung; a project without an entry, as on its first
run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL
for the worker and the session /talk opens; with both set, nothing is asked.
the session /talk opens and the judge on another rung, a model at an effort. A project without an
entry, as on its first run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the
judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with both set, nothing
is asked.
Where 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. Where it steps none and the worker runs no higher than the cheapest
rung, a pass REPLAYED there 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. 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. 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). 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. 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, any taken-in E + I that picks a higher review rung (archived as a step-up
too), and the mark. 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.
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when
the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher
rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
without it.
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.
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
loop to close one measures every finished chunk there, with no model run, and writes
routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures
make for a routing change, unless raised before, is an interrupt: claude, on the project's model,
on the terminal in ~/.claude, asked to put the calls to the human. Once that claude ends, the calls
are listed in routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the
calls are said on stderr, the loop goes on, and they are raised again at the next measurement.
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
loop-claude --help succeeds: the loop reloads into the edited script.
@@ -154,34 +106,35 @@ Exit 1, saying why, when:
more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is
always retried every 10 minutes. stderr says when the next try is due.
Exit 2, when the human is needed and cannot answer:
Exit 2, when the human is needed to go on:
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
- the input ends while a model is picked
- an interrupt's answer is empty, or the input ends before one is typed
- the claude opened for /talk, or for a release ready to cut, ends with nothing typed
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
Rerunning resumes any open session.
"""
import dataclasses
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.cycle.run import archived_stop, Concluded, Cycle, run_cycle
from loop_claude.loop.routing_check import check_routing
from loop_claude.project.checkout import checkout_root
from loop_claude.cycle.run import 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 loop_claude.cycle.judge import escalation_mark, Finished, Unfinished
from loop_claude.effects import Effects, say
from failure import Failure
from loop_claude.routing import first_route, kept, routed_item, stepped
from loop_claude.verdicts import Finished, Unfinished
from loop_claude.project.model_choice import get_or_ask_models
from todo_table import Item
from transcript_archive.read import latest_worker
from loop_claude.stop import needs_human, Stop
from transcript_archive import outcomes
from loop_claude.paths import Paths
from project_key import project_key
@@ -191,10 +144,11 @@ from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from model_routing.route import Route, route_from
from claude_code.session import Session, session_named, session_open, transcript_file
from loop_claude.stop import Stop
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
ORIGIN_TIMEOUT = 60
# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts.
UNFINISHED_LIMIT = 6
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
@@ -203,7 +157,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
except KeyboardInterrupt:
stop = Stop(130, "")
if stop.reason:
print(stop.reason, file=sys.stderr if stop.code else sys.stdout)
say(stop.reason, effects, stdout=not stop.code)
return stop.code
@@ -231,61 +185,89 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
return models
# After the reads above, so a loop that stops on one makes no worktree.
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
anchor = project_rung(models.worker)
loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), item)
route = loop_run.route or Route(Rung(models.worker))
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))
project = project_rung(models.worker)
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item)
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True)
concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
if isinstance(concluded, Stop):
return concluded
# 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):
return stop
if stop := check_routing(archive_root(paths.home, env), anchor or Rung(models.worker), paths, effects):
closed = closed_cycle(loop_run, project, concluded, archive_folder, session, effects)
if isinstance(closed, Stop):
return closed
loop_run = closed
if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects):
return stop
def routed(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."""
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()))
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
"""The route the cycle runs on. project is the project's rung, and model the project's model.
Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh.
"""
if project is None:
return Route(Rung(model))
route = route or archived()
return route if route and kept(route, project) else first_route(project, item())
def after_verdict(loop_run: LoopRun, anchor: Rung | None, verdict: Finished | Unfinished) -> LoopRun:
def closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, session: Session, effects: Effects) -> LoopRun | Stop:
"""The loop run after a cycle concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
after = after_verdict(loop_run, project, concluded)
if stop := archive_step(archive_folder, session, after.task, concluded.route, after.route, effects):
return stop
if limit := reached_limit(after):
# An unfinished verdict always leaves a route; the `or` only satisfies LoopRun.route's optional type. The stop is archived with that route, the one the next cycle would run on, so a rerun resumes there.
return archived_stop(archive_folder, session, after.task, after.route or concluded.route, limit, limit.reason, effects)
return after
def reached_limit(loop_run: LoopRun) -> Stop | None:
"""The stop that needs the human once the loop run holds UNFINISHED_LIMIT unfinished verdicts running."""
if loop_run.unfinished_run < UNFINISHED_LIMIT:
return None
return needs_human("go on with the chunk", f"the judge ruled it unfinished {loop_run.unfinished_run} cycles running; finish the chunk yourself, or rerun loop-claude to give it {UNFINISHED_LIMIT} more cycles")
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
"""The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route stepped_route makes, the evidence the judge gave for the verdict, and counts the verdict."""
verdict = concluded.verdict
if isinstance(verdict, Finished):
return dataclasses.replace(loop_run, route=None, unfinished_evidence="")
route = stepped(anchor, loop_run.route, verdict.bundled, escalation_mark(verdict)).taking_in(verdict.bundled_escape_and_impact) if anchor and loop_run.route else loop_run.route
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence)
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0)
route = stepped_route(project, concluded.route, verdict)
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1)
def 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 stepped_route(project: Rung | None, ended_on: Route, verdict: Unfinished) -> Route:
"""The route an unfinished chunk's next cycle starts on: the route after_unfinished makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised. Off the ladder there is no rung to step, and it keeps that route."""
return after_unfinished(project, ended_on, verdict) if project else ended_on
def archive_step(archive_folder: pathlib.Path, session: Session, task: str, before: Route, after: Route | None, effects: Effects) -> Stop | None:
"""Archives the route after an unfinished verdict as a step-up, where its worker line differs from the one before it: a higher rung, or a higher E + I taken in. The verdict itself names the route before, which its cycle ran on."""
if after is None or after.worker_line() == before.worker_line():
return None
path = transcript_file(session)
failure = archive(archive_folder, path, 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.worker_line()), effects.now(), lambda text: say(text, effects)) if path else None
return Stop(1, failure.reason) if failure else None
def archived_route(archive_folder: pathlib.Path, session: Session) -> Route | None:
def archived_route(archive_folder: pathlib.Path, session: Session, effects: Effects) -> Route | None:
"""The route the latest verdict archived for the session's open chunk names; None for a chunk not yet judged."""
transcript = transcript_file(session)
worker = latest_worker(archive_folder, transcript) if transcript else None
if isinstance(worker, Failure):
print(f"routing the chunk afresh: {worker.reason}", file=sys.stderr)
say(f"routing the chunk afresh: {worker.reason}", effects)
return None
return route_from(worker) if worker else None
route = route_from(worker) if worker else None
if worker and route is None:
say(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", effects)
return route
def chunk_start(session: Session, preflight: pathlib.Path, root: str, effects: Effects) -> tuple[str, typing.Callable[[], Item | None]]:
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
facts = "" if session_open(session) else chunk_facts(preflight, root, effects)
return facts, lambda: plan_item(fetched_plan(root))
return facts, lambda: plan_item(fetched_plan(root), effects)
def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str:
@@ -302,8 +284,9 @@ def fetched_plan(root: str) -> DefaultPlan | Failure:
return ref if isinstance(ref, Failure) else default_plan(root, ref)
def plan_item(plan: DefaultPlan | Failure) -> Item | None:
def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None:
"""The item that routes a chunk, chunk_pick.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
# It prints the reason itself, through effects, like the other loop-claude functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone.
if isinstance(plan, Failure):
item: Item | Failure | None = plan
elif isinstance(plan.todo, Failure):
@@ -311,7 +294,7 @@ def plan_item(plan: DefaultPlan | Failure) -> Item | None:
else:
item = routed_item(plan.todo, plan.cut)
if isinstance(item, Failure):
print(f"routing on the project's rung: {item.reason}", file=sys.stderr)
say(f"routing on the project's rung: {item.reason}", effects)
return None
return item
+5 -3
View File
@@ -6,7 +6,7 @@ import sys
import types
import typing
from loop_claude.effects import Effects
from loop_claude.effects import Effects, say
from model_routing.route import Route
from loop_claude.stop import Stop
@@ -22,8 +22,10 @@ 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
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
unfinished_run: int = 0
def decode_handed(handed: str, kind: type[T]) -> T | None:
@@ -82,7 +84,7 @@ def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, eff
return None
trial = effects.python([str(launcher), "--help"], loop_run.root)
if trial.returncode != 0:
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
say(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", effects)
return None
try:
effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
+6 -7
View File
@@ -1,10 +1,9 @@
"""Every CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing:`."""
import pathlib
import sys
from routing_figures import archive
from routing_figures.measure import calls, due, render, totals
from loop_claude.effects import Effects
from loop_claude.effects import Effects, say
from failure import Failure
from loop_claude.cycle.interrupt import hand_over
from loop_claude.paths import Paths
@@ -18,7 +17,7 @@ def check_routing(root: pathlib.Path, rung: Rung, paths: Paths, effects: Effects
with archive.locked(root) as held:
new = new_calls(root, paths, effects) if held else []
if isinstance(new, Failure):
print(f"routing figures: {new.reason}", file=sys.stderr)
say(f"routing figures: {new.reason}", effects)
return None
return raise_calls(root, new, rung, paths, effects) if new else None
@@ -32,7 +31,7 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] |
kept = archive.raised(root)
if isinstance(kept, Failure):
return kept
print(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", flush=True)
say(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", effects, stdout=True)
measured = archive.measure_archive(root, str(paths.home), kept.since)
if isinstance(measured, Failure):
return measured
@@ -46,14 +45,14 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] |
def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
listed = "".join(f"- {call}\n" for call in new)
print(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", file=sys.stderr)
say(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", effects)
if not effects.on_terminal():
print("Not on a terminal: the calls are raised again at the next measurement.", file=sys.stderr)
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
return None
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, {}, effects):
return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}")
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
print(f"routing figures: {unmarked.reason}", file=sys.stderr)
say(f"routing figures: {unmarked.reason}", effects)
return None
+6 -9
View File
@@ -5,7 +5,7 @@ import sys
import typing
from claude_code.model_catalog import catalog_models
from loop_claude.effects import Effects
from loop_claude.effects import Effects, say
from failure import Failure
from loop_claude.stop import needs_human, needs_terminal, Stop
from loop_claude.paths import Paths
@@ -44,7 +44,7 @@ def get_or_ask_model(project_key: str, paths: Paths, effects: Effects) -> str |
return models
if failure := replace_json(saved, {**models, project_key: chosen}, indent="\t", sort_keys=True):
return Stop(1, f"could not save the model in {saved}: {failure.reason}")
print(f"{project_key} runs on {chosen}", file=sys.stderr)
say(f"{project_key} runs on {chosen}", effects)
return chosen
@@ -65,20 +65,17 @@ def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, e
if stop := needs_terminal(f"pick {project_key}'s model, or merge {{\"{project_key}\": \"<model>\"}} into {saved}", effects.on_terminal()):
return stop
offered = catalog_models(folder)
print(f"\nThe model to run {project_key} on, saved in {saved}:", file=sys.stderr)
for number, (model_id, label) in enumerate(offered, 1):
print(f" {number}. {label} ({model_id})", file=sys.stderr)
if not offered:
print(f" no model catalog cached in {folder}", file=sys.stderr)
choices = [f" {number}. {label} ({model_id})" for number, (model_id, label) in enumerate(offered, 1)] or [f" no model catalog cached in {folder}"]
say("\n".join([f"\nThe model to run {project_key} on, saved in {saved}:", *choices]), effects)
while True:
try:
answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ")
except EOFError:
print(file=sys.stderr)
print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time.
return needs_human(f"pick {project_key}'s model", "the input ended")
picked = model_picked(answer, offered)
if isinstance(picked, Failure):
print(picked.reason, file=sys.stderr)
say(picked.reason, effects)
elif picked:
return picked
+54 -39
View File
@@ -1,10 +1,20 @@
"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`."""
"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`.
The worker, and the session /talk opens, run on a Route (model_routing/route.py). A model off the ladder gets a route without an item, and it is never stepped.
- Start. routed_item finds the plan item that routes a fresh chunk, if there is one with L, E and I scored; first_route picks the worker's rung from its L, or the project's rung without an item.
- Rerun. kept decides whether a rerun resumes the route its archive last names.
- Step-up. after_unfinished raises the route after an unfinished verdict, after_ruling after an interrupt or a quoted answer that carries an escalation; escalation_cap bounds an escalation, and loop_claude/escalation_mark.py states the escalation mark's rule.
- Judge. judge_rung picks the rung of the judge of a JUDGE_REPLAYED model.
"""
import dataclasses
from chunk_pick import chunk_item, LastCut, Next
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung
from loop_claude import escalation_mark
from failure import Failure
from todo_table import Item, items
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
from todo_table import Item, items, NoItemsTable
from model_routing.route import Route
UNFINISHED_PER_STEP = 2
@@ -17,68 +27,73 @@ 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
def first_route(anchor: Rung, item: Item | None) -> Route:
"""The route a chunk starts on: the rung its item's L picks from anchor, the project's rung."""
def first_route(project: Rung, item: Item | None) -> Route:
"""The route a chunk starts on: the rung its item's L picks from the project's rung, or the project's rung without an item."""
if item is None:
return Route(anchor)
return Route(worker_rung(anchor, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
return Route(project)
return Route(worker_rung(project, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
def kept(route: Route, anchor: Rung) -> bool:
def kept(route: Route, project: Rung) -> bool:
"""Whether a chunk keeps route: its rung is on the ladder and at or above item_rung."""
return kept_rung(anchor, route) == route.rung
return kept_rung(project, route) == route.rung
def kept_rung(anchor: Rung, route: Route) -> Rung:
def kept_rung(project: Rung, route: Route) -> Rung:
"""The route's rung, raised to item_rung where it is lower or off the ladder."""
return highest(route.rung, item_rung(anchor, route))
return highest(route.rung, item_rung(project, route))
def item_rung(anchor: Rung, route: Route) -> Rung:
"""The rung the route's item's L picks from anchor, the project's rung, or anchor itself when no item routed it. The worker may run on a rung below anchor."""
return worker_rung(anchor, route.likelihood) if route.item else anchor
def item_rung(project: Rung, route: Route) -> Rung:
"""The rung the route's item's L picks from the project's rung, or the project's rung itself when no item routed it. The worker may run on a rung below the project's."""
return worker_rung(project, route.likelihood) if route.item else project
def escalation_rungs(anchor: Rung, route: Route) -> tuple[Rung, ...]:
def escalation_rungs(project: Rung, route: Route) -> tuple[Rung, ...]:
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder."""
if route.rung not in LADDER:
return ()
return LADDER[position(route.rung) + 1:position(escalation_cap(anchor, route)) + 1]
return LADDER[position(route.rung) + 1:position(escalation_cap(project, route)) + 1]
def escalation_cap(anchor: Rung, route: Route) -> Rung:
def escalation_cap(project: Rung, route: Route) -> Rung:
"""The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
It counts from item_rung, the rung the chunk started on, so a step-up between cycles narrows what the worker may climb without a yes, and never widens it.
"""
return climbed(item_rung(anchor, route), ESCALATION_CAP)
return climbed(item_rung(project, route), ESCALATION_CAP)
def stepped(anchor: Rung, route: Route, bundled: int, escalated_at: int | None) -> 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(project: Rung, route: Route, verdict: Unfinished) -> Route:
"""The route the next cycle runs on after an unfinished verdict.
bundled is the highest L the judge saw the worker take in, 0 for none. escalated_at is how many transcript entries the judge read where the verdict carries an escalation, None where it carries none. A step moves the route's mark, Route.escalated_at, to escalated_at; a step on the count of unfinished verdicts alone keeps the mark. They are passed in place of 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 mark, as loop_claude/escalation_mark.py says; a step on the count of unfinished verdicts alone keeps it. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
"""
rung = taken_in(anchor, route, bundled)
unfinished = route.unfinished + 1
if unfinished >= UNFINISHED_PER_STEP or (escalated_at is not None and below_cap(anchor, route, rung)):
return one_rung_up(route, rung, route.escalated_at if escalated_at is None else escalated_at)
return dataclasses.replace(route, rung=rung, unfinished=unfinished)
rung = raised(project, route, verdict.highest_likelihood_taken_in)
mark = escalation_mark.moved_to(verdict)
if route.unfinished + 1 >= UNFINISHED_PER_STEP or (mark is not None and below_cap(project, route, rung)):
after = one_rung_up(route, rung, route.escalated_at if mark is None else mark)
else:
after = dataclasses.replace(route, rung=rung, unfinished=route.unfinished + 1)
return after.taking_in(verdict.highest_escape_and_impact_taken_in)
def stepped_by_ruling(anchor: Rung, route: Route, bundled: int, escalated_at: int | None) -> Route:
"""The route after the judge's interrupt or quoted answer, its arguments as stepped's: unchanged without an escalation; with one, 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."""
if escalated_at is None:
def after_ruling(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
"""The route after the judge's interrupt or quoted answer: unchanged without an escalation. With one, raised to the rung the highest L taken in picks, and one rung up from there while below escalation_cap, moving the mark as after_unfinished does. Neither is an unfinished verdict, so the count of those restarts only with a step."""
mark = escalation_mark.moved_to(verdict)
if mark is None:
return route
rung = taken_in(anchor, route, bundled)
return one_rung_up(route, rung, escalated_at) if below_cap(anchor, route, rung) else dataclasses.replace(route, rung=rung)
rung = raised(project, route, verdict.highest_likelihood_taken_in)
return one_rung_up(route, rung, mark) if below_cap(project, route, rung) else dataclasses.replace(route, rung=rung)
def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
@@ -86,14 +101,14 @@ def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0, escalated_at=escalated_at)
def below_cap(anchor: Rung, route: Route, rung: Rung) -> bool:
def below_cap(project: Rung, route: Route, rung: Rung) -> bool:
"""Whether an escalation trigger may take the worker one rung up from rung without the human's yes: rung is below escalation_cap, two rungs above item_rung."""
return position(rung) < position(escalation_cap(anchor, route))
return position(rung) < position(escalation_cap(project, route))
def 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(project: Rung, route: Route, likelihood_taken_in: int) -> Rung:
"""kept_rung, raised to the rung that likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, or 0 for none."""
return highest(kept_rung(project, route), worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else kept_rung(project, route)
def judge_rung(judge_model: str, route: Route) -> Rung:
@@ -101,7 +116,7 @@ def judge_rung(judge_model: str, route: Route) -> Rung:
A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give.
"""
anchor = project_rung(judge_model)
if anchor is None or judge_model not in JUDGE_REPLAYED:
cheapest = project_rung(judge_model)
if cheapest is None or judge_model not in JUDGE_REPLAYED:
return Rung(judge_model)
return review_floor(anchor, route.reviewed_on())
return review_floor(cheapest, route.reviewed_on())
+78 -23
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,
@@ -112,6 +116,11 @@ if os.path.basename(sys.argv[0]) == "loop-claude":
record({"argv": sys.argv[1:]})
pause = time.sleep
time.sleep = lambda seconds: record({"sleep": seconds}) if seconds >= 1 else pause(seconds)
# The host's own memory doesn't matter: every read finds all of it available.
sys.path.insert(0, os.path.dirname(os.path.realpath(sys.argv[0])))
import pathlib
from machine_load import memory
memory.MEMINFO = pathlib.Path(os.environ["FAKE_MEMINFO"])
"""
PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n"
@@ -129,8 +138,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}
@@ -148,8 +157,11 @@ class Run:
code: int
sleeps: list
starts: list
# stderr and stdout are without the local time that opens each message loop-claude prints; raw_stderr and raw_stdout keep it.
stderr: str
stdout: str
raw_stderr: str
raw_stdout: str
def roles(self):
return [call["role"] for call in self.calls]
@@ -177,8 +189,10 @@ class Checkout:
site = self.temp / "site"
site.mkdir()
(site / "sitecustomize.py").write_text(SITECUSTOMIZE)
(self.temp / "meminfo").write_text("MemTotal: 16 kB\nMemAvailable: 16 kB\n")
self.env.update({
"FAKE_CLAUDE_LOG": str(self.temp / "calls.jsonl"),
"FAKE_MEMINFO": str(self.temp / "meminfo"),
"FAKE_CLAUDE_SCENARIO": str(self.temp / "scenario.json"),
"GIT_CONFIG_GLOBAL": os.devnull,
"GIT_CONFIG_NOSYSTEM": "1",
@@ -217,8 +231,10 @@ class Checkout:
code=code,
sleeps=[event["sleep"] for event in started if "sleep" in event],
starts=[event["argv"] for event in started if "argv" in event],
stderr=stderr,
stdout=stdout,
stderr=unstamped(stderr),
stdout=unstamped(stdout),
raw_stderr=stderr,
raw_stdout=stdout,
)
def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing, typed_early):
@@ -236,7 +252,7 @@ class Checkout:
os.write(controller, typed.encode())
output, deadline = b"", time.monotonic() + 60
while time.monotonic() < deadline:
if select.select([controller], [], [], 1)[0]:
if select.select([controller], [], [], 0.05)[0]:
try:
chunk = os.read(controller, 4096)
except OSError:
@@ -284,6 +300,13 @@ class Checkout:
return outcomes
STAMP = r"\d{4}-\d\d-\d\d \d\d:\d\d:\d\d"
def unstamped(text):
return re.sub(rf"(?m)^{STAMP} ", "", text)
def argument(call, flag):
return call["argv"][call["argv"].index(flag) + 1] if flag in call["argv"] else None
@@ -300,7 +323,7 @@ class Premises(unittest.TestCase):
outside.mkdir()
run = checkout.run([], cwd=outside)
self.assertEqual((run.code, run.calls), (1, []))
self.assertIn("not a git repository", run.stderr)
self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} .*not a git repository")
readmes = {
None: "README.md in {root}: No such file or directory - no premises.",
b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "README.md in {root} is not UTF-8 on line 3 - no premises.",
@@ -385,10 +408,11 @@ class Cycles(unittest.TestCase):
self.assertNotIn("landed-it", run.calls[5]["stdin"])
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)
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 3, worker on worker-model ===$", run.raw_stdout)), 1)
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 +422,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 +438,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 +484,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, escalated at transcript entry 4\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, escalated at transcript entry 4\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 +501,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, escalated at transcript entry 4\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, escalated at transcript entry 4\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 +515,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 +523,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 +533,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)
@@ -573,7 +597,7 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.code, 130)
self.assertEqual(run.roles(), ["worker"] * 5 + ["judge"] * 2 + ["worker"])
self.assertEqual([round(seconds, -1) for seconds in run.sleeps], [60, 60, 3720, 60, 600])
self.assertIn(f"the worker hit a usage limit (You've hit your session limit); retrying at {datetime.datetime.fromtimestamp(resets_at + 120, datetime.timezone.utc):%Y-%m-%d %H:%M} UTC\n", run.stderr)
self.assertIn(f"the worker hit a usage limit (You've hit your session limit); retrying at {datetime.datetime.fromtimestamp(resets_at + 120, datetime.timezone.utc):%Y-%m-%d %H:%M:%S}\n", run.stderr)
self.assertIn("the judge hit a usage limit (You've hit your session limit); retrying at ", run.stderr)
def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self):
@@ -636,6 +660,36 @@ class Cycles(unittest.TestCase):
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
self.assertIn("claude left no transcript for session", run.stderr)
def test_exits_2_after_six_unfinished_verdicts_running_and_a_rerun_gets_six_more(self):
checkout = Checkout(self)
six = [step for _ in range(6) for step in (worker(), judge())]
run = checkout.run(six + [worker()])
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"] * 6))
self.assertIn("the judge ruled it unfinished 6 cycles running", run.stderr.strip().splitlines()[-1])
self.assertIn("rerun loop-claude to give it 6 more cycles", run.stderr.strip().splitlines()[-1])
stops = [outcome for outcome in checkout.archived().values() if "Stopped: " in outcome]
self.assertEqual(len(stops), 1)
self.assertIn(f"\n\nWorker: {OFF_LADDER}\n", stops[0])
run = checkout.run(six[:-2] + [worker()])
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 6))
def test_archives_the_stop_on_the_route_the_sixth_verdict_stepped_to_and_a_rerun_resumes_there(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
checkout.commit_plan(CHEAP)
run = checkout.run([step for _ in range(6) for step in (worker(), judge())] + [worker()])
self.assertEqual(run.code, 2)
stepped = '<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stopped: '
self.assertEqual(len([outcome for outcome in checkout.archived().values() if stepped in outcome]), 1)
run = checkout.run([worker()])
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-opus-5-5", "xhigh")])
def test_five_unfinished_verdicts_and_a_finished_one_do_not_add_up_to_six(self):
checkout = Checkout(self)
five = [step for _ in range(5) for step in (worker(), judge())]
run = checkout.run(five + [worker(), judge(finished=True)] + five + [worker()])
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 12))
class Interrupt(unittest.TestCase):
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
@@ -647,9 +701,10 @@ 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)
self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} transcript: ")
session = argument(run.calls[0], "--session-id")
run = checkout.run(steps, terminal_input="", stdout_on_terminal=False)
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
@@ -857,7 +912,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, "unfinished_run": cycle} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5,", run.stdout)
outside = checkout.temp / "outside"
+300 -179
View File
@@ -17,27 +17,38 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from routing_figures import archive
from routing_figures import archive, measure
from loop_claude.project import checkout, model_choice, records
from chunk_pick import DefaultPlan, LastCut
from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python
from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python, say, system_effects
from claude_code import entries, reply, session
from loop_claude import escalation_mark, paths, routing
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 machine_load import memory
from transcript_archive import outcomes, write
from loop_claude import paths, routing
from transcript_archive.location import project_archive
from model_routing.route import Route, route_from
from model_routing.route import Route, route_from, WorkerLine
from loop_claude.stop import Stop
from utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
# 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
# How a line said at NOW opens, with FakeEffects' local_time.
STAMP = f"<{NOW}>"
def assistant(*parts):
@@ -51,9 +62,11 @@ def human(content):
class FakeEffects:
"""Effects that record each call and answer from a script, one answer per call."""
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True):
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()):
self.calls = []
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
# Without a script, every read finds all memory available.
self.free_memory = list(free_memory)
self.terminal = on_terminal
self.worker_environments = []
self.terminal_environments = []
@@ -67,6 +80,7 @@ class FakeEffects:
git=lambda *args, cwd: self.answer("git", list(args)),
input=lambda prompt: self.answer("input", prompt),
local_time=lambda seconds: f"<{seconds}>",
memory=self.memory,
now=lambda: NOW,
on_terminal=lambda: self.terminal,
python=lambda args, cwd: self.answer("python", (args, cwd)),
@@ -74,6 +88,10 @@ class FakeEffects:
stream_claude=self.stream,
)
def memory(self):
self.calls.append(("memory", None))
return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16)
def on_terminal_claude(self, args, cwd, env):
self.terminal_environments.append(env)
return self.answer("claude_on_terminal", args)
@@ -97,18 +115,12 @@ class FakeEffects:
return [what for called, what in self.calls if called == seam]
def uuid7():
# Python 3.11, the floor, has no uuid.uuid7.
random = int.from_bytes(os.urandom(10))
return uuid.UUID(int=int(time.time() * 1000) << 80 | 7 << 76 | (random >> 62 & 0xFFF) << 64 | 2 << 62 | random & (1 << 62) - 1)
def ran(stdout="", code=0, stderr=""):
return subprocess.CompletedProcess([], code, stdout, stderr)
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}))
@@ -127,7 +139,7 @@ class Worker:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "a") as handle:
if flag == "--session-id":
handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid7())}) + "\n")
handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid.uuid7())}) + "\n")
if self.prompted:
handle.write(json.dumps({**human(args[args.index("-p") + 1]), "promptSource": "sdk"}) + "\n")
handle.write(json.dumps(assistant({"type": "text", "text": self.text})) + "\n")
@@ -185,6 +197,20 @@ class Transitions(unittest.TestCase):
with self.subTest(state=state, event=event), self.assertRaises(ValueError):
states.transition(state, event)
def test_a_rulings_step_up_reaches_the_worker_it_resumes_through_the_answer_the_human_types_and_no_further(self):
step_up = escalation_mark.StepUp(Route(Rung("claude-opus-5-5", "medium")), Route(Rung("claude-opus-5-5", "high"), escalated_at=3))
interrupt, quoted = Interrupt("e", "q", "round 2: 🔴"), QuotedAnswer("e", "q", "A.", "round 2: 🔴")
for state, event, after in (
(states.Judging("/t"), states.Ruled(quoted, step_up), states.Working(quoted, 1, step_up)),
(states.Judging("/t", 3), states.Ruled(quoted, step_up), states.Interrupting("/t", quoted, 3, step_up)),
(states.Judging("/t"), states.Ruled(interrupt, step_up), states.Interrupting("/t", interrupt, 0, step_up)),
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTyped(TYPED), states.Working(TYPED, 0, step_up)),
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen(), states.Talking("/t")),
(states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")),
):
with self.subTest(state=state, event=event):
self.assertEqual(states.transition(state, event), after)
class QuestionFor(unittest.TestCase):
def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self):
@@ -202,7 +228,7 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
return run.Cycle(anchor=None, effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence)
return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -210,7 +236,7 @@ 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):
@@ -222,11 +248,11 @@ class Cycles(unittest.TestCase):
self.assertIn("- A preflight fact.", fresh)
self.assertNotIn("- A preflight fact.", resumed)
def test_a_worker_is_handed_the_projects_rung_its_own_and_its_reviews_e_plus_i_in_its_environment(self):
def test_a_worker_is_handed_the_projects_rung_its_own_its_reviews_e_plus_i_and_its_compaction_window_in_its_environment(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
cycle = dataclasses.replace(self.cycle(fake), project=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
self.assertEqual(run.run_cycle(cycle).verdict, Finished("working"))
self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}])
self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5", "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "200000"}])
def test_the_claude_an_interrupt_resumes_is_handed_the_same_rungs_as_the_worker(self):
def answer(args):
@@ -234,7 +260,7 @@ class Cycles(unittest.TestCase):
handle.write(json.dumps(human("the second")) + "\n")
return 0
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], inputs=["/talk"], on_terminal_claude=[answer], git=[""])
cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
cycle = dataclasses.replace(self.cycle(fake), project=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(cycle).verdict, Finished("working"))
self.assertEqual(fake.terminal_environments, fake.worker_environments)
@@ -249,14 +275,14 @@ class Cycles(unittest.TestCase):
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}}))
@@ -268,7 +294,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)
@@ -332,14 +358,14 @@ class Cycles(unittest.TestCase):
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", entries_read=4))
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(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*.")
@@ -351,12 +377,12 @@ 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))
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
@@ -364,8 +390,8 @@ class Cycles(unittest.TestCase):
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}. 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, escalated_at=3)}\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)
@@ -373,26 +399,25 @@ class Cycles(unittest.TestCase):
def test_a_quoted_answer_past_the_cap_archives_the_escalation_it_carried_with_the_interrupt_and_steps_up(self):
steps = [judged("quoted", answer="Use A.")] * 3 + [judged("quoted", answer="Use A.", escalation="working")]
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, inputs=[""])
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
kept = "".join(self.archived_outcomes())
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, escalated_at=6)}\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_bundled_l_picks(self):
cycle = dataclasses.replace(self.cycle(FakeEffects()), anchor=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4))
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()), project=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4))
for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)):
with self.subTest(ruling=ruling):
self.assertEqual(run.escalated(cycle, states.Ruled(ruling)), cycle)
stepped = run.escalated(cycle, states.Ruled(Interrupt("e", "q", "round 2: 🔴", 4, entries_read=3)))
self.assertEqual((stepped.route, stepped.stepped_from), (Route(Routing.XHIGH, 3, 3, 4, escalated_at=3), cycle.route))
self.assertIsNone(run.ruling_step_up(cycle, ruling))
self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", 4, entries_read=3)), escalation_mark.StepUp(cycle.route, Route(Routing.XHIGH, 3, 3, 4, escalated_at=3)))
def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self):
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)]
rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("quoted", answer="Use A.", escalation="working"), judged("finished")]
fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."])
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.HIGH, 179, 2, 5, escalated_at=4))
@@ -405,7 +430,7 @@ class Cycles(unittest.TestCase):
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent)]
rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("unfinished", escalation=escalation)]
fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."])
cycle = dataclasses.replace(self.cycle(fake), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
cycle = dataclasses.replace(self.cycle(fake), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded, run.Concluded(verdict, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)))
@@ -415,7 +440,7 @@ class Cycles(unittest.TestCase):
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", entries_read=6))
self.assertIn("\nWhich one?\n", said.getvalue())
self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue())
self.assertEqual(fake.made("claude_on_terminal"), [])
resumed = fake.made("stream_claude")[1]
self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id))
@@ -429,7 +454,7 @@ class Cycles(unittest.TestCase):
def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."])
cycle = dataclasses.replace(self.cycle(fake), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
cycle = dataclasses.replace(self.cycle(fake), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
@@ -482,7 +507,7 @@ class Cycles(unittest.TestCase):
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
self.assertEqual(len(fake.made("stream_claude")), 1)
self.assertIn("\nWhich one?\n", said.getvalue())
self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue())
self.assertNotIn("Use ... A.", said.getvalue())
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
@@ -495,7 +520,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)])
@@ -532,7 +557,40 @@ class Retried(unittest.TestCase):
results = [Limited(NOW + 3600, "You've hit your session limit"), "done"]
with contextlib.redirect_stderr(io.StringIO()) as said:
retry.retried("judge", lambda: results.pop(0), FakeEffects().effects())
self.assertEqual(said.getvalue(), f"the judge hit a usage limit (You've hit your session limit); retrying at <{NOW + 3720}>\n")
self.assertEqual(said.getvalue(), f"{STAMP} the judge hit a usage limit (You've hit your session limit); retrying at <{NOW + 3720}>\n")
class Said(unittest.TestCase):
def test_opens_a_line_with_the_local_time_of_the_effects_clock(self):
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
say("hello", FakeEffects().effects())
self.assertEqual((stderr.getvalue(), stdout.getvalue()), (f"{STAMP} hello\n", ""))
def test_stamps_only_the_first_line_of_a_question_after_its_blank_line(self):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
say("\nWhich one?\n\nA or B?", FakeEffects().effects())
self.assertEqual(stderr.getvalue(), f"\n{STAMP} Which one?\n\nA or B?\n")
def test_says_on_stdout_where_asked(self):
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
say("\n=== cycle 2 ===", FakeEffects().effects(), stdout=True)
self.assertEqual((stderr.getvalue(), stdout.getvalue()), ("", f"\n{STAMP} === cycle 2 ===\n"))
def test_keeps_the_indent_of_the_first_line_after_the_time(self):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
say("\n indented", FakeEffects().effects())
self.assertEqual(stderr.getvalue(), f"\n{STAMP} indented\n")
def test_flushes_so_piped_lines_arrive_when_said(self):
flushes = []
class Counting(io.StringIO):
def flush(self):
flushes.append(self.getvalue())
with contextlib.redirect_stderr(Counting()):
say("hello", FakeEffects().effects())
self.assertEqual(flushes, [f"{STAMP} hello\n"])
class Limits(unittest.TestCase):
@@ -562,6 +620,21 @@ class Limits(unittest.TestCase):
self.assertEqual(entries.rejected_until({"type": "rate_limit_event", "rate_limit_info": info}), want, info)
class MemoryWait(unittest.TestCase):
def test_a_worker_starts_only_once_a_quarter_of_memory_is_available(self):
fake = FakeEffects(free_memory=[memory.Memory(available=3, total=16), memory.Memory(available=3, total=16), memory.Memory(available=4, total=16)], streams=[Streamed(0)])
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertIsNone(worker.run_worker("/r", [], {}, fake.effects()))
self.assertEqual([seam for seam, _ in fake.calls], ["memory", "sleep", "memory", "sleep", "memory", "stream_claude"])
self.assertEqual(fake.made("sleep"), [worker.MEMORY_POLL] * 2)
self.assertEqual(said.getvalue().count("waiting"), 1, said.getvalue())
def test_a_worker_starts_at_once_where_memory_cannot_be_read(self):
fake = FakeEffects(free_memory=[None], streams=[Streamed(0)])
self.assertIsNone(worker.run_worker("/r", [], {}, fake.effects()))
self.assertEqual([seam for seam, _ in fake.calls], ["memory", "stream_claude"])
class Interrupts(unittest.TestCase):
def put(self, fake, answer_here=True):
with contextlib.redirect_stderr(io.StringIO()) as said:
@@ -570,12 +643,12 @@ class Interrupts(unittest.TestCase):
def test_stops_off_a_terminal_before_asking(self):
fake = FakeEffects(on_terminal=False)
self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), "\nWhich one?\n"))
self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n"))
self.assertEqual(fake.calls, [])
def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self):
fake = FakeEffects(inputs=[" Use B. "])
self.assertEqual(self.put(fake), ("Use B.", "\nWhich one?\n"))
self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n"))
self.assertEqual(fake.calls, [("discard_typed", None), ("input", "Answer (/talk opens claude, Enter stops the loop): ")])
def test_talks_on_talk_or_at_once_where_the_answer_is_not_asked_for_here(self):
@@ -589,14 +662,14 @@ class Interrupts(unittest.TestCase):
def test_stops_on_an_empty_answer_or_the_inputs_end(self):
for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")):
with self.subTest(why=why):
self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\nWhich one?\n{said}"))
self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\n{STAMP} Which one?\n{said}"))
def test_stops_when_nothing_was_typed_in_the_session(self):
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=[""])
stop = interrupt.talk(home, uuid7(), Rung("m", "high"), str(path), paths.paths_from(pathlib.Path(home)), {}, fake.effects())
stop = interrupt.talk(home, uuid.uuid7(), Rung("m", "high"), str(path), paths.paths_from(pathlib.Path(home)), {}, fake.effects())
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
@@ -606,7 +679,7 @@ class Interrupts(unittest.TestCase):
path.write_text(json.dumps(human("a")) + "\n")
fake = FakeEffects(on_terminal_claude=[0], git=[""])
handed = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort"}
interrupt.talk(home, uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects())
interrupt.talk(home, uuid.uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects())
self.assertEqual(fake.terminal_environments, [handed])
@@ -736,6 +809,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")
@@ -774,47 +857,47 @@ class Routing(unittest.TestCase):
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, None)
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, None), Route(self.HIGH, 3, 3, 4))
self.assertEqual(routing.stepped(self.OPUS, Route(LADDER[-1], unfinished=1), 0, None).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, None).rung, self.HIGH)
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 4, None).rung, self.XHIGH)
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, unfinished=1), 4, None).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(self.SONNET, 3, 1, 3, unfinished=1)
self.assertEqual(routing.stepped(self.OPUS, low, 0, None).rung, self.OPUS)
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 0, None).rung, low.rung)
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 3, None).rung, self.OPUS)
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_marking_the_transcript_entries_it_read(self):
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5), 0, 7), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), 0, 9), Route(self.MAX, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.stepped(self.OPUS, Route(self.MAX, 3, 4, 5, escalated_at=9), 0, 12), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), 0, 7), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 0, 7), Route(self.XHIGH, unfinished=1))
self.assertEqual(routing.stepped(self.OPUS, Route(self.SONNET, 3, 2, 4), 4, 7), Route(self.HIGH, 3, 2, 4, unfinished=1))
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.stepped(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), 0, None), Route(self.HIGH, 3, 3, 4, escalated_at=5))
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, 7), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), 0, 9), Route(self.MAX, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9), 0, 12), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.SONNET, 3, 2, 4), 0, 7), Route(self.OPUS, 3, 2, 4, escalated_at=7))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2), 4, None), Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2))
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.stepped_by_ruling(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), 4, 7), Route(self.HIGH, 3, 1, 3, escalated_at=2))
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, 7), Route(self.XHIGH, 3, 3, 4, escalated_at=7))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5), 4, 7), Route(self.MAX, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1), 4, 7), 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)
@@ -829,8 +912,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, None).rung, self.OPUS)
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 2, None).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)
@@ -864,81 +947,90 @@ 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_worker_line_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"))
marked = Route(self.HIGH, 3, 4, 5, escalated_at=12, escape_and_impact_taken_in=7)
self.assertEqual(str(marked), "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")
self.assertEqual(route_from(str(marked)), marked)
self.assertEqual(route_from(str(Route(self.HIGH, escalated_at=3))), Route(self.HIGH, escalated_at=3))
self.assertEqual(route.worker_line(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5}')
self.assertEqual(route_from(route.worker_line()), route)
self.assertEqual(Route(Rung("worker-model")).worker_line(), '{"model": "worker-model"}')
self.assertEqual(route_from('{"model": "worker-model"}'), Route(Rung("worker-model")))
marked = Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12)
self.assertEqual(marked.worker_line(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}')
self.assertEqual(route_from(marked.worker_line()), marked)
self.assertEqual(route_from(Route(self.HIGH, escalated_at=3).worker_line()), Route(self.HIGH, escalated_at=3))
def test_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_worker_line_so_a_rerun_restarts_it(self):
self.assertEqual(route_from(Route(self.HIGH, 3, 4, 5, unfinished=1).worker_line()), Route(self.HIGH, 3, 4, 5))
def test_reads_no_route_from_a_worker_line_of_unknown_or_mistyped_fields_or_levels_off_their_scales(self):
for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": '):
with self.subTest(line=line):
self.assertIsNone(route_from(line))
def test_reads_the_route_from_a_line_loop_claude_wrote_before_it_archived_json(self):
self.assertEqual(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5"), Route(self.HIGH, 3, 4, 5))
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):
def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self):
self.assertIsNone(main.plan_item(DefaultPlan("", NO_CUT)))
self.assertEqual(main.plan_item(DefaultPlan(TODO, LastCut("v0.1.0", "", 3, [TODO]))).id, 3)
self.assertIsNone(main.plan_item(DefaultPlan(TODO, LastCut("v0.2.0", "", 3, [TODO]))))
self.assertIsNone(main.plan_item(DefaultPlan("", NO_CUT), FakeEffects().effects()))
self.assertEqual(main.plan_item(DefaultPlan(TODO, LastCut("v0.1.0", "", 3, [TODO])), FakeEffects().effects()).id, 3)
self.assertIsNone(main.plan_item(DefaultPlan(TODO, LastCut("v0.2.0", "", 3, [TODO])), FakeEffects().effects()))
unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8")
for plan, said in ((DefaultPlan(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")):
with self.subTest(said=said):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIsNone(main.plan_item(plan))
self.assertTrue(stderr.getvalue().startswith(said), stderr.getvalue())
self.assertIsNone(main.plan_item(plan, FakeEffects().effects()))
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue())
def test_resumes_on_the_archived_route_and_says_why_it_routes_afresh(self):
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, FakeEffects().effects()))
transcript.parent.mkdir(parents=True)
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
self.assertIsNone(main.archived_route(archive, opened, FakeEffects().effects()))
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.worker_line(), "working", "j", ""), NOW))
with contextlib.redirect_stderr(stderr):
self.assertEqual(main.archived_route(archive, opened, FakeEffects().effects()), route)
self.assertEqual(stderr.getvalue(), "")
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIsNone(main.archived_route(archive, opened, FakeEffects().effects()))
self.assertEqual(stderr.getvalue(), f'{STAMP} 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:
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIsNone(main.archived_route(archive, opened))
self.assertIsNone(main.archived_route(archive, opened, FakeEffects().effects()))
finally:
chunk.chmod(0o700)
self.assertTrue(stderr.getvalue().startswith("routing the chunk afresh: could not read the archive"), stderr.getvalue())
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue())
class Steps(unittest.TestCase):
@@ -946,13 +1038,24 @@ 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(dataclasses.replace(run_with, unfinished_run=3), self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", 4), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4))
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, Unfinished("new", 0, "round 2: 🔴", entries_read=9)).route, Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=9))
self.assertEqual(main.after_verdict(run_with, self.OPUS, Unfinished("new", entries_read=9)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, 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:
@@ -963,18 +1066,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.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.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", 4), before))
self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects()))
self.assertEqual(main.archived_route(archive, opened, FakeEffects().effects()), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
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, FakeEffects().effects()), 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):
@@ -986,10 +1088,10 @@ 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.assertEqual(main.archived_route(archive, opened), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6))
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", highest_escape_and_impact_taken_in=6), before))
self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects()))
self.assertEqual(main.archived_route(archive, opened, FakeEffects().effects()), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6))
class ChunkFacts(unittest.TestCase):
@@ -1023,6 +1125,17 @@ class ChunkFacts(unittest.TestCase):
self.assertEqual((resumed.made("python"), facts), ([], ""))
class LocalTime(unittest.TestCase):
def test_renders_seconds_in_the_machines_zone(self):
# A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before time.tzset makes the clock read it again.
self.addCleanup(time.tzset)
zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"})
zone.start()
self.addCleanup(zone.stop)
time.tzset()
self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20")
class PythonEffect(unittest.TestCase):
def test_runs_a_script_in_the_given_directory(self):
with tempfile.TemporaryDirectory() as cwd:
@@ -1133,10 +1246,11 @@ class WorkerArgs(unittest.TestCase):
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus))
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 4, 8), opus))
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "max"), 3, 4, 5), opus))
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus))
self.assertIn("before creating a new one.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
self.assertIn("before creating a new one.\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self):
opus = Rung("claude-opus-5-5", "medium")
@@ -1242,13 +1356,21 @@ class JudgePrompt(unittest.TestCase):
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 agent up", prompt)
self.assertNotIn("stepped the worker up", prompt)
self.assertEqual(grounds.shown, "round 2: 🔴\n\nround 3: 🔴")
self.assertEqual(grounds.since_step, "round 2: 🔴\n\nround 3: 🔴")
def test_drops_an_escalation_quote_from_after_the_step_up_that_the_tail_it_shows_cuts_off(self):
@@ -1282,56 +1404,51 @@ class Grounded(unittest.TestCase):
self.assertFalse(judge.grounded("Decision for you ... invented", transcript))
self.assertFalse(judge.grounded("... …", transcript))
def test_an_answer_holds_only_word_for_word(self):
self.assertTrue(judge.verbatim("Merge **ff-only**.", "Merge ff-only.\nNever squash."))
self.assertFalse(judge.verbatim("Merge ... squash.", "Merge ff-only.\nNever squash."))
self.assertFalse(judge.verbatim("", "Merge ff-only."))
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
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?"
@@ -1339,10 +1456,10 @@ class Verdict(unittest.TestCase):
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?"
@@ -1439,6 +1556,10 @@ class HelpLimits(unittest.TestCase):
self.assertIn("fails three times running, retried a minute apart", said)
self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said)
self.assertIn(f"still running after {PYTHON_TIMEOUT} s", said)
self.assertIn(f"Once {measure.CYCLES_PER_CHECK} cycles have closed across all projects", said)
self.assertIn(f"run with a {worker.COMPACT_WINDOW // 1000}k auto-compact window", said)
self.assertIn(f"unfinished {main.UNFINISHED_LIMIT} cycles running", said)
self.assertIn(f"rerun to give it {main.UNFINISHED_LIMIT} more", said)
class ExitContract(unittest.TestCase):
@@ -1453,7 +1574,7 @@ class ExitContract(unittest.TestCase):
("cycle/interrupt.py", "talk", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
("cycle/interrupt.py", "talk", "1", "f'could not tell whether you typed anything:", read),
("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
("cycle/run.py", "stopped", "1", "f'{failure.reason}", read),
("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
("cycle/run.py", "keep_answer", "1", "failure.reason", read),
("cycle/run.py", "rule", "1", "entries.reason", read),
+50
View File
@@ -0,0 +1,50 @@
"""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 escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
entries_read: int | None = None
@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
# The verdicts that may carry an escalation.
Escalating = Interrupt | QuotedAnswer | Unfinished
View File
+38
View File
@@ -0,0 +1,38 @@
"""How much of the machine's memory is available, as /proc/meminfo's MemAvailable and MemTotal state it. A worker starts while at least ROOM_SHARE of it is available. The rest is split across the heavy slots, as the memory limit run-heavy gives each container."""
import dataclasses
import pathlib
import re
MEMINFO = pathlib.Path("/proc/meminfo")
# A worker starts only while at least this share of the machine's memory is available; the human chose it, as no standard sets one. The rest is the heavy slots' share, so changing it also changes the memory limit run-heavy gives a container.
ROOM_SHARE = 0.25
@dataclasses.dataclass(frozen=True)
class Memory:
"""The machine's memory, in kB as /proc/meminfo counts it: what a new process can have without swapping, and all of it."""
available: int
total: int
def has_room(self) -> bool:
return self.available >= ROOM_SHARE * self.total
def slot_share(self, slots: int) -> int:
"""The memory limit, in MiB, that run-heavy gives each container a slot's command makes: what ROOM_SHARE leaves, split evenly across the slots."""
return int(self.total * (1 - ROOM_SHARE)) // slots // 1024
def parsed(meminfo: str) -> Memory | None:
"""The memory a /proc/meminfo text states; None where it lacks MemAvailable or MemTotal."""
fields = dict(re.findall(r"^(MemAvailable|MemTotal):\s+(\d+) kB$", meminfo, re.MULTILINE))
if len(fields) != 2:
return None
return Memory(available=int(fields["MemAvailable"]), total=int(fields["MemTotal"]))
def read_memory(meminfo: pathlib.Path | None = None) -> Memory | None:
"""The machine's memory, read from meminfo or else MEMINFO; None where it cannot be read, as off Linux."""
try:
return parsed((meminfo or MEMINFO).read_text())
except OSError:
return None
+51
View File
@@ -0,0 +1,51 @@
"""The machine's heavy slots: one per 4 CPUs, and at least one, each a file locked with flock that every session on the machine shares."""
import fcntl
import os
import pathlib
import time
import typing
CPUS_PER_SLOT = 4
# Seconds between tries while every slot is held; a slot frees as its command exits.
POLL_SECONDS = 1
def usable_cpus() -> int | None:
"""The CPUs this process may run on, which an affinity mask can make fewer than the machine's; None where the count is unknown."""
return len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count()
def slot_count(cpus: int | None) -> int:
return max(1, (cpus or 0) // CPUS_PER_SLOT)
def slot_folder(env: typing.Mapping[str, str]) -> pathlib.Path:
state = env.get("XDG_STATE_HOME") or str(pathlib.Path.home() / ".local" / "state")
return pathlib.Path(state) / "run-heavy"
def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None:
"""The number and open file of a slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
for slot in range(slots):
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
os.close(fd)
continue
except OSError:
os.close(fd)
raise
return slot, fd
return None
def waited_slot(folder: pathlib.Path, slots: int, say: typing.Callable[[], None], sleep: typing.Callable[[float], None] = time.sleep) -> tuple[int, int]:
"""The number and open file of a slot this call locked, once one frees. While every slot is held, it calls say once and tries again each POLL_SECONDS."""
said = False
while (taken := taken_slot(folder, slots)) is None:
if not said:
say()
said = True
sleep(POLL_SECONDS)
return taken
+91
View File
@@ -0,0 +1,91 @@
import errno
import fcntl
import os
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from machine_load import memory
from machine_load.slots import slot_count
from machine_load import slots
class SlotCount(unittest.TestCase):
def test_one_slot_per_four_cpus_and_never_none(self):
for cpus, slots in ((16, 4), (8, 2), (7, 1), (4, 1), (1, 1), (None, 1)):
self.assertEqual(slot_count(cpus), slots, cpus)
class MemoryShare(unittest.TestCase):
def test_has_room_from_a_quarter_of_memory_available(self):
self.assertFalse(memory.Memory(available=3, total=16).has_room())
self.assertTrue(memory.Memory(available=4, total=16).has_room())
def test_reads_available_and_total_memory_from_meminfo(self):
meminfo = "MemTotal: 16387072 kB\nMemFree: 981236 kB\nMemAvailable: 4096000 kB\n"
self.assertEqual(memory.parsed(meminfo), memory.Memory(available=4096000, total=16387072))
for unread in ("MemTotal: 16 kB\n", "MemTotal: x kB\nMemAvailable: 1 kB\n", ""):
self.assertIsNone(memory.parsed(unread), unread)
def test_reads_a_meminfo_file_and_none_where_it_cannot(self):
with tempfile.TemporaryDirectory() as temp:
meminfo = pathlib.Path(temp, "meminfo")
meminfo.write_text("MemTotal: 8 kB\nMemAvailable: 2 kB\n")
self.assertEqual(memory.read_memory(meminfo), memory.Memory(available=2, total=8))
self.assertIsNone(memory.read_memory(pathlib.Path(temp, "gone")))
class SlotShare(unittest.TestCase):
def test_splits_the_three_quarters_a_worker_leaves_evenly_across_the_slots_in_mib(self):
self.assertEqual(memory.Memory(available=0, total=32 * 1024 * 1024).slot_share(4), 6144)
self.assertEqual(memory.Memory(available=0, total=8000000).slot_share(2), 2929)
class SlotFolder(unittest.TestCase):
def test_every_session_shares_the_slots_under_the_users_state_folder(self):
self.assertEqual(slots.slot_folder({}), pathlib.Path.home() / ".local" / "state" / "run-heavy")
self.assertEqual(slots.slot_folder({"XDG_STATE_HOME": "/s"}), pathlib.Path("/s/run-heavy"))
class TakenSlot(unittest.TestCase):
def test_a_lock_that_fails_for_another_reason_than_a_holder_closes_its_file_and_raises(self):
closed = []
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch("fcntl.flock", side_effect=OSError(errno.ENOLCK, "No locks available")), unittest.mock.patch("os.close", side_effect=closed.append):
with self.assertRaises(OSError):
slots.taken_slot(pathlib.Path(folder), 2)
self.assertEqual(len(closed), 1)
self.assertIsInstance(closed[0], int)
os.close(closed[0])
class WaitedSlot(unittest.TestCase):
def test_waits_while_every_slot_is_held_saying_so_once_then_takes_the_freed_one(self):
with tempfile.TemporaryDirectory() as folder:
held = [open(pathlib.Path(folder, f"slot-{slot}"), "a") for slot in range(2)]
for file in held:
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
said, slept = [], []
def sleep(seconds):
slept.append(seconds)
if len(slept) == 2:
held[1].close()
slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: said.append(True), sleep)
os.close(fd)
held[0].close()
self.assertEqual((slot, said, slept), (1, [True], [slots.POLL_SECONDS] * 2))
def test_takes_a_free_slot_at_once(self):
with tempfile.TemporaryDirectory() as folder:
slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: self.fail("said it waits"), lambda seconds: self.fail("slept"))
os.close(fd)
self.assertEqual(slot, 0)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -111,7 +111,7 @@ 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 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: every tool in bin/ but the status line, item 204's, reads git's output through git_repo.git's one contract.
# 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
+9 -6
View File
@@ -3,10 +3,10 @@ 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")
# A pass an agent under agents/ reviews, named as skills/larv-review/SKILL.md → "Passes" names it in lower case.
ReviewedPass = typing.Literal["architecture", "principles", "overrides", "stability", "product-owner", "prose"]
# What a review launch reviews: such a pass, a comprehension seat or the security pass.
ReviewKind = ReviewedPass | typing.Literal["seat", "security"]
@@ -36,7 +36,7 @@ class Rung:
return Rung(model, effort)
return Rung(family.model, effort) if effort else family
# The one spelling of a rung. 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.worker_line hold it, so parse must keep reading it.
def __str__(self) -> str:
return f"{self.model} at {self.effort} effort" if self.effort else self.model
@@ -65,8 +65,6 @@ LADDER = (
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}
# Each pass an agent under agents/ reviews, in the order of SKILL.md's pass table, and that agent.
REVIEWERS: dict[ReviewedPass, str] = {"architecture": "systems-architect", "principles": "principles-auditor", "overrides": "override-reviewer", "stability": "stability-reviewer", "product-owner": "product-owner-reviewer", "prose": "prose-reviewer"}
# 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] = {}
@@ -107,11 +105,16 @@ def review_rungs(project: Rung, worker: Rung, escape_and_impact: int) -> dict[Re
A pass's reviewer runs on reviewers_rung. Where the E + I steps no review up and the worker runs no higher than the project's rung, a pass whose replay chose a rung for the project's model runs on that rung instead, even below the worker's: the replay compared reviews on the project's rung only, never on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
"""
rungs: dict[ReviewKind, Rung] = {**dict.fromkeys(REVIEWERS, reviewers_rung(project, worker, escape_and_impact)), "seat": project, "security": project}
if escape_and_impact not in REVIEW_STEPS and position(worker) <= position(project):
if replay_applies(project, worker, escape_and_impact):
rungs |= {kind: rung for (kind, model), rung in REPLAYED.items() if model == project.model}
return rungs
def replay_applies(project: Rung, worker: Rung, escape_and_impact: int) -> bool:
"""Whether a pass's replay chose its rung for a chunk like this: only where the E + I steps no review up and the worker runs no higher than the project's rung."""
return escape_and_impact not in REVIEW_STEPS and position(worker) <= position(project)
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int) -> Rung:
"""The rung of each pass's reviewer that no replay lowered: the higher of the worker's rung and review_floor's."""
return highest(worker, review_floor(project, escape_and_impact))
+32
View File
@@ -0,0 +1,32 @@
"""Where a chunk's reviews run, chosen from its route and the project's rung."""
import dataclasses
from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route
from model_routing.ladder import replay_applies, review_rungs, reviewers_rung, Rung
from review_passes import ReviewedPass, REVIEWERS
@dataclasses.dataclass(frozen=True)
class ReviewChoice:
# The rung of each pass's reviewer that no replay lowered.
reviewers: Rung
# The passes whose replay chose another rung, with that rung.
lowered: dict[ReviewedPass, Rung]
seat: Rung
security: Rung
# Each rung a higher E + I than the route's picks for the reviewers, with the lowest E + I that picks it, in rising order.
higher: dict[Rung, int]
def chosen(project: Rung, route: Route) -> ReviewChoice:
"""The rung each kind of review runs on for a chunk whose route is route, on a project whose rung is project."""
rungs = review_rungs(project, route.rung, route.reviewed_on())
reviewers = reviewers_rung(project, route.rung, route.reviewed_on())
lowered = {kind: rungs[kind] for kind in REVIEWERS if rungs[kind] != reviewers}
higher: dict[Rung, int] = {}
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
# A higher E + I changes a review by moving the reviewers' rung, or by ending the replay that lowered a pass.
rung = reviewers_rung(project, route.rung, escape_and_impact)
if rung != reviewers or (lowered and not replay_applies(project, route.rung, escape_and_impact)):
higher.setdefault(rung, escape_and_impact)
return ReviewChoice(reviewers, lowered, rungs["seat"], rungs["security"], higher)
+41 -39
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 JSON on the Worker: line that ends each outcome."""
import dataclasses
import json
import re
import typing
@@ -8,24 +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. 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.
# Each group reads one fragment of Route.__str__. A reworded fragment leaves the line unreadable, so the chunk routes afresh, its mark back at 0.
ROUTED = re.compile(r"""
(?P<rung>.+?) # the rung, lazy so the groups below take what follows it
(?:,\ routed\ by\ item\ (?P<item>[0-9]+)'s\ (?:L\ of\ (?P<likelihood>[0-9]+)\ and\ E\ \+\ I\ of\ (?P<escape_and_impact>[0-9]+)|.+?))? # routed: `, routed by item 3's L of 4 and E + I of 5`, or an older line's R + C
(?:,\ taking\ in\ an\ E\ \+\ I\ of\ (?P<escape_and_impact_taken_in>[0-9]+))? # taken_in: `, taking in an E + I of 6`
(?:,\ escalated\ at\ transcript\ entry\ (?P<escalated_at>[0-9]+))? # escalated: `, escalated at transcript entry 12`
""", re.VERBOSE)
class ArchivedWorker(typing.NamedTuple):
"""What an archived worker line names: the worker's rung, the item that routed it, its L and E + I, the E + I taken in and the escalation's mark; 0 for each it does not name."""
rung: Rung
item: int
likelihood: int
escape_and_impact: int
escape_and_impact_taken_in: int
escalated_at: int
# What Route.worker_line writes. The outcome writers take only this as the worker, so mypy refuses a str(route) there.
WorkerLine = typing.NewType("WorkerLine", str)
# A worker line loop-claude wrote before it archived the route as JSON. Nothing writes this format any more, so its wording never changes. route_from reads it for the chunks the routing figures still count, and for a chunk a rerun resumes across the change.
LEGACY_WORKER = re.compile(r"(?P<rung>.+?)(?:, routed by item (?P<item>[0-9]+)'s L of (?P<likelihood>[0-9]+) and E \+ I of (?P<escape_and_impact>[0-9]+))?(?:, taking in an E \+ I of (?P<escape_and_impact_taken_in>[0-9]+))?(?:, escalated at transcript entry (?P<escalated_at>[0-9]+))?")
HIGHEST_ESCAPE_AND_IMPACT = LEVELS["E"] + LEVELS["I"]
@@ -53,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 worker lines, so renaming one makes the lines already archived unreadable, and their chunks route afresh.
# The fields a loop-claude from before L and E + I replaced R + C hands on reload; the reloaded script drops such a route, and the chunk routes afresh.
RETIRED: typing.ClassVar[frozenset[str]] = frozenset({"risk_and_complexity"})
rung: Rung
@@ -62,17 +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.
# The escalation mark, as loop_claude/escalation_mark.py says: how many transcript entries the session held when an escalation last stepped the worker up, 0 before any.
escalated_at: int = 0
def __post_init__(self) -> None:
# 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":
@@ -83,26 +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 ""
escalated = f", escalated at transcript entry {self.escalated_at}" if self.escalated_at else ""
return f"{self.rung}{routed}{taken_in}{escalated}"
def worker_line(self) -> WorkerLine:
"""What the archive records as each verdict's worker: a JSON object of the rung's model and effort and the WORKER_LINE_FIELDS, leaving out each that is 0 or empty; route_from reads it back."""
fields = {"model": self.rung.model, "effort": self.rung.effort, **{name: getattr(self, name) for name in WORKER_LINE_FIELDS}}
return WorkerLine(json.dumps({name: value for name, value in fields.items() if value}))
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", "escalated_at")))
# The Route fields a worker line holds beside the rung's model and effort. A human reads the line in the archive, so it is flatter than the JSON a reload hands over (loop_claude/loop/reload.py) and leaves out zeros. It leaves out unfinished, so a rerun restarts that count.
WORKER_LINE_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if field.name not in ("rung", "unfinished"))
def route_from(worker: str) -> Route | None:
"""The route an archived worker line names; 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 JSON or a line written before JSON. None where it names no model, holds fields Route.worker_line never writes, or holds levels off their scales; and for an older line, where it names a model without an effort."""
fields = json_fields(worker) if worker.startswith("{") else legacy_fields(worker)
if fields is None or not Route.fits(fields):
return None
return Route(archived.rung, archived.item, archived.likelihood, archived.escape_and_impact, escape_and_impact_taken_in=archived.escape_and_impact_taken_in, escalated_at=archived.escalated_at)
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})
def json_fields(line: str) -> dict[str, typing.Any] | None:
"""The fields of a line Route.worker_line wrote; None for any other text."""
try:
fields = json.loads(line)
except ValueError:
return None
if not (isinstance(fields, dict) and isinstance(fields.get("model"), str) and isinstance(fields.get("effort", ""), str) and fields.keys() <= {"model", "effort", *WORKER_LINE_FIELDS}):
return None
# type(), not isinstance(): JSON true is no integer.
return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) else None
def legacy_fields(line: str) -> dict[str, typing.Any] | None:
"""The fields of a LEGACY_WORKER line, as json_fields gives them; None for any other text."""
found = LEGACY_WORKER.fullmatch(line)
rung = Rung.parse(found["rung"]) if found else None
if not (found and rung):
return None
return {"model": rung.model, "effort": rung.effort, **{name: int(value or 0) for name, value in found.groupdict().items() if name != "rung"}}
+2 -7
View File
@@ -1,14 +1,14 @@
import pathlib
import sys
import typing
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, position, project_rung, review_floor, review_rungs, ReviewedPass, REVIEWERS, 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")
@@ -105,11 +105,6 @@ class Ladder(unittest.TestCase):
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), {**dict.fromkeys(REVIEWERS, LADDER[-1]), "seat": OPUS, "security": OPUS})
def test_names_every_kind_of_review_once_each_pass_with_its_agent_under_agents(self):
self.assertEqual(list(REVIEWERS), list(typing.get_args(ReviewedPass)))
agents = pathlib.Path(__file__).resolve().parents[2] / "agents"
self.assertEqual(sorted(REVIEWERS.values()), sorted(path.stem for path in agents.glob("*.md")))
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}):
+26
View File
@@ -0,0 +1,26 @@
import unittest
import unittest.mock
from model_routing.review_choice import chosen, ReviewChoice
from model_routing import ladder
from model_routing.route import Route
from model_routing.ladder import Rung
HAIKU = Rung("claude-haiku-5-5", "low")
OPUS = Rung("claude-opus-5-5", "medium")
OPUS_MAX = Rung("claude-opus-5-5", "max")
FABLE = Rung("claude-fable-5-1", "max")
SONNET = Rung("claude-sonnet-5-5", "high")
class Chosen(unittest.TestCase):
def test_names_no_higher_rung_on_the_top_one(self):
self.assertEqual(chosen(OPUS, Route(FABLE, 3, 4, 5)).higher, {})
def test_names_the_e_plus_i_that_ends_a_replay_even_where_the_reviewers_are_on_the_top_rung(self):
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-fable-5-1"): HAIKU}):
self.assertEqual(chosen(FABLE, Route(OPUS_MAX, 3, 4, 4)), ReviewChoice(FABLE, {"prose": HAIKU}, FABLE, FABLE, {FABLE: 5}))
def test_puts_every_pass_on_the_reviewers_rung_once_an_e_plus_i_steps_a_review_up(self):
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): HAIKU}):
self.assertEqual(chosen(OPUS, Route(SONNET, 3, 2, 5)).lowered, {})
+8 -8
View File
@@ -9,8 +9,8 @@ from markdown_text import sections
from utc_stamp import STAMPED
FIGURE = re.compile(rf"^Reading cost, chunk (\w+), finished ({STAMPED})$")
FIGURE_PLACE = re.compile(r"^- `(.+)` (\d+)$")
PLACES_KEPT = 10
FIGURE_FILE = re.compile(r"^- `(.+)` (\d+)$")
FILES_KEPT = 10
RECORD = "docs/reading-cost.md"
RESET = "Reading cost reset, "
RESET_AT = re.compile(rf"^{RESET}({STAMPED})$")
@@ -28,8 +28,8 @@ def chunk_id(chunk: FinishedChunk) -> str:
def figure(chunk: FinishedChunk, reading: Reading) -> str:
places = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.places))
return f"## Reading cost, chunk {chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\n\n{places}" if places else "")
files = "".join(f"- `{path}` {times}\n" for path, times in ranked(reading.files))
return f"## Reading cost, chunk {chunk_id(chunk)}, finished {chunk.finished}\n\n{reading.tokens} new input tokens before the first commit.\n" + (f"\nRead most (opens and searches):\n\n{files}" if files else "")
# The figures after the last reset, in the order their chunks finished: each machine appends its own archive's chunks.
@@ -44,14 +44,14 @@ def readings_of(record: str) -> list[Reading] | Failure:
tokens = [int(match.group(1)) for line in lines if (match := TOKENS.match(line))]
if len(tokens) != 1:
return Failure(f"the figure under \"## {heading}\" holds no single tokens line; restore it from git history")
dated.append((named.group(2), heading, Reading(tokens[0], collections.Counter({match.group(1): int(match.group(2)) for line in lines if (match := FIGURE_PLACE.match(line))}))))
dated.append((named.group(2), heading, Reading(tokens[0], collections.Counter({match.group(1): int(match.group(2)) for line in lines if (match := FIGURE_FILE.match(line))}))))
elif heading.startswith("Reading cost"):
return Failure(f"\"## {heading}\" names no chunk and UTC time, or no reset time; restore it from git history")
return [reading for finished, _, reading in sorted(dated, key=lambda item: item[:2]) if finished > max(resets)]
def ranked(places: collections.Counter[str]) -> list[tuple[str, int]]:
return sorted(places.items(), key=lambda item: (-item[1], item[0]))[:PLACES_KEPT]
def ranked(files: collections.Counter[str]) -> list[tuple[str, int]]:
return sorted(files.items(), key=lambda item: (-item[1], item[0]))[:FILES_KEPT]
def merged(record: str, figures: list[str]) -> str:
@@ -65,7 +65,7 @@ def trend(readings: list[Reading]) -> str:
medians = f"the last {WINDOW} chunks' median is {last} new input tokens before their first commit, the {WINDOW} before them {earlier}."
if last <= earlier:
return f"Not rising: {medians}"
read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.places for reading in readings[-WINDOW:]), collections.Counter())))
read_most = "".join(f"\n- `{path}` {times}" for path, times in ranked(sum((reading.files for reading in readings[-WINDOW:]), collections.Counter())))
return f"Rising: {medians}\n\nRead most over the last {WINDOW} (opens and searches):\n{read_most}"
+4 -4
View File
@@ -11,9 +11,9 @@ from shell_command import resolved, simple_commands
@dataclasses.dataclass(frozen=True)
class Reading:
"""What the worker and its subagents took in before the worker's first commit."""
"""What the worker and its subagents took in before the worker's first commit: tokens counts the new input tokens, and files counts how often each tracked file was opened or searched, by its path in the checkout."""
tokens: int
places: collections.Counter[str]
files: collections.Counter[str]
@dataclasses.dataclass(frozen=True)
@@ -32,8 +32,8 @@ def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | No
before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)]
reads = [reads_of(part, str(entry.get("cwd") or "/"), home) for thread in before for entry in thread for part in assistant_parts(entry)]
roots = [checkout.main_root, *(added for found in reads for added in found.added)]
places = collections.Counter(place for found in reads for path in found.read if (place := relative(path, roots)) in checkout.tracked)
return Reading(sum(map(tokens_in, before)), places)
files = collections.Counter(file for found in reads for path in found.read if (file := relative(path, roots)) in checkout.tracked)
return Reading(sum(map(tokens_in, before)), files)
def entries_of(raw: bytes) -> list[dict]:
+4
View File
@@ -0,0 +1,4 @@
import pathlib
# The checkout root.
ROOT = pathlib.Path(__file__).resolve().parents[2]
+1 -1
View File
@@ -7,7 +7,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_claude.project.records import HUMAN_RULE_DIRS
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
RULE_PATH = rf"(?:{'|'.join(map(re.escape, HUMAN_RULE_DIRS))})/[\w-]+\.md"
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
+1 -1
View File
@@ -5,7 +5,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
PRIVATE = [
".claude/settings.local.json",
+1 -1
View File
@@ -6,7 +6,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
def bound(node: ast.Import | ast.ImportFrom) -> list[str]:
+1 -1
View File
@@ -5,7 +5,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
class Install(unittest.TestCase):
-27
View File
@@ -1,27 +0,0 @@
import pathlib
import re
import shutil
import subprocess
import sys
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
FLOOR = re.compile(r"Python 3\.(\d+) or newer")
def readme_floor() -> tuple[int, int] | None:
named = FLOOR.search((ROOT / "README.md").read_text(encoding="utf-8"))
return (3, int(named.group(1))) if named else None
class PythonFloor(unittest.TestCase):
def test_the_suite_passes_on_the_python_the_readme_names_as_floor(self):
floor = readme_floor()
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if sys.version_info[:2] == floor:
self.skipTest("this run is on the floor")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches the floor interpreter; see README.md's Test line")
suite = ["python", "-m", "unittest", "discover", "-s", "bin", "-p", "test_*.py"]
ran = subprocess.run(["uv", "run", "--no-project", "--python", "%d.%d" % floor, *suite], capture_output=True, cwd=ROOT, text=True)
self.assertEqual(ran.returncode, 0, ran.stderr)
+16
View File
@@ -0,0 +1,16 @@
import pathlib
import re
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from machine_load.slots import CPUS_PER_SLOT
from repo_checks import ROOT
class TestLine(unittest.TestCase):
def test_the_readme_runs_the_tests_in_one_heavy_slots_cpus(self):
workers = re.search(r"pytest==\S+ -n (\d+) bin`", (ROOT / "README.md").read_text(encoding="utf-8"))
self.assertIsNotNone(workers, "README.md's Test line runs `pytest==X -n N bin`")
self.assertEqual(int(workers.group(1)), CPUS_PER_SLOT)
+11 -13
View File
@@ -5,27 +5,25 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from round_titles import PASSES
from model_routing.ladder import REVIEWERS
from repo_checks.test_python_floor import ROOT
from review_passes import PASS_AGENTS, PASSES
from repo_checks import ROOT
from rule_hook.reviewer_rung import SEAT, SECURITY_OPENER
OPENING = re.compile(r"^## Opening\n+```\n([^\n]+?\.)(?: |\n)", re.MULTILINE)
# A row of the pass table whose reviewer is an agent: its pass and that agent.
REVIEWED_ROW = re.compile(r"^\| ([A-Z][a-z-]+) \| ([a-z]+(?:-[a-z]+)*-(?:reviewer|architect|auditor)) \|", re.MULTILINE)
# 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_passes_and_agents_larv_review_s_pass_table_names_in_its_order(self):
passes = LARV_REVIEW.split("## 3. Passes", 1)[1].split("A comment is prose", 1)[0]
self.assertEqual({name.lower(): agent for name, agent in REVIEWED_ROW.findall(passes)}, REVIEWERS)
self.assertEqual([name.lower() for name, _ in REVIEWED_ROW.findall(passes)], list(REVIEWERS))
def test_each_reviewed_pass_is_a_pass_the_round_titles_count(self):
self.assertEqual([name for name in PASSES if name in REVIEWERS], list(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"))
+1 -1
View File
@@ -7,7 +7,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from settings_filter import cleaned
from git_repo import git
from repo_checks.test_python_floor import ROOT
from repo_checks import ROOT
INSTALL = "git config filter.settings.clean bin/settings_filter.py"
+20 -5
View File
@@ -1,4 +1,5 @@
import pathlib
import re
import shutil
import subprocess
import sys
@@ -6,14 +7,28 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks.test_python_floor import readme_floor, ROOT
from repo_checks import ROOT
SUPPORTED = re.compile(r"the latest stable Python, today (3\.\d+)")
def tools() -> list[str]:
"""mypy's arguments naming every package and module under bin/ except `repo_checks`, so a new tool is checked without being listed."""
bin_folder = ROOT / "bin"
packages = sorted(init.parent.name for init in bin_folder.glob("*/__init__.py") if init.parent.name != "repo_checks")
modules = sorted(path.stem for path in bin_folder.glob("*.py") if not path.name.startswith("test_"))
return [*(word for package in packages for word in ("-p", package)), *(word for module in modules for word in ("-m", module))]
class Types(unittest.TestCase):
def test_mypy_passes_on_the_tools_at_the_floor(self):
floor = readme_floor()
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
def test_mypy_passes_on_the_tools_for_the_python_readme_install_names(self):
supported = SUPPORTED.search((ROOT / "README.md").read_text(encoding="utf-8"))
self.assertIsNotNone(supported, "README.md's Install names `the latest stable Python, today 3.N`")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line")
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "chunk_preflight", "-p", "claude_code", "-m", "comprehension_history", "-m", "git_repo", "-p", "judge_replay", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-p", "review_replay", "-m", "round_titles", "-p", "rule_hook", "-p", "rung_replay", "-p", "score_outcomes", "-m", "settings_filter", "-m", "shell_command", "-m", "statusline", "-p", "subagent_rung", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", sys.executable, "mypy==2.3.1", "--python-version", supported.group(1), "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", *tools()], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
def test_mypy_checks_run_heavy_and_each_root_module(self):
self.assertLessEqual({("-p", "run_heavy"), ("-p", "machine_load"), ("-m", "chunk_pick"), ("-m", "docker_command")}, set(zip(tools()[::2], tools()[1::2])))
self.assertNotIn("repo_checks", tools())
+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)}
+5 -4
View File
@@ -16,11 +16,11 @@ folder, holding only the reports written after the chunk began and before the ro
finds nothing where its prompt still names the review folder, or names a file there, other than a
round's report, that the folder did not hold from the chunk's start until the round's.
It first replays every round on the project's rung, the reference reviewer. Findings on record
It first replays every round on the project's rung, the reference reviewer. Archived findings
that the reference reviewer does not raise again may rest on code or rules that have changed
since; no rung is held to them. It then replays the rounds where the reference raised any, on each
rung below, highest first, down to the ladder's lowest, and stops at the first rung that misses
one. For each replay, claude on the project's rung matches the report to the findings on record,
one. For each replay, claude on the project's rung matches the report to the archived findings,
and counts a finding only where the report raises it as 🔴 or 🟡. The tool prints each finding a
rung missed and the lowest rung that, like each rung above it, missed none. That rung is the
evidence for running the pass's reviewer on it; the decision above records each run.
@@ -47,9 +47,10 @@ 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, ReviewedPass, REVIEWERS, Rung
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 review_passes import ReviewedPass, REVIEWERS
TOOL = "review-replay"
USAGE = f"{TOOL} <pass> <model>, <pass> one of {', '.join(REVIEWERS)} and <model> a model on the routing ladder"
@@ -149,7 +150,7 @@ def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Roun
def code_of(found: Round, effects: Effects) -> Code | Failure:
"""Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the folder rounds.reviewed_path guesses from the prompt, and the commits authored by then.
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess costs no rung: the reference reviewer, replayed on that code, finds fewer findings on record, and no rung is held to those.
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess costs no rung: the reference reviewer, replayed on that code, finds fewer of the archived findings, and no rung is held to those.
"""
if not os.path.isdir(found.root):
return Failure("the project has no checkout")
+1 -1
View File
@@ -14,7 +14,7 @@ FINDING = re.compile(r"^[\s#>*+|-]*(?:\d+[.)]\s*)?[*_]*\s*(?:🔴|🟡)")
# An absolute path in a prompt, up to the quote, bracket or punctuation that ends it.
PATH = re.compile(r"/[^\s`'\"()<>\[\],;]+")
LINE_OR_STOP = re.compile(r"(?::\d+(?:-\d+)?)?[.:]?$")
# A round's report, as skills/larv-review/SKILL.md → "Reports" names it, such as stability-round-2.md or principles-goals-round-1-rerun.md.
# A round's report, as skills/larv-review/SKILL.md → "Reports" names it, such as stability-round-2.md or principles-round-1-rerun.md.
ROUND_REPORT = re.compile(r"-round-\d+(?:-rerun)?\.md$")
+4 -3
View File
@@ -19,7 +19,8 @@ from loop_claude.effects import Effects, system_effects
from failure import Failure
from review_replay import main
from rung_replay.search import Miss, Replay, Tried
from model_routing.ladder import REVIEWERS, Rung
from review_passes import REVIEWERS
from model_routing.ladder import Rung
TOOL = pathlib.Path(__file__).resolve().parents[1] / "review-replay"
REFERENCE = Rung("claude-opus-5-5", "medium")
@@ -81,7 +82,7 @@ class ReviewedPath(unittest.TestCase):
class LostInputs(unittest.TestCase):
def test_names_each_file_the_prompt_names_in_the_copy_that_it_lacks_other_than_a_round_report(self):
prompt = "Read /c/branch.diff and /c/ls-files.txt:3. Earlier: /c/prose-round-1.md. Write /c/principles-goals-round-2-rerun.md; see /elsewhere/x.diff."
prompt = "Read /c/branch.diff and /c/ls-files.txt:3. Earlier: /c/prose-round-1.md. Write /c/principles-round-2-rerun.md; see /elsewhere/x.diff."
self.assertEqual(lost_inputs(prompt, "/c", {"ls-files.txt"}.__contains__), ["branch.diff"])
self.assertEqual(lost_inputs(prompt, "/c", {"branch.diff", "ls-files.txt"}.__contains__), [])
@@ -214,7 +215,7 @@ class Main(unittest.TestCase):
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
+42 -14
View File
@@ -1,11 +1,22 @@
"""The titles of larv-review's round commits, `Answer <pass> round <n>: <k> 🔴, <m> 🟡; <summary>`: each pass's round count, and the findings the rounds reported."""
"""The titles of larv-review's round commits, `Answer <pass> round <n>: <k> 🔴, <m> 🟡 (<j> misread); <summary>`: each pass's round count against its cap, and the findings the rounds reported. <j> counts the 🔴 and 🟡 findings a reviewer marked `[misread]`."""
import dataclasses
import re
CAP = 3
PASSES = ("architecture", "principles", "full scan", "security", "overrides", "stability", "product-owner", "prose")
from review_passes import PASSES
# The most rounds a pass takes per chunk, per `docs/decisions.md` → `review: a pass gets at most two rounds per chunk, …`. rule-hook's `round-cap` refuses a round commit that `past_cap` finds takes its pass past it, and `larv-review round-count` marks a pass that reached it.
CAP = 2
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
# What follows a round title's colon: the round's 🔴 and 🟡 counts, then `;` and its summary, if any.
FINDINGS = re.compile(r" ([0-9]+) 🔴, ([0-9]+) 🟡(?:;|$)")
# What follows a round title's colon: the round's 🔴 and 🟡 counts, then how many of them a reviewer marked `[misread]`, a count that titles from before it lack, then `;` and its summary, if any.
FINDINGS = re.compile(r" ([0-9]+) 🔴, ([0-9]+) 🟡(?: \(([0-9]+) misread\))?(?:;|$)")
@dataclasses.dataclass(frozen=True)
class Findings:
"""A round title's findings: its 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None for a title from before that count."""
red: int
yellow: int
misread: int | None
def round_counts(titles: list[str]) -> dict[str, int]:
@@ -21,18 +32,35 @@ def round_counts(titles: list[str]) -> dict[str, int]:
def lacks_counts(title: str) -> bool:
"""Whether title is a round title without the counts after its colon."""
"""Whether title is a round title without all three counts after its colon, or with more misread findings than 🔴 and 🟡 findings."""
return ROUND.match(title) is not None and ((counts := title_counts(title)) is None or counts.misread is None)
def past_cap(title: str, earlier: list[str]) -> bool:
"""Whether title is a round title that takes its pass past CAP, as round_counts counts title among the branch's earlier commit titles."""
named = ROUND.match(title)
return named is not None and not FINDINGS.match(title, named.end())
return named is not None and round_counts([*earlier, title])[named.group(1).lower()] > CAP
def round_findings(titles: list[str]) -> tuple[int, int] | None:
"""The 🔴 and 🟡 counts summed over the round titles among titles; None where a round title lacks them, or no title is a round."""
def title_counts(title: str) -> Findings | None:
"""The counts after a round title's colon; None where title is no round title, lacks the 🔴 and 🟡 counts, or counts more misread findings than both."""
named = ROUND.match(title)
found = FINDINGS.match(title, named.end()) if named else None
if not found:
return None
counts = Findings(int(found.group(1)), int(found.group(2)), None if found.group(3) is None else int(found.group(3)))
return None if counts.misread is not None and counts.misread > counts.red + counts.yellow else counts
def round_findings(titles: list[str]) -> Findings | None:
"""The counts summed over the round titles among titles; None where a round title lacks the 🔴 and 🟡 counts, or no title is a round. Its misread is None where a round title lacks that count."""
counts = []
for title in titles:
if named := ROUND.match(title):
found = FINDINGS.match(title, named.end())
if not found:
if ROUND.match(title):
if (found := title_counts(title)) is None:
return None
counts.append((int(found.group(1)), int(found.group(2))))
return (sum(red for red, _ in counts), sum(yellow for _, yellow in counts)) if counts else None
counts.append(found)
if not counts:
return None
misreads = [found.misread for found in counts if found.misread is not None]
return Findings(sum(found.red for found in counts), sum(found.yellow for found in counts), sum(misreads) if len(misreads) == len(counts) else None)
+1 -1
View File
@@ -19,7 +19,7 @@ FIGURES = "routing-figures.md"
LOCK = "routing-figures.lock"
RAISED = "routing-calls-raised.md"
RAISED_HEADING = "# Routing calls raised\n"
# Each line is a call and when it was raised, or a reset: `- <UTC time> <call>` or `- <UTC time> Reset`.
# Each line is a call and when it was raised, or a reset: `- <UTC time> <call>` or `- <UTC time> Reset`. After a reset the figures count only chunks that finished after it, and a call raised before it may be raised again.
RAISED_LINE = re.compile(rf"^- ({STAMPED}) (.+)$", re.MULTILINE)
RESET = "Reset"
+97 -51
View File
@@ -1,13 +1,14 @@
"""Token spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`."""
"""Dollar spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`. A chunk that cannot be read is skipped and named in the figures."""
import collections
import dataclasses
import re
import statistics
import typing
from model_routing.route import archived_worker, ESCALATION_MARKER
from claude_code.entries import assistant_parts, parts, tool_call, usage_count
from claude_code.entries import assistant_parts, parts, tool_call, tool_result
from git_command import commits
from model_routing.route import ESCALATION_MARKER, route_from
from routing_figures.prices import listed
from model_routing.ladder import position, Rung
from round_titles import round_counts
from shell_command import simple_commands
@@ -18,6 +19,8 @@ MEASURED_AT = re.compile(r"^Measured .+, at cycle ([0-9]+) across", re.MULTILINE
# A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change.
MEASURED_AT_LEAST = 5
DIMENSIONS = ("project", "subagent type", "rung", "tool")
# Each of DIMENSIONS to its labels' dollars.
Dollars = dict[str, collections.defaultdict[str, float]]
# The tool label of a message that follows no tool call, such as the first message after a prompt.
PROMPT = "prompt"
ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):")
@@ -53,32 +56,50 @@ class Reports:
@dataclasses.dataclass(frozen=True)
class ChunkFigures:
"""tokens maps each of DIMENSIONS to its labels' tokens; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger."""
tokens: dict[str, collections.Counter[str]]
"""dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive."""
dollars: Dollars
start: Rung | None
rounds_past_first: int
unfinished: int
delegated: collections.Counter[str]
reports: dict[str, Reports]
escalated: collections.Counter[int]
unattributed: float
lacking: int = 0
@dataclasses.dataclass(frozen=True)
class Figures:
"""escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole."""
chunks: int
tokens: dict[str, collections.Counter[str]]
dollars: Dollars
routed: dict[Rung, list[ChunkFigures]]
reports: dict[str, Reports]
escalated: collections.Counter[int]
skipped: tuple[str, ...] = ()
unattributed: float = 0.0
lacking: int = 0
@dataclasses.dataclass(frozen=True)
class Message:
"""An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices."""
at: str
tools: list[str]
model: str
list_price: float
class Spent(typing.NamedTuple):
"""A message with the subagent type that wrote it, or `worker`, and the rung it ran on."""
kind: str
rung: str
message: Message
def measured(chunk: Chunk, home: str) -> ChunkFigures:
cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0])
tokens: dict[str, collections.Counter[str]] = {dimension: collections.Counter() for dimension in DIMENSIONS}
for at, tools, spent in spend(chunk.worker):
add(tokens, chunk.project, "worker", str(rung_at(cycles, at)), tools, spent)
spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)]
launches = agent_calls(chunk.worker)
reported = results(chunk.worker)
delegated: collections.Counter[str] = collections.Counter()
@@ -89,17 +110,19 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
rung = str(subagent_rung(subagent.entries, arguments, rung_at(cycles, launched_at)))
delegated[rung] += 1
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values())))
for _, tools, spent in spend(subagent.entries):
add(tokens, chunk.project, kind, rung, tools, spent)
start = archived_worker(cycles[0][1]) if cycles else None
spent += [Spent(kind, rung, message) for message in messages(subagent.entries)]
dollars, unattributed = costed(spent, chunk.project, recorded_costs(chunk.worker))
start = route_from(cycles[0][1]) if cycles else None
return ChunkFigures(
tokens=tokens,
dollars=dollars,
start=start.rung if start and start.item else None,
rounds_past_first=rounds_past_first(chunk.worker, home),
unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes),
delegated=delegated,
reports=reports,
escalated=escalations(launches),
unattributed=unattributed,
lacking=max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in chunk.subagents) - len(chunk.subagents)),
)
@@ -120,21 +143,38 @@ def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]:
return found
def add(tokens: dict[str, collections.Counter[str]], project: str, kind: str, rung: str, tools: list[str], spent: int) -> None:
tokens["project"][project] += spent
tokens["subagent type"][kind] += spent
tokens["rung"][rung] += spent
# Split whole, the first tools taking the remainder, so the tool table adds up to the others.
for place, tool in enumerate(tools):
tokens["tool"][tool] += spent // len(tools) + (place < spent % len(tools))
# {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...}
def recorded_costs(worker: list[dict]) -> dict[str, float]:
"""The cost the worker transcript's last cost-state entry records for each model. Claude Code counts every call of the session in it, the subagents' and the compactions' too."""
for entry in reversed(worker):
if entry.get("type") == "cost-state" and isinstance(by_model := entry.get("modelUsage"), dict):
return {model: cost for model, usage in by_model.items() if isinstance(usage, dict) and isinstance(cost := usage.get("costUSD"), (int, float))}
return {}
def costed(spent: list[Spent], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]:
"""Each message's dollars by DIMENSIONS, and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices."""
listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float)
for _, _, message in spent:
listed_by_model[message.model] += message.list_price
scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded}
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
for kind, rung, message in spent:
cost = message.list_price * scale.get(message.model, 1.0)
dollars["project"][project] += cost
dollars["subagent type"][kind] += cost
dollars["rung"][rung] += cost
for tool in message.tools:
dollars["tool"][tool] += cost / len(message.tools)
return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model])
def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str:
"""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:
@@ -144,39 +184,27 @@ def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> R
return Rung(model, str(effort))
def spend(entries: list[dict]) -> list[tuple[str, list[str], int]]:
"""Each message's timestamp, the tools whose results it took in, and its input, cache-written and output tokens, counted once per message, as reading_cost's tokens_in dedupes them, though tokens_in leaves output tokens out."""
messages: dict[str, tuple[str, object, list[str]]] = {}
def messages(entries: list[dict]) -> list[Message]:
"""The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in."""
# Claude Code writes one entry per content block of a message, each with the message's usage. The usage is the same in every entry (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last.
kept: dict[str, tuple[str, dict, list[str]]] = {}
for entry in entries:
if entry.get("type") != "assistant" or not isinstance(message := entry.get("message"), dict):
continue
key = str(message.get("id") or entry.get("uuid"))
kept = messages.setdefault(key, (str(entry.get("timestamp", "")), message.get("usage"), []))
kept[2].extend(name for part in assistant_parts(entry) if (found := tool_call(part)) and isinstance(name := found[0], str))
spent = []
found = kept.setdefault(str(message.get("id") or entry.get("uuid")), (str(entry.get("timestamp", "")), message, []))
found[2].extend(name for part in assistant_parts(entry) if (call := tool_call(part)) and isinstance(name := call[0], str))
counted = []
before = [PROMPT]
for at, usage, called in messages.values():
tokens = sum(usage_count(usage, field) for field in ("input_tokens", "cache_creation_input_tokens", "output_tokens")) if isinstance(usage, dict) else 0
spent.append((at, before, tokens))
for at, message, called in kept.values():
model = str(message.get("model") or "")
counted.append(Message(at, before, model, listed(model, message.get("usage"))))
before = called or [PROMPT]
return spent
return counted
def results(entries: list[dict]) -> dict[str, str]:
"""Each tool result's text by the id of the call it answers."""
found = {}
for entry in entries:
for part in parts(entry):
if isinstance(part, dict) and part.get("type") == "tool_result":
found[str(part.get("tool_use_id"))] = result_text(part.get("content"))
return found
# {"type": "tool_result", "content": "hi"} or {"type": "tool_result", "content": [{"type": "text", "text": "hi"}]}
def result_text(body: object) -> str:
if isinstance(body, str):
return body
return "".join(block["text"] for block in body if isinstance(block, dict) and isinstance(block.get("text"), str)) if isinstance(body, list) else ""
return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))}
def rounds_past_first(worker: list[dict], home: str) -> int:
@@ -196,7 +224,11 @@ def due(cycle: int, last_measured: int) -> bool:
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures:
tokens = {dimension: sum((chunk.tokens.get(dimension, collections.Counter()) for chunk in chunks), collections.Counter()) for dimension in DIMENSIONS}
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
for chunk in chunks:
for dimension in DIMENSIONS:
for label, amount in chunk.dollars.get(dimension, {}).items():
dollars[dimension][label] += amount
routed: dict[Rung, list[ChunkFigures]] = {}
reports: dict[str, Reports] = {}
for chunk in chunks:
@@ -204,7 +236,7 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures
routed.setdefault(chunk.start, []).append(chunk)
for kind, found in chunk.reports.items():
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found
return Figures(len(chunks), tokens, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped)
return Figures(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks))
def calls(figures: Figures) -> list[str]:
@@ -224,14 +256,24 @@ def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -
return statistics.mean(map(of, chunks))
def basis(figures: Figures) -> str:
"""What the dollars are, what they leave out, and where the archive falls short of the recorded cost."""
text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's runs are not archived, so their cost is not counted."
if figures.unattributed:
text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive."
if figures.lacking:
text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls."
return text
def render(figures: Figures, found: list[str], at: str, cycle: int, since: str) -> str:
"""The figures as markdown; MEASURED_AT reads the cycle back. since is the latest reset's stamp, empty for none."""
sections = [
"# Routing figures",
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. Tokens are input, cache-written and output tokens; cache reads are left out. A message's tokens count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`.",
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
"## Calls for a routing change",
"".join(f"- {call}\n" for call in found).rstrip("\n") or "None.",
*[part for dimension in DIMENSIONS for part in (f"## Tokens by {dimension}", table((dimension.capitalize(), "Tokens"), [(label, str(tokens)) for label, tokens in figures.tokens[dimension].most_common()]))],
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])]))],
"## Routed chunks by the rung they started on",
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Subagent rungs", "Escalations by trigger"), [
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated)))
@@ -260,6 +302,10 @@ def triggers(escalated: collections.Counter[int]) -> str:
return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items()))
def money(dollars: float) -> str:
return f"${dollars:,.2f}"
def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str:
if not rows:
return "None."
+44
View File
@@ -0,0 +1,44 @@
"""What a message costs at list prices: the weights that split a chunk's recorded cost between its messages."""
import dataclasses
from claude_code.entries import usage_count
@dataclasses.dataclass(frozen=True)
class Price:
"""Dollars per million tokens. A cache write costs 1.25 times the input for a five-minute cache and 2 times for an hour's, as Opus 5.5's $5 and $8 show."""
input: float
read: float
output: float
@property
def write_5m(self) -> float:
return self.input * 1.25
@property
def write_1h(self) -> float:
return self.input * 2
# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Where a chunk records its cost, only the proportions between one model's messages matter, so these may be a little off.
PRICES = {
"claude-fable-5-1": Price(10, 0.25, 50),
"claude-haiku-5-5": Price(0.1, 0.01, 0.5),
"claude-opus-5-5": Price(4, 0.2, 20),
"claude-sonnet-5-5": Price(2, 0.2, 10),
}
# {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 25919}, "cache_read_input_tokens": 10365, "output_tokens": 193, ...}
def listed(model: str, usage: object) -> float:
"""The cost of one message's usage at the model's list price; 0 for a model without one."""
price = PRICES.get(model)
if not price or not isinstance(usage, dict):
return 0.0
written = usage.get("cache_creation")
# A write without the split by lifetime counts as a five-minute one.
five, hour = (usage_count(written, "ephemeral_5m_input_tokens"), usage_count(written, "ephemeral_1h_input_tokens")) if isinstance(written, dict) else (usage_count(usage, "cache_creation_input_tokens"), 0)
return (
usage_count(usage, "input_tokens") * price.input + five * price.write_5m + hour * price.write_1h
+ usage_count(usage, "cache_read_input_tokens") * price.read + usage_count(usage, "output_tokens") * price.output
) / 1_000_000
+94 -32
View File
@@ -1,5 +1,6 @@
import collections
import contextlib
import dataclasses
import io
import json
import pathlib
@@ -15,14 +16,20 @@ 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).worker_line()
def message(id_, at, *parts, model="claude-opus-5-5", tokens=(1, 10, 100)):
return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": {"input_tokens": tokens[0], "cache_creation_input_tokens": tokens[1], "output_tokens": tokens[2], "cache_read_input_tokens": 5000}}}
def message(id_, at, *parts, model="claude-opus-5-5", usage=None):
"""Costs $2 on Opus 5.5, whose output is $20 per million tokens, and $1 on Sonnet 5.5, whose output is $10."""
return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": usage or {"output_tokens": 100_000}}}
def cost_state(**costs):
return {"type": "cost-state", "totalCostUSD": sum(costs.values()), "modelUsage": {model.replace("_", "-"): {"costUSD": cost} for model, cost in costs.items()}}
def call(name, id_="t1", **arguments):
@@ -38,23 +45,23 @@ def stamped(at, outcome):
def figures(start=LOW, rounds=0, unfinished=0, reports=None, escalated=None):
return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {}))
return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {}), 0.0)
class Measured(unittest.TestCase):
def test_counts_each_messages_tokens_once_by_project_type_rung_and_the_tool_it_followed(self):
def test_prices_each_message_once_by_project_type_rung_and_the_tool_it_followed(self):
worker = [
message("m1", "2026-10-14T10:00:00.100Z", {"type": "text", "text": "reading"}),
message("m1", "2026-10-14T10:00:00.200Z", call("Read", file_path="/c/a")),
message("m2", "2026-10-14T10:05:00.000Z", {"type": "text", "text": "done"}),
message("m3", "2026-10-14T11:00:00.000Z", {"type": "text", "text": "on"}),
]
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(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).worker_line())) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j"))
found = measured(Chunk("log", [kept], worker, []), "/h")
self.assertEqual(found.tokens["project"], {"log": 333})
self.assertEqual(found.tokens["subagent type"], {"worker": 333})
self.assertEqual(found.tokens["rung"], {str(LOW): 222, str(HIGH): 111})
self.assertEqual(found.tokens["tool"], {"prompt": 222, "Read": 111})
self.assertEqual(found.dollars["project"], {"log": 6.0})
self.assertEqual(found.dollars["subagent type"], {"worker": 6.0})
self.assertEqual(found.dollars["rung"], {str(LOW): 4.0, str(HIGH): 2.0})
self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 2.0})
self.assertEqual((found.start, found.unfinished), (LOW, 1))
def test_reads_a_subagents_rung_from_its_model_and_the_effort_its_call_set_or_else_the_workers(self):
@@ -69,7 +76,7 @@ class Measured(unittest.TestCase):
]
found = measured(Chunk("log", [stamped("2026-10-14T11:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j"))], worker, subagents), "/h")
self.assertEqual(found.delegated, {"claude-sonnet-5-5 at high effort": 1, str(LOW): 1})
self.assertEqual(found.tokens["subagent type"], {"worker": 111, "Explore": 222})
self.assertEqual(found.dollars["subagent type"], {"worker": 2.0, "Explore": 3.0})
self.assertEqual(found.reports, {"Explore": Reports(2, 35, 20)})
def test_counts_the_workers_escalations_by_the_trigger_each_subagents_prompt_opens_with(self):
@@ -84,22 +91,21 @@ 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})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0})
def test_starts_no_route_for_a_chunk_no_item_routed(self):
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(str(LOW), "m", "j"))
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).worker_line(), "m", "j"))
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
self.assertIsNone(found.start)
self.assertEqual(found.tokens["rung"], {str(LOW): 111})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0})
def test_puts_a_subagent_on_the_model_it_ran_at_the_effort_of_the_cycle_that_launched_it(self):
kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(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).worker_line(), "m", "j"))
worker = [
message("m1", "2026-10-14T10:00:00.900Z"),
message("m2", "2026-10-14T10:30:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet")),
@@ -108,23 +114,72 @@ class Measured(unittest.TestCase):
subagents = [Subagent("Explore", "a1", [result("r", "x")]), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-opus-5-5")])]
found = measured(Chunk("log", [kept], worker, subagents), "/h")
self.assertEqual(found.delegated, {"sonnet at high effort": 1, str(HIGH): 1})
self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 333})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 6.0})
def test_names_a_subagent_by_its_meta_or_else_its_call_or_else_unknown(self):
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Plan"))]
subagents = [Subagent("stability-reviewer", "a1", []), Subagent("", "a2", []), Subagent("", "", [])]
self.assertEqual(measured(Chunk("log", [], worker, subagents), "/h").reports, {"stability-reviewer": Reports(1, 0, 0), "Plan": Reports(1, 0, 0), "unknown": Reports(1, 0, 0)})
def test_counts_a_message_without_usage_as_nothing_and_splits_tokens_whole_across_tools(self):
def test_counts_a_message_without_usage_or_a_priced_model_as_nothing_and_splits_a_cost_evenly_across_tools(self):
worker = [
{"type": "assistant", "uuid": "u1", "message": {"content": [call("Read"), call("Grep")], "usage": {"input_tokens": 3, "output_tokens": "many"}}},
{"type": "assistant", "uuid": "u1", "message": {"model": "claude-opus-5-5", "content": [call("Read"), call("Grep")], "usage": {"input_tokens": 1_000_000, "output_tokens": "many"}}},
{"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "t1", "content": "plain"}, "odd"]}},
{"type": "assistant", "uuid": "u2", "message": {"content": [], "usage": {"input_tokens": 5}}},
{"type": "assistant", "uuid": "u3", "message": {"content": []}},
{"type": "assistant", "uuid": "u2", "message": {"model": "claude-opus-5-5", "content": [], "usage": {"input_tokens": 2_000_000}}},
{"type": "assistant", "uuid": "u3", "message": {"model": "claude-opus-5-5", "content": []}},
{"type": "assistant", "uuid": "u4", "message": {"model": "claude-unheard-of", "content": [], "usage": {"input_tokens": 9_000_000}}},
]
found = measured(Chunk("log", [], worker, []), "/h")
self.assertEqual(found.tokens["tool"], {"prompt": 3, "Read": 3, "Grep": 2})
self.assertEqual(found.tokens["project"], {"log": 8})
self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 4.0, "Grep": 4.0})
self.assertEqual(found.dollars["project"], {"log": 12.0})
def test_prices_input_cache_writes_by_their_lifetime_cache_reads_and_output_at_the_models_list_prices(self):
usage = {"input_tokens": 1_000_000, "cache_creation_input_tokens": 2_000_000, "cache_creation": {"ephemeral_5m_input_tokens": 1_000_000, "ephemeral_1h_input_tokens": 1_000_000}, "cache_read_input_tokens": 1_000_000, "output_tokens": 1_000_000}
opus = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
self.assertAlmostEqual(opus.dollars["project"]["log"], 4 + 5 + 8 + 0.2 + 20)
sonnet = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", model="claude-sonnet-5-5", usage=usage)], []), "/h")
self.assertAlmostEqual(sonnet.dollars["project"]["log"], 2 + 2.5 + 4 + 0.2 + 10)
def test_counts_a_cache_write_without_a_lifetime_as_a_five_minute_one(self):
usage = {"cache_creation_input_tokens": 1_000_000}
found = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
self.assertAlmostEqual(found.dollars["project"]["log"], 5)
def test_splits_the_cost_a_chunks_last_cost_state_records_for_each_model_across_its_messages_by_list_price(self):
worker = [
message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore")),
message("m2", "2026-10-14T10:01:00Z"),
cost_state(claude_opus_5_5=1.0),
cost_state(claude_opus_5_5=9.0, claude_haiku_5_5=0.5),
]
subagents = [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]
found = measured(Chunk("log", [], worker, subagents), "/h")
self.assertEqual(found.dollars["subagent type"], {"worker": 6.0, "Explore": 3.0})
self.assertEqual(found.dollars["project"], {"log": 9.0})
self.assertEqual(found.unattributed, 0.5)
def test_counts_the_subagents_the_worker_launched_that_have_no_transcript(self):
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Explore"), call("Read", "r1", file_path="/c/a"))]
found = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]), "/h")
self.assertEqual(found.lacking, 1)
unnamed = measured(Chunk("log", [], worker, [Subagent("", "", [message("s1", "2026-10-14T10:00:01Z")]), Subagent("", "", [message("s2", "2026-10-14T10:00:02Z")])]), "/h")
self.assertEqual(unnamed.lacking, 0)
nested = [message("s1", "2026-10-14T10:00:01Z", call("Agent", "n1", subagent_type="Explore"))]
launched = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:00:02Z")]), Subagent("Explore", "n1", [message("s3", "2026-10-14T10:00:03Z")])]), "/h")
self.assertEqual(launched.lacking, 0)
self.assertEqual(measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [])]), "/h").lacking, 1)
def test_charges_a_message_without_a_timestamp_to_the_rung_of_the_last_outcome(self):
undated = message("m1", "")
del undated["timestamp"]
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j"))
self.assertEqual(measured(Chunk("log", [kept], [undated], []), "/h").dollars["rung"], {str(HIGH): 2.0})
def test_keeps_list_prices_for_a_model_the_cost_state_does_not_name(self):
worker = [message("m1", "2026-10-14T10:00:00Z"), message("m2", "2026-10-14T10:01:00Z", model="claude-sonnet-5-5"), cost_state(claude_opus_5_5=3.0)]
found = measured(Chunk("log", [], worker, []), "/h")
self.assertEqual(found.dollars["project"], {"log": 4.0})
self.assertEqual(found.unattributed, 0.0)
class Calls(unittest.TestCase):
@@ -153,13 +208,20 @@ class Calls(unittest.TestCase):
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), [])
def test_renders_each_dimension_largest_first_and_the_calls(self):
chunk = ChunkFigures({"project": collections.Counter({"a": 2, "b": 20})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter())
chunk = ChunkFigures({"project": collections.Counter({"a": 2.5, "b": 1234.5})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter(), 0.0)
text = render(totals([chunk]), ["Call."], "2026-10-15T00:00:00Z", 40, "")
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text)
self.assertIn("## Calls for a routing change\n\n- Call.\n", text)
self.assertIn("| b | 20 |\n| a | 2 |", text)
self.assertIn("## Dollars by project", text)
self.assertIn("| b | $1,234.50 |\n| a | $2.50 |", text)
self.assertIn("cache reads included", text)
self.assertIn("The judge's runs are not archived, so their cost is not counted.", text)
self.assertNotIn("left out", text)
self.assertNotIn("no transcript", text)
self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("$0.50 of the recorded cost is left out", render(totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |", text)
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter())
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter(), 0.0)
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("| Explore | 2 | 3 | 4 |", text)
escalated = render(totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "")
@@ -199,8 +261,8 @@ class Archive(unittest.TestCase):
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")]))
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")), [message("m1", "2026-10-14T09:00:00Z")])
found = archive.measure_archive(self.root, "/h", "")
self.assertEqual([chunk.tokens["project"] for chunk in found.chunks], [{"home/x": 222}])
self.assertEqual(found.chunks[0].tokens["subagent type"], {"worker": 111, "Explore": 111})
self.assertEqual([chunk.dollars["project"] for chunk in found.chunks], [{"home/x": 4.0}])
self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0})
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z"), archive.Measured([], ()))
def test_reads_each_cycles_route_from_its_own_outcomes_file(self):
@@ -211,10 +273,10 @@ class Archive(unittest.TestCase):
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000))
transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n")
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(str(HIGH), "m", "j"), 4070908800))
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).worker_line(), "m", "j"), 4070908800))
(found,) = archive.measure_archive(kept, "/h", "").chunks
self.assertEqual((found.start, found.unfinished), (LOW, 1))
self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 111})
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 2.0})
def test_skips_a_chunk_it_cannot_read_and_names_it(self):
self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [])
+9 -2
View File
@@ -2,6 +2,7 @@ import dataclasses
import typing
from failure import Failure
from claude_code.session import subagent_transcript
FILE_TOOLS = ("Edit", "MultiEdit", "Write")
@@ -13,6 +14,8 @@ class Call:
cwd: str
# The subagent the call comes from, such as prose-reviewer; empty for the session's own agent.
agent: str = ""
# The transcript of the agent that makes the call: a subagent's own, not its session's.
transcript: str = ""
def parsed_call(hook_input: object) -> Call | Failure:
@@ -21,8 +24,12 @@ def parsed_call(hook_input: object) -> Call | Failure:
tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd")
if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str):
return Failure("the hook input has no string tool_name and cwd and object tool_input")
agent = hook_input.get("agent_type")
return Call(tool, given, cwd, agent if isinstance(agent, str) else "")
agent, agent_id, transcript = hook_input.get("agent_type"), hook_input.get("agent_id"), hook_input.get("transcript_path")
transcript = transcript if isinstance(transcript, str) else ""
if isinstance(agent_id, str) and transcript:
# Inside a subagent, transcript_path still names the session's transcript.
transcript = subagent_transcript(transcript, agent_id)
return Call(tool, given, cwd, agent if isinstance(agent, str) else "", transcript)
def text(given: dict[str, typing.Any], key: str) -> str:
+24
View File
@@ -0,0 +1,24 @@
"""Whether a simple command is a heavy one, for the `run-heavy` rule: a docker build, or a run of a mutation tool."""
from docker_command import docker_subcommand
from shell_command import launched, tool_name
# Each mutation tool, and the words that make its call a mutation run when one of them follows it within two words; where the set is empty, every call is one.
MUTATORS = {"cargo": {"mutants"}, "infection": set(), "mutmut": {"run"}, "stryker": {"run"}}
# Flags with which a tool only prints its help, version or list, so a call that carries one is light. Not -h, which docker run reads as the container's hostname.
LIGHT_FLAGS = frozenset({"--help", "--list", "--version"})
BUILDS = (["build"], ["buildx", "build"], ["compose", "build"])
def heavy(words: list[str]) -> bool:
"""Whether the simple command, run directly or through a launcher, is a docker build or a mutation run, or runs one in a container, and is not under run-heavy."""
launch = launched(words, {"docker", *MUTATORS})
if launch is None or "run-heavy" in launch.launchers or LIGHT_FLAGS & set(words):
return False
if launch.tool == "docker":
subcommand = docker_subcommand(launch.arguments)
return subcommand in BUILDS or (subcommand[-1:] in (["run"], ["exec"]) and mutation_run([tool_name(word) for word in launch.arguments]))
return mutation_run([launch.tool, *(tool_name(word) for word in launch.arguments)])
def mutation_run(names: list[str]) -> bool:
return any(name in MUTATORS and (not MUTATORS[name] or MUTATORS[name] & set(names[i + 1:i + 3])) for i, name in enumerate(names))
+47 -9
View File
@@ -3,7 +3,7 @@
usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin)
rule-hook overrides (prints this chunk's overrides)
settings.json runs it before each Bash, Edit, MultiEdit, Write and Agent call, in every session and
settings.json runs it before each Agent, Bash, Edit, MultiEdit, Read and Write call, in every session and
subagent. The rules:
{rules}
@@ -29,20 +29,26 @@ override cannot be logged; 0 otherwise. `rule-hook overrides` exits 1 when git c
checkout or the branch's reflog. Exit 1, a non-blocking error to Claude Code, on input it
cannot read.
"""
import datetime
import itertools
import json
import os
import pathlib
import stat
import sys
import time
import typing
from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
from rule_hook.rules import Breach, command_breaches, file_breaches, Outcome, rules_help, verdict
from rule_hook.repeat_read import asked_lines, repeat_breaches, shown_lines
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
from git_command import commits
from claude_code.transcript import current_thread, read_transcript
from failure import Failure
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
from rule_hook.reviewer_report import report_breaches
from rule_hook.reviewer_rung import reviewer_breaches
from rule_hook.round_cap import round_cap_breaches
from shell_command import simple_commands
from rule_hook.todo_check import todo_breaches
@@ -67,7 +73,7 @@ def main(argv: list[str], stdin: str) -> int:
if found is None:
return 0
written, what, breaches = found
return answer(verdict(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), what, time.time())
return answer(check(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), what, time.time())
def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tuple[str, str, list[Breach]] | None:
@@ -76,7 +82,9 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
return text(call.given, "prompt"), text(call.given, "subagent_type"), reviewer_breaches(call, environ)
if call.tool == "Bash":
command = text(call.given, "command")
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home)
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home)
if call.tool == "Read":
return "", text(call.given, "file_path"), read_breaches(call, home)
path = text(call.given, "file_path")
if call.tool not in FILE_TOOLS or not path:
return None
@@ -85,12 +93,12 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
return added, path, report_breaches(call, path, home) + file_breaches(path, before, added, after)
def answer(judged: Outcome, what: str, now: float) -> int:
for message in judged.messages:
def answer(checked: Checked, what: str, now: float) -> int:
for message in checked.messages:
print(message, file=sys.stderr)
if judged.blocked:
if checked.blocked:
return 2
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in judged.overridden]
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in checked.overridden]
# Resolve every log before writing any, so a call that ends blocked has logged nothing.
unloggable = [f"{breach.rule}: {log.reason}" for breach, _, log in logs if isinstance(log, Failure)]
if not unloggable:
@@ -104,7 +112,37 @@ def answer(judged: Outcome, what: str, now: float) -> int:
def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
simples = simple_commands(command, cwd, home)
return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in todo_breaches(commit.directory)]
return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in round_cap_breaches(commit) + todo_breaches(commit.directory)]
def read_breaches(call: Call, home: str) -> list[Breach]:
"""The repeat-read breaches of a call, read from the calling agent's transcript and the asked file; none where either cannot be read, or the file is not a regular file."""
asked = asked_lines(call.tool, call.given, call.cwd, home)
changed = modified(asked.path) if asked else None
entries = read_transcript(call.transcript) if changed and call.transcript else []
if asked is None or changed is None or isinstance(entries, Failure):
return []
shown = shown_lines(current_thread(entries), call.tool, asked.path, changed, home)
# No line past the last one shown is in context, so the file's lines through one past it tell as much as all of them, and a long file is not read whole.
return repeat_breaches(asked, first_lines(asked.path, max(shown) + 1), shown, call.cwd) if shown else []
def modified(path: str) -> str | None:
"""When a regular file last changed, stamped as a transcript entry is; None for any other path, such as a FIFO, whose read could hang."""
try:
status = os.stat(path)
except (OSError, ValueError):
return None
return datetime.datetime.fromtimestamp(status.st_mtime, datetime.UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z") if stat.S_ISREG(status.st_mode) else None
def first_lines(path: str, count: int) -> list[str]:
"""The file's first count lines, without their line ends; none where it cannot be read as UTF-8."""
try:
with open(path, encoding="utf-8") as file:
return [line.removesuffix("\n") for line in itertools.islice(file, count)]
except (OSError, UnicodeDecodeError):
return []
def read(path: str) -> str:
+9 -8
View File
@@ -6,6 +6,7 @@ import sys
import typing
from rule_hook.rules import Breach
from git_repo import default_ref
from rule_hook.git import existing, git
from failure import Failure
from utc_stamp import utc
@@ -34,10 +35,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))
@@ -96,10 +101,10 @@ def print_overrides(directory: str) -> int:
if unread:
print(f"rule-hook overrides cannot read the branch's reflog, so it cannot tell which overrides are this chunk's: {unread.reason}", file=sys.stderr)
return 1
default = local_default_branch(directory)
default = default_ref(directory, guarded=True)
log = pathlib.Path(common) / LOG
entries = [parsed_entry(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.is_file() else []
on_default = (lambda commit: holds(directory, default, commit)) if default else (lambda commit: False)
on_default = (lambda commit: False) if isinstance(default, Failure) else (lambda commit: holds(directory, default, commit))
for entry in entries:
if entry and this_chunks(entry, set(str(reflog).split()), branch, on_default):
print(entry.line(), end="")
@@ -115,9 +120,5 @@ def unread_reflog(reflog: str | Failure, head: str | Failure) -> Failure | None:
return None if head in reflog.split() else Failure("it does not hold HEAD")
def local_default_branch(directory: str) -> str | None:
return next((name for name in ("origin/HEAD", "main", "master") if not isinstance(git(directory, "rev-parse", "--verify", "--quiet", name), Failure)), None)
def holds(directory: str, descendant: str, ancestor: str) -> bool:
return bool(ancestor) and not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)
+115
View File
@@ -0,0 +1,115 @@
"""Whether a read asks for lines of a file already in the agent's context, for the `repeat-read` rule.
A line is in context when a read since the transcript thread's last compaction showed it at its line number, as the file holds it now.
Against a Read, no line is in context when the file changed after the agent last read it with Read or wrote it with Edit, MultiEdit or Write, or when it never did."""
import dataclasses
import re
from rule_hook.rules import Breach
from rule_hook.call import FILE_TOOLS, text
from claude_code.entries import parts, tool_call, tool_result, tool_use_id
from shell_command import resolved, simple_commands
# The lines a Read without a limit returns.
READ_LIMIT = 2000
# A line of a Read result: its number, then a tab, or an arrow in older Claude Code versions.
NUMBERED = re.compile(r" *(\d+)[\t→](.*)", re.DOTALL)
HEAD_COUNT = re.compile(r"-(?:n ?)?(\d+)")
SED_RANGE = re.compile(r"(\d+)(?:,(\d+|\$))?p")
@dataclasses.dataclass(frozen=True)
class Asked:
path: str
first: int
# None: to the file's end.
last: int | None
def repeat_breaches(asked: Asked, lines: list[str], shown: dict[int, str], cwd: str) -> list[Breach]:
"""shown is what shown_lines found, and lines the asked file's lines now, read at least through one past the last shown line."""
last = len(lines) if asked.last is None else min(asked.last, len(lines))
if not in_context(asked.first, last, lines, shown):
return []
named = f"line {last} of {asked.path} is" if asked.first == last else f"lines {asked.first}-{last} of {asked.path} are"
return [Breach("repeat-read", f"{named} in your context, unchanged since your last read of it", cwd)]
def in_context(first: int, last: int, lines: list[str], shown: dict[int, str]) -> bool:
return first <= last and all(shown.get(number) == lines[number - 1] for number in range(first, last + 1))
def asked_lines(tool: object, given: object, cwd: str, home: str) -> Asked | None:
"""The lines a tool call reads; None for any call but a Read and the Bash reads the rule names, such as one whose output goes elsewhere."""
if not isinstance(given, dict):
return None
return read_asked(given, cwd, home) if tool == "Read" else shell_asked(text(given, "command"), cwd, home) if tool == "Bash" else None
def read_asked(given: dict, cwd: str, home: str) -> Asked | None:
path, offset, limit = text(given, "file_path"), given.get("offset"), given.get("limit")
first = offset if isinstance(offset, int) and offset > 0 else 1
return Asked(resolved(cwd, path, home), first, first + (limit if isinstance(limit, int) and limit > 0 else READ_LIMIT) - 1) if path else None
# reading_cost/shell_reads.py parses a shell read too, loosely: a measure of reading counts any file a reader names, while a rule that blocks must match only a read whose lines it knows exactly.
def shell_asked(command: str, cwd: str, home: str) -> Asked | None:
simples = simple_commands(command, cwd, home) if not set("|<>") & set(command) else []
if len(simples) != 1 or len(simples[0].words) < 2 or simples[0].words[-1].startswith("-"):
return None
(name, *options, path), directory = simples[0].words, simples[0].directory
path = resolved(directory, path, home)
if name == "cat" and not options:
return Asked(path, 1, None)
if name == "head" and (counted := HEAD_COUNT.fullmatch(" ".join(options) or "-10")):
return Asked(path, 1, int(counted.group(1)))
if name == "sed" and len(options) == 2 and options[0] == "-n" and (ranged := SED_RANGE.fullmatch(options[1])):
start, end = ranged.groups()
return Asked(path, int(start), None if end == "$" else int(end or start))
return None
def shown_lines(thread: list[dict], asker: str, path: str, changed: str, home: str) -> dict[int, str]:
"""Each line number of path that a successful read in the thread showed, with the line its latest read showed; none against a Read when the file changed after the agent last read it with Read or wrote it with Edit, MultiEdit or Write, or when it never did.
changed is when the file last changed, stamped as the transcript stamps its entries, so the two compare as text."""
used = results_on(thread, path, home)
# Claude Code's Edit and Write refuse such a file until a Read, and a Bash read does not count as one.
touched = max((stamp for tool, _, _, stamp in used if tool == "Read" or tool in FILE_TOOLS), default="")
if asker == "Read" and changed > touched:
return {}
shown: dict[int, str] = {}
for tool, asked, result, _ in used:
shown |= result_lines(tool, asked, result) if asked else {}
return shown
def results_on(thread: list[dict], path: str, home: str) -> list[tuple[object, Asked | None, str, str]]:
"""Each successful result in the thread of a call that read lines of path or wrote it: the call's tool, the lines it read (None for a write), the result's text and its entry's timestamp."""
calls: dict[str, tuple[object, Asked | None]] = {}
found: list[tuple[object, Asked | None, str, str]] = []
for entry in thread:
cwd = str(entry.get("cwd", ""))
for part in parts(entry):
if (call := tool_call(part)) and (called := tool_use_id(part)):
asked = asked_lines(*call, cwd, home)
if (asked.path if asked else written(*call, cwd, home)) == path:
calls[called] = (call[0], asked)
elif (result := tool_result(part)) and not result.failed and (use := calls.get(result.tool_use_id)):
found.append((use[0], use[1], result.text, text(entry, "timestamp")))
return found
def written(tool: object, given: object, cwd: str, home: str) -> str:
"""The file an Edit, MultiEdit or Write call writes; empty for any other call."""
return resolved(cwd, path, home) if tool in FILE_TOOLS and isinstance(given, dict) and (path := text(given, "file_path")) else ""
def result_lines(tool: object, asked: Asked, result: str) -> dict[int, str]:
if tool == "Read":
return {int(numbered.group(1)): numbered.group(2) for line in result.split("\n") if (numbered := NUMBERED.fullmatch(line))}
# Claude Code cuts a long Bash output short with a note: before the output, "<persisted-output>\n" or "<truncated-output>\n" and a few more lines, or after it, "\n\n... [N lines truncated] ...".
# The note's lines would take the numbers of the file's, so such an output shows no lines.
if result.startswith(("<persisted-output>\n", "<truncated-output>\n")) or result.endswith(" lines truncated] ..."):
return {}
return {number: line for number, line in enumerate(result.split("\n"), asked.first) if asked.last is None or number <= asked.last}
+2 -1
View File
@@ -4,7 +4,8 @@ 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 position, review_rungs, REVIEWERS, ReviewKind, Rung
from model_routing.ladder import position, review_rungs, ReviewKind, Rung
from review_passes import REVIEWERS
# The pass each agent under agents/ reviews.
PASS_OF = {agent: kind for kind, agent in REVIEWERS.items()}
+32
View File
@@ -0,0 +1,32 @@
from rule_hook.rules import Breach
from round_titles import CAP, past_cap, ROUND, round_counts
from git_command import Commit
from failure import Failure
import git_repo
def round_cap_breaches(commit: Commit) -> list[Breach]:
"""A breach where the commit's title takes its pass past the cap, counted with the branch's earlier round commits."""
if not any(ROUND.match(message) for message in commit.messages):
return []
earlier = earlier_titles(commit.directory, commit.amends)
refused = [(named.group(1).lower(), message) for message in commit.messages if (named := ROUND.match(message)) and past_cap(message, earlier)]
return [Breach("round-cap", refusal(name, message, earlier), commit.directory) for name, message in refused]
def refusal(name: str, title: str, earlier: list[str]) -> str:
"""Why title, a round title of the pass name, is refused, listing the pass's round commits counted, and how to commit the fixes in hand."""
counted = [earlier_title for earlier_title in earlier if (named := ROUND.match(earlier_title)) and named.group(1).lower() == name]
listed = ", ".join(f"`{counted_title}`" for counted_title in counted) or "none found"
return f"this would be {name}'s round {round_counts([*counted, title])[name]}, past its {CAP}; {name}'s round commits on this branch: {listed}. Fold the fixes into its last round commit with `git commit --amend` where that is the newest commit, or commit them under a title that doesn't open `Answer <pass> round`; they merge once the gate passes"
def earlier_titles(directory: str, amends: bool) -> list[str]:
"""The branch's titles, less the one an --amend replaces; none where git cannot list them within 5 seconds or the checkout records no default branch for origin, so the title's own number still counts.
Run guarded, as the hook runs git, which neither fetches nor asks origin: the default branch is as last fetched."""
default = git_repo.default_ref(directory, guarded=True)
titles = default if isinstance(default, Failure) else git_repo.branch_titles(default, directory, timeout=5, guarded=True)
if isinstance(titles, Failure):
return []
return titles[1:] if amends else titles
+53 -9
View File
@@ -3,12 +3,14 @@ import posixpath
import re
import typing
from round_titles import CAP, lacks_counts
from git_command import commits
from round_titles import lacks_counts
from rule_hook.heavy_command import heavy
from shell_command import launched, Simple, tool_name
from review_folder import REPORTS
from shell_command import Simple
from docker_command import unlimited
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-title-counts", "todo-rank-check"]
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
@dataclasses.dataclass(frozen=True)
@@ -28,6 +30,10 @@ RULES: dict[RuleName, Rule] = {
"a commit message is one line, prefixed with the ticket ID when the work has one",
"git commit takes its message as one -m with no line break; -F, a second -m and a heredoc are blocked",
),
"docker-run-memory": Rule(
"a container made with docker run or docker create has a memory limit and a swap limit, as large as its work needs, such as `--memory 4g --memory-swap 4g`, so a runaway container fails alone instead of starving the machine; a swap limit equal to the memory limit keeps it out of swap",
"docker run, docker create, docker container run and docker container create, whether direct or through a launcher such as nice or timeout. One under run-heavy passes, as run-heavy's docker adds the limits on Linux, unless it names docker by its path, or changes or clears PATH, as env -i, sudo or doas do. A container a script or docker compose starts is not checked",
),
"ignorefile-sorted": Rule(
"each block of an ignore file is sorted in code-point order, as LC_ALL=C sort does, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment",
"a .*ignore file; a block already unsorted before the edit is left alone",
@@ -40,6 +46,12 @@ RULES: dict[RuleName, Rule] = {
"no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line",
"a git, gh or tea command, and any file written",
),
# A Read carries no text for a marker, and a misjudged read has a way through that the message names, so no marker waives it.
"repeat-read": Rule(
"an agent reads no lines of a file that its context already holds unchanged, since each read pays for them again; where the context lacks them although the transcript shows them, as after Claude Code cleared old tool results, read them with another command, such as `grep -n '' <file> | sed -n '<A>,<B>p'`; a Read goes through until the agent has read the file with Read or written it with Edit, MultiEdit or Write, and again once the file changed after that, since those refuse a file until then",
"a Read call, and a Bash command that is one `cat <file>`, `head [-n <N> | -<N>] <file>` or `sed -n '<A>[,<B>]p' <file>`, with no pipe or redirect, against the reads in the calling agent's own transcript since its last compaction",
overridable=False,
),
# A reviewer only reports, so no marker waives it.
"reviewer-report": Rule(
f"a reviewer writes nothing but its report, with Write, into a file under ~/{REPORTS}/",
@@ -52,10 +64,20 @@ RULES: dict[RuleName, Rule] = {
"an Agent call, in a claude loop-claude started, whose subagent type is an agent under agents/, or whose prompt opens with seat-prompts.md's opening sentence or the one larv-review's Security section sets",
overridable=False,
),
# The cap holds with no ask, so no marker waives it.
"round-cap": Rule(
f"a larv-review pass takes at most {CAP} rounds per chunk, and none after them: the fixes answering its last round merge once the gate passes",
"a git commit whose message opens `Answer <pass> round <n>:`, counted with the pass's round commits on the branch since the default branch as last fetched, less the one an --amend replaces",
overridable=False,
),
"round-title-counts": Rule(
"a larv-review round's commit title gives the counts of 🔴 and 🟡 findings the round reported, such as `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`, since score-outcomes counts them",
"a larv-review round's commit title gives the counts of 🔴 and 🟡 findings the round reported, and how many of them a reviewer marked `[misread]`, at most the two together, such as `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); flag a deleted test`, since score-outcomes counts them",
"a git commit whose message opens `Answer <pass> round <n>:`",
),
"run-heavy": Rule(
"a heavy command, which loads the machine for minutes, runs under ~/.claude/bin/run-heavy, so sessions running at once cannot starve the machine",
"a docker build, docker buildx build or docker compose build, and a run of cargo mutants, Infection, mutmut or Stryker, the mutation tools stability-reviewer names, whether direct, through a launcher such as uvx, or inside docker run, docker exec or docker compose run or exec. A gate script is not checked, since no program can tell it from a light one",
),
"todo-rank-check": Rule(
"while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it",
"a git commit in a checkout whose todo.md has changes",
@@ -84,7 +106,8 @@ class Breach:
@dataclasses.dataclass(frozen=True)
class Outcome:
class Checked:
"""What rule-hook found in one tool call: the messages to show, whether it blocks the call, and the overrides to log."""
messages: list[str]
blocked: bool
# Each breach an override let through, with its reason; logged only when the call goes through.
@@ -98,7 +121,7 @@ def overrides(written: str) -> tuple[dict[str, str], list[str]]:
return granted, [f"rule-override {rule}: {reason}" for rule, reason in given if rule not in RULES or not reason]
def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Outcome:
def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Checked:
granted, malformed = overrides(written)
blocking = [breach for breach in breaches if breach.rule not in granted]
messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else []
@@ -106,11 +129,11 @@ def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) ->
for rule in sorted({breach.rule for breach in blocking}):
details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
if not RULES[rule].overridable:
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}.")
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. No marker overrides it.")
continue
marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.")
return Outcome(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
return Checked(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]:
@@ -119,16 +142,37 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre
publishing = [simple for simple in simples if simple.words[0] in ("gh", "git", "tea")]
if publishing and ATTRIBUTION.search(command):
breaches.append(Breach("no-ai-attribution", "the command carries an attribution", publishing[0].directory))
for simple in simples:
if heavy(simple.words):
breaches.append(Breach("run-heavy", f"run `{' '.join(simple.words)[:80]}` under `~/.claude/bin/run-heavy`, in the background", simple.directory))
if unlimited_container(simple.words):
breaches.append(Breach("docker-run-memory", f"give `{' '.join(simple.words)[:80]}` a memory limit and a swap limit as large as its work needs", simple.directory))
for commit in found:
if commit.from_file:
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', not from a file", commit.directory))
elif len(commit.messages) > 1 or any("\n" in message.strip() for message in commit.messages):
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', with no heredoc, second -m or newline", commit.directory))
if any(lacks_counts(message) for message in commit.messages):
breaches.append(Breach("round-title-counts", "open the summary after the round's colon with `<k> 🔴, <m> 🟡;`", commit.directory))
breaches.append(Breach("round-title-counts", "open the summary after the round's colon with `<k> 🔴, <m> 🟡 (<j> misread);`, where <j> is at most <k> + <m>", commit.directory))
return breaches
def unlimited_container(words: list[str]) -> bool:
"""Whether the simple command, directly or through a launcher, starts a container that lacks a memory limit or a swap limit."""
docker = launched(words, {"docker"})
if docker is None or not unlimited(docker.arguments):
return False
# On Linux, run-heavy's docker adds the limits a container lacks, where PATH finds it: docker named bare, with PATH left as run-heavy set it.
before = words[:len(words) - len(docker.arguments) - 1]
capped = "run-heavy" in docker.launchers and words[len(before)] == "docker" and not any(resets_path(word) for word in before)
return not capped
def resets_path(word: str) -> bool:
"""Whether a word before docker drops the PATH run-heavy set: a PATH= of its own, env's -i or -u, or sudo or doas, which reset it."""
return word.startswith(("PATH=", "--unset")) or word in ("-i", "--ignore-environment", "-u") or tool_name(word) in ("doas", "sudo")
def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
"""Breaches in an edit of path: added is the text the edit writes, after the whole file it leaves."""
breaches = [Breach("no-ai-attribution", f"{path} would carry an attribution", posixpath.dirname(path))] if ATTRIBUTION.search(added) else []
+342 -17
View File
@@ -1,3 +1,4 @@
import datetime
import json
import os
import pathlib
@@ -9,9 +10,10 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from rule_hook.rules import blocks, Breach, command_breaches, file_breaches, overrides, verdict
from rule_hook.main import breaches_of
from rule_hook.call import Call
from rule_hook.repeat_read import Asked, result_lines
from rule_hook.rules import blocks, Breach, check, command_breaches, file_breaches, overrides
from rule_hook.main import breaches_of, modified, read_breaches
from rule_hook.call import Call, parsed_call
from git_command import Commit, commit_message, commits
from test_rank_todo import DECISIONS, README, TODO
from test_env import isolated_env
@@ -20,7 +22,7 @@ from rule_hook.override_log import LogLine, parsed_entry, this_chunks
from rule_hook.reviewer_rung import reviewer_breaches
from rule_hook.git import git as rule_hook_git
from model_routing.ladder import Rung
from shell_command import simple_commands
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.
@@ -40,7 +42,7 @@ def checked(command: str) -> list[str]:
def hook(call: dict, cwd: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env() | (env or {}), input=json.dumps(call), text=True)
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env() | (env or {}), input=json.dumps(call), text=True, timeout=10)
def git(cwd: str, *args: str) -> str:
@@ -49,21 +51,25 @@ def git(cwd: str, *args: str) -> str:
class Commits(unittest.TestCase):
def test_cd_and_dash_capital_c_move_the_commit(self):
self.assertEqual(committed("cd a && git -C ~/b commit -am 'x'"), [Commit("/h/b", ["x"], False)])
self.assertEqual(committed("cd a && git -C ~/b commit -am 'x'"), [Commit("/h/b", ["x"], False, False)])
self.assertEqual(committed("cd a && git -c x=y -C b commit -m x")[0].directory, "/r/a/b")
def test_each_message_spelling_is_read(self):
self.assertEqual(commit_message(["--message=a", "-m", "b=c", "--message", "c", "-mz", "-am", "d"]), (["a", "b=c", "c", "z", "d"], False))
self.assertEqual(commit_message(["--message=a", "-m", "b=c", "--message", "c", "-mz", "-am", "d"]), (["a", "b=c", "c", "z", "d"], False, False))
def test_an_amend_is_seen(self):
self.assertEqual([commit.amends for commit in committed("git commit --amend -m x && git commit -m y")], [True, False])
self.assertEqual(commit_message(["--", "--amend"]), ([], False, False), "after --, --amend names a path")
def test_a_file_message_is_seen(self):
self.assertEqual(commit_message(["-F", "-"]), ([], True))
self.assertEqual(commit_message(["--file=x"]), ([], True))
self.assertEqual(commit_message(["-F", "-"]), ([], True, False))
self.assertEqual(commit_message(["--file=x"]), ([], True, False))
def test_other_git_commands_are_no_commit(self):
self.assertEqual(committed("git log --grep commit; echo git commit"), [])
def test_a_line_break_or_a_comment_separates_commands(self):
self.assertEqual(committed("cd a # go there\nGIT_EDITOR=true git commit -m x"), [Commit("/r/a", ["x"], False)])
self.assertEqual(committed("cd a # go there\nGIT_EDITOR=true git commit -m x"), [Commit("/r/a", ["x"], False, False)])
def test_a_commit_after_a_heredoc_or_a_blank_line_is_seen(self):
self.assertEqual(len(committed("cat <<EOF > notes\nhello\nEOF\ngit commit -m a")), 1)
@@ -75,6 +81,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, False)])
self.assertEqual(committed("git commit >&2 -m hi 2>&1"), [Commit("/r", ["hi"], False, False)])
self.assertEqual(committed("> out git commit -m hi"), [Commit("/r", ["hi"], False, 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, False)])
class CommandBreaches(unittest.TestCase):
def test_one_line_passes(self):
@@ -87,10 +107,31 @@ class CommandBreaches(unittest.TestCase):
def test_a_round_title_without_its_counts_breaks_round_title_counts(self):
self.assertEqual(checked("git commit -m 'Answer stability round 1: fix the parser'"), ["round-title-counts"])
self.assertEqual(checked("git commit --allow-empty -m 'Answer prose round 2: 0 🔴, 0 🟡'"), [])
self.assertEqual(checked("git commit -m 'Answer stability round 1: 1 🔴, 2 🟡; fix the parser'"), [])
self.assertEqual(checked("git commit -m 'Answer stability round 1: 1 🔴, 2 🟡; fix the parser'"), ["round-title-counts"])
self.assertEqual(checked("git commit --allow-empty -m 'Answer prose round 2: 0 🔴, 0 🟡 (0 misread)'"), [])
self.assertEqual(checked("git commit -m 'Answer stability round 1: 1 🔴, 2 🟡 (1 misread); fix the parser'"), [])
self.assertEqual(checked("git commit -m 'Answer the question in the README'"), [])
def test_a_docker_build_or_a_mutation_run_outside_run_heavy_breaks_run_heavy(self):
for command in ["docker build -t x .", "cd /w && docker buildx build .", "docker compose build", "docker compose -f x.yml --verbose build app", "uvx --with pytest 'mutmut>=3,<4' run", "cargo mutants --in-diff d", "npx stryker run", "vendor/bin/infection --git-diff-lines", "docker compose run --rm app mutmut run", "docker run --rm -m 4g --memory-swap 4g -v /w:/w rust:1.90.0 cargo mutants", "docker compose exec app npx stryker run", "docker run -h box -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "nice -n 19 docker build .", "env DOCKER_BUILDKIT=1 docker build .", "time -p docker compose build", "docker --tlscacert ca.pem build .", "docker --tlscert c.pem --tlskey k.pem build .", "docker buildx --builder b build .", "docker container run -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "uvx mutmut --verbose run"]:
with self.subTest(command):
self.assertEqual(checked(command), ["run-heavy"])
def test_a_heavy_command_under_run_heavy_or_a_light_docker_or_mutmut_call_passes(self):
for command in ["~/.claude/bin/run-heavy docker build -t x .", "/home/me/.claude/bin/run-heavy uvx mutmut run", "nice -n 19 ~/.claude/bin/run-heavy docker build .", "env X=1 run-heavy docker compose run app mutmut run", "docker images", "docker compose run --rm app go vet", "docker compose run app make build", "uvx 'mutmut>=3,<4' results", "echo docker build", "npx prettier --check infection.json5", "echo mutmut run", "env", "docker build --help", "cargo mutants --list", "infection --version", "uvx mutmut a b run"]:
with self.subTest(command):
self.assertEqual(checked(command), [])
def test_a_docker_run_or_create_without_a_memory_limit_breaks_docker_run_memory(self):
for command in ["docker run --rm node:24.22.1-alpine3.24 node x.js", "cd /w && docker run -v /w:/w alpine:3.22.2 true", "docker create alpine:3.22.2", "docker container run alpine:3.22.2 true", "docker container create alpine:3.22.2", "nice -n 19 docker run alpine:3.22.2 true", "docker -H unix:///d.sock run alpine:3.22.2 true", "docker run --memory-swap 4g alpine:3.22.2 true", "docker run -m 4g alpine:3.22.2 true", "docker run --memory=4g alpine:3.22.2 sh -c 'x --memory-swap 4g'", "docker run -m 4g alpine:3.22.2 tool --memory-swap", "docker run -m 4g --memory-swap -1 alpine:3.22.2 true", "docker run -m 4g --memory-swap=0 alpine:3.22.2 true", "docker run --rm python:3.13.1 python -m pytest", "docker run alpine:3.22.2 git commit -m x", "timeout 60 docker run alpine:3.22.2 true", "docker run node:24.22.1-alpine3.24 node --help", "docker run alpine:3.22.2 --help", "docker run -m 4g alpine:3.22.2 sleep 60", "~/.claude/bin/run-heavy /usr/bin/docker run alpine:3.22.2 true", "docker run --memory-swap 4g alpine:3.22.2 grep -m 1 x", "run-heavy env PATH=/usr/bin docker run alpine:3.22.2 true", "run-heavy sudo docker run alpine:3.22.2 true", "docker run alpine:3.22.2 git tag -m 1.2.3", "run-heavy env -i docker run alpine:3.22.2 true", "run-heavy env -u PATH docker run alpine:3.22.2 true", "run-heavy env --unset=PATH docker run alpine:3.22.2 true", "run-heavy env --ignore-environment docker run alpine:3.22.2 true", "run-heavy doas docker run alpine:3.22.2 true"]:
with self.subTest(command):
self.assertEqual(checked(command), ["docker-run-memory"])
def test_a_docker_run_with_a_memory_limit_or_another_docker_call_passes_docker_run_memory(self):
for command in ["docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run -m4g --memory-swap=4g alpine:3.22.2 true", "docker run --memory 512M --memory-swap 1g alpine:3.22.2 true", "docker run -m 1073741824 --memory-swap 2g alpine:3.22.2 true", "timeout 60 docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run --rm --memory=1.5GiB --memory-swap=1.5GiB alpine:3.22.2 true", "docker container create -m 1g --memory-swap 1g alpine:3.22.2", "docker run --help", "docker container run --help", "docker --context run run --help", "docker --help", "docker ps", "docker images", "docker container ls", "docker compose run --rm app go vet", "docker exec box true", "echo docker run alpine:3.22.2", "~/.claude/bin/run-heavy docker run alpine:3.22.2 true"]:
with self.subTest(command):
self.assertEqual(checked(command), [])
def test_an_attribution_breaks_only_in_a_git_gh_or_tea_command(self):
self.assertEqual(checked(f"tea pr create --description '{TRAILER}'"), ["no-ai-attribution"])
self.assertEqual(checked(f"grep -rn '{TRAILER}' ."), [])
@@ -146,13 +187,13 @@ class Overrides(unittest.TestCase):
def test_a_blocked_call_overrides_nothing_yet(self):
breaches = [Breach("image-pin", "x", "/r"), Breach("action-pin", "y", "/r")]
judged = verdict(breaches, "# rule-override image-pin: a", False, False)
self.assertTrue(judged.blocked)
passed = verdict(breaches[:1], "# rule-override image-pin: a", False, False)
blocked_call = check(breaches, "# rule-override image-pin: a", False, False)
self.assertTrue(blocked_call.blocked)
passed = check(breaches[:1], "# rule-override image-pin: a", False, False)
self.assertEqual((passed.blocked, passed.overridden), (False, [(breaches[0], "a")]))
def test_a_markdown_file_is_told_the_html_comment(self):
self.assertIn("`<!-- rule-override no-ai-attribution: <reason> -->`", verdict([Breach("no-ai-attribution", "x", "/r")], "", True, False).messages[0])
self.assertIn("`<!-- rule-override no-ai-attribution: <reason> -->`", check([Breach("no-ai-attribution", "x", "/r")], "", True, False).messages[0])
class OverrideLog(unittest.TestCase):
@@ -281,6 +322,242 @@ class ReviewerReport(unittest.TestCase):
self.assertEqual(self.breached("Write", "/r/README.md", "general-purpose"), [])
class RepeatRead(unittest.TestCase):
LINES = [f"line {n}" for n in range(1, 31)]
# The file is written at WRITTEN and each entry stamped READ_AT, unless a test changes the file at CHANGED and stamps a later entry AFTER_THE_CHANGE.
WRITTEN = datetime.datetime(2026, 5, 1, tzinfo=datetime.UTC).timestamp()
READ_AT = "2026-06-01T00:00:00.000Z"
CHANGED = datetime.datetime(2026, 7, 1, tzinfo=datetime.UTC).timestamp()
AFTER_THE_CHANGE = "2026-07-01T00:00:01.000Z"
def setUp(self):
self.folder = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", self.folder])
self.file = f"{self.folder}/f.txt"
self.write(self.LINES, self.WRITTEN)
self.transcript = f"{self.folder}/s.jsonl"
self.entries: list[dict] = []
def write(self, lines: list[str], at: float) -> None:
pathlib.Path(self.file).write_text("\n".join(lines) + "\n")
os.utime(self.file, (at, at))
def change(self, number: int) -> None:
self.write([("changed" if n == number else line) for n, line in enumerate(self.LINES, 1)], self.CHANGED)
def add(self, entry: dict, parent: str | None = "last") -> str:
uuid = f"u{len(self.entries)}"
parent = (self.entries[-1]["uuid"] if self.entries else None) if parent == "last" else parent
self.entries.append({"uuid": uuid, "parentUuid": parent, "cwd": self.folder, "timestamp": self.READ_AT} | entry)
pathlib.Path(self.transcript).write_text("\n".join(json.dumps(entry) for entry in self.entries) + "\n")
return uuid
def used(self, tool: str, given: dict, result: str, error: bool = False, at: str = READ_AT) -> None:
tool_id = f"toolu_{len(self.entries)}"
self.add({"type": "assistant", "timestamp": at, "message": {"content": [{"type": "tool_use", "id": tool_id, "name": tool, "input": given}]}})
self.add({"type": "user", "timestamp": at, "message": {"content": [{"type": "tool_result", "tool_use_id": tool_id, "content": result, "is_error": error}]}})
def numbered(self, start: int, end: int) -> str:
return "\n".join(f"{n}\t{self.LINES[n - 1]}" for n in range(start, end + 1))
def read(self, start: int, end: int) -> None:
self.used("Read", {"file_path": self.file, "offset": start, "limit": end - start + 1}, self.numbered(start, end))
def shown(self, start: int, end: int) -> str:
return "\n".join(self.LINES[start - 1:end])
def found(self, tool: str, given: dict, agent: str = "") -> list[Breach]:
return read_breaches(Call(tool, given, self.folder, agent, self.transcript), "/h")
def test_a_read_of_lines_already_read_is_blocked_with_a_note(self):
self.read(1, 10)
found = self.found("Read", {"file_path": self.file, "offset": 2, "limit": 5})
self.assertEqual(rules(found), ["repeat-read"])
self.assertIn(f"lines 2-6 of {self.file} are in your context", found[0].detail)
def test_the_note_names_a_single_line_as_one(self):
self.read(1, 10)
self.assertIn(f"line 7 of {self.file} is in your context", self.found("Bash", {"command": "sed -n 7p f.txt"})[0].detail)
def test_lines_read_in_two_reads_are_in_context(self):
self.read(1, 10)
self.read(11, 20)
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 5, "limit": 10})), ["repeat-read"])
def test_a_read_past_what_was_read_goes_through(self):
self.read(1, 10)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 5, "limit": 10}), [])
def test_a_read_without_a_limit_asks_for_the_whole_file(self):
self.read(1, 10)
self.assertEqual(self.found("Read", {"file_path": self.file}), [])
def test_a_read_result_in_the_older_arrow_format_counts(self):
self.used("Read", {"file_path": self.file, "offset": 1, "limit": 10}, "\n".join(f"{n:6}→{self.LINES[n - 1]}" for n in range(1, 11)))
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10})), ["repeat-read"])
def test_a_compaction_lets_the_read_through(self):
self.read(1, 10)
self.add({"type": "system", "subtype": "compact_boundary"}, parent=None)
self.add({"type": "user", "message": {"content": "This session is being continued"}})
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_a_changed_line_lets_the_read_through(self):
self.read(1, 10)
self.change(1)
self.assertEqual(self.found("Bash", {"command": f"head {self.file}"}), [])
def test_a_change_in_the_last_asked_line_lets_the_read_through(self):
self.read(1, 10)
self.change(10)
self.assertEqual(self.found("Bash", {"command": "sed -n 1,10p f.txt"}), [])
def test_lines_that_did_not_change_stay_in_context(self):
self.read(1, 10)
self.change(1)
self.assertEqual(rules(self.found("Bash", {"command": "sed -n 2,10p f.txt"})), ["repeat-read"])
def test_a_read_without_an_offset_starts_at_line_1(self):
self.read(2, 11)
self.assertEqual(self.found("Read", {"file_path": self.file, "limit": 10}), [])
def test_calls_that_neither_read_nor_write_the_file_are_passed_over(self):
self.used("Grep", {"pattern": "line", "path": self.folder}, "f.txt")
self.used("Bash", {"command": "ls"}, "f.txt")
self.read(1, 10)
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10})), ["repeat-read"])
# Claude Code's Edit refuses a file changed since the agent last read it with Read, or wrote it with Edit or Write, until it reads it again.
def test_a_change_in_the_millisecond_of_the_last_read_counts_as_before_it(self):
self.read(1, 10)
at = datetime.datetime(2026, 6, 1, tzinfo=datetime.UTC).timestamp()
os.utime(self.file, (at, at))
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10})), ["repeat-read"])
def test_a_file_s_change_is_stamped_as_the_transcript_stamps_its_entries(self):
at = datetime.datetime(2026, 6, 1, 12, 30, 5, 250000, tzinfo=datetime.UTC).timestamp()
os.utime(self.file, (at, at))
self.assertEqual(modified(self.file), "2026-06-01T12:30:05.250Z")
def test_a_read_goes_through_once_the_file_changed_after_the_last_read(self):
self.read(1, 10)
self.change(30)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_a_refused_edit_does_not_count_as_reading_the_file(self):
self.read(1, 10)
self.change(30)
self.used("Edit", {"file_path": self.file, "old_string": "line 5", "new_string": "five"}, "<tool_use_error>File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.</tool_use_error>", error=True, at=self.AFTER_THE_CHANGE)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_an_edit_keeps_the_lines_it_left_unchanged_in_context(self):
self.read(1, 10)
self.change(30)
self.used("Edit", {"file_path": self.file, "old_string": "line 30", "new_string": "changed"}, f"The file {self.file} has been updated successfully.", at=self.AFTER_THE_CHANGE)
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10})), ["repeat-read"])
def test_a_failed_read_holds_no_lines(self):
self.used("Read", {"file_path": self.file, "offset": 1, "limit": 10}, self.numbered(1, 10), error=True)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_a_read_on_a_branch_the_session_rewound_holds_no_lines(self):
start = self.add({"type": "user", "message": {"content": "go"}})
self.read(1, 10)
self.add({"type": "user", "message": {"content": "go again"}}, parent=start)
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
def test_head_and_sed_of_lines_read_are_blocked(self):
self.read(1, 20)
for command in [f"head -n 5 {self.file}", f"head -n5 {self.file}", f"head -5 {self.file}", f"head {self.file}", "sed -n '3,8p' f.txt", "sed -n 7p f.txt"]:
with self.subTest(command):
self.assertEqual(rules(self.found("Bash", {"command": command})), ["repeat-read"])
def test_a_head_starts_at_line_1(self):
self.read(2, 11)
self.assertEqual(self.found("Bash", {"command": f"head {self.file}"}), [])
def test_a_cat_asks_for_the_whole_file(self):
self.read(1, 20)
self.assertEqual(self.found("Bash", {"command": f"cat {self.file}"}), [])
# Claude Code's Edit and Write take only a Read as having read the file.
def test_a_read_goes_through_until_the_agent_read_the_file_with_read(self):
self.used("Bash", {"command": f"sed -n '1,20p' {self.file}"}, self.shown(1, 20))
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 4, "limit": 3}), [])
def test_a_bash_output_counts_against_a_read_once_the_agent_read_the_file_with_read(self):
self.read(21, 30)
self.used("Bash", {"command": f"sed -n '1,20p' {self.file}"}, self.shown(1, 20))
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 4, "limit": 3})), ["repeat-read"])
def test_a_cat_output_puts_every_line_in_context(self):
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 30))
self.assertEqual(rules(self.found("Bash", {"command": "sed -n '25,$p' f.txt"})), ["repeat-read"])
def test_a_relative_path_in_the_transcript_is_under_its_entry_s_cwd(self):
self.used("Bash", {"command": "cat f.txt"}, self.shown(1, 30))
self.assertEqual(rules(read_breaches(Call("Bash", {"command": f"head -n 5 {self.file}"}, "/", "", self.transcript), "/h")), ["repeat-read"])
def test_a_tilde_path_is_under_the_home_folder(self):
self.used("Read", {"file_path": "~/f.txt", "offset": 1, "limit": 10}, self.numbered(1, 10))
self.used("Bash", {"command": "cat ~/f.txt"}, self.shown(1, 30))
for tool, given in [("Read", {"file_path": "~/f.txt", "offset": 1, "limit": 10}), ("Bash", {"command": "sed -n 1,30p ~/f.txt"})]:
with self.subTest(tool):
self.assertEqual(rules(read_breaches(Call(tool, given, "/", "", self.transcript), self.folder)), ["repeat-read"])
def test_other_commands_on_the_file_are_not_checked(self):
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 30))
for command in [f"cat {self.file} > copy", f"cat {self.file} | wc -l", f"cat {self.file} {self.file}", f"head -c 5 {self.file}", f"sed 's/a/b/' {self.file}"]:
with self.subTest(command):
self.assertEqual(self.found("Bash", {"command": command}), [])
# As Claude Code 2.1.312 writes a Bash output it cut short.
def test_an_output_cut_short_shows_no_lines(self):
for cut in [
f"<persisted-output>\nOutput too large (37.9KB). Full output saved to: {self.folder}/tool-results/b2hymdt7w.txt\n\nPreview (first 2KB):\n{self.shown(1, 30)}\n...\n</persisted-output>",
f"<truncated-output>\nOutput too large (37.9KB). It could not be saved, so only the first 2KB are shown; the rest was dropped. If the tool can page or filter its results, call it again for the part you need.\n\n{self.shown(1, 30)}\n</truncated-output>",
self.shown(1, 5) + "\n\n... [25 lines truncated] ...",
]:
with self.subTest(cut[:20]):
self.assertEqual(result_lines("Bash", Asked(self.file, 1, None), cut), {})
def test_a_fifo_is_never_opened(self):
fifo = f"{self.folder}/fifo"
os.mkfifo(fifo)
self.used("Bash", {"command": f"cat {fifo}"}, "line 1")
# Opened, the FIFO would block the hook, since it has no writer.
ran = hook({"cwd": self.folder, "tool_name": "Bash", "tool_input": {"command": f"head -n 1 {fifo}"}, "transcript_path": self.transcript}, self.folder)
self.assertEqual((ran.returncode, ran.stderr), (0, ""))
def called(self, agent_id: str = "") -> Call:
given = {"cwd": self.folder, "tool_name": "Read", "tool_input": {"file_path": self.file, "offset": 1, "limit": 10}, "transcript_path": self.transcript}
return parsed_call(given | ({"agent_id": agent_id, "agent_type": "Explore"} if agent_id else {}))
def test_a_subagent_s_transcript_is_beside_the_session_s(self):
self.assertEqual(self.called("a1").transcript, f"{self.folder}/s/subagents/agent-a1.jsonl")
def test_the_session_s_reads_are_not_in_a_subagent_s_context(self):
self.read(1, 10)
self.assertEqual(read_breaches(self.called("a1"), "/h"), [])
def test_the_session_is_judged_on_its_own_transcript(self):
self.read(1, 10)
self.assertEqual(rules(read_breaches(self.called(), "/h")), ["repeat-read"])
def test_a_missing_transcript_lets_the_read_through(self):
self.assertEqual(read_breaches(Call("Read", {"file_path": self.file}, self.folder, "", f"{self.folder}/none.jsonl"), "/h"), [])
def test_the_hook_blocks_a_repeated_read_without_offering_an_override(self):
self.read(1, 10)
self.used("Bash", {"command": f"head -n 5 {self.file}"}, self.shown(1, 5))
for tool, given in [("Read", {"file_path": self.file, "offset": 1, "limit": 10}), ("Bash", {"command": f"head -n 5 {self.file}"})]:
with self.subTest(tool):
ran = hook({"cwd": self.folder, "tool_name": tool, "tool_input": given, "transcript_path": self.transcript}, self.folder)
self.assertEqual(ran.returncode, 2)
self.assertIn("Blocked by rule repeat-read: ", ran.stderr)
self.assertNotIn("rule-override", ran.stderr)
class Hook(unittest.TestCase):
def setUp(self):
self.repo = tempfile.mkdtemp()
@@ -379,6 +656,54 @@ class Hook(unittest.TestCase):
call = {"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/.gitignore", "new_string": "d", "old_string": "a"}, "tool_name": "Edit"}
self.assertEqual(hook(call, self.repo).returncode, 2)
def round_commit(self, title: str, given: str = "") -> subprocess.CompletedProcess:
return hook({"cwd": self.repo, "tool_input": {"command": f"git commit {given}-m '{title}'"}, "tool_name": "Bash"}, self.repo)
def test_a_round_commit_past_round_2_is_refused_and_offers_no_override(self):
ran = self.round_commit("Answer stability round 3: 0 🔴, 1 🟡 (0 misread); fix # rule-override round-cap: the human said yes")
self.assertEqual(ran.returncode, 2)
self.assertIn("Blocked by rule round-cap: this would be stability's round 3, past its 2", ran.stderr)
self.assertNotIn("rule-override", ran.stderr)
self.assertEqual(self.round_commit("Answer stability round 2: 0 🔴, 1 🟡 (0 misread); fix").returncode, 0)
def test_a_third_round_commit_of_a_pass_on_the_branch_is_refused_whatever_its_number(self):
for title in ["Answer stability round 1: 1 🔴, 0 🟡 (0 misread); a", "Answer prose round 1: 0 🔴, 1 🟡 (0 misread); b", "Answer stability round 2: 0 🔴, 1 🟡 (0 misread); c"]:
git(self.repo, "commit", "-q", "--allow-empty", "-m", title)
ran = self.round_commit("Answer stability round 2: 0 🔴, 0 🟡 (0 misread); d")
self.assertEqual(ran.returncode, 2)
self.assertIn("stability's round commits on this branch: `Answer stability round 2: 0 🔴, 1 🟡 (0 misread); c`, `Answer stability round 1: 1 🔴, 0 🟡 (0 misread); a`", ran.stderr)
self.assertIn("`git commit --amend` where that is the newest commit", ran.stderr)
self.assertEqual(self.round_commit("Answer prose round 2: 0 🔴, 0 🟡 (0 misread); d").returncode, 0)
self.assertEqual(self.round_commit("Answer stability round 2: 0 🔴, 1 🟡 (0 misread); c, reworded", "--amend --allow-empty ").returncode, 0, "an amend replaces the commit it counts")
git(self.repo, "commit", "-q", "--allow-empty", "-m", "fix a typo")
self.assertEqual(self.round_commit("Answer stability round 2: 0 🔴, 1 🟡 (0 misread); e", "--amend --allow-empty ").returncode, 2, "an amend replaces the newest commit, not the oldest")
def test_a_stalled_origin_holds_up_neither_a_round_commit_nor_the_overrides_listing(self):
git(self.repo, "config", "protocol.ext.allow", "always")
git(self.repo, "remote", "add", "origin", "ext::sleep 30")
self.assertEqual(self.round_commit("Answer stability round 1: 0 🔴, 1 🟡 (0 misread); a").returncode, 0)
hook({"cwd": self.repo, "tool_input": {"command": "git commit -m a -m b # rule-override commit-one-line: a body is needed"}, "tool_name": "Bash"}, self.repo)
listed = subprocess.run([str(HOOK), "overrides"], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True, timeout=10).stdout
self.assertIn("\tcommit-one-line\ta body is needed\t", listed)
def test_round_commits_merged_in_from_the_default_branch_do_not_count(self):
git(self.repo, "checkout", "-q", "main")
for title in ["Answer stability round 1: 0 🔴, 1 🟡 (0 misread); a", "Answer stability round 2: 0 🔴, 1 🟡 (0 misread); b"]:
git(self.repo, "commit", "-q", "--allow-empty", "-m", title)
git(self.repo, "checkout", "-q", "chunk")
git(self.repo, "merge", "-q", "--no-ff", "-m", "Merge main", "main")
git(self.repo, "branch", "-f", "main", "main~2")
self.assertEqual(self.round_commit("Answer stability round 1: 0 🔴, 1 🟡 (0 misread); c").returncode, 0, "a stale default branch still leaves another chunk's rounds out")
def test_a_stale_local_main_does_not_stand_in_for_a_default_branch_origin_left_unrecorded(self):
git(self.repo, "checkout", "-q", "main")
for title in ["Answer stability round 1: 0 🔴, 1 🟡 (0 misread); a", "Answer stability round 2: 0 🔴, 1 🟡 (0 misread); b"]:
git(self.repo, "commit", "-q", "--allow-empty", "-m", title)
git(self.repo, "checkout", "-q", "-B", "chunk", "main")
git(self.repo, "branch", "-f", "main", "main~2")
git(self.repo, "remote", "add", "origin", f"{self.repo}/gone.git")
self.assertEqual(self.round_commit("Answer stability round 1: 0 🔴, 1 🟡 (0 misread); c").returncode, 0, "another chunk's rounds, fast-forwarded into the default branch, are not this chunk's")
def test_a_commit_while_an_unranked_todo_has_changes_is_blocked(self):
pathlib.Path(self.repo, "docs").mkdir()
for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]:
@@ -430,7 +755,7 @@ class Hook(unittest.TestCase):
def test_help_lists_every_rule(self):
helped = subprocess.run([str(HOOK), "--help"], capture_output=True, check=True, env=isolated_env(), text=True).stdout
for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-title-counts", "todo-rank-check"]:
for rule in ["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]:
self.assertIn(f" {rule}\n The rule: ", helped)
self.assertIn("reviewer-report\n The rule: a reviewer writes nothing but its report", helped)
self.assertRegex(helped, r" reviewer-report\n( .*\n){2} Takes no override\.\n")
Executable
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
import os
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from run_heavy import main
from machine_load.memory import read_memory
from machine_load.slots import usable_cpus
sys.exit(main.main(sys.argv[1:], os.environ, usable_cpus(), read_memory()))
View File
+35
View File
@@ -0,0 +1,35 @@
"""The docker that run-heavy puts first on its command's PATH. It adds the memory limits a container lacks, from the slot's share, then runs the real docker."""
import os
import pathlib
import shutil
import sys
import typing
from docker_command import capped
# The folder run-heavy puts first on its command's PATH, holding the docker that runs main.
PATH_ENTRY = pathlib.Path(__file__).resolve().parent / "path_entry"
# The environment variable that hands this docker the slot's memory share, in MiB.
SHARE_VARIABLE = "RUN_HEAVY_MEMORY"
CANNOT_RUN = 126
NOT_FOUND = 127
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
"""Replaces this process with the real docker; returns only where none is found or it cannot run."""
path = without_path_entry(env.get("PATH", ""))
docker = shutil.which("docker", path=path)
if docker is None:
print("run-heavy: docker: command not found", file=sys.stderr)
return NOT_FOUND
share = env.get(SHARE_VARIABLE)
try:
os.execve(docker, [docker, *(capped(argv, f"{share}m") if share else argv)], {**env, "PATH": path})
except OSError as failure:
print(f"run-heavy: cannot run {docker}: {failure.strerror}", file=sys.stderr)
return CANNOT_RUN
def without_path_entry(path: str) -> str:
"""path less PATH_ENTRY, so the real docker is the one found."""
return os.pathsep.join(entry for entry in path.split(os.pathsep) if pathlib.Path(entry).resolve() != PATH_ENTRY)
+93
View File
@@ -0,0 +1,93 @@
"""Run a heavy command once it holds one of the machine's heavy slots, so sessions running at once cannot starve the machine.
usage: run-heavy <command> [<arg>...]
A heavy command is one that loads the machine for minutes: a full gate, mutation tests, an e2e run,
a docker build. The machine has one heavy slot for every 4 CPUs that run-heavy may use, and at least one, shared by every
session that runs run-heavy. Each slot is a file locked with flock, under
$XDG_STATE_HOME/run-heavy (default ~/.local/state/run-heavy). While every slot is held, run-heavy
says so once on stderr and waits. It then replaces itself with the command. The slot's lock stays held
until the command, and every process that inherited the lock, exits. Its exit code is the command's.
On Linux, run-heavy also caps the memory of each container the command makes with docker run or
docker create. The cap is the slot's share: three quarters of the machine's memory, split evenly
across the slots, handed to the command in RUN_HEAVY_MEMORY, in MiB. run-heavy puts its own docker
first on the command's PATH. That docker adds the limits a container lacks, then runs the real one:
- A container that sets neither limit gets a memory limit and a swap limit, both the share.
- A container that sets one of them keeps it, and gets the other at the same size.
- A --memory-swap of -1, unlimited swap, is dropped and replaced.
- A --memory of 0, unlimited memory, leaves the call as it is.
Every other docker call goes through unchanged. A docker compose service, and a docker named by its
full path, get no cap: give those containers their own limits.
A command it runs carries the slot's number in RUN_HEAVY_SLOT, and run-heavy called with that set
runs its command at once, so a gate that wraps its own steps cannot wait on itself.
As GNU env, nice and timeout do, it exits 125, saying why, when no command is given or the slot
folder or a slot file cannot be made or locked; 126 when the command is found but cannot run; and 127 when it is not found.
"""
import os
import pathlib
import shutil
import sys
import typing
from failure import Failure
from machine_load.memory import Memory
from run_heavy.capped_docker import PATH_ENTRY, SHARE_VARIABLE, without_path_entry
from machine_load.slots import slot_count, slot_folder, waited_slot
OWN_FAILURE = 125
CANNOT_RUN = 126
NOT_FOUND = 127
HELD = "RUN_HEAVY_SLOT"
USAGE = "usage: run-heavy <command> [<arg>...]"
def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None, memory: Memory | None) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if not argv:
print(f"run-heavy: no command given; {USAGE}", file=sys.stderr)
return OWN_FAILURE
if HELD not in env:
slot = held_slot(slot_folder(env), slot_count(cpus))
if isinstance(slot, Failure):
print(f"run-heavy: {slot.reason}", file=sys.stderr)
return OWN_FAILURE
env = {**env, HELD: str(slot), **capping(memory, slot_count(cpus), env)}
return run(argv, env)
def capping(memory: Memory | None, slots: int, env: typing.Mapping[str, str]) -> dict[str, str]:
"""What the command's environment needs for its docker to cap each container it makes at the slot's share of memory; nothing where the memory is unknown, as off Linux, or where PATH finds no docker to cap."""
path = env.get("PATH", "")
if memory is None or shutil.which("docker", path=without_path_entry(path)) is None:
return {}
return {SHARE_VARIABLE: str(memory.slot_share(slots)), "PATH": os.pathsep.join([str(PATH_ENTRY), path])}
def held_slot(folder: pathlib.Path, slots: int) -> int | Failure:
"""The number of the slot this call holds, its lock left for the command to inherit, or why no slot could be taken."""
try:
folder.mkdir(parents=True, exist_ok=True)
slot, fd = waited_slot(folder, slots, lambda: print(f"run-heavy: waiting for a heavy slot, of {slots} on this machine, in {folder}; `fuser {folder}/slot-*` names the processes that hold them", file=sys.stderr, flush=True))
except OSError as failure:
return Failure(f"cannot take a heavy slot in {folder}: {failure.strerror}")
os.set_inheritable(fd, True)
return slot
def run(argv: list[str], env: typing.Mapping[str, str]) -> int:
"""Replaces this process with the command; returns only where the command cannot start."""
try:
os.execvpe(argv[0], argv, env)
except FileNotFoundError:
print(f"run-heavy: {argv[0]}: command not found", file=sys.stderr)
return NOT_FOUND
except OSError as failure:
print(f"run-heavy: cannot run {argv[0]}: {failure.strerror}", file=sys.stderr)
return CANNOT_RUN
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env python3
import os
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from run_heavy import capped_docker
sys.exit(capped_docker.main(sys.argv[1:], os.environ))
+146
View File
@@ -0,0 +1,146 @@
import contextlib
import fcntl
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from run_heavy import main
from machine_load.memory import read_memory
from machine_load.slots import slot_count, usable_cpus
TOOL = pathlib.Path(__file__).resolve().parents[1] / "run-heavy"
class RunHeavy(unittest.TestCase):
def setUp(self):
state = tempfile.TemporaryDirectory()
self.addCleanup(state.cleanup)
self.env = {**os.environ, "XDG_STATE_HOME": state.name}
self.env.pop(main.HELD, None)
self.slots = pathlib.Path(state.name) / "run-heavy"
def run_tool(self, *args: str, env=None) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, text=True, env=env or self.env, timeout=30)
def start_tool(self, *args: str, env=None) -> subprocess.Popen[str]:
tool = subprocess.Popen([sys.executable, str(TOOL), *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env or self.env)
self.addCleanup(tool.kill)
return tool
@contextlib.contextmanager
def every_slot_held(self):
self.slots.mkdir(parents=True, exist_ok=True)
with contextlib.ExitStack() as held:
for slot in range(slot_count(usable_cpus())):
file = held.enter_context(open(self.slots / f"slot-{slot}", "a"))
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
def free_slots(self) -> int:
free = 0
for slot in range(slot_count(usable_cpus())):
with open(self.slots / f"slot-{slot}", "a") as file:
try:
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
free += 1
except BlockingIOError:
pass
return free
def test_runs_the_command_and_exits_with_its_code(self):
result = self.run_tool("sh", "-c", "echo out; echo err >&2; exit 3")
self.assertEqual((result.returncode, result.stdout, result.stderr), (3, "out\n", "err\n"))
def test_holds_a_slot_while_the_command_runs_and_frees_it_after(self):
tool = self.start_tool("sh", "-c", "echo started; read line")
self.assertEqual(tool.stdout.readline(), "started\n")
self.assertEqual(self.free_slots(), slot_count(usable_cpus()) - 1)
tool.communicate("\n", timeout=30)
self.assertEqual(self.free_slots(), slot_count(usable_cpus()))
def test_a_command_inside_a_held_slot_runs_at_once(self):
with self.every_slot_held():
result = self.run_tool("echo", "nested", env={**self.env, main.HELD: "0"})
self.assertEqual((result.returncode, result.stdout), (0, "nested\n"))
def test_exits_125_saying_why_where_the_slot_folder_cannot_be_made(self):
with tempfile.NamedTemporaryFile() as state:
result = self.run_tool("echo", "ran", env={**self.env, "XDG_STATE_HOME": state.name})
self.assertEqual((result.returncode, result.stdout), (125, ""))
self.assertIn(state.name, result.stderr)
def test_a_command_not_found_exits_127_and_one_that_cannot_run_126_saying_why(self):
missing = self.run_tool("no-such-command-anywhere")
self.assertEqual((missing.returncode, missing.stdout), (127, ""))
self.assertIn("no-such-command-anywhere", missing.stderr)
with tempfile.NamedTemporaryFile(suffix=".sh") as unrunnable:
denied = self.run_tool(unrunnable.name)
self.assertEqual((denied.returncode, denied.stdout), (126, ""))
self.assertIn(unrunnable.name, denied.stderr)
def fake_docker(self) -> dict[str, str]:
"""An environment whose PATH finds, ahead of any real one, a docker that prints the arguments it was given."""
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
docker = pathlib.Path(folder.name) / "docker"
docker.write_text("#!/bin/sh\necho \"$@\"\n")
docker.chmod(0o755)
return {**self.env, "PATH": f"{folder.name}:{self.env['PATH']}"}
def test_a_docker_run_without_limits_gets_three_quarters_of_the_memory_split_across_the_slots(self):
memory = read_memory()
if memory is None:
self.skipTest("no /proc/meminfo to read the share from")
share = f"{memory.total * 3 // 4 // slot_count(usable_cpus()) // 1024}m"
result = self.run_tool("docker", "run", "--rm", "img", "true", env=self.fake_docker())
self.assertEqual((result.returncode, result.stdout), (0, f"run --memory {share} --memory-swap {share} --rm img true\n"))
def test_a_docker_call_with_its_own_limits_or_that_starts_no_container_is_passed_on_unchanged(self):
env = self.fake_docker()
for args in [["run", "-m", "40g", "--memory-swap", "40g", "img"], ["ps", "-a"], ["build", "."]]:
with self.subTest(args):
result = self.run_tool("docker", *args, env=env)
self.assertEqual((result.returncode, result.stdout), (0, " ".join(args) + "\n"))
def test_a_command_on_a_machine_without_docker_finds_none(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
(pathlib.Path(folder.name) / "python3").symlink_to(sys.executable)
(pathlib.Path(folder.name) / "sh").symlink_to("/bin/sh")
result = self.run_tool("sh", "-c", "command -v docker || echo none", env={**self.env, "PATH": folder.name})
self.assertEqual((result.returncode, result.stdout), (0, "none\n"))
def test_the_capped_docker_passes_a_call_on_unchanged_without_a_share(self):
env = self.fake_docker()
env.pop("RUN_HEAVY_MEMORY", None)
shim = pathlib.Path(TOOL).parent / "run_heavy" / "path_entry" / "docker"
result = subprocess.run([str(shim), "run", "img"], capture_output=True, text=True, env=env, timeout=30)
self.assertEqual((result.returncode, result.stdout), (0, "run img\n"))
def test_no_cap_where_the_memory_is_unknown(self):
self.assertEqual(main.capping(None, 4, self.fake_docker()), {})
def test_a_capped_docker_that_finds_no_docker_exits_127_saying_so(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
(pathlib.Path(folder.name) / "python3").symlink_to(sys.executable)
result = self.run_tool("docker", "ps", env={**self.env, "PATH": folder.name})
self.assertEqual((result.returncode, result.stdout), (127, ""))
self.assertIn("docker", result.stderr)
def test_no_command_exits_125_with_the_usage_and_help_exits_0(self):
bare = self.run_tool()
self.assertEqual((bare.returncode, bare.stdout), (125, ""))
self.assertIn("usage: run-heavy <command>", bare.stderr)
helped = self.run_tool("--help")
self.assertEqual(helped.returncode, 0)
self.assertIn("usage: run-heavy <command>", helped.stdout)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -13,7 +13,7 @@ from model_routing.ladder import Rung
AT_ONCE = 4
Case = typing.TypeVar("Case")
# What of a case's record a reply reproduces, such as a verdict's kind or a finding's index.
# What of an archived case a reply reproduces, such as a verdict's kind or a finding's index.
Item = typing.TypeVar("Item")
Reply = typing.TypeVar("Reply")
T = typing.TypeVar("T")
+3 -3
View File
@@ -2,7 +2,7 @@ import re
from todo_table import cells, LEVELS, parse_ids
from failure import Failure
from score_outcomes.outcomes import Outcome, render
from score_outcomes.results import render, Result
ANCHORS_PATH = "docs/score-anchors.md"
# A level, such as `L 1`; every scale tops out below 10.
@@ -29,13 +29,13 @@ def parse_anchors(text: str) -> Anchors | Failure:
return found
def anchor_lines(found: Anchors | Failure, outcomes: list[Outcome]) -> list[str]:
def anchor_lines(found: Anchors | Failure, results: list[Result]) -> list[str]:
"""Each level, then each of its anchors with what its chunk measured. Where the file cannot be read, one line saying why; where it names no level, one line saying how to choose anchors."""
if isinstance(found, Failure):
return [f"- None: {found.reason}"]
if not found:
return [f"- None: the project has no {ANCHORS_PATH}, or it names no level; ~/.claude/rules/todo-items.md says how to choose anchors."]
by_id = {outcome.item.id: outcome for outcome in outcomes}
by_id = {result.item.id: result for result in results}
lines = []
for level, ids in found:
lines.append(f"{level}:")
+31 -23
View File
@@ -19,8 +19,11 @@ holds R and S, and C too where its table also had A, G and Goals. The chunk meas
- review rounds past each pass's first: among the branch's `Answer <pass> round <n>:` commit
titles, each pass's rounds as `larv-review round-count` counts them, less one, summed;
- 🔴 and 🟡 findings: summed over those titles, each opening `<k> 🔴, <m> 🟡` after the colon,
such as `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`. Unknown where a round title
lacks the counts, or the branch has no round.
such as `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); flag a deleted test`. Unknown where a
round title lacks the counts, or the branch has no round;
- misread findings: how many of those 🔴 and 🟡 findings a reviewer marked `[misread]`, the
`(<j> misread)` after the 🟡 count, summed over the titles. Unknown where a round title lacks
that count, as every title written before the count does, or the branch has no round.
A chunk is marked `by rebase` where a commit in it has a committer time apart from its author time,
since a rebase replays a pull request's commits at once, and `never replayed` where none does, since
@@ -48,6 +51,10 @@ that shipped one item, since a chunk measures all its items at once. It leaves o
replayed, which may hold only part of a pull request. It reports a score only once 10 of the chunks
it counts hold it and its outcomes.
Then, newest first, each finished chunk's 🔴 and 🟡 findings with its misread findings, for every
chunk whose round titles count them: code health's counter-signal in
~/.claude/CLAUDE.md → "Shared goal".
Exit 1, saying why, on bad arguments, when git cannot start, finds no checkout or reads a shallow
clone, or the default branch cannot be read; or, after the rest of the report, when the anchors are
left out.
@@ -57,7 +64,7 @@ import re
import sys
from score_outcomes.anchors import anchor_lines, Anchors, ANCHORS_PATH, parse_anchors
from score_outcomes.outcomes import Chunk, Landing, nearest, Outcome, outcomes_of, render, report, shipped
from score_outcomes.results import Chunk, Landing, misreads, nearest, render, report, Result, results_of, shipped
from git_repo import default_branch, file_at, full_history, git, top
from failure import Failure
from todo_table import LEVELS, risk, TOP_SCORE
@@ -91,24 +98,25 @@ def main(argv: list[str]) -> int:
default, note = found
if note:
print(f"score-outcomes: {note}", file=sys.stderr)
outcomes = read_outcomes(default)
if isinstance(outcomes, Failure):
return failed(outcomes)
results = read_results(default)
if isinstance(results, Failure):
return failed(results)
anchored = read_anchors()
print(report_text(outcomes, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None))
print(report_text(results, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None))
return failed(anchored) if isinstance(anchored, Failure) else 0
def report_text(outcomes: list[Outcome], anchored: Anchors | Failure, given: dict[str, int] | None) -> str:
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians."""
def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[str, int] | None) -> str:
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians, then each chunk's misread findings."""
sections = []
if given is not None:
r = risk(given["L"], given["E"], given["I"])
near = [render(outcome) for outcome in nearest(outcomes, given | {"R": r})] or ["- None: no chunk on the default branch shipped an item from todo.md."]
near = [render(result) for result in nearest(results, given | {"R": r})] or ["- None: no chunk on the default branch shipped an item from todo.md."]
sections.append([f"Finished items nearest L {given['L']}, E {given['E']}, I {given['I']}, so R {r}, and S {given['S']}, closest first:", "", *near])
sections.append([f"Anchors in {ANCHORS_PATH}, each level's shipped items:", "", *anchor_lines(anchored, outcomes)])
sections.append(["Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:", "", *report(outcomes)])
if any(outcome.landed != "merge" for outcome in outcomes):
sections.append([f"Anchors in {ANCHORS_PATH}, each level's shipped items:", "", *anchor_lines(anchored, results)])
sections.append(["Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:", "", *report(results)])
sections.append(["🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:", "", *misreads(results)])
if any(result.landed != "merge" for result in results):
sections.append(UNMERGED)
return "\n\n".join("\n".join(section) for section in sections)
@@ -131,19 +139,19 @@ def read_anchors() -> Anchors | Failure:
return Failure(f"cannot read {ANCHORS_PATH}: {failure}")
def read_outcomes(default: str) -> list[Outcome] | Failure:
def read_results(default: str) -> list[Result] | Failure:
"""What each chunk on the default branch's first-parent line measured."""
if partial := full_history():
return partial
log = git("log", "--first-parent", "--format=%x1e%h %ct %at %p", "--name-only", default)
if isinstance(log, Failure):
return log
# Each record is a commit's line, then the files it changed against its first parent.
records = [record.splitlines() for record in log.split("\x1e")[1:]]
headers = [record[0] for record in records]
# Each commit's part of the log is its line, then the files it changed against its first parent.
commits = [part.splitlines() for part in log.split("\x1e")[1:]]
headers = [commit[0] for commit in commits]
hashes = [header.split()[0] for header in headers]
plan = {short for short, record in zip(hashes, records) if "todo.md" in record}
outcomes: list[Outcome] = []
plan = {short for short, commit in zip(hashes, commits) if "todo.md" in commit}
results: list[Result] = []
for first, last, committed, landed in chunk_log(headers):
# Only a chunk that changed todo.md can ship an item, so the others skip measure's git calls.
if not any(short in plan for short in hashes[hashes.index(last):hashes.index(first) + 1]):
@@ -153,8 +161,8 @@ def read_outcomes(default: str) -> list[Outcome] | Failure:
measured = measure(f"{first}^1", last, label, utc(committed), titled, landed)
if isinstance(measured, Failure):
return measured
outcomes += measured
return outcomes
results += measured
return results
def chunk_log(lines: list[str]) -> list[Chunk]:
@@ -175,7 +183,7 @@ def chunk_log(lines: list[str]) -> list[Chunk]:
return chunks
def measure(before: str, tip: str, label: str, merged: str, titled: str, landed: Landing) -> list[Outcome] | Failure:
def measure(before: str, tip: str, label: str, merged: str, titled: str, landed: Landing) -> list[Result] | Failure:
"""What one chunk measured for each item it shipped: its change from the commit before it to its tip, and the titles of the commits in the range titled."""
planned = file_at(before, "todo.md")
if isinstance(planned, Failure):
@@ -192,4 +200,4 @@ def measure(before: str, tip: str, label: str, merged: str, titled: str, landed:
titles = git("log", "--format=%s", titled)
if isinstance(titles, Failure):
return titles
return outcomes_of(items, label, merged, numstat, titles.splitlines(), landed)
return results_of(items, label, merged, numstat, titles.splitlines(), landed)
-132
View File
@@ -1,132 +0,0 @@
import dataclasses
import statistics
import typing
from comprehension_history import HISTORY
from todo_table import Item, items
from markdown_text import listed
from reading_cost.figures import RECORD
from round_titles import round_counts, round_findings
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
ENOUGH = 10
# The plan, and the records tools append to: none of their lines are the chunk's work.
NOT_WORK = ("todo.md", HISTORY, RECORD)
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
Landing = typing.Literal["merge", "rebase", "push"]
# A chunk's first and last commit as short hashes, its commit time, and how it reached the default branch.
Chunk = tuple[str, str, int, Landing]
@dataclasses.dataclass(frozen=True)
class Outcome:
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, None where a round title lacks them or the branch has no round. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed."""
item: Item
merge: str
merged: str
shipped_with: tuple[int, ...]
lines: int
files: int
rounds_past_first: int
findings: tuple[int, int] | None
landed: Landing
# An outcome's name and how to read it from an Outcome, None where the chunk did not record it.
Measure = tuple[str, typing.Callable[[Outcome], int | None]]
# The scores whose median outcome the report gives at each guessed value.
MEDIANS: dict[str, Measure] = {"R": ("🔴 findings", lambda outcome: outcome.findings[0] if outcome.findings else None), "S": ("lines changed", lambda outcome: outcome.lines)}
# The levels R is built from; for each, the report gives how well it orders chunks by review rounds and by 🔴 findings.
ORDERED = ("L", "E", "I")
# The scores render shows, in this order; C only on an item scored before L, E and I replaced it.
SHOWN = ("L", "E", "I", "R", "S", "C")
def shipped(before: str, after: str) -> list[Item]:
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
planned, left = items(before), items(after)
if not isinstance(planned, list) or not isinstance(left, list):
return []
kept = {item.id for item in left}
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
def outcomes_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing) -> list[Outcome]:
"""What one chunk measured for each item it shipped, from `git diff --numstat` against the commit before it and its commit titles; none where it changed nothing but the plan and the records."""
changed = [row.split("\t", 2) for row in numstat.splitlines()]
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
if not work:
return []
# Git counts a binary file's lines as "-".
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
ids = [item.id for item in shipped]
return [Outcome(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed) for item in shipped]
def nearest(outcomes: list[Outcome], given: dict[str, int], count: int = 5) -> list[Outcome]:
"""The outcomes whose guesses sit closest to the given scores: the least mean squared difference over the scores both hold, the newest first among equals."""
def distance(outcome: Outcome) -> float:
shared = [name for name in given if name in outcome.item.scores]
return sum((given[name] - outcome.item.scores[name]) ** 2 for name in shared) / len(shared)
newest_first = sorted(outcomes, key=lambda outcome: outcome.merged, reverse=True)
return sorted(newest_first, key=distance)[:count]
def report(outcomes: list[Outcome]) -> list[str]:
"""Among chunks that shipped one item, since a chunk measures all its items at once, and that were merged or replayed, since a never-replayed one may hold only part of a pull request: for each score in MEDIANS, the median outcome at each value it was guessed at; for each level in ORDERED, how well it orders chunks by review rounds and by 🔴 findings."""
single = [outcome for outcome in outcomes if not outcome.shipped_with and outcome.landed != "push"]
lines = []
for name, (what, measure) in MEDIANS.items():
held = [(outcome.item.scores[name], value) for outcome in single if name in outcome.item.scores and (value := measure(outcome)) is not None]
if len(held) < ENOUGH:
lines.append(f"- {name}, {what}: {too_few(len(held), name, 'its outcome')}")
continue
medians = [(guess, [value for at, value in held if at == guess]) for guess in sorted({guess for guess, _ in held})]
lines.append(f"- {name}, {what}: " + ", ".join(f"{guess} → {statistics.median(found):g} ({plural(len(found), 'chunk')})" for guess, found in medians))
for name in ORDERED:
# Each pass takes a first round whatever the change, so only the rounds after it measure how hard the change was to get right.
rows = [(outcome.item.scores[name], outcome.rounds_past_first, outcome.findings[0]) for outcome in single if name in outcome.item.scores and outcome.findings is not None]
opening = f"- {name}, by review rounds past each pass's first and 🔴 findings: "
if len(rows) < ENOUGH:
lines.append(opening + too_few(len(rows), name, "both outcomes"))
continue
guesses, rounds, red = ([row[column] for row in rows] for column in range(3))
found = [rank_correlation(guesses, rounds), rank_correlation(guesses, red)]
undefined = ", since every chunk held one value" if None in found else ""
lines.append(opening + f"rank correlation {listed(['none' if value is None else f'{value:+.2f}' for value in found], 'and')}{undefined} ({plural(len(rows), 'chunk')})")
return lines
def too_few(held: int, name: str, what: str) -> str:
chunks = "such chunk records" if held == 1 else "such chunks record"
return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}."
def rank_correlation(guesses: list[int], outcomes: list[int]) -> float | None:
"""Spearman's rank correlation, tied values sharing their mean rank; None where either side holds one value, which no order can rank."""
if len(set(guesses)) < 2 or len(set(outcomes)) < 2:
return None
return statistics.correlation(ranks(guesses), ranks(outcomes))
def ranks(values: list[int]) -> list[float]:
"""Each value's rank from 1, tied values sharing their mean rank."""
ordered = sorted(values)
return [ordered.index(value) + (ordered.count(value) + 1) / 2 for value in values]
def render(outcome: Outcome) -> str:
scores = ", ".join(f"{name} {outcome.item.scores[name]}" for name in SHOWN if name in outcome.item.scores)
# Rebase drops a round's commit that changed no file, so history shows such a chunk's rounds and findings short.
at_least = "" if outcome.landed == "merge" else "at least "
merged = {"merge": f"merged {outcome.merged} in {outcome.merge}", "rebase": f"merged {outcome.merged} by rebase in {outcome.merge}", "push": f"committed {outcome.merged} in {outcome.merge}, never replayed, so perhaps part of a pull request"}[outcome.landed]
findings = f"{at_least}{outcome.findings[0]} 🔴, {outcome.findings[1]} 🟡" if outcome.findings else "findings unknown"
others = outcome.shipped_with
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
return f"- Item {outcome.item.id}, {scores}: {plural(outcome.lines, 'line')} in {plural(outcome.files, 'file')}, {at_least}{plural(outcome.rounds_past_first, 'round')} past each pass's first, {findings}; {merged}{together}. {outcome.item.tagline}"
def plural(count: int, noun: str) -> str:
return f"{count} {noun}{'' if count == 1 else 's'}"
+152
View File
@@ -0,0 +1,152 @@
import dataclasses
import statistics
import typing
from round_titles import Findings, round_counts, round_findings
from comprehension_history import HISTORY
from todo_table import Item, items
from markdown_text import listed
from reading_cost.figures import RECORD
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
ENOUGH = 10
# The plan, and the records tools append to: none of their lines are the chunk's work.
NOT_WORK = ("todo.md", HISTORY, RECORD)
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
Landing = typing.Literal["merge", "rebase", "push"]
# A chunk's first and last commit as short hashes, its commit time, and how it reached the default branch.
Chunk = tuple[str, str, int, Landing]
# The tool's name and report call a Result an outcome, a word the code keeps for an entry of a `.outcomes.md` file: docs/decisions.md → `bin/: an outcome is an entry`.
@dataclasses.dataclass(frozen=True)
class Result:
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None where a round title lacks the 🔴 and 🟡 counts or the branch has no round; its misread is None where a round title lacks that count. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed."""
item: Item
merge: str
merged: str
shipped_with: tuple[int, ...]
lines: int
files: int
rounds_past_first: int
findings: Findings | None
landed: Landing
# A measure's name and how to read it from a Result, None where the chunk did not record it.
Measure = tuple[str, typing.Callable[[Result], int | None]]
# The scores whose median result the report gives at each guessed value.
MEDIANS: dict[str, Measure] = {"R": ("🔴 findings", lambda result: result.findings.red if result.findings else None), "S": ("lines changed", lambda result: result.lines)}
# The levels R is built from; for each, the report gives how well it orders chunks by review rounds and by 🔴 findings.
ORDERED = ("L", "E", "I")
# The scores render shows, in this order; C only on an item scored before L, E and I replaced it.
SHOWN = ("L", "E", "I", "R", "S", "C")
def shipped(before: str, after: str) -> list[Item]:
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
planned, left = items(before), items(after)
if not isinstance(planned, list) or not isinstance(left, list):
return []
kept = {item.id for item in left}
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
def results_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing) -> list[Result]:
"""What one chunk measured for each item it shipped, from `git diff --numstat` against the commit before it and its commit titles; none where it changed nothing but the plan and the records."""
changed = [row.split("\t", 2) for row in numstat.splitlines()]
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
if not work:
return []
# Git counts a binary file's lines as "-".
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
ids = [item.id for item in shipped]
return [Result(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed) for item in shipped]
def nearest(results: list[Result], given: dict[str, int], count: int = 5) -> list[Result]:
"""The results whose guesses sit closest to the given scores: the least mean squared difference over the scores both hold, the newest first among equals."""
def distance(result: Result) -> float:
shared = [name for name in given if name in result.item.scores]
return sum((given[name] - result.item.scores[name]) ** 2 for name in shared) / len(shared)
newest_first = sorted(results, key=lambda result: result.merged, reverse=True)
return sorted(newest_first, key=distance)[:count]
def report(results: list[Result]) -> list[str]:
"""Among chunks that shipped one item, since a chunk measures all its items at once, and that were merged or replayed, since a never-replayed one may hold only part of a pull request: for each score in MEDIANS, the median result at each value it was guessed at; for each level in ORDERED, how well it orders chunks by review rounds and by 🔴 findings."""
single = [result for result in results if not result.shipped_with and result.landed != "push"]
lines = []
for name, (what, measure) in MEDIANS.items():
held = [(result.item.scores[name], value) for result in single if name in result.item.scores and (value := measure(result)) is not None]
if len(held) < ENOUGH:
lines.append(f"- {name}, {what}: {too_few(len(held), name, 'its outcome')}")
continue
medians = [(guess, [value for at, value in held if at == guess]) for guess in sorted({guess for guess, _ in held})]
lines.append(f"- {name}, {what}: " + ", ".join(f"{guess} → {statistics.median(found):g} ({plural(len(found), 'chunk')})" for guess, found in medians))
for name in ORDERED:
# Each pass takes a first round whatever the change, so only the rounds after it measure how hard the change was to get right.
rows = [(result.item.scores[name], result.rounds_past_first, result.findings.red) for result in single if name in result.item.scores and result.findings is not None]
opening = f"- {name}, by review rounds past each pass's first and 🔴 findings: "
if len(rows) < ENOUGH:
lines.append(opening + too_few(len(rows), name, "both outcomes"))
continue
guesses, rounds, red = ([row[column] for row in rows] for column in range(3))
found = [rank_correlation(guesses, rounds), rank_correlation(guesses, red)]
undefined = ", since every chunk held one value" if None in found else ""
lines.append(opening + f"rank correlation {listed(['none' if value is None else f'{value:+.2f}' for value in found], 'and')}{undefined} ({plural(len(rows), 'chunk')})")
return lines
def misreads(results: list[Result]) -> list[str]:
"""Newest first, each chunk's 🔴 and 🟡 findings with how many of them a reviewer marked `[misread]`, for each chunk whose round titles count those."""
# A chunk that shipped several items has a Result for each, so one line per chunk.
chunks = {result.merge: result for result in results}
newest_first = sorted(chunks.values(), key=lambda result: result.merged, reverse=True)
lines = [f"- {result.merged} in {result.merge}: {counted(result)}" for result in newest_first if result.findings is not None and result.findings.misread is not None]
return lines or ["- None: no chunk's round titles count them."]
def too_few(held: int, name: str, what: str) -> str:
chunks = "such chunk records" if held == 1 else "such chunks record"
return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}."
def rank_correlation(guesses: list[int], results: list[int]) -> float | None:
"""Spearman's rank correlation, tied values sharing their mean rank; None where either side holds one value, which no order can rank."""
if len(set(guesses)) < 2 or len(set(results)) < 2:
return None
return statistics.correlation(ranks(guesses), ranks(results))
def ranks(values: list[int]) -> list[float]:
"""Each value's rank from 1, tied values sharing their mean rank."""
ordered = sorted(values)
return [ordered.index(value) + (ordered.count(value) + 1) / 2 for value in values]
def render(result: Result) -> str:
scores = ", ".join(f"{name} {result.item.scores[name]}" for name in SHOWN if name in result.item.scores)
merged = {"merge": f"merged {result.merged} in {result.merge}", "rebase": f"merged {result.merged} by rebase in {result.merge}", "push": f"committed {result.merged} in {result.merge}, never replayed, so perhaps part of a pull request"}[result.landed]
others = result.shipped_with
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
return f"- Item {result.item.id}, {scores}: {plural(result.lines, 'line')} in {plural(result.files, 'file')}, {at_least(result)}{plural(result.rounds_past_first, 'round')} past each pass's first, {counted(result)}; {merged}{together}. {result.item.tagline}"
def at_least(result: Result) -> str:
"""The words that mark a chunk's rounds and findings as lower bounds: rebase drops a round's commit that changed no file, so history shows a chunk that left no merge commit short."""
return "" if result.landed == "merge" else "at least "
def counted(result: Result) -> str:
"""A chunk's findings as its round titles spell them: `1 🔴, 2 🟡 (1 misread)`, the misread count left out where they lack it."""
if result.findings is None:
return "findings unknown"
misread = "" if result.findings.misread is None else f" ({result.findings.misread} misread)"
return f"{at_least(result)}{result.findings.red} 🔴, {result.findings.yellow} 🟡{misread}"
def plural(count: int, noun: str) -> str:
return f"{count} {noun}{'' if count == 1 else 's'}"
+52 -36
View File
@@ -10,9 +10,10 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from score_outcomes.anchors import anchor_lines, parse_anchors
from score_outcomes.main import chunk_log, report_text
from failure import Failure
from round_titles import Findings
from test_env import isolated_env
from todo_table import Item
from score_outcomes.outcomes import Landing, nearest, Outcome, outcomes_of, rank_correlation, render, report, shipped
from score_outcomes.results import Landing, nearest, rank_correlation, render, report, Result, results_of, shipped
TOOL = pathlib.Path(__file__).resolve().parents[1] / "score-outcomes"
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
@@ -29,8 +30,8 @@ def item(id_: int, scores: dict[str, int]) -> Item:
return Item(id_, (0, 1, 0), "", f"**Item {id_}.**", scores, (("1", None),), ())
def outcome(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, findings: tuple[int, int] | None = (0, 0), merged: str = "2026-10-13T10:00:00Z", shipped_with: tuple[int, ...] = (), levels: dict[str, int] | None = None, landed: Landing = "merge") -> Outcome:
return Outcome(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), "aaaaaaa", merged, shipped_with, lines, 1, rounds, findings, landed)
def result(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, findings: tuple[int, int] | None = (0, 0), merged: str = "2026-10-13T10:00:00Z", shipped_with: tuple[int, ...] = (), levels: dict[str, int] | None = None, landed: Landing = "merge", misread: int | None = None, merge: str = "aaaaaaa") -> Result:
return Result(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), merge, merged, shipped_with, lines, 1, rounds, None if findings is None else Findings(*findings, misread), landed)
class Shipped(unittest.TestCase):
@@ -72,47 +73,47 @@ class ChunkLog(unittest.TestCase):
self.assertEqual(chunk_log(["c2 300 300 c1", "c1 200 200 r"]), [("c2", "c2", 300, "push"), ("c1", "c1", 200, "push")])
class OutcomesOf(unittest.TestCase):
class ResultsOf(unittest.TestCase):
def test_measures_the_change_less_the_plan_and_the_tool_records_and_counts_binary_files(self):
numstat = "3\t1\ta.py\n-\t-\tlogo.png\n0\t1\t2026\n5\t0\ttodo.md\n9\t0\tdocs/reading-cost.md\n4\t0\tdocs/comprehension-history.md\n"
titles = ["Answer stability round 1: 1 🔴, 2 🟡; fix", "Answer stability round 2: 0 🔴, 1 🟡; fix", "Answer prose round 1: 0 🔴, 3 🟡", "Do it"]
found = outcomes_of([item(4, {"R": 2}), item(5, {"R": 3})], "abc1234", "2026-10-13T10:00:00Z", numstat, titles, "merge")
self.assertEqual(found[0], Outcome(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, (1, 6), "merge"))
found = results_of([item(4, {"R": 2}), item(5, {"R": 3})], "abc1234", "2026-10-13T10:00:00Z", numstat, titles, "merge")
self.assertEqual(found[0], Result(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, Findings(1, 6, None), "merge"))
self.assertEqual(found[1].shipped_with, (4,))
def test_measures_no_chunk_that_changed_only_the_plan(self):
self.assertEqual(outcomes_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", [], "merge"), [])
self.assertEqual(results_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", [], "merge"), [])
class Nearest(unittest.TestCase):
def test_lists_the_closest_guesses_first_by_the_mean_over_the_scores_both_hold(self):
found = [outcome(1, 9, 9, 9), outcome(2, 3, 5, None), outcome(3, 3, 4, 6), outcome(4, 3, 4, 9)]
found = [result(1, 9, 9, 9), result(2, 3, 5, None), result(3, 3, 4, 6), result(4, 3, 4, 9)]
self.assertEqual([each.item.id for each in nearest(found, {"R": 3, "S": 4, "C": 5}, 3)], [3, 2, 4])
def test_lists_five_by_default(self):
self.assertEqual(len(nearest([outcome(id_, 3, 4, 5) for id_ in range(6)], {"R": 3, "S": 4, "C": 5})), 5)
self.assertEqual(len(nearest([result(id_, 3, 4, 5) for id_ in range(6)], {"R": 3, "S": 4, "C": 5})), 5)
def test_compares_an_item_scored_before_l_e_and_i_by_its_r_and_s(self):
given = {"L": 2, "E": 2, "I": 3, "R": 5, "S": 4}
found = [outcome(1, 8, 4, None, levels={"L": 4, "E": 3, "I": 3}), outcome(2, 5, 4, 9, merged="2026-10-12T10:00:00Z"), outcome(3, 5, 4, None, levels={"L": 2, "E": 2, "I": 3})]
found = [result(1, 8, 4, None, levels={"L": 4, "E": 3, "I": 3}), result(2, 5, 4, 9, merged="2026-10-12T10:00:00Z"), result(3, 5, 4, None, levels={"L": 2, "E": 2, "I": 3})]
self.assertEqual([each.item.id for each in nearest(found, given)], [3, 2, 1])
def test_lists_the_newest_first_among_equals(self):
found = [outcome(1, 3, 4, 5, merged="2026-10-12T10:00:00Z"), outcome(2, 3, 4, 5, merged="2026-10-13T09:00:00Z")]
found = [result(1, 3, 4, 5, merged="2026-10-12T10:00:00Z"), result(2, 3, 4, 5, merged="2026-10-13T09:00:00Z")]
self.assertEqual([each.item.id for each in nearest(found, {"R": 3, "S": 4, "C": 5})], [2, 1])
class Report(unittest.TestCase):
def test_gives_each_guessed_values_median_outcome_once_ten_single_item_chunks_hold_it(self):
found = [outcome(id_, 2, 1 + id_ % 2, 4, lines=10 * id_, rounds=id_, findings=(1, 3)) for id_ in range(1, 11)]
lines = report(found + [outcome(11, 2, 2, None, lines=1000, findings=None, shipped_with=(12,))])
def test_gives_each_guessed_values_median_result_once_ten_single_item_chunks_hold_it(self):
found = [result(id_, 2, 1 + id_ % 2, 4, lines=10 * id_, rounds=id_, findings=(1, 3)) for id_ in range(1, 11)]
lines = report(found + [result(11, 2, 2, None, lines=1000, findings=None, shipped_with=(12,))])
self.assertIn("- R, 🔴 findings: 2 → 1 (10 chunks)", lines)
self.assertIn("- S, lines changed: 1 → 60 (5 chunks), 2 → 50 (5 chunks)", lines)
self.assertFalse([line for line in lines if line.startswith("- C")])
def test_says_how_many_chunks_it_has_under_ten(self):
self.assertIn("- S, lines changed: 1 such chunk records S and its outcome; the report needs 10.", report([outcome(1, 2, 2, 4), outcome(2, 2, 2, None, shipped_with=(1,))]))
too_few = report([outcome(1, 2, 2, None, levels={"L": 2, "E": 1, "I": 1}), outcome(2, 2, 2, None, levels={"L": 2}, findings=None)])
self.assertIn("- S, lines changed: 1 such chunk records S and its outcome; the report needs 10.", report([result(1, 2, 2, 4), result(2, 2, 2, None, shipped_with=(1,))]))
too_few = report([result(1, 2, 2, None, levels={"L": 2, "E": 1, "I": 1}), result(2, 2, 2, None, levels={"L": 2}, findings=None)])
for name in "LEI":
with self.subTest(name=name):
self.assertIn(f"- {name}, by review rounds past each pass's first and 🔴 findings: 1 such chunk records {name} and both outcomes; the report needs 10.", too_few)
@@ -122,12 +123,12 @@ class Report(unittest.TestCase):
self.assertAlmostEqual(rank_correlation([1, 1, 2, 3], [1, 2, 3, 4]), 0.949, places=3)
self.assertAlmostEqual(rank_correlation([1, 2, 3, 4], [1, 1, 2, 3]), 0.949, places=3)
def test_ranks_an_outcome_that_holds_two_values(self):
def test_ranks_a_result_that_holds_two_values(self):
self.assertAlmostEqual(rank_correlation([1, 2, 3, 4, 5], [1, 1, 2, 2, 2]), 0.866, places=3)
def test_gives_how_well_l_e_and_i_each_order_chunks_by_review_rounds_and_red_findings(self):
levels = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4]
found = [outcome(id_, 2, 2, None, rounds=level, findings=(5 - level, 0), levels={"L": level, "E": 2, "I": level}) for id_, level in enumerate(levels, 1)]
found = [result(id_, 2, 2, None, rounds=level, findings=(5 - level, 0), levels={"L": level, "E": 2, "I": level}) for id_, level in enumerate(levels, 1)]
lines = report(found)
self.assertIn("- L, by review rounds past each pass's first and 🔴 findings: rank correlation +1.00 and -1.00 (10 chunks)", lines)
self.assertIn("- I, by review rounds past each pass's first and 🔴 findings: rank correlation +1.00 and -1.00 (10 chunks)", lines)
@@ -136,19 +137,23 @@ class Report(unittest.TestCase):
class Render(unittest.TestCase):
def test_shows_an_items_l_e_and_i_before_its_r_and_s(self):
self.assertTrue(render(outcome(4, 3, 3, None, levels={"L": 2, "E": 2, "I": 1})).startswith("- Item 4, L 2, E 2, I 1, R 3, S 3:"))
self.assertTrue(render(result(4, 3, 3, None, levels={"L": 2, "E": 2, "I": 1})).startswith("- Item 4, L 2, E 2, I 1, R 3, S 3:"))
def test_names_the_items_shipped_together_and_unknown_findings(self):
self.assertEqual(render(outcome(4, 2, 3, None, lines=1, rounds=2, findings=None, shipped_with=(5, 6))), "- Item 4, R 2, S 3: 1 line in 1 file, 2 rounds past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z in aaaaaaa, with items 5, 6. **Item 4.**")
self.assertEqual(render(outcome(4, 2, 3, 4, findings=(1, 2))), "- Item 4, R 2, S 3, C 4: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**")
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa, with item 5. ", render(outcome(4, 2, 3, 4, rounds=1, shipped_with=(5,))))
self.assertEqual(render(result(4, 2, 3, None, lines=1, rounds=2, findings=None, shipped_with=(5, 6))), "- Item 4, R 2, S 3: 1 line in 1 file, 2 rounds past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z in aaaaaaa, with items 5, 6. **Item 4.**")
self.assertEqual(render(result(4, 2, 3, 4, findings=(1, 2))), "- Item 4, R 2, S 3, C 4: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**")
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa, with item 5. ", render(result(4, 2, 3, 4, rounds=1, shipped_with=(5,))))
def test_gives_the_misread_count_where_the_round_titles_do(self):
self.assertIn("1 round past each pass's first, 1 🔴, 2 🟡 (1 misread); merged", render(result(4, 2, 3, None, findings=(1, 2), misread=1)))
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡 (0 misread); merged", render(result(4, 2, 3, None, misread=0)))
def test_gives_a_rebase_merged_chunks_rounds_and_findings_as_lower_bounds(self):
self.assertEqual(render(outcome(4, 2, 3, None, findings=(1, 2), landed="rebase")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa. **Item 4.**")
self.assertIn("at least 1 round past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa", render(outcome(4, 2, 3, None, findings=None, landed="rebase")))
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="rebase")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa. **Item 4.**")
self.assertIn("at least 1 round past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa", render(result(4, 2, 3, None, findings=None, landed="rebase")))
def test_says_a_chunk_never_replayed_may_be_part_of_a_pull_request(self):
self.assertEqual(render(outcome(4, 2, 3, None, findings=(1, 2), landed="push")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; committed 2026-10-13T10:00:00Z in aaaaaaa, never replayed, so perhaps part of a pull request. **Item 4.**")
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="push")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; committed 2026-10-13T10:00:00Z in aaaaaaa, never replayed, so perhaps part of a pull request. **Item 4.**")
ANCHORS_TEXT = "# Score anchors\n\nWhy these.\n\n| Level | Items |\n|---|---|\n| L 1 | 4, 9 |\n| I 3 | 5 |\n"
@@ -173,7 +178,7 @@ class Anchors(unittest.TestCase):
self.assertEqual(parse_anchors(ANCHORS_TEXT + "| L 1 | 7 |\n"), Failure("docs/score-anchors.md names L 1 twice"))
def test_lists_each_anchor_with_what_its_chunk_measured_and_says_which_it_cannot_find(self):
lines = anchor_lines([("L 1", (4, 9))], [outcome(4, 2, 3, None, findings=(1, 2))])
lines = anchor_lines([("L 1", (4, 9))], [result(4, 2, 3, None, findings=(1, 2))])
self.assertEqual(lines, ["L 1:", "- Item 4, R 2, S 3: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**", "- Item 9: no chunk shipped it."])
def test_points_to_the_rules_where_the_project_names_no_anchors(self):
@@ -186,7 +191,7 @@ class Anchors(unittest.TestCase):
class ReportText(unittest.TestCase):
def test_lists_the_nearest_by_r_then_the_anchors_then_the_medians(self):
found = [outcome(1, 5, 3, None, merged="2026-10-13T10:00:00Z"), outcome(2, 1, 3, None, merged="2026-10-12T10:00:00Z")]
found = [result(1, 5, 3, None, merged="2026-10-13T10:00:00Z"), result(2, 1, 3, None, merged="2026-10-12T10:00:00Z")]
too_few = "such chunks record"
self.assertEqual(report_text(found, [("L 1", (2,))], {"L": 1, "E": 1, "I": 1, "S": 3}), f"""Finished items nearest L 1, E 1, I 1, so R 1, and S 3, closest first:
@@ -204,24 +209,35 @@ Median outcome at each guessed score, among chunks that shipped one item, never-
- S, lines changed: 2 {too_few} S and its outcome; the report needs 10.
- L, by review rounds past each pass's first and 🔴 findings: 0 {too_few} L and both outcomes; the report needs 10.
- E, by review rounds past each pass's first and 🔴 findings: 0 {too_few} E and both outcomes; the report needs 10.
- I, by review rounds past each pass's first and 🔴 findings: 0 {too_few} I and both outcomes; the report needs 10.""")
- I, by review rounds past each pass's first and 🔴 findings: 0 {too_few} I and both outcomes; the report needs 10.
🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:
- None: no chunk's round titles count them.""")
def test_lists_each_chunks_findings_with_their_misread_count_newest_first_once_per_chunk(self):
found = [result(1, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(2,)), result(2, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(1,)), result(3, 5, 3, None, findings=(0, 4), misread=0, merge="ccccccc", merged="2026-10-14T10:00:00Z", landed="rebase"), result(4, 5, 3, None)]
self.assertIn("""🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:
- 2026-10-14T10:00:00Z in ccccccc: at least 0 🔴, 4 🟡 (0 misread)
- 2026-10-12T10:00:00Z in bbbbbbb: 1 🔴, 2 🟡 (1 misread)""", report_text(found, [], None))
def test_ends_with_how_it_reads_chunks_merged_by_rebase_only_where_it_measured_one(self):
text = report_text([outcome(1, 5, 3, None, landed="rebase")], [], None)
text = report_text([result(1, 5, 3, None, landed="rebase")], [], None)
self.assertIn("\n\nChunks that left no merge commit:\n\n- Each is the run of commits", text.split("Median outcome")[1])
self.assertIn("a pull request that shipped nothing adds its lines, files and rounds", text)
self.assertIn("at least what history shows, and the medians count the rebased ones as shown.", text)
self.assertIn("Chunks that left no merge commit", report_text([outcome(1, 5, 3, None, landed="push")], [], None))
self.assertNotIn("Chunks that left no merge commit", report_text([outcome(1, 5, 3, None)], [], None))
self.assertIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None, landed="push")], [], None))
self.assertNotIn("Chunks that left no merge commit", report_text([result(1, 5, 3, None)], [], None))
def test_leaves_a_never_replayed_chunk_out_of_the_s_medians_and_keeps_a_rebased_one(self):
found = [outcome(id_, 2, 2, None, lines=10 * id_, landed="rebase" if id_ == 1 else "merge") for id_ in range(1, 11)]
self.assertIn("- S, lines changed: 2 → 55 (10 chunks)", report_text(found + [outcome(11, 2, 2, None, lines=100000, landed="push")], [], None))
found = [result(id_, 2, 2, None, lines=10 * id_, landed="rebase" if id_ == 1 else "merge") for id_ in range(1, 11)]
self.assertIn("- S, lines changed: 2 → 55 (10 chunks)", report_text(found + [result(11, 2, 2, None, lines=100000, landed="push")], [], None))
def test_leaves_a_never_replayed_chunk_out_of_the_r_medians_and_the_rank_correlations(self):
levels = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4]
found = [outcome(id_, 2, 2, None, rounds=level, findings=(5 - level, 0), levels={"L": level, "E": 2, "I": level}) for id_, level in enumerate(levels, 1)]
pushed = outcome(11, 2, 2, None, rounds=9, findings=(9, 0), levels={"L": 1, "E": 2, "I": 1}, landed="push")
found = [result(id_, 2, 2, None, rounds=level, findings=(5 - level, 0), levels={"L": level, "E": 2, "I": level}) for id_, level in enumerate(levels, 1)]
pushed = result(11, 2, 2, None, rounds=9, findings=(9, 0), levels={"L": 1, "E": 2, "I": 1}, landed="push")
text = report_text(found + [pushed], [], None)
self.assertIn("- R, 🔴 findings: 2 → 2.5 (10 chunks)", text)
self.assertIn("- L, by review rounds past each pass's first and 🔴 findings: rank correlation +1.00 and -1.00 (10 chunks)", text)
@@ -229,7 +245,7 @@ Median outcome at each guessed score, among chunks that shipped one item, never-
self.assertIn("- E, by review rounds past each pass's first and 🔴 findings: rank correlation none and none, since every chunk held one value (10 chunks)", text)
def test_keeps_a_never_replayed_chunk_in_the_nearest_and_anchors_lists(self):
pushed = outcome(9, 2, 3, None, landed="push")
pushed = result(9, 2, 3, None, landed="push")
text = report_text([pushed], [("L 1", (9,))], {"L": 1, "E": 1, "I": 1, "S": 3})
nearest_section, anchors_section = text.split("Anchors in ")
self.assertIn("- Item 9, R 2, S 3:", nearest_section)

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