Compare commits

...

183 Commits

Author SHA1 Message Date
lilleman c7af0ff900 Answer product-owner round 4: nothing to fix 2026-10-07 00:45:09 +02:00
lilleman 4d4abd208f Merge remote-tracking branch 'origin/main' into update-command
# Conflicts:
#	CHANGELOG.md
2026-10-07 00:44:40 +02:00
lilleman 8c082eec1c Merge pull request 'Let a project decision suspend larv-review's scoring run for the plan items it names' (#219) from suspend-scoring-run into main 2026-10-04 23:41:18 +02:00
lilleman f54d6b5ff8 Answer prose round 3 and stability round 3: a suspended chunk is one shipping only named items, and a release's last item is measured even then 2026-10-04 23:39:02 +02:00
lilleman b5637320fc Answer prose round 2 and stability round 2: only a scoring run ends a suspension, and only the scoring run is suspended 2026-10-04 23:37:37 +02:00
lilleman 673165d650 Answer prose round 1 and stability round 1: a suspension names the item that ends it, a release's last item is always measured, and CLAUDE.md says so 2026-10-04 23:35:34 +02:00
lilleman 7e54a67b87 Let a project decision suspend larv-review's scoring run for the plan items it names 2026-10-04 23:32:24 +02:00
lilleman 2cbf57cbd5 Answer prose round 3: nothing to fix 2026-10-04 22:32:09 +02:00
lilleman c6930745a3 Answer prose round 2: name the latest tag 2026-10-04 22:31:51 +02:00
lilleman f5e3f7f10c Answer prose round 1: lead with the action to keep a change, and say which files git status lists 2026-10-04 22:31:23 +02:00
lilleman 0047b8c624 Answer product-owner round 3: nothing to fix 2026-10-04 22:30:17 +02:00
lilleman f735a8ad80 Answer product-owner round 2: show the old tag, push the release tag, scope what git status lists 2026-10-04 22:29:41 +02:00
lilleman 57e67f8f0a Answer product-owner round 1: list what the move discards, keep a change through a release, follow the changelog 2026-10-04 22:28:32 +02:00
lilleman 95e613380b Give README an Update section that moves a machine's checkout to the latest tag 2026-10-04 22:26:45 +02:00
lilleman 26fb73f8eb Merge pull request 'Check Claude Code's settings.json changes for a credential before committing them, and give Install the checkout commands' (#216) from settings-secret-check into main 2026-10-04 22:24:45 +02:00
lilleman 54bc5df401 Merge remote-tracking branch 'origin/main' into settings-secret-check
# Conflicts:
#	CHANGELOG.md
2026-10-04 22:23:55 +02:00
lilleman 83df315f48 Merge pull request 'Add sane defaults as a technical principle, at the edge beside explicit over implicit' (#217) from sane-defaults-principle into main 2026-10-04 21:53:38 +02:00
lilleman 3531995d21 Answer prose round 3: nothing to fix 2026-10-04 21:53:36 +02:00
lilleman 21e0843f12 Answer prose round 2: the CLI is the wiring code that defaults what changes between runs 2026-10-04 21:53:14 +02:00
lilleman 54cec00d85 Answer prose round 1: defaults at the program's edge, a library still asking for what changes between runs, and an example of a default worth having 2026-10-04 21:52:34 +02:00
lilleman 7146b447ab Add sane defaults as a technical principle, at the edge beside explicit over implicit 2026-10-04 21:51:27 +02:00
lilleman 9e984572c2 Answer prose round 2: nothing to change 2026-10-04 20:35:26 +02:00
lilleman 22c3dbfa33 Answer prose round 1: one order of steps in the settings.json rule, one idea per sentence in Install 2026-10-04 20:35:03 +02:00
lilleman fb32976336 Answer product-owner round 3: nothing to change 2026-10-04 20:33:49 +02:00
lilleman de6d218ca1 Answer product-owner round 2: the changelog line covers a ~/.claude Claude Code has not created 2026-10-04 20:33:37 +02:00
lilleman bdf081aadd Answer product-owner round 1: ask the human to move the credential out, mkdir before cd, release tags only, file item 71 2026-10-04 20:33:02 +02:00
lilleman b65c23582f Check Claude Code's settings.json changes for a credential before committing them, and give Install the checkout commands 2026-10-04 20:31:14 +02:00
lilleman 5baedb58df Merge pull request 'Audit only the principles that apply, and rerun only the architecture reviewers a fix answers' (#215) from scoped-audit into main 2026-10-04 20:28:07 +02:00
lilleman 6425d42ee7 Record shipping PR #215 under the floor, as lilleman decided 2026-10-04 20:28:05 +02:00
lilleman c63d2fe850 Record the owner's answers: auto mode is deliberate in the sandbox, the repo may name bender, bender-infra and ai-sandbox, the ships under the floor stand until item 62 2026-10-04 19:42:49 +02:00
lilleman d9d8491493 Answer prose round 3: nothing to change 2026-10-04 18:07:00 +02:00
lilleman 381be8f930 Answer prose round 2: item 62 says what 0.1.0 waits on, item 60 drops 'records' in a second sense 2026-10-04 18:06:38 +02:00
lilleman db2f38749c Answer prose round 1: the later-round rule in two sentences, the last-item trigger first, items 60 and 62-65 and 70 reworded; the records comment kept for the seats 2026-10-04 18:04:06 +02:00
lilleman f3b9378e9f Answer product-owner round 3: nothing to change; whether to ship under the fall is asked 2026-10-04 17:58:20 +02:00
lilleman 8e63fa0f0b Answer stability round 3: nothing to change; the prompts sent to claude are byte-identical 2026-10-04 17:58:20 +02:00
lilleman f948839eec Answer architecture round 3: at the round cap; the scores fell within the panel's noise, the ship decision is the human's 2026-10-04 17:56:31 +02:00
lilleman 0a2a2711dc Answer architecture round 2: the judge's contract owns the sentences naming where answers are quoted from and recorded, records.py only reads; the cycle's vocabulary names CLAUDE.md as a quote source 2026-10-04 17:53:29 +02:00
lilleman b95f2c89cf Answer architecture round 1: one module owns the judge's file lists, the reviewer agents read each principles file's Applies to line, logging applies to services; the audits' findings filed 2026-10-04 17:47:47 +02:00
lilleman bed98f5306 Answer product-owner round 2: nothing to change 2026-10-04 17:36:03 +02:00
lilleman f24754ed43 Answer stability round 2: nothing to change; the last-item clause scored 6.7, under the bar 2026-10-04 17:36:03 +02:00
lilleman b6ca06c790 Answer product-owner round 1: fixed in the stability round 1 commit; skipped files listed in the summary checklist, a file without the line applies everywhere 2026-10-04 17:32:23 +02:00
lilleman e99d640b51 Answer stability round 1: rerun the scoring run every later architecture round, judge applicability from the diff too, and seat the architect in a whole-round rerun 2026-10-04 17:32:23 +02:00
lilleman 12f743c629 Audit only the principles that apply, and rerun only the architecture reviewers a fix answers 2026-10-04 17:28:21 +02:00
lilleman 4749bb7fa6 Merge pull request 'Resume an unfinished chunk with the judge's quote of the work remaining' (#214) from judge-evidence into main 2026-10-04 17:17:28 +02:00
lilleman e80114d068 Answer product-owner round 3: the judge-naming idea scored 7.6, under the bar; the repeated unfinished reads fine 2026-10-04 17:17:08 +02:00
lilleman 7828fe1edf Answer stability round 3: the old fixture wording stays; the rendering test ignores the text 2026-10-04 17:17:08 +02:00
lilleman 4f7ac81a93 Answer product-owner round 2: nothing to change 2026-10-04 17:17:08 +02:00
lilleman 9a757f849f Answer stability round 2: nothing to change 2026-10-04 17:17:08 +02:00
lilleman 8ec4bfa336 Answer prose round 2: nothing to change 2026-10-04 17:17:08 +02:00
lilleman b6c42bbf48 Answer prose round 1: the help, changelog and resume prompt say who is shown the passage; the reload message names the state; item 59 holds one change 2026-10-04 17:15:41 +02:00
lilleman 96b93d7852 Answer stability round 1: nothing to change; the unbounded quote fails loudly, as a quoted answer already does 2026-10-04 17:12:42 +02:00
lilleman e5d82308c8 Answer security round 1: no vulnerabilities 2026-10-04 17:12:42 +02:00
lilleman ffc524975f Answer product-owner round 1: blockquote the judge's passage in the resume prompt; item 59 names the judge stating what remains 2026-10-04 17:12:42 +02:00
lilleman edbe3af024 Resume an unfinished chunk with the judge's quote of the work remaining 2026-10-04 17:09:28 +02:00
lilleman f807bc8bd5 Merge pull request 'Make larv-review's pass names and comprehension floor readable on their own' (#213) from larv-review-readable into main 2026-10-04 16:51:56 +02:00
lilleman 5da1a3e407 Answer prose round 5: fixed in the stability round 5 commit; the entry named, a PR merges 2026-10-04 16:51:13 +02:00
lilleman 24f0b29303 Answer product-owner round 5: nothing to change 2026-10-04 16:51:13 +02:00
lilleman c8757a96f6 Answer stability round 5: a standing decision counts only if the repo held it before the chunk began 2026-10-04 16:51:13 +02:00
lilleman 406feffbce Answer prose round 4: fixed in the stability round 4 commit; the fall sentence, the changelog and the decision body read on one pass 2026-10-04 12:58:29 +02:00
lilleman 31f202650b Answer product-owner round 4: fixed in the stability round 4 commit 2026-10-04 12:58:29 +02:00
lilleman 809a1ed23b Answer stability round 4: only a decision letting every chunk ship under the floor stands in for the user, never the list of past ships 2026-10-04 12:58:29 +02:00
lilleman 124dc16459 Answer prose round 3: fixed in the owner's-answers commit 2026-10-04 12:55:57 +02:00
lilleman ed300dd630 Answer product-owner round 3: fixed in the owner's-answers commit 2026-10-04 12:55:57 +02:00
lilleman 847ba14aa0 Answer stability round 3: fixed in the owner's-answers commit 2026-10-04 12:55:57 +02:00
lilleman da55c778ed Record the owner's answers: drop the rebuild bar, fix at the lowest dimension, keep only the global baseline, a fall asks after three rounds 2026-10-04 12:55:57 +02:00
lilleman 6b0aac6198 Answer prose round 2: fixed in the stability round 2 commit; one consequence for floor and ratchet, under the floor throughout 2026-10-04 12:27:34 +02:00
lilleman 5ba01eefae Answer product-owner round 2: fixed in the stability round 2 commit; an existing comprehension bar stands beside the ratchet, never overwritten 2026-10-04 12:27:34 +02:00
lilleman 01bba7f4a5 Answer stability round 2: a seat's overall stays within one of its lowest dimension, a fall in the overall alone names the lowest dimension, the ratchet holds every bar the project's decisions set 2026-10-04 12:27:34 +02:00
lilleman 83c31db36b Answer security round 1: nothing to change 2026-10-04 12:25:32 +02:00
lilleman 86b42e57dd Answer prose round 1: fixed in the stability round 1 commit; the scoring run names the step, capping matches the decision 2026-10-04 12:25:32 +02:00
lilleman 0c5f362295 Answer product-owner round 1: fixed in the stability round 1 commit; no branch carries an old pass name 2026-10-04 12:25:32 +02:00
lilleman 2154c8bf28 Answer stability round 1: the ratchet reads the default branch's scores and points at each fallen dimension, a project without the entry gets one, the rebuild rule stays 2026-10-04 12:25:32 +02:00
lilleman f7b5f3ac1e Make larv-review's pass names and comprehension floor readable on their own 2026-10-04 12:20:50 +02:00
lilleman dd8d6a519b Merge pull request 'Bench a new syntax with its users, and never let comprehension fall' (#212) from claude-md-bench-and-ratchet into main 2026-10-04 12:11:23 +02:00
lilleman dd5cce9367 Bench a new syntax with its users, and never let comprehension fall 2026-10-04 12:11:15 +02:00
lilleman f8f87dfdd1 Merge pull request 'Keep every answer on record, so loop-claude does not ask it twice' (#211) from answers-on-record into main 2026-10-04 12:01:10 +02:00
lilleman f99588cc45 Answer product-owner round 5: nothing to change 2026-10-04 12:00:31 +02:00
lilleman 44f3e57708 Answer prose round 4: the list is in one constant, landed in the stability round 5 commit 2026-10-04 12:00:31 +02:00
lilleman 970f80a210 Answer stability round 5: one constant holds the places a written answer counts in; the prompts are unchanged 2026-10-04 12:00:31 +02:00
lilleman 0488189f8a Answer product-owner round 4: the judge names the places a written answer counts in 2026-10-04 11:38:40 +02:00
lilleman 1dd5c7bb72 Answer stability round 4: nothing to change 2026-10-04 11:37:57 +02:00
lilleman 9c6cc055e3 Answer prose round 3: nothing to change 2026-10-03 21:17:32 +02:00
lilleman 72ad23f7c2 Answer prose round 2: the resume prompt and the judge state the finish rule without a second reading 2026-10-03 21:17:17 +02:00
lilleman d23a2f4837 Answer product-owner round 3: the places just listed, never CLAUDE.md, land in the prose round 1 commit 2026-10-03 21:15:44 +02:00
lilleman cf243cc72c Answer prose round 1: one list of places for an answer, plainer help and changelog, the todo.md premise named 2026-10-03 21:15:44 +02:00
lilleman d14e854879 Answer product-owner round 2: "in one of" lands in the stability round 3 commit 2026-10-03 21:12:37 +02:00
lilleman 19baebd388 Answer stability round 3: credit CLAUDE.md only where it already holds an answer, never a worker's write to it 2026-10-03 21:12:37 +02:00
lilleman 3afc075079 Answer stability round 2: help rewrapped in the product-owner round 1 commit 2026-10-03 21:09:31 +02:00
lilleman a6207e55c0 Answer product-owner round 1: count an answer written where it belongs, todo.md and CLAUDE.md included, align help and changelog, file item 58 2026-10-03 21:09:31 +02:00
lilleman a43ef188d3 Answer stability round 1: count an answer the transcript shows written, give worker and judge one finish rule, cite CLAUDE.md by its heading, test a quoted answer that cannot be archived 2026-10-03 21:06:34 +02:00
lilleman 0d85574a98 Answer security round 1: nothing to change 2026-10-03 20:58:10 +02:00
lilleman a48ac5c16a Keep every answer on record: the judge reads CLAUDE.md, holds a chunk open for an unrecorded answer, and archives each answer it quotes 2026-10-03 20:57:24 +02:00
lilleman c28f4ecf6b Merge pull request 'Archive each verdict's evidence, and stamp each outcome with its UTC time' (#210) from archive-verdict-evidence into main 2026-10-03 20:50:08 +02:00
lilleman 2e046a976f Answer prose round 3: nothing to change 2026-10-03 20:49:22 +02:00
lilleman 3b5ddd145c Answer product-owner round 2: nothing to change 2026-10-03 20:48:59 +02:00
lilleman eb65cef466 Answer stability round 2: nothing to change 2026-10-03 20:48:59 +02:00
lilleman f60d646dfd Answer prose round 2: the changelog bullet takes one idea a sentence 2026-10-03 20:48:59 +02:00
lilleman f75408fba2 Answer product-owner round 1: fixed in the prose round 1 commit; quoted answers filed as item 57 2026-10-03 20:47:33 +02:00
lilleman aec15ccca7 Answer stability round 1: fixed in the prose round 1 commit 2026-10-03 20:47:33 +02:00
lilleman 915b9683d2 Answer prose round 1: the help text says what opens with the UTC time, the evidence reads as a blockquote 2026-10-03 20:47:33 +02:00
lilleman 47347ad0b0 Answer security round 1: nothing to change 2026-10-03 20:47:33 +02:00
lilleman 69ffd6c1a1 Archive each verdict's evidence, and stamp each outcome with its UTC time 2026-10-03 20:44:36 +02:00
lilleman 8e1cd07402 Merge pull request 'Record that the judge is to read CLAUDE.md whole' (#209) from judge-reads-claude-md into main 2026-10-03 20:40:11 +02:00
lilleman 8d321e6ae2 Answer prose round 3: nothing to change 2026-10-03 20:40:09 +02:00
lilleman dd4219e253 Answer prose round 2: the reason for reading CLAUDE.md whole reads on one pass 2026-10-03 20:39:45 +02:00
lilleman d1d7c56bed Answer prose round 1: the decision log holds the reason for reading CLAUDE.md whole; item 1 asks no reminder 2026-10-03 20:39:10 +02:00
lilleman d69d7010a0 Record that the judge is to read CLAUDE.md whole 2026-10-03 20:38:14 +02:00
lilleman 42a569a10c Merge pull request 'Fix the places the 2026-10-03 scoring runs named under Shape and Self-sufficiency' (#208) from comprehension-shape into main 2026-10-03 20:32:49 +02:00
lilleman c132f736e2 Answer prose round 5: nothing to change 2026-10-03 20:32:41 +02:00
lilleman 5af00ee603 Cover the bench's transcripts in goal 2 2026-10-03 20:31:44 +02:00
lilleman b04874bda3 Answer prose round 4: the floor record states only what the scores show, item 1 names its action 2026-10-03 19:44:50 +02:00
lilleman 3cdf130bf0 Record shipping under the comprehension floor, file its places and the human's answers 2026-10-03 19:43:56 +02:00
lilleman ba7047d889 Answer product-owner round 3: nothing to change 2026-10-03 18:24:27 +02:00
lilleman 0331a6d45e Answer prose round 3: nothing to change 2026-10-03 18:24:27 +02:00
lilleman 732c4a45b4 Answer stability round 2: nothing to change 2026-10-03 18:23:49 +02:00
lilleman c1ea5c4127 Answer product-owner round 2: fixed in the prose round 2 commit 2026-10-03 18:23:49 +02:00
lilleman 3766aed995 Answer prose round 2: the precedent title keeps the plan item's credit to the pass 2026-10-03 18:23:49 +02:00
lilleman b3a843a313 Answer security round 1: nothing to change 2026-10-03 18:21:33 +02:00
lilleman 68adaf316c Answer stability round 1: fixed in the prose round 1 commit 2026-10-03 18:21:33 +02:00
lilleman 82789d34fa Answer product-owner round 1: fixed in the prose round 1 commit 2026-10-03 18:21:33 +02:00
lilleman 7b38aed614 Answer prose round 1: precedent names what a pass skips on, the bench and floor-decision prose reads on one pass 2026-10-03 18:21:33 +02:00
lilleman 7f7d5d259f Answer architecture round 3: nothing to change 2026-10-03 18:16:53 +02:00
lilleman 38c2e24f96 Answer architecture round 2: the shared modules and the judge's reply contract are named for what they hold 2026-10-03 18:12:38 +02:00
lilleman d3613f45d4 Answer architecture round 1: Failure and the file modules get truthful homes, the interrupt question is a pure function, the judge grounds on what it saw 2026-10-03 18:06:56 +02:00
lilleman ae7c332ba3 Give the judge's contract one home in cycle/verdicts.py 2026-10-03 17:55:19 +02:00
lilleman 5f7d34b87d Give record, verdict and judge one meaning each 2026-10-03 17:53:25 +02:00
lilleman 9f75fe8c51 Move the modules rank_todo.py shares into bin/file_io/, inside reload's fingerprint 2026-10-03 17:52:02 +02:00
lilleman 848e25a36e Merge pull request 'Make larv-review §3 readable on its own, name its rules, and record each pass's rounds in the branch's log' (#207) from review-rules-named into main 2026-10-03 17:02:06 +02:00
lilleman d85b7a5ba0 Answer prose round 5: nothing to change 2026-10-03 17:02:01 +02:00
lilleman 38405b859a Answer stability round 4: nothing to change 2026-10-03 16:37:46 +02:00
lilleman dbdae79272 Answer prose round 4: the count reads titles holding the round's pattern 2026-10-03 16:37:46 +02:00
lilleman bb354001fe Answer stability round 3: fixed in the prose round 3 commit 2026-10-03 16:19:37 +02:00
lilleman 2fed341c1b Answer prose round 3: the later round's diff starts at the commit the previous round reviewed; the count reads only a title's prefix 2026-10-03 16:19:37 +02:00
lilleman b9584369ea Answer prose round 2: fixed in the stability round 2 commit 2026-10-03 16:18:49 +02:00
lilleman ccae14f1f0 Answer stability round 2: count against the fetched remote branch, the highest round named, the later round's diff taken locally 2026-10-03 16:18:49 +02:00
lilleman a7625512b3 Answer prose round 1: fixed in the stability round 1 commit 2026-10-03 16:17:19 +02:00
lilleman 91d29fc843 Answer security round 1: nothing to change 2026-10-03 16:17:19 +02:00
lilleman 09f2d71910 Answer stability round 1 and prose round 1: count rounds on the branch's own commits, push only when the gate runs, one commit format 2026-10-03 16:17:11 +02:00
lilleman bea0716bf5 Make larv-review §3 readable on its own, name its rules, and record each pass's rounds in the branch's log 2026-10-03 16:14:56 +02:00
lilleman c039ee35ce Merge pull request 'Make the judge's prompt readable on its own, ask once before the full scan, and sort imports by their first binding' (#206) from judge-readable into main 2026-10-03 16:12:25 +02:00
lilleman c736861272 Answer the round's nits: name the plugin, state the explanation once, one referent for --resume 2026-10-03 16:11:04 +02:00
lilleman 9d74a5c54e Answer prose round one: the chunk as the agent's current work, the release last in its list, one idea per comment, the changelog for its reader 2026-10-03 16:09:28 +02:00
lilleman 8f272dd87a Answer stability round one: keep the worker's "ready to cut" in the judge prompt 2026-10-03 16:06:39 +02:00
lilleman ce1ee9b6d2 Make the judge's prompt readable on its own, ask once before the full scan, and sort imports by their first binding 2026-10-03 16:02:02 +02:00
lilleman e9365c26fc Merge pull request 'Hand the security pass back to the run, and accept a judge's elided quote' (#205) from judge-quotes into main 2026-10-03 15:58:07 +02:00
lilleman 31ec74498c Answer round two: an answer quoted without elisions, unambiguous referents in --help, the changelog and the security line 2026-10-03 15:56:54 +02:00
lilleman 61b7b44243 Answer round one: the bench runs the security pass in a subagent, an unavailable skill is reported, the answer's strictness explained where it is checked, prose nits 2026-10-03 15:54:42 +02:00
lilleman b39bf5065e Hand the security pass back to the run, and accept a judge's elided quote 2026-10-03 15:49:10 +02:00
lilleman 41b3f4705b Merge pull request 'Give the judge what the project records and ten times more of the chunk's transcript' (#202) from judge-records into main 2026-10-03 15:44:22 +02:00
lilleman 07b88542ef Merge main; renumber the import-order item to 45 beside main's item 39 2026-10-03 15:44:17 +02:00
lilleman 2cd26461e8 Answer the last prose and stability nits: the judge's first rule and evidence wording, the floor entry's new paragraph, rewrap --help 2026-10-03 15:43:04 +02:00
lilleman e906ebc87b Ship under the floor: record PR #202's scores, rank the places the seats named after item 41 2026-10-03 15:40:48 +02:00
lilleman d1435684df Answer round eight: a quoted answer without a question fails the judge run, the first rule names the [loop] repeat, prose nits 2026-10-03 14:18:52 +02:00
lilleman 50e8056f4d Move the Markdown section parser out of premises into its own module; file the log loop's ellipsis crash as item 41 2026-10-03 14:13:30 +02:00
lilleman 28cbea70d4 Answer round seven: the judge's rules no longer contradict on a repeated question, QUOTE_SOURCES names README.md's Goals and Audience, the decision names its premise, file item 40 2026-10-03 12:13:57 +02:00
lilleman 74b7f4a4b9 File larv-review's security pass ending the run's turn as a defect 2026-10-03 11:57:31 +02:00
lilleman 2d46aa3b8f Fix under the floor's Shape: interrupt means only the human, QuotedAnswer names the verdict, one owner for the record files, Limited beside its cycle 2026-10-03 11:33:34 +02:00
lilleman fdc3bc38d4 Answer the prose pass's third round: name the three files in the worker's prompt, say They once named 2026-10-03 01:53:58 +02:00
lilleman 45b4030347 Match the help-limits test to the reworded sentence 2026-10-03 01:52:34 +02:00
lilleman 03cccd24f4 Answer the prose pass's second round: the quote goes with the fourth question only, name the three files the human sees 2026-10-03 01:51:47 +02:00
lilleman 0eb97e9e88 Answer the prose pass: name README.md beside the records, one idea per sentence in --help and the judge's rules, date the decision's revision 2026-10-03 01:49:33 +02:00
lilleman 80f1cc2dc9 Answer the stability pass's second round: say why a misquote is no failure, rewrap --help 2026-10-03 01:44:23 +02:00
lilleman 09fb7dcdd5 Answer the stability and product passes: print each records answer, name its question, drop a misquote to an interrupt, budget the whole prompt 2026-10-03 01:42:37 +02:00
lilleman 74d9df412e Name what the records-answer backstop bounds 2026-10-03 01:34:31 +02:00
lilleman 4eec8d74ff Answer the fifth round's nits: cycle holds worker runs, a test ties --help's limits to the constants 2026-10-03 01:34:25 +02:00
lilleman 9252884a55 Say in the changelog that only the fourth question carries the quote 2026-10-03 01:33:34 +02:00
lilleman 1839c8a19e Answer the fourth round: a repeated question goes to the human, three records answers a cycle as the backstop, the quote in the interrupt, the cycle redefined 2026-10-03 01:32:22 +02:00
lilleman 387c22087c Merge main 2026-10-03 01:29:26 +02:00
lilleman 8b3da15658 Merge pull request 'Add principle, a fifth exempt reason, for a finding of the principles audit' (#203) from principle-exempt into main 2026-10-03 01:13:28 +02:00
lilleman c42e6fe18f Put the changelog's condition first 2026-10-03 01:12:06 +02:00
lilleman 5699eb931f Say in the changelog that another Exempt reason comes first 2026-10-03 01:11:59 +02:00
lilleman 5e4f2a21a5 Answer the prose pass's second round: name whose detail, one idea per sentence 2026-10-03 01:11:31 +02:00
lilleman aacd5e42c2 Answer the product pass's second round: the skill's principle rule yields to any other reason 2026-10-03 01:11:23 +02:00
lilleman 9465075d3e Answer the stability pass: principle only where no other reason fits, and watch the items it marks 2026-10-03 01:10:37 +02:00
lilleman 3b416168e1 Answer the product pass: principle keeps a 🟡 only, names its principle, and the earlier reason wins 2026-10-03 01:09:38 +02:00
lilleman fb720b57e3 Name principle as the Exempt reason in the changelog 2026-10-03 01:09:13 +02:00
lilleman 002fb5aede Answer the prose pass: scope principle to the principles files, give a 🔴 defect 2026-10-03 01:09:07 +02:00
lilleman ef7066cf03 Add principle, a fifth exempt reason, for a finding of the principles audit 2026-10-03 01:08:03 +02:00
lilleman 2f46a13e5d Answer the third round: show the judge loop-claude's prompts, one records answer per cycle through an interrupt, name the answer's two sources apart 2026-10-03 00:54:16 +02:00
lilleman 160b1dae5f Answer the architect: fail a judge that answers without interrupting, read every checkout file through one function 2026-10-03 00:39:20 +02:00
lilleman 6340e5a993 Answer the first round: resume the worker with the records' answer to its question, read docs/decisions.md alone, scope --help's promise 2026-10-03 00:35:40 +02:00
lilleman 6d5d19bd69 Give the judge what the project records and ten times more of the chunk's transcript 2026-10-03 00:25:24 +02:00
lilleman 1568b3888d Merge pull request 'Install every plugin settings.json enables, and prove the bench's private files stay off the remote' (#201) from plugins-and-bench-ignore into main 2026-10-03 00:20:42 +02:00
52 changed files with 960 additions and 425 deletions
+5 -2
View File
@@ -17,10 +17,13 @@
!agents/
!agents/*.md
!bin/
!bin/failure.py
!bin/file_writes.py
!bin/loop-claude
!bin/loop_claude/
!bin/loop_claude/**/
!bin/loop_claude/**/*.py
!bin/markdown_sections.py
!bin/rank_todo.py
!bin/statusline.py
!bin/test_*.py
@@ -35,6 +38,6 @@
!skills/larv-review/*.md
!workflow-bench/
!workflow-bench/bench.py
!workflow-bench/judge-prompt.md
!workflow-bench/judge.py
!workflow-bench/compare-prompt.md
!workflow-bench/compare.py
!workflow-bench/run-prompt.md
+7 -4
View File
@@ -2,8 +2,8 @@
Decisions live in `docs/decisions.md`:
- larv-review: a project under the comprehension floor is fixed at the capping dimension
- loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing
- larv-review: a project under the comprehension floor is fixed at the lowest dimension
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md` and `~/.claude/CLAUDE.md`, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
- bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
@@ -12,7 +12,8 @@ Decisions live in `docs/decisions.md`:
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
- review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human
- review: a fix for a 🟢 or ❓ re-enters review like any fix
- review: a pass skips only on a record older than the chunk
- review: a project decision may suspend the scoring run for the plan items it names
- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
- loop-claude: a `claude` that cannot start is a failed worker run, retried
- review: an ask no user answers leaves the PR unmerged
@@ -20,11 +21,13 @@ Decisions live in `docs/decisions.md`:
- review: `/security-review` is the security pass of record
- 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
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items scored by the formula and goal weights it states, held to its bar, ranked by `bin/rank_todo.py`
## Working rules
- When `~/.claude/settings.json` has uncommitted changes, commit them on a branch of their own and merge them through a PR: Claude Code writes that file from any session.
- When `~/.claude/settings.json` has uncommitted changes, commit them on a branch of their own and merge them through a PR: Claude Code writes that file from any session. Read their diff first. When it holds a credential, such as a token in `env` or `mcpServers`, ask the human to move it out of the file, and commit only once it is gone. A token in `env` moves to the shell profile; a server in `mcpServers` moves to `~/.claude.json` with `claude mcp add --scope user`.
## Scoring run
+19 -1
View File
@@ -2,6 +2,24 @@
## Unreleased
- larv-review skips the comprehension scoring run for a chunk whose plan items a project decision names. The decision also names the later item whose scoring run ends the suspension. Neither the comprehension floor nor the ratchet can block a skipped chunk, its summary cites the decision, and a chunk shipping its release's last item is always measured.
- README → Install and Update give the commands that check the latest tag out into `~/.claude`: on a new machine, whether or not Claude Code has already created the directory, and on one already on an older tag.
- A session commits changes Claude Code made to `settings.json` only once their diff holds no credential, and asks you to move any credential out of the file first.
- A technical principle, "Sane defaults, where a default serves better than an explicit ask". A default suits a value most callers want, does no harm when wrong, and can be seen and changed. It lives at the program's edge, such as a CLI; a library still asks for data, the clock and randomness.
- larv-review's principles audit reads only the files under `~/.claude/principles/` that apply to the project, launching a file's auditor when unsure. A file's `Applies to` line says what it covers; one without the line covers every project. The summary names each file left out. After its first round, the architecture pass reruns the scoring run and only the reviewers whose 🔴 or 🟡 the fixes answer, unless the fixes carry an architectural decision.
- When `loop-claude`'s judge rules a chunk unfinished, the resumed worker is shown the passage the judge quoted as the work remaining. A loop started before this change exits 1 at its next reload; rerun it.
- larv-review's architecture pass and full security scan get short names, `Architecture` and `Full scan`. Each round's commit is titled with its pass's name in lower case: `Answer full scan round 1: …`.
- larv-review's comprehension floor now says, without another file open, what the scoring run measures. A project's `docs/decisions.md` keeps the last scoring run's scores, and a later run scoring below them blocks the merge until fixed. After three rounds larv-review asks you; an unattended run leaves the PR unmerged with the question. A PR under the floor that scores no lower than the last run merges once you decide to ship. A decision in `docs/decisions.md` that lets every chunk ship under the floor counts as yours. A project without those scores gets them at its next scoring run.
- `loop-claude`'s judge reads your `~/.claude/CLAUDE.md` beside the project's `AGENTS.md` and `docs/decisions.md`. It no longer interrupts for a choice that file settles, and it answers the worker's questions from it.
- `loop-claude`'s judge holds a chunk open until each answer you typed in it that a later chunk could need is recorded. An answer counts as recorded once the README's goals or audience, `AGENTS.md`, `docs/decisions.md` or `~/.claude/CLAUDE.md` hold it. It also counts once the transcript shows the worker writing it into the README's goals or audience, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. The worker writing to `~/.claude/CLAUDE.md` does not count, since new rules there are yours. The resumed worker is told this rule.
- `loop-claude` archives each answer the judge quotes, with the question it answers and its UTC time, in `<sha256>.outcomes.md`.
- larv-review keeps its three-round cap across a resumed session. It closes each review round with a commit naming the pass and the round, empty when the round changed nothing, and counts rounds from the branch's own commits.
- larv-review runs `/security-review` in a subagent, so the run goes on to the next pass without you prompting it.
- larv-review asks once before the full security scan: it states the evidence and its recommendation, and `claude-security`'s cost prompt is the ask.
- `loop-claude` accepts the judge's quote of the transcript when it elides with an ellipsis and the transcript holds each fragment in order. The transcript the judge reads, and the worker's printed output, show tool input with its non-ASCII characters as written, so the judge can quote it.
- Unless another Exempt reason fits, larv-review marks a `todo.md` item filed from a 🟡 finding against `~/.claude/principles/` with `principle`, an Exempt reason that keeps it whatever its score.
- `loop-claude`'s judge reads the project's `AGENTS.md` and `docs/decisions.md` beside the README's goals and audience, and does not interrupt for a choice they settle. When the worker asks a question that the README or those files answer, the worker resumes with the judge's quote of the answer, which `loop-claude` prints. A quote they do not hold word for word is dropped, and the question goes to you. So does a question asked again after its answer. The fourth question they answer in one cycle goes to you too, with the quote. The judge reads as much of the transcript's end as fits a 400,000-character prompt, up from the last 40,000 characters. `loop-claude` exits 1 when `AGENTS.md` or `docs/decisions.md` cannot be read or is not UTF-8.
- A project's decision log is `docs/decisions.md` alone, the one file the judge, `rank_todo.py` and the reviewers read.
- `loop-claude` waits out a usage limit and retries: 2 minutes past the reset, or every 10 minutes when the reset time is unknown. A limit is not a failure, and restarts the count of three failures in a row. It prints what claude said about the limit and when the next try is due.
- Add the official plugin marketplace and install every plugin `settings.json` enables (README → Install): `claude-security`, `code-review` and `rust-analyzer-lsp`, which needs `rust-analyzer` on `PATH` for Rust projects. With `claude-security`, larv-review's full security scan runs once you confirm its cost; an unattended larv-review reports the scan as not run. `settings.json` silences the plugin's scan tip after `git push`.
- systems-architect and product-owner-reviewer can no longer edit what they review; stability-reviewer keeps its shell to run tests, and loses Claude Code's file-editing tools.
@@ -20,6 +38,6 @@
- `loop-claude` retries a failed worker within its cycle.
- `loop-claude` counts an interrupt reply starting with `<` as typed.
- `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed.
- `loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and failures included, in one folder per chunk. Each distinct transcript is kept once, named by its SHA-256, with `<sha256>.verdict.md` beside it holding the verdict and why the loop stopped. The subagents' transcripts and the session's other files go in the chunk folder's `session/` subfolder. `loop-claude` exits 1 when it cannot archive.
- `loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and failures included, in one folder per chunk. Each distinct transcript is kept once, named by its SHA-256. Beside it, `<sha256>.outcomes.md` holds the verdict, with the transcript passage the judge rested it on, and why the loop stopped. The verdict and the stop each open with their UTC time. The subagents' transcripts and the session's other files go in the chunk folder's `session/` subfolder. `loop-claude` exits 1 when it cannot archive.
- `loop-claude` exits 1 when it cannot delete a finished chunk's session, naming what to delete before rerunning; the next chunk would otherwise resume it.
- `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600.
+6 -5
View File
@@ -13,6 +13,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, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once.
- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they name one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md` per "Todo items". An item marked `question` waits for the human; take the next item.
- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. If an answer is a goal and something else too, write the goal, and record a choice only for what the goal leaves open.
- **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the README's `## Audience`, picks it.
- **Ship every chunk with `/larv-review`.**
- **Remove a finished item's row and detail from `todo.md`, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record.
- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision.
@@ -26,17 +27,17 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
- **A** — its value to the audience in `README.md` → `## Audience`.
- **G** — its value to the goals it cites in the Goals column; W is the weight of the heaviest of them.
- **An item scoring under the bar is deleted, with every item that needs it, and a finding under the bar is not filed.** The chunk's summary names each, with its score.
- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding, `question` for a question only the human can answer, `decision` for an item `docs/decisions.md` cites. Every item `docs/decisions.md` cites carries one of these reasons.
- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding, `question` for a question only the human can answer, `decision` for an item `docs/decisions.md` cites, and, where no other reason fits, `principle` for a 🟡 finding against a file under `~/.claude/principles/`, whose item's detail names that principle. Every item `docs/decisions.md` cites carries one of these reasons.
- Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, under the next release, marked `security`, naming the exposure and the path it reaches. `rank_todo.py` ranks it first in its release. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
- **Unless the project has a reason to differ, weigh goals by position, the first heaviest.** When the weights stop listing the README's goals, `rank_todo.py` fails and prints those weights.
## Quality
Quality is proven by review. Every change is reviewed as a diff. The whole project is measured when a change carries an architectural decision, and before each release, because a project can drift from the principles one clean diff at a time. `larv-review` §3 says which review runs when. Quality has three parts. When two pull against each other, the earlier one wins.
Quality is proven by review. Every change is reviewed as a diff. The whole project is measured when a change carries an architectural decision, and before each release, because a project can drift from the principles one clean diff at a time. A project decision may suspend only the comprehension panel's scoring run (`larv-review` §3 → "Architecture" → "Suspended"). `larv-review` §3 says which review runs when. Quality has three parts. When two pull against each other, the earlier one wins.
1. **Correct.** The work does what the goals and the plan say, and tests prove it.
2. **True to the technical principles** (`~/.claude/principles/technical-principles.md`). The `comprehension-panel` skill scores KISS; a score under the comprehension floor (`larv-review` §3 → "Architecture") blocks a merge, and the aim is always higher.
2. **True to the technical principles** (`~/.claude/principles/technical-principles.md`). The `comprehension-panel` skill scores KISS; a score under the comprehension floor (`larv-review` §3 → "Architecture") blocks a merge. **Comprehension never falls:** a chunk starts from the last panel recorded on the default branch, and when its own panel scores any dimension or the overall lower, even within the panel's noise, improve what the readers named and score again. An equal score passes. After three such rounds, stop and ask the human.
3. **Plainly written**, per "Prose".
## Prose
@@ -87,7 +88,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`,
### Decisions: one home, each linked to a goal or a technical principle
**A choice that shapes what the code does, made in one place, is a comment there, with its reason. Made in more than one place, it is a decision, and the decision log owns it.** A decision's rejected alternative, or what it deliberately does not cover, stays out of every call site. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. A title states the whole decision in one line: what holds at the commit it ships in, in words a reader finds in the code or the plan. `AGENTS.md` lists every title, so a session works by the decisions without loading their background. A session reads the entry under a title only to question, revise or add a decision. The entry holds the background: its date, who made it, the reasoning, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A choice found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves: to a comment at its one place, or, once made in more than one place, to the log, leaving its title in `AGENTS.md`'s list. A goal stays a goal in the README; the log records only what the goal leaves open.
**A choice that shapes what the code does, made in one place, is a comment there, with its reason. Made in more than one place, it is a decision, and the decision log owns it.** A decision's rejected alternative, or what it deliberately does not cover, stays out of every call site. **The decision log has one home: `docs/decisions.md`**. A title states the whole decision in one line: what holds at the commit it ships in, in words a reader finds in the code or the plan. `AGENTS.md` lists every title, so a session works by the decisions without loading their background. A session reads the entry under a title only to question, revise or add a decision. The entry holds the background: its date, who made it, the reasoning, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A choice found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves: to a comment at its one place, or, once made in more than one place, to the log, leaving its title in `AGENTS.md`'s list. A goal stays a goal in the README; the log records only what the goal leaves open.
**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — "Ask, don't guess" under "Working loop" says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it.
@@ -151,7 +152,7 @@ The rules every project follows, compose-not-entangle first: `~/.claude/principl
## Vocabulary
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
- **cycle** — one worker run and the judge's verdict on it, in `loop-claude`.
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `AGENTS.md`, `docs/decisions.md` or `~/.claude/CLAUDE.md`.
- **gate** — the merge gate: the checks a PR passes before it merges.
- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
+32 -4
View File
@@ -1,11 +1,11 @@
# Claude Code configuration
My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; and `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review.
My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold projects to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; and `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review.
## Goals
1. Make my claude setup shareable between computers.
2. Keep my claude setup and the transcripts of unattended runs, backed up.
2. Keep my claude setup and the transcripts of unattended runs, the bench's included, backed up.
3. Leak nothing to the remote — no credentials, no transcripts, no memory files.
4. Get the highest quality out of Claude Code while interrupting me the least, so development scales.
1. Proven, stellar output quality: code, documentation and plans.
@@ -20,7 +20,17 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it.
## Install
Check out the latest tag in `~/.claude`, with 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:
Claude Code may already have created `~/.claude`, where `git clone` refuses to run, so make the repository in place:
```sh
mkdir -p ~/.claude && cd ~/.claude
git init
git remote add origin ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git
```
Then run Update's commands.
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:
```sh
claude plugin marketplace add anthropics/claude-plugins-official
@@ -31,9 +41,27 @@ claude plugin install rust-analyzer-lsp@claude-plugins-official
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run `loop-claude` only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt included, skips every permission prompt.
## Update
Move a machine that takes tagged releases to the latest tag. The move discards every uncommitted change to a file the latest tag tracks, such as a `settings.json` Claude Code wrote. List the uncommitted changes to files the checkout tracks, and the tag it is on:
```sh
cd ~/.claude
git fetch --tags origin
git status
```
To keep an uncommitted change, merge it per `AGENTS.md` → "Working rules" and cut a release ("Release") before moving: a machine gets only what a tag holds. Then move:
```sh
git checkout -f "$(git tag -l 'v*' --sort=-v:refname | head -n 1)"
```
Then do what `CHANGELOG.md` asks of each version since the old tag, such as a new step under Install.
## Release
Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that commit `v<version>`.
Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit `v<version>`, and push both.
## Tools
+1 -1
View File
@@ -19,7 +19,7 @@ You consider internal logic **only** when it directly affects an external surfac
## Your Review Method
Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` and `frontend.md`. `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change.
Before anything else, **read the shared principles** at `~/.claude/principles/`. Your territory is each file whose `Applies to` line names an external surface; `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change.
1. **Identify the change surface**: Read the recent changes and pinpoint what external behavior is affected. If the change is purely internal with no external impact, say so plainly and stop — don't manufacture concerns.
+1 -1
View File
@@ -10,7 +10,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
## First Steps
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
2. **Read every file in the shared principles** at `~/.claude/principles/` — not just `technical-principles.md`, also `frontend.md`, `logging.md`, and `rest-apis.md`. These are mandatory org guidelines; all code MUST comply. Map the relevant file(s) to the change (frontend PR → `frontend.md`; API PR → `rest-apis.md`; etc.). Re-read each time — they change. Flag violations prominently.
2. **Read every file in the shared principles** at `~/.claude/principles/`. These are mandatory org guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently.
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them.
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script in a temp dir, a targeted test run — before reporting it. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5. **Two passes minimum, then hunt absences.**
@@ -3,7 +3,7 @@ import os
import pathlib
import typing
from loop_claude.failure import Failure
from failure import Failure
def make_private(folder: pathlib.Path) -> None:
+7
View File
@@ -65,6 +65,13 @@ def human_text(entry: dict) -> str | None:
return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry))
# {"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."""
text = content(entry)
return text if entry.get("type") == "user" and entry.get("promptSource") == "sdk" and isinstance(text, str) else None
# What the human types while claude works, written only as this entry:
# {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": "human"}, "prompt": "B"}}
def queued_human_text(entry: dict) -> str | None:
+1 -1
View File
@@ -5,7 +5,7 @@ import pathlib
import shutil
import uuid
from loop_claude.failure import Failure
from failure import Failure
from loop_claude.paths import Paths
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
+5 -3
View File
@@ -1,7 +1,7 @@
import json
from loop_claude.claude_code.entries import assistant_parts, human_text, parse_entry, part_text, tool_call
from loop_claude.failure import Failure
from loop_claude.claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call
from failure import Failure
JUDGED_TOOL_INPUT = 400
@@ -30,6 +30,8 @@ def render(entries: list[dict]) -> str:
lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))]
if (text := human_text(entry)) is not None:
lines.append("[human] " + text)
elif (text := loop_text(entry)) is not None:
lines.append("[loop] " + text)
return "\n\n".join(lines)
@@ -38,5 +40,5 @@ def part_line(part: object, tool_input_chars: int) -> str:
return text
if call := tool_call(part):
name, arguments = call
return f"[tool {name}] {json.dumps(arguments)[:tool_input_chars]}"
return f"[tool {name}] {json.dumps(arguments, ensure_ascii=False)[:tool_input_chars]}"
return ""
+2 -2
View File
@@ -2,8 +2,8 @@ import json
import pathlib
import sys
from loop_claude.failure import Failure
from loop_claude.file_writes import replace_json
from failure import Failure
from file_writes import replace_json
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
+15 -13
View File
@@ -2,15 +2,16 @@ import hashlib
import os
import pathlib
import sys
import time
from loop_claude.claude_code.session import session_files
from failure import Failure
from loop_claude.claude_code.transcript import first_timestamped_line
from loop_claude.failure import Failure
from loop_claude.file_writes import make_private, replace_file
from file_writes import make_private, replace_file
from loop_claude.paths import Paths
from loop_claude.claude_code.session import session_files
def archive(project_key: str, path: str, task: str, outcome: str, paths: Paths) -> Failure | None:
def archive(project_key: str, path: str, task: str, outcome: str, at: float, paths: Paths) -> Failure | None:
try:
with open(path, "rb") as handle:
raw = handle.read()
@@ -23,11 +24,12 @@ def archive(project_key: str, path: str, task: str, outcome: str, paths: Paths)
if sibling != path and (unkept := mirror(pathlib.Path(sibling), folder / "session" / os.path.basename(sibling))):
return unkept
copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl"
verdict = copy.with_suffix(".verdict.md")
if copy.exists():
return add_outcome(verdict, outcome)
# The copy lands last, so a copy on disk always has its verdict and its session's files beside it.
for dest, data in ((verdict, f"Task: {task}\n\n{outcome}\n".encode()), (copy, raw)):
outcomes = copy.with_suffix(".outcomes.md")
stamped = f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(at))} {outcome}"
if copy.exists() and outcomes.exists():
return add_outcome(outcomes, stamped)
# The copy lands last, so a copy on disk always has its outcomes and its session's files beside it.
for dest, data in ((outcomes, f"Task: {task}\n\n{stamped}\n".encode()), (copy, raw)):
if unwritten := replace_file(dest, data):
return unarchived(dest, unwritten.reason)
print(f"transcript: {copy}", file=sys.stderr)
@@ -38,13 +40,13 @@ def unarchived(where: object, why: str | None) -> Failure:
return Failure(f"could not archive the transcript: {where}: {why}")
def add_outcome(verdict: pathlib.Path, outcome: str) -> Failure | None:
def add_outcome(outcomes: pathlib.Path, outcome: str) -> Failure | None:
try:
outcomes = verdict.read_bytes()
kept = outcomes.read_bytes()
except OSError as failure:
return unarchived(failure.filename, failure.strerror)
if unwritten := replace_file(verdict, outcomes + f"\n{outcome}\n".encode()):
return unarchived(verdict, unwritten.reason)
if unwritten := replace_file(outcomes, kept + f"\n{outcome}\n".encode()):
return unarchived(outcomes, unwritten.reason)
return None
+4 -4
View File
@@ -1,13 +1,13 @@
import sys
import uuid
from loop_claude.claude_code.transcript import human_turns, read_transcript
from loop_claude.claude_code.trust import trust
from loop_claude.effects import Effects
from loop_claude.failure import Failure
from failure import Failure
from loop_claude.claude_code.transcript import human_turns, read_transcript
from loop_claude.stop import needs_human, needs_terminal, Stop
from loop_claude.paths import Paths
from loop_claude.claude_code.trust import trust
from loop_claude.project.checkout import worktrees
from loop_claude.stop import Stop, needs_human, needs_terminal
ANSWER_QUESTION = "answer the question above"
+41 -71
View File
@@ -1,55 +1,19 @@
import dataclasses
import json
import typing
import re
from loop_claude.claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
from loop_claude.cycle.retry import retried
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict
from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.limited import Limited
from failure import Failure
from loop_claude.claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
from loop_claude.cycle.judge_reply import Interrupt, JUDGE_RULES, JUDGE_SCHEMA, QuotedAnswer, Verdict, verdict_from
from loop_claude.cycle.retry import Limited, retried
from loop_claude.stop import Stop
JUDGED_TRANSCRIPT_TAIL = 40000
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
"- the agent asks the human anything, seeks approval, or says a decision is the human's\n"
"- it carried on under an assumption that decides the deliverable and that the human could "
"reasonably reject; a caveat about transient state it then handled is not one\n"
"- it is blocked on something only the human can supply: a credential, a version bump, a release "
"ready to cut, a choice outside the repo\n"
"- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n"
"- it chose between alternatives the README text does not discriminate between - it does not "
"rule the rejected one out - and the choice materially changes the deliverable\n"
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
"where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
"is still open, never a question they already answered there.\n"
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
"wording; never construct another from facts it stated.\n"
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
"its own. finished=false when work remains that a further run can continue: an open PR, a review "
"not yet run, CI not yet reported."
)
@dataclasses.dataclass(frozen=True)
class Reply:
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining."})
finished: bool
interrupt: bool
question: str = dataclasses.field(metadata={"description": "The single question to put to the human. Empty when interrupt is false."})
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
JUDGE_PROMPT_CHARS = 400000
REPLY_TYPES = typing.get_type_hints(Reply)
JSON_TYPES = {bool: "boolean", str: "string"}
JUDGE_SCHEMA = {
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
"required": list(REPLY_TYPES),
"type": "object",
}
def judge(root: str, task: str, premises: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop:
def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop:
# --json-schema has claude check its reply against the schema and return it as the json result's structured_output.
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
args = [
"-p",
@@ -60,11 +24,11 @@ def judge(root: str, task: str, premises: str, rendered_transcript: str, model:
"--permission-mode", "bypassPermissions",
"--tools", "",
]
prompt = judge_prompt(task, premises, rendered_transcript)
return retried("judge", lambda: run_judge(root, args, prompt, rendered_transcript, effects), effects)
prompt, shown = judge_prompt(task, premises, records, rendered_transcript)
return retried("judge", lambda: run_judge(root, args, prompt, shown, f"{premises}\n\n{records}", effects), effects)
def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, effects: Effects) -> Verdict | Failure | Limited:
def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
try:
proc = effects.claude(args, root, prompt)
except OSError as failure:
@@ -78,38 +42,44 @@ def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str,
verdict = verdict_from(structured_output(reply))
if isinstance(verdict, Failure):
return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}")
if not grounded(verdict.evidence, rendered_transcript):
return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt) else ""))
if not grounded(verdict.evidence, shown):
return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else ""))
# Not a Failure: a misquote would otherwise exit an unattended loop. Never elided: stitched fragments can say what the records do not.
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable):
return Interrupt(verdict.evidence, verdict.question)
return verdict
def judge_prompt(task: str, premises: str, rendered_transcript: str) -> str:
return (
def judge_prompt(task: str, premises: str, records: str, rendered_transcript: str) -> tuple[str, str]:
"""The prompt, and the part of the transcript it shows, which the judge's evidence must quote."""
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"
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{rendered_transcript[-JUDGED_TRANSCRIPT_TAIL:]}\n\n"
f"{JUDGE_RULES}"
"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"
)
def verdict_from(output: object) -> Verdict | Failure:
if not isinstance(output, dict):
return Failure("the judge returned no reply")
for name, kind in REPLY_TYPES.items():
if not isinstance(output.get(name), kind):
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
# An interrupt outranks finished: the human answers before the chunk can close.
if output["interrupt"]:
if not output["question"].strip():
return Failure("the judge interrupted without a question")
return Interrupt(output["evidence"], output["question"])
return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"])
room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2)
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
shown = rendered_transcript[max(0, len(rendered_transcript) - room):]
return f"{head}{shown}\n\n{JUDGE_RULES}", shown
def grounded(evidence: str, rendered_transcript: str) -> bool:
quoted = plain(evidence)
return quoted != "" and quoted in plain(rendered_transcript)
# The judge joins passages with an ellipsis though told to quote one.
fragments = [fragment.strip() for fragment in re.split(r"\.\.\.|…", plain(evidence)) if fragment.strip()]
transcript = plain(rendered_transcript)
at = 0
for fragment in fragments:
found = transcript.find(fragment, at)
if found < 0:
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:
+104
View File
@@ -0,0 +1,104 @@
import dataclasses
import typing
from failure import Failure
from loop_claude.project.records import HUMAN_RULES, RECORD_FILES
# Where the judge may quote an answer from, named as the human and the worker see them; of README.md the judge sees only the premises.
QUOTE_SOURCES = "README.md's Goals and Audience, " + ", ".join(RECORD_FILES) + " or " + HUMAN_RULES
# Where the worker may write an answer the human typed, so it counts as recorded.
ANSWER_DESTINATIONS = "README.md's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
"- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither "
"README.md nor the records settle the matter\n"
"- it asks again a question a [loop] line already answered\n"
"- it carried on under an assumption that decides the deliverable, that the human could "
"reasonably reject and that neither README.md nor the records settle; a caveat about "
"transient state it then handled is not one\n"
"- it is blocked on something only the human can supply: a credential, a version bump, a choice "
"outside the repo, or a release ready to cut, which only the human may publish\n"
"- it flags that the goals, the plan in todo.md or the task itself is unclear, missing or in need of change\n"
"- it chose between alternatives that neither README.md nor the records discriminate "
"between - neither rules the rejected one out - and the choice materially changes the deliverable\n"
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
"where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
"is still open, never a question they already answered there. A [loop] line is what loop-claude told "
"the agent, such as an answer quoted from README.md or the records.\n"
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
"wording; never construct another from facts it stated.\n"
"Where README.md or the records answer the agent's own question and no [loop] line has "
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the agent is "
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
"outranks finished.\n"
"The chunk is the piece of work the agent is on, shipped as one pull request. "
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}. An answer counts as recorded "
f"where README.md or the records above hold it, {HUMAN_RULES} included. It also counts where "
f"the transcript shows the agent writing it into {ANSWER_DESTINATIONS}; writing it into "
f"{HUMAN_RULES} does not count. finished=false when work remains that a further run can "
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
)
@dataclasses.dataclass(frozen=True)
class Reply:
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."})
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the agent's question; else what shows the chunk finished or the work remaining."})
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."})
REPLY_TYPES = typing.get_type_hints(Reply)
JSON_TYPES = {bool: "boolean", str: "string"}
JUDGE_SCHEMA = {
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
"required": list(REPLY_TYPES),
"type": "object",
}
@dataclasses.dataclass(frozen=True)
class Interrupt:
evidence: str
question: str
@dataclasses.dataclass(frozen=True)
class QuotedAnswer:
"""The agent asked a question that README.md or the records answer. The answer field quotes the passage."""
evidence: str
question: str
answer: str
@dataclasses.dataclass(frozen=True)
class Finished:
evidence: str
@dataclasses.dataclass(frozen=True)
class Unfinished:
evidence: str
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
def verdict_from(output: object) -> Verdict | Failure:
if not isinstance(output, dict):
return Failure("the judge returned no reply")
for name, kind in REPLY_TYPES.items():
if not isinstance(output.get(name), kind):
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
if output["interrupt"]:
if not output["question"].strip():
return Failure("the judge interrupted without a question")
return Interrupt(output["evidence"], output["question"])
if output["answer"].strip():
if not output["question"].strip():
return Failure("the judge quoted an answer without a question")
return QuotedAnswer(output["evidence"], output["question"], output["answer"])
return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"])
+13 -4
View File
@@ -1,17 +1,26 @@
import dataclasses
import sys
import typing
from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.limited import Limited
from failure import Failure
from loop_claude.stop import Stop
T = typing.TypeVar("T")
FAILURES_RUNNING = 3
PAST_RESET = 120
RETRY_DELAY = 60
UNKNOWN_RESET_POLL = 600
@dataclasses.dataclass(frozen=True)
class Limited:
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
resets_at: int | None
said: str
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop:
failures = 0
while True:
@@ -27,10 +36,10 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec
if not isinstance(result, Failure):
return result
failures += 1
if failures == 3:
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)
effects.sleep(60)
effects.sleep(RETRY_DELAY)
def limit_wait(limited: Limited, now: float) -> float:
+50 -24
View File
@@ -1,19 +1,19 @@
import dataclasses
import typing
from loop_claude.claude_code.session import Session, delete_session, session_open, transcript_file
from loop_claude.claude_code.transcript import read_transcript, render
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working
from loop_claude.cycle.archive import archive
from loop_claude.claude_code.session import delete_session, Session, session_open, transcript_file
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.cycle.judge_reply import Finished, Interrupt, QUOTE_SOURCES, QuotedAnswer, Unfinished
from loop_claude.cycle.interrupt import interrupt
from loop_claude.cycle.judge import judge
from loop_claude.cycle.retry import retried
from loop_claude.cycle.states import Active, Answered, Archived, Closing, Ended, Event, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition
from loop_claude.cycle.verdicts import Finished, Unfinished
from loop_claude.cycle.worker import run_worker, worker_args
from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.paths import Paths
from loop_claude.project.model_choice import Models
from loop_claude.paths import Paths
from loop_claude.claude_code.transcript import read_transcript, render
from loop_claude.cycle.retry import retried
from loop_claude.cycle.worker import run_worker, worker_args
from loop_claude.stop import Stop
@@ -24,12 +24,15 @@ class Cycle:
paths: Paths
premises: str
project_key: str
records: str
# The evidence of the previous cycle's unfinished verdict, empty after any other.
remaining: str
root: str
session: Session
task: str
def run_cycle(cycle: Cycle) -> Stop | None:
def run_cycle(cycle: Cycle) -> Stop | Finished | Unfinished:
state: State = Working()
try:
while not isinstance(state, Ended):
@@ -39,57 +42,80 @@ def run_cycle(cycle: Cycle) -> Stop | None:
state = transition(state, event)
except KeyboardInterrupt:
return stopped(cycle, Stop(130, ""), "Ctrl-C")
return None
return state.verdict
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
path = transcript_file(cycle.session)
failure = archive(cycle.project_key, path, cycle.task, f"Stopped: {why}", cycle.paths) if path else None
failure = archive(cycle.project_key, path, cycle.task, f"Stopped: {why}", cycle.effects.now(), cycle.paths) if path else None
# A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once.
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
def step(cycle: Cycle, state: Active) -> Event | Stop:
match state:
case Working():
return work(cycle)
case Judging(transcript_path):
case Working(answered, _):
return work(cycle, answered)
case Judging(transcript_path, _):
return rule(cycle, transcript_path)
case Interrupting(transcript_path, question):
return ask(cycle, transcript_path, question)
case Interrupting(transcript_path, ruling, _):
return ask(cycle, transcript_path, ruling)
case Closing(transcript_path, verdict):
return close(cycle, transcript_path, verdict)
case _:
typing.assert_never(state)
def work(cycle: Cycle) -> WorkerRan | Stop:
def work(cycle: Cycle, answered: QuotedAnswer | None) -> WorkerRan | Stop:
if answered is not None:
print(f"\n=== {QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
if stop := keep_answer(cycle, answered):
return stop
# session_open runs inside the lambda: a failed attempt may have opened the session.
if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, session_open(cycle.session)), cycle.effects), cycle.effects):
if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, session_open(cycle.session), answered, quoted(cycle.remaining)), cycle.effects), cycle.effects):
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 keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None:
path = transcript_file(cycle.session)
if path and (failure := archive(cycle.project_key, path, cycle.task, f"Verdict: quoted answer\n\n{answered.question}\n\n{QUOTE_SOURCES} says:\n{quoted(answered.answer)}\n\nEvidence:\n{quoted(answered.evidence)}", cycle.effects.now(), cycle.paths)):
return Stop(1, failure.reason)
return None
def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
entries = read_transcript(transcript_path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
verdict = judge(cycle.root, cycle.task, cycle.premises, render(entries), cycle.models.judge, cycle.effects)
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, render(entries), cycle.models.judge, cycle.effects)
return verdict if isinstance(verdict, Stop) else Ruled(verdict)
def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop:
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | Stop:
question = question_for(ruling)
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: interrupt\n\n{question}", cycle.paths):
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: interrupt\n\n{question}\n\nEvidence:\n{quoted(ruling.evidence)}", cycle.effects.now(), cycle.paths):
return Stop(1, failure.reason)
return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or Answered()
return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or HumanAnswered()
def question_for(ruling: Interrupt | QuotedAnswer) -> str:
if isinstance(ruling, Interrupt):
return ruling.question
return f"{ruling.question}\n\n{QUOTE_SOURCES} says:\n{ruling.answer}\n\nThose files have answered {QUOTED_ANSWERS_PER_CYCLE} questions this cycle, the most allowed, so this one comes to you."
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
finished = isinstance(verdict, Finished)
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: {'finished' if finished else 'unfinished'}", cycle.paths):
if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: {'finished' if finished else 'unfinished'}\n\nEvidence:\n{quoted(verdict.evidence)}", cycle.effects.now(), cycle.paths):
return Stop(1, failure.reason)
if finished and (failure := delete_session(cycle.session)):
return Stop(1, failure.reason)
return Archived()
# Blockquoted, so evidence holding blank lines still ends visibly where the text after it starts.
def quoted(passage: str) -> str:
return "\n".join(f"> {line}" for line in passage.splitlines())
+26 -15
View File
@@ -1,22 +1,31 @@
import dataclasses
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict
from loop_claude.cycle.judge_reply import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
# A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records.
QUOTED_ANSWERS_PER_CYCLE = 3
@dataclasses.dataclass(frozen=True)
class Working:
"""The worker runs."""
"""The worker runs, resumed with an answer quoted from README.md or the records when there is one."""
answered: QuotedAnswer | None = None
quoted_answers: int = 0
@dataclasses.dataclass(frozen=True)
class Judging:
"""The judge rules; quoted_answers counts the questions README.md or the records answered this cycle, and an interrupt does not reset it."""
transcript_path: str
quoted_answers: int = 0
@dataclasses.dataclass(frozen=True)
class Interrupting:
"""The human answers; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
transcript_path: str
question: str
ruling: Interrupt | QuotedAnswer
quoted_answers: int = 0
@dataclasses.dataclass(frozen=True)
@@ -27,7 +36,7 @@ class Closing:
@dataclasses.dataclass(frozen=True)
class Ended:
"""The cycle is over."""
verdict: Finished | Unfinished
Active = Working | Judging | Interrupting | Closing
@@ -45,7 +54,7 @@ class Ruled:
@dataclasses.dataclass(frozen=True)
class Answered:
class HumanAnswered:
pass
@@ -54,20 +63,22 @@ class Archived:
pass
Event = WorkerRan | Ruled | Answered | Archived
Event = WorkerRan | Ruled | HumanAnswered | Archived
def transition(state: State, event: Event) -> State:
match state, event:
case Working(), WorkerRan(transcript_path):
return Judging(transcript_path)
case Judging(transcript_path), Ruled(Interrupt(question=question)):
return Interrupting(transcript_path, question)
case Judging(transcript_path), Ruled(Finished() | Unfinished() as verdict):
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(Interrupt() | QuotedAnswer() as ruling):
return Interrupting(transcript_path, ruling, quoted_answers)
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
return Closing(transcript_path, verdict)
# The human works in the interrupt's claude session, so the judge rules again on the transcript it leaves.
case Interrupting(transcript_path), Answered():
return Judging(transcript_path)
case Closing(), Archived():
return Ended()
case Interrupting(transcript_path, _, quoted_answers), HumanAnswered():
return Judging(transcript_path, quoted_answers)
case Closing(_, verdict), Archived():
return Ended(verdict)
raise ValueError(f"no transition from {state} on {event}")
-20
View File
@@ -1,20 +0,0 @@
import dataclasses
@dataclasses.dataclass(frozen=True)
class Interrupt:
evidence: str
question: str
@dataclasses.dataclass(frozen=True)
class Finished:
evidence: str
@dataclasses.dataclass(frozen=True)
class Unfinished:
evidence: str
Verdict = Interrupt | Finished | Unfinished
+13 -7
View File
@@ -1,9 +1,10 @@
from loop_claude.cycle.judge_reply import ANSWERS_RECORDED, QUOTE_SOURCES, QuotedAnswer
from loop_claude.claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
from loop_claude.claude_code.session import Session
from loop_claude.claude_code.transcript import part_line
from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.limited import Limited
from failure import Failure
from loop_claude.cycle.retry import Limited
from loop_claude.claude_code.transcript import part_line
from loop_claude.claude_code.session import Session
PRINTED_TOOL_INPUT = 160
@@ -37,11 +38,16 @@ def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure
return None if result is not None else Failure("claude exited 0 without a result event")
def worker_args(task: str, session: Session, model: str, resuming: bool) -> list[str]:
if resuming:
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session.id)]
def worker_args(task: str, session: Session, model: str, resuming: bool, answered: QuotedAnswer | None = None, remaining: str = "") -> list[str]:
if answered is not None:
start = ["-p", f"Your question: {answered.question}\n\n{QUOTE_SOURCES} answers it:\n\n{answered.answer}\n\nContinue the task.", "--resume", str(session.id)]
elif resuming:
ruled = f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{remaining}\n\n" if remaining else " "
start = ["-p", f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}.", "--resume", str(session.id)]
else:
# --session-id creates the session under the id loop-claude keeps; --resume continues that session.
start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.", "--name", session.name, "--session-id", str(session.id)]
# -p fails without --verbose under stream-json.
return [
*start,
"--output-format", "stream-json",
-8
View File
@@ -1,8 +0,0 @@
import dataclasses
@dataclasses.dataclass(frozen=True)
class Limited:
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
resets_at: int | None
said: str
+47 -26
View File
@@ -3,11 +3,21 @@
usage: loop-claude <task>
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads
the transcript against the premises and rules whether the chunk, the work of one PR, is finished.
premises; the task runs at the checkout root. Each cycle a worker runs the task. A judge then reads
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md
and the human's ~/.claude/CLAUDE.md, where they exist. It rules whether the chunk, the work of one
PR, is finished. A chunk stays unfinished until each answer the human typed in it that a later chunk
could need is recorded: the premises or the records hold it, or the transcript shows the worker
writing it into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the
worker made that the premises or the records settle is not asked about. When the worker asks a
question they answer, the judge quotes the answer, loop-claude prints it, and the worker resumes
with it. A quote they do not hold word for word is dropped, and the question goes to the human. So
does a question asked again after its answer. The fourth question they answer in one cycle goes to
the human too, with the quote.
A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume`
on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes
its session next cycle; the next chunk starts a fresh session.
its session next cycle, and the worker is shown the passage the judge quoted as the work remaining.
The next chunk starts a fresh session.
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
@@ -15,24 +25,27 @@ relative to ~/code, or to / outside it. The session is deleted when its chunk fi
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>.verdict.md
holds the verdict, and why the loop stopped. 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>.
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; each answer the judge
quoted, with the question it answers; 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>.
Every claude loop-claude starts runs the project's model, saved per <key> in
~/.claude/loop-claude-models.json and read each cycle; 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 interrupt; with both set, nothing is asked.
A change to bin/loop-claude or bin/loop_claude/**/*.py takes effect at the next cycle boundary, once
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.
Exit 1, saying why, when:
- no task is given
- git cannot start or finds no checkout
- README.md, or AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md where they exist, cannot be
read or is not UTF-8
- README.md holds no premises
- the models file cannot be read or written
- claude leaves no transcript
@@ -40,16 +53,17 @@ Exit 1, saying why, when:
- a finished chunk's session cannot be deleted
- claude cannot start for an interrupt
- python cannot start for a reload
- a reload cannot read the cycle number, checkout root and task the running script handed it,
likely because the edit changed that handover
- a reload cannot read the state the running script handed it, likely because the edit changed that
handover
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
a judge when claude cannot start or exits non-zero, or its reply misses or mistypes a field,
interrupts without a question, or quotes a line the transcript does not hold. A usage limit is
not a failure, and restarts the count of three: the worker or the judge is retried 2 minutes
after the limit resets, or every 10 minutes when the reset time is unknown or 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.
interrupts or quotes an answer without a question, or quotes a passage the transcript does not
hold; it holds an elided passage when each fragment appears in order.
A usage limit is not a failure, and restarts the count of three: the worker or the judge is
retried 2 minutes after the limit resets, or every 10 minutes when the reset time is unknown or
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:
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
@@ -63,15 +77,17 @@ import pathlib
import sys
import typing
from loop_claude.claude_code.session import session_for
from loop_claude.cycle.run import Cycle, run_cycle
from loop_claude.effects import Effects
from loop_claude.loop.reload import RELOAD_FLAG, LoopRun, decode_handed, exec_if_edited, fingerprint
from loop_claude.paths import Paths
from loop_claude.project.checkout import checkout_root, project_key
from loop_claude.cycle.run import Cycle, run_cycle
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
from loop_claude.effects import Effects
from loop_claude.project.model_choice import get_or_ask_models
from loop_claude.paths import Paths
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from loop_claude.claude_code.session import session_for
from loop_claude.stop import Stop
from loop_claude.cycle.judge_reply import Unfinished
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
@@ -98,12 +114,17 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
premises = read_premises(loop_run.root)
if isinstance(premises, Stop):
return premises
records = read_records(loop_run.root, paths.claude_md)
if isinstance(records, Stop):
return records
models = get_or_ask_models(key, paths, env, effects)
if isinstance(models, Stop):
return models
print(f"\n=== cycle {loop_run.cycle_number} ===", flush=True)
if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project_key=key, root=loop_run.root, session=session, task=loop_run.task)):
return stop
verdict = run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project_key=key, records=records, remaining=loop_run.remaining, root=loop_run.root, session=session, task=loop_run.task))
if isinstance(verdict, Stop):
return verdict
loop_run = dataclasses.replace(loop_run, remaining=verdict.evidence if isinstance(verdict, Unfinished) else "")
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
@@ -112,8 +133,8 @@ def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopR
if task in ("", "-h", "--help"):
return Stop(0 if task else 1, __doc__.strip())
root = checkout_root(cwd, effects)
return root if isinstance(root, Stop) else LoopRun(0, root, task)
return root if isinstance(root, Stop) else LoopRun(0, "", root, task)
loop_run = decode_handed(argv[1], LoopRun) if len(argv) == 2 else None
if not (loop_run and loop_run.root and loop_run.task):
return Stop(1, f"the edited loop-claude cannot read the cycle number, checkout root and task the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
return Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
return loop_run
+2 -1
View File
@@ -17,6 +17,7 @@ T = typing.TypeVar("T")
class LoopRun:
"""What a reload hands the edited script, as JSON on argv."""
cycle_number: int
remaining: str
root: str
task: str
@@ -36,7 +37,7 @@ def decode_handed(handed: str, kind: type[T]) -> T | None:
def fingerprint(launcher: pathlib.Path) -> str:
digest = hashlib.sha256()
for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]:
for path in [launcher, *sorted(launcher.parent.rglob("*.py"))]:
try:
content = path.read_bytes()
except OSError as failure:
+2
View File
@@ -7,6 +7,7 @@ import typing
class Paths:
claude_code_transcripts: pathlib.Path
claude_json: pathlib.Path
claude_md: pathlib.Path
code: pathlib.Path
model_catalog: pathlib.Path
models_file: pathlib.Path
@@ -18,6 +19,7 @@ def paths_from(home: pathlib.Path, env: typing.Mapping[str, str]) -> Paths:
return Paths(
claude_code_transcripts=claude / "projects",
claude_json=home / ".claude.json",
claude_md=claude / "CLAUDE.md",
code=home / "code",
model_catalog=claude / "cache" / "model-catalog",
models_file=claude / "loop-claude-models.json",
+10
View File
@@ -27,3 +27,13 @@ def worktrees(root: str, effects: Effects) -> list[str]:
def project_key(root: str, code: pathlib.Path) -> str:
return root.removeprefix(f"{code}/").lstrip("/")
def read_utf8(folder: str, name: str, consequence: str) -> str | Stop:
try:
return pathlib.Path(folder, name).read_text(encoding="utf-8")
except OSError as failure:
return Stop(1, f"{name} in {folder}: {failure.strerror} - {consequence}.")
except UnicodeDecodeError as failure:
line = failure.object.count(b"\n", 0, failure.start) + 1
return Stop(1, f"{name} in {folder} is not UTF-8 on line {line} - {consequence}.")
+3 -3
View File
@@ -6,10 +6,10 @@ import typing
from loop_claude.claude_code.model_catalog import catalog_models
from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.file_writes import replace_json
from failure import Failure
from loop_claude.stop import needs_human, needs_terminal, Stop
from loop_claude.paths import Paths
from loop_claude.stop import Stop, needs_human, needs_terminal
from file_writes import replace_json
@dataclasses.dataclass(frozen=True)
+6 -36
View File
@@ -1,19 +1,13 @@
import pathlib
import re
from loop_claude.project.checkout import read_utf8
from markdown_sections import sections
from loop_claude.stop import Stop
FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M)
def read_premises(root: str) -> str | Stop:
try:
found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8"))
except OSError as failure:
return Stop(1, f"README.md in {root}: {failure.strerror} - no premises.")
except UnicodeDecodeError as failure:
line = failure.object.count(b"\n", 0, failure.start) + 1
return Stop(1, f"README.md is not UTF-8 on line {line} - no premises.")
text = read_utf8(root, "README.md", "no premises")
if isinstance(text, Stop):
return text
found = sections(text)
for name in ("Goals", "Audience"):
bodies = found.get(name, [])
if not bodies:
@@ -23,27 +17,3 @@ def read_premises(root: str) -> str | Stop:
if not bodies[0]:
return Stop(1, f"README.md has nothing under ## {name} - no premises.")
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
def sections(text: str) -> dict[str, list[str]]:
blocks: list[tuple[str | None, list[str]]] = []
opener = ""
for line in text.splitlines():
if fence := FENCE.match(line):
marker = fence.group(1)
if not opener:
opener = marker
elif marker[0] == opener[0] and len(marker) >= len(opener) and not line[fence.end():].strip():
opener = ""
fenced = bool(opener or fence)
if not fenced and line.startswith("## "):
blocks.append((line.strip()[3:], []))
elif not fenced and line.startswith("# "):
blocks.append((None, []))
elif blocks and line.strip():
blocks[-1][1].append(line)
found: dict[str, list[str]] = {}
for name, body in blocks:
if name is not None:
found.setdefault(name, []).append("\n".join(body))
return found
+22
View File
@@ -0,0 +1,22 @@
import pathlib
from loop_claude.project.checkout import read_utf8
from loop_claude.stop import Stop
# The records: these project files and HUMAN_RULES; the judge reads them beside the README's premises.
RECORD_FILES = ("AGENTS.md", "docs/decisions.md")
HUMAN_RULES = "~/.claude/CLAUDE.md"
def read_records(root: str, claude_md: pathlib.Path) -> str | Stop:
"""The project's record files, then the human's rules for every project, each headed by its name; a file that does not exist is left out."""
sources = [(root, name, name) for name in RECORD_FILES] + [(str(claude_md.parent), claude_md.name, HUMAN_RULES)]
records = []
for folder, name, heading in sources:
if not pathlib.Path(folder, name).exists():
continue
text = read_utf8(folder, name, "the judge cannot read the records")
if isinstance(text, Stop):
return text
records.append(f"From {heading}:\n{text.strip()}")
return "\n\n".join(records)
+27
View File
@@ -0,0 +1,27 @@
import re
FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M)
def sections(text: str) -> dict[str, list[str]]:
blocks: list[tuple[str | None, list[str]]] = []
opener = ""
for line in text.splitlines():
if fence := FENCE.match(line):
marker = fence.group(1)
if not opener:
opener = marker
elif marker[0] == opener[0] and len(marker) >= len(opener) and not line[fence.end():].strip():
opener = ""
fenced = bool(opener or fence)
if not fenced and line.startswith("## "):
blocks.append((line.strip()[3:], []))
elif not fenced and line.startswith("# "):
blocks.append((None, []))
elif blocks and line.strip():
blocks[-1][1].append(line)
found: dict[str, list[str]] = {}
for name, body in blocks:
if name is not None:
found.setdefault(name, []).append("\n".join(body))
return found
+7 -8
View File
@@ -41,9 +41,9 @@ A valid todo.md; ## Details and each item's detail are optional:
- A new item takes Next ID, and Next ID then goes up by one; every ID stays below it.
- The goal weights list README.md's numbered goals in order, a sub-goal such as 1.1 included.
- An item's R, S, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated.
- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect, question
or security. An item docs/decisions.md cites as "`todo.md` item N" must be exempt, and a row
marked decision must be cited there.
- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect,
principle, question or security. An item docs/decisions.md cites as "`todo.md` item N" must be
exempt, and a row marked decision must be cited there.
- An item's Item cell is one bold tagline; its detail, if any, sits under its ID in ## Details.
Exit 1, saying why, on bad arguments, a file that cannot be read or written, a todo.md, README.md or
@@ -57,12 +57,11 @@ import pathlib
import re
import sys
# Kept inside loop_claude/ so reload's fingerprint covers them.
from loop_claude.failure import Failure
from loop_claude.file_writes import replace_file
from loop_claude.project.premises import FENCE, sections
from failure import Failure
from markdown_sections import FENCE, sections
from file_writes import replace_file
EXEMPTIONS = ("", "decision", "defect", "question", "security")
EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
LARGEST_FORMULA = 200
LONGEST_FORMULA = 4 * LARGEST_FORMULA
+22
View File
@@ -0,0 +1,22 @@
import os
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from failure import Failure
import file_writes
class ReplaceFile(unittest.TestCase):
def test_removes_what_it_staged_when_the_replace_fails(self):
with tempfile.TemporaryDirectory() as root:
os.mkdir(os.path.join(root, "in-the-way"))
self.assertEqual(file_writes.replace_file(pathlib.Path(root, "in-the-way"), b"data"), Failure("Is a directory"))
self.assertEqual(os.listdir(root), ["in-the-way"])
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -27,7 +27,7 @@ PRIVATE = [
"tasks/a/b.json",
"workflow-bench/a-1-1.md",
"workflow-bench/a-1-1/README.md",
"workflow-bench/judge/a/A1/fixes.diff",
"workflow-bench/compare/a/A1/fixes.diff",
"workflow-bench/logs/a.jsonl",
]
+29
View File
@@ -0,0 +1,29 @@
import ast
import subprocess
import unittest
from test_python_floor import ROOT
def bound(node: ast.Import | ast.ImportFrom) -> list[str]:
return [alias.asname or alias.name for alias in node.names]
def unsorted_imports(source: str) -> list[int]:
"""The line numbers of imports whose names are out of order, or whose first name sorts before the first name of the import on the line above, ignoring case."""
imports = [node for node in ast.parse(source).body if isinstance(node, ast.Import | ast.ImportFrom)]
names_out = [node.lineno for node in imports if bound(node) != sorted(bound(node), key=str.casefold)]
lines_out = [node.lineno for above, node in zip(imports, imports[1:]) if node.lineno == above.end_lineno + 1 and bound(node)[0].casefold() < bound(above)[0].casefold()]
return sorted(set(names_out + lines_out))
class ImportOrder(unittest.TestCase):
def test_each_python_file_sorts_its_imports_by_their_first_binding(self):
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
self.assertIn("bin/loop-claude", listed)
for name in listed:
with self.subTest(name):
self.assertEqual(unsorted_imports((ROOT / name).read_text(encoding="utf-8")), [])
def test_a_case_insensitive_name_out_of_order_is_found(self):
self.assertEqual(unsorted_imports("import B\nimport a\n\nfrom x import C, b\n"), [2, 4])
+199 -63
View File
@@ -16,15 +16,15 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude import file_writes, paths
from loop_claude.claude_code import entries, session, transcript, trust
from loop_claude.cycle import archive, interrupt, judge, retry, run, states, worker
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished
from loop_claude.project import checkout, model_choice, records
from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.limited import Limited
from loop_claude.claude_code import entries, session, transcript, trust
from failure import Failure
from loop_claude.cycle.judge_reply import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from
from loop_claude.cycle.retry import Limited
from loop_claude.loop import main, reload
from loop_claude.project import checkout, model_choice, premises
from loop_claude import paths
from loop_claude.stop import Stop
CWD = pathlib.Path("/c")
@@ -91,8 +91,8 @@ def ran(stdout="", code=0, stderr=""):
return subprocess.CompletedProcess([], code, stdout, stderr)
def judged(verdict, evidence="working"):
reply = {"evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict == "interrupt" else ""}
def judged(verdict, evidence="working", answer=""):
reply = {"answer": answer, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else ""}
return ran(json.dumps({"structured_output": reply}))
@@ -127,19 +127,29 @@ class Streamed:
class Transitions(unittest.TestCase):
def test_each_state_moves_on_its_events_and_only_on_them(self):
answered = states.Ruled(QuotedAnswer("e", "Which one?", "A."))
legal = (
(states.Working(), states.WorkerRan("/t"), states.Judging("/t")),
(states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")),
(states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
(states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"))),
(states.Judging("/t", 3), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"), 3)),
(states.Judging("/t"), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 1)),
(states.Judging("/t", 2), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 3)),
(states.Judging("/t", 3), answered, states.Interrupting("/t", QuotedAnswer("e", "Which one?", "A."), 3)),
(states.Judging("/t"), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
(states.Interrupting("/t", "q"), states.Answered(), states.Judging("/t")),
(states.Closing("/t", Finished("e")), states.Archived(), states.Ended()),
(states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanAnswered(), states.Judging("/t")),
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanAnswered(), states.Judging("/t", 3)),
(states.Closing("/t", Finished("e")), states.Archived(), states.Ended(Finished("e"))),
(states.Closing("/t", Unfinished("e")), states.Archived(), states.Ended(Unfinished("e"))),
)
for state, event, after in legal:
with self.subTest(state=state, event=event):
self.assertEqual(states.transition(state, event), after)
every_state = (states.Working(), states.Judging("/t"), states.Interrupting("/t", "q"), states.Closing("/t", Finished("e")), states.Ended())
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.Answered(), states.Archived())
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.HumanAnswered(), states.Archived())
for state in every_state:
for event in every_event:
if (state, event) not in [(state, event) for state, event, _ in legal]:
@@ -147,6 +157,17 @@ class Transitions(unittest.TestCase):
states.transition(state, event)
class QuestionFor(unittest.TestCase):
def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self):
self.assertEqual(run.question_for(Interrupt("e", "Which one?")), "Which one?")
self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
class Quoted(unittest.TestCase):
def test_quotes_every_line_of_a_passage_blank_ones_included(self):
self.assertEqual(run.quoted("merged\n\nPR #1"), "> merged\n> \n> PR #1")
class Cycles(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
@@ -155,34 +176,35 @@ class Cycles(unittest.TestCase):
self.paths = paths.paths_from(self.home, {})
self.session = session.session_for("proj", self.paths)
def cycle(self, fake):
return run.Cycle(effects=fake.effects(), models=model_choice.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_key="proj", root=str(self.home), session=self.session, task="Do it.")
def cycle(self, fake, records="", remaining=""):
return run.Cycle(effects=fake.effects(), models=model_choice.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_key="proj", records=records, remaining=remaining, root=str(self.home), session=self.session, task="Do it.")
def archived_verdicts(self):
return sorted(path.read_text() for path in (self.paths.transcript_archive / "proj").glob("*/*.verdict.md"))
def archived_outcomes(self):
return sorted(path.read_text() for path in (self.paths.transcript_archive / "proj").glob("*/*.outcomes.md"))
def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"])
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n"])
self.assertIsNone(session.transcript_file(self.session))
def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session(self):
def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session_with_the_judges_evidence(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
self.assertTrue(session.transcript_file(self.session))
self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertEqual(run.run_cycle(self.cycle(fake, remaining="working")), Unfinished("working"))
workers = fake.made("stream_claude")
self.assertIn("--session-id", workers[0])
self.assertIn("--resume", workers[1])
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: unfinished\n"] * 2)
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"] * 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_verdicts(), ["Task: Do it.\n\nStopped: Ctrl-C\n", "Task: Do it.\n\nStopped: the judge failed three times running: the judge exited 1\n"])
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n"])
def test_archives_each_chunks_session_folder_replacing_a_copy_only_with_what_grew_from_it(self):
folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id)
@@ -192,7 +214,7 @@ class Cycles(unittest.TestCase):
(folder / "custom-title.json").write_text("first")
(folder.parent / f"{self.session.id}.orphaned-1.jsonl").write_text("o\n")
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 3, claude=[judged("unfinished"), judged("finished"), judged("unfinished")])
self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
[chunk] = (self.paths.transcript_archive / "proj").iterdir()
kept = chunk / "session" / str(self.session.id)
self.assertEqual((chunk / "session" / f"{self.session.id}.orphaned-1.jsonl").read_text(), "o\n")
@@ -200,7 +222,7 @@ class Cycles(unittest.TestCase):
with open(folder / "subagents" / "agent-a.jsonl", "a") as handle:
handle.write("more\n")
(folder / "custom-title.json").write_text("second")
self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
self.assertFalse(folder.exists())
self.assertEqual((kept / "subagents" / "agent-a.jsonl").read_text(), "a\nmore\n")
self.assertEqual((kept / "subagents" / "workflows" / "journal.jsonl").stat().st_mtime, 0)
@@ -208,7 +230,7 @@ class Cycles(unittest.TestCase):
self.assertEqual(stat.S_IMODE((kept / "subagents" / "agent-a.jsonl").stat().st_mode), 0o600)
folder.mkdir()
(folder / "custom-title.json").write_text("third")
self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
[next_chunk] = set((self.paths.transcript_archive / "proj").iterdir()) - {chunk}
self.assertEqual(sorted(path.read_text() for path in (next_chunk / "session" / str(self.session.id)).glob("custom-title.json*")), ["third"])
@@ -227,14 +249,43 @@ 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("unfinished")], on_terminal_claude=[answer], git=[ran()])
self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n", "Task: Do it.\n\nVerdict: unfinished\n"])
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n"])
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
prompts = [stdin for args, stdin in fake.made("claude")]
self.assertEqual(len(prompts), 2)
self.assertNotIn("the second", prompts[0])
self.assertIn("[human] the second", prompts[1])
def test_a_question_the_records_answer_resumes_the_worker_with_the_answer_three_times_a_cycle(self):
answered = judged("quoted", answer="Use *A*.")
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=[answered] * 4, on_terminal_claude=[0], git=[ran()])
with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed:
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
resumed = fake.made("stream_claude")[1]
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md answers it:\n\nUse *A*.\n\nContinue the task.")
self.assertEqual(len(fake.made("stream_claude")), 4)
self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md answered: Which one? ===\nUse *A*."), 3)
self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
quoted = "2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md says:\n> Use *A*.\n\nEvidence:\n> working\n"
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md or ~/.claude/CLAUDE.md says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
def test_stops_when_a_quoted_answer_cannot_be_archived(self):
self.paths.transcript_archive.parent.mkdir(parents=True)
self.paths.transcript_archive.write_text("")
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use A.")])
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(1, f"could not archive the transcript: {self.paths.transcript_archive / 'proj'}: Not a directory"))
self.assertEqual(len(fake.made("stream_claude")), 1)
def test_an_answer_the_records_do_not_hold_is_dropped_and_the_question_goes_to_the_human(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use ... A.")], on_terminal_claude=[0], git=[ran()])
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 the interrupt ended with nothing typed"))
self.assertEqual(len(fake.made("stream_claude")), 1)
self.assertIn("\nWhich one?\n", said.getvalue())
self.assertNotIn("Use ... A.", said.getvalue())
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
def test_stops_keeping_the_transcript_when_the_finished_chunks_session_cannot_be_deleted(self):
folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id)
@@ -245,7 +296,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_verdicts(), [f"Task: Do it.\n\nVerdict: finished\n\nStopped: {stop.reason}\n"])
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n"])
def test_stops_when_the_worker_leaves_no_transcript(self):
fake = FakeEffects(streams=[Streamed(0)])
@@ -295,7 +346,7 @@ class Limits(unittest.TestCase):
def test_the_judge_reports_a_limit_whatever_its_exit_code(self):
reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"})
fake = FakeEffects(claude=[ran(reply, code=1, stderr="limited")])
self.assertEqual(judge.run_judge("/r", [], "", "", fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"))
self.assertEqual(judge.run_judge("/r", [], "", "", "", fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"))
def test_reads_only_a_rejecting_events_whole_seconds(self):
for info, want in [({"status": "rejected", "resetsAt": NOW}, NOW), ({"status": "allowed", "resetsAt": NOW}, None), ({"status": "rejected", "resetsAt": True}, None), ({"status": "rejected"}, None), ("rejected", None)]:
@@ -346,21 +397,35 @@ class WorkerArgs(unittest.TestCase):
resumed = worker.worker_args("Do it.", opened, "m", True)
self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id))
self.assertNotIn("Do it.", " ".join(resumed))
self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once"))
class Sections(unittest.TestCase):
def test_keeps_every_headed_section_with_its_bodies(self):
text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n"
self.assertEqual(premises.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]})
class Records(unittest.TestCase):
def test_heads_each_record_by_its_name_the_humans_rules_last(self):
with tempfile.TemporaryDirectory() as root:
claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md")
self.assertEqual(records.read_records(root, claude_md), "")
claude_md.parent.mkdir(parents=True)
claude_md.write_text("# Global\n")
self.assertEqual(records.read_records(root, claude_md), "From ~/.claude/CLAUDE.md:\n# Global")
pathlib.Path(root, "docs").mkdir()
pathlib.Path(root, "docs", "decisions.md").write_text("# Decisions\n")
pathlib.Path(root, "AGENTS.md").write_text("\n# Rules\n")
self.assertEqual(records.read_records(root, claude_md), "From AGENTS.md:\n# Rules\n\nFrom docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global")
def test_closes_a_fence_only_on_its_own_marker(self):
text = "## Goals\n````md\n~~~\n## Quoted\n```\n````\n ~~~\n## Also quoted\n ~~~\n1. one\n## Audience\nme\n"
self.assertEqual(list(premises.sections(text)), ["Goals", "Audience"])
self.assertEqual(list(premises.sections("```\nquoted:\n```python\n## Inside\n```\n## Goals\n1. one\n")), ["Goals"])
def test_stops_on_a_record_it_cannot_read(self):
with tempfile.TemporaryDirectory() as root:
claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md")
claude_md.mkdir(parents=True)
self.assertEqual(records.read_records(root, claude_md), Stop(1, f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records."))
pathlib.Path(root, "docs", "decisions.md").mkdir(parents=True)
self.assertEqual(records.read_records(root, claude_md), Stop(1, f"docs/decisions.md in {root}: Is a directory - the judge cannot read the records."))
pathlib.Path(root, "AGENTS.md").write_bytes(b"# Rules\n\xff\n")
self.assertEqual(records.read_records(root, claude_md), Stop(1, f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records."))
class Render(unittest.TestCase):
def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self):
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self):
said = transcript.render([
human("do it"),
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
@@ -372,7 +437,21 @@ class Render(unittest.TestCase):
queued("origin/main moved", "coordinator"),
{**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"},
])
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work')
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.')
class Archive(unittest.TestCase):
def test_writes_afresh_a_copy_whose_outcomes_file_is_missing(self):
with tempfile.TemporaryDirectory() as root:
kept = paths.paths_from(pathlib.Path(root), {})
transcript = pathlib.Path(root, "t.jsonl")
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(archive.archive("proj", str(transcript), "Do it.", "Verdict: unfinished", NOW, kept))
(outcomes,) = kept.transcript_archive.glob("proj/*/*.outcomes.md")
outcomes.unlink()
self.assertIsNone(archive.archive("proj", str(transcript), "Do it.", "Stopped: Ctrl-C", NOW, kept))
self.assertEqual(outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n")
class CopyFor(unittest.TestCase):
@@ -421,6 +500,7 @@ class PartLine(unittest.TestCase):
self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}, 20), "")
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
self.assertEqual(transcript.part_line("not a part", 20), "")
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Write", "input": {"content": "Hälsa på"}}, 40), '[tool Write] {"content": "Hälsa på"}')
class Parse(unittest.TestCase):
@@ -439,6 +519,15 @@ class MarkTrusted(unittest.TestCase):
self.assertEqual(trust.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"]))
class JudgePrompt(unittest.TestCase):
def test_shows_the_transcripts_tail_and_returns_what_it_showed(self):
prompt, shown = judge.judge_prompt("Do it.", "## Goals", "", "old " + "x" * judge.JUDGE_PROMPT_CHARS + " new")
self.assertTrue(shown.endswith(" new"))
self.assertNotIn("old", shown)
self.assertIn(shown, prompt)
self.assertLessEqual(len(prompt), judge.JUDGE_PROMPT_CHARS)
class Grounded(unittest.TestCase):
def test_every_verdict_must_quote_the_transcript(self):
self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n"))
@@ -450,23 +539,38 @@ class Grounded(unittest.TestCase):
self.assertTrue(judge.grounded("Your step: ``` ./run.sh ``` Run it.", transcript))
self.assertFalse(judge.grounded("**", transcript))
def test_an_elided_quote_holds_when_its_fragments_appear_in_order(self):
transcript = "**Decision for you:** security, or not.\n\nI recommend one more round of each.\n\nI recommend skipping it: it costs."
self.assertTrue(judge.grounded("**Decision for you:** security, … ... I recommend one more round of each ... I recommend skipping it: …", transcript))
self.assertFalse(judge.grounded("I recommend skipping it ... Decision for you", transcript))
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(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e"))
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e"))
self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?"))
self.assertEqual(judge.verdict_from({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question"))
self.assertEqual(judge.verdict_from(None), Failure("the judge returned no reply"))
self.assertEqual(verdict_from({"answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e"))
self.assertEqual(verdict_from({"answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e"))
self.assertEqual(verdict_from({"answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A."))
self.assertEqual(verdict_from({"answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"answer": "", "interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
class LoopRuns(unittest.TestCase):
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "remaining": "", "root": "/r"})], [json.dumps({"cycle_number": 3, "remaining": "", "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "remaining": "", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "remaining": "", "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "remaining": "", "root": "/r", "task": "do it", "turns": 1})], [json.dumps({"cycle_number": 3, "failures": 0, "remaining": "", "root": "/r", "task": "do it"})]):
with self.subTest(handed=handed):
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the cycle number, checkout root and task the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(handed)}"))
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(handed)}"))
def test_decodes_a_state_whose_annotations_are_strings(self):
@dataclasses.dataclass(frozen=True)
@@ -481,13 +585,24 @@ class LoopRuns(unittest.TestCase):
launcher = pathlib.Path(root, "loop-claude")
launcher.write_text("")
fake = FakeEffects(python=[ran()])
self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(1, "/r", "do it"), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(1, "", "/r", "do it"), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
class HelpLimits(unittest.TestCase):
def test_help_states_the_limits_the_code_holds(self):
said = " ".join(main.__doc__.split())
self.assertIn(f"The {['second', 'third', 'fourth', 'fifth'][states.QUOTED_ANSWERS_PER_CYCLE - 1]} question they answer in one cycle", said)
# The retry messages say these limits in words too.
self.assertEqual((retry.FAILURES_RUNNING, retry.RETRY_DELAY), (3, 60))
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)
class ExitContract(unittest.TestCase):
def test_every_exit_1_stop_has_its_clause_in_help(self):
read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "README.md holds no premises"
models_ = "the models file cannot be read or written"
unreadable = f"README.md, or {', '.join(records.RECORD_FILES)} or {records.HUMAN_RULES} where they exist, cannot be read or is not UTF-8"
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
clauses = [
("cycle/interrupt.py", "interrupt", "1", "entries.reason", read),
@@ -496,20 +611,21 @@ class ExitContract(unittest.TestCase):
("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", "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),
("cycle/run.py", "ask", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("loop/main.py", "loop_run_from", "0 if task else 1", "__doc__.strip()", "no task is given"),
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the cycle number,', "a reload cannot read the cycle number, checkout root and task"),
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
("project/checkout.py", "checkout_root", "1", "f'could not start git:", git),
("project/checkout.py", "checkout_root", "1", "found.stderr.strip()", git),
("project/checkout.py", "read_utf8", "1", "f'{name} in {folder}:", unreadable),
("project/checkout.py", "read_utf8", "1", "f'{name} in {folder} is not UTF-8", unreadable),
("project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_),
("project/model_choice.py", "read_models_file", "1", 'f"could not read {saved}: {getattr(', models_),
("project/model_choice.py", "read_models_file", "1", "f'could not read {saved}: not an object", models_),
("project/premises.py", "read_premises", "1", "f'README.md in {root}:", premises_),
("project/premises.py", "read_premises", "1", "f'README.md is not UTF-8", premises_),
("project/premises.py", "read_premises", "1", "f'README.md has no ##", premises_),
("project/premises.py", "read_premises", "1", "f'README.md has ## {name} more than once", premises_),
("project/premises.py", "read_premises", "1", "f'README.md has nothing under", premises_),
@@ -524,23 +640,43 @@ class ExitContract(unittest.TestCase):
for (path, function, code, reason), (want_path, want_function, want_code, reason_start, _) in zip(found, clauses):
self.assertEqual((path, function, code), (want_path, want_function, want_code))
self.assertTrue(reason.startswith(reason_start), f"{path} {function}: {reason}")
help_exit_1 = main.__doc__[main.__doc__.index("Exit 1"):main.__doc__.index("Exit 2")]
help_exit_1 = " ".join(main.__doc__[main.__doc__.index("Exit 1"):main.__doc__.index("Exit 2")].split())
self.assertEqual([clause for *_, clause in clauses if f"- {clause}" not in help_exit_1], [])
class JudgeFailures(unittest.TestCase):
def test_every_failed_judge_run_has_its_clause_in_help(self):
started, field, unasked = "claude cannot start or exits non-zero", "its reply misses or mistypes a field", "interrupts or quotes an answer without a question"
# Every Failure the judge's run returns, in source order: path, function, start of reason, its --help clause.
clauses = [
("cycle/judge.py", "run_judge", "f'could not start claude:", started),
("cycle/judge.py", "run_judge", "proc.stderr.strip() or f'the judge exited", started),
("cycle/judge.py", "run_judge", 'f"{verdict.reason}; it replied:', field),
("cycle/judge.py", "run_judge", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"),
("cycle/judge_reply.py", "verdict_from", "'the judge returned no reply'", field),
("cycle/judge_reply.py", "verdict_from", 'f"the judge\'s reply has no {name}', field),
("cycle/judge_reply.py", "verdict_from", "'the judge interrupted without a question'", unasked),
("cycle/judge_reply.py", "verdict_from", "'the judge quoted an answer without a question'", unasked),
]
root = pathlib.Path(main.__file__).parents[1]
found = []
for path in ("cycle/judge.py", "cycle/judge_reply.py"):
functions = [node for node in ast.walk(ast.parse((root / path).read_text())) if isinstance(node, ast.FunctionDef)]
failures = sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Failure")
found += [(path, function, reason) for _, function, reason in failures]
self.assertEqual(len(found), len(clauses), found)
for (path, function, reason), (want_path, want_function, reason_start, _) in zip(found, clauses):
self.assertEqual((path, function), (want_path, want_function))
self.assertTrue(reason.startswith(reason_start), f"{path} {function}: {reason}")
judge_clause = " ".join(main.__doc__[main.__doc__.index("a judge when"):main.__doc__.index("A usage limit")].split())
self.assertEqual([clause for *_, clause in clauses if clause not in judge_clause], [])
class Worktrees(unittest.TestCase):
def test_lists_the_root_alone_when_git_cannot_start(self):
fake = FakeEffects(git=[FileNotFoundError(2, "No such file or directory")])
self.assertEqual(checkout.worktrees("/r", fake.effects()), ["/r"])
class ReplaceFile(unittest.TestCase):
def test_removes_what_it_staged_when_the_replace_fails(self):
with tempfile.TemporaryDirectory() as root:
os.mkdir(os.path.join(root, "in-the-way"))
self.assertEqual(file_writes.replace_file(pathlib.Path(root, "in-the-way"), b"data"), Failure("Is a directory"))
self.assertEqual(os.listdir(root), ["in-the-way"])
if __name__ == "__main__":
unittest.main()
+30 -20
View File
@@ -5,6 +5,7 @@ import json
import os
import pathlib
import pty
import re
import select
import shutil
import stat
@@ -116,7 +117,7 @@ def worker(**step):
def judge(interrupt=False, finished=False, evidence="working", question="", **step):
verdict = {"evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
verdict = {"answer": "", "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
return {"role": "judge", "verdict": verdict, **step}
@@ -250,17 +251,17 @@ class Checkout:
return pathlib.Path(self.env.get("LOOP_CLAUDE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts"))
def archived(self):
"""Each archived transcript's verdict, after checking the copy is named by its content hash."""
verdicts = {}
"""Each archived transcript's outcomes, with every UTC stamp replaced by <UTC>, after checking the copy is named by its content hash."""
outcomes = {}
for folder in (self.archive(), self.archive() / "proj", *(self.archive() / "proj").iterdir()):
self.test.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700, folder)
for copy in sorted((self.archive() / "proj").glob("*/*.jsonl")):
self.test.assertEqual(copy.stem, hashlib.sha256(copy.read_bytes()).hexdigest())
verdict = copy.with_suffix(".verdict.md")
for archived in (copy, verdict):
kept = copy.with_suffix(".outcomes.md")
for archived in (copy, kept):
self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600)
verdicts[copy.read_text()] = verdict.read_text()
return verdicts
outcomes[copy.read_text()] = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", "<UTC> ", kept.read_text(), flags=re.MULTILINE)
return outcomes
def argument(call, flag):
@@ -282,7 +283,7 @@ class Premises(unittest.TestCase):
self.assertIn("not a git repository", run.stderr)
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 is not UTF-8 on line 3 - 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.",
b"# P\n## Audience\nme\n": "README.md has no ## Goals heading - no premises.",
b"# P\n## Goals\n1. g\n": "README.md has no ## Audience heading - no premises.",
b"# P\n## Goals\n\n## Audience\nme\n": "README.md has nothing under ## Goals - no premises.",
@@ -323,6 +324,10 @@ class Cycles(unittest.TestCase):
def test_resumes_the_session_while_unfinished_and_starts_it_fresh_after_finishing(self):
checkout = Checkout(self)
(checkout.root / "sub").mkdir()
(checkout.root / "docs").mkdir()
(checkout.root / "docs" / "decisions.md").write_text("# Decisions\n")
(checkout.home / ".claude").mkdir()
(checkout.home / ".claude" / "CLAUDE.md").write_text("# Global instructions\n")
run = checkout.run([
worker(say="started"), judge(evidence="started"),
worker(say="landed-it", siblings=True), judge(finished=True, evidence="landed-it"),
@@ -339,8 +344,11 @@ class Cycles(unittest.TestCase):
self.assertEqual(argument(workers[2], "--session-id"), session)
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
self.assertNotIn(TASK, argument(workers[1], "-p"))
self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p"))
self.assertIn("as the work remaining:\n\n> started\n\n", argument(workers[1], "-p"))
self.assertEqual({call["cwd"] for call in run.calls}, {str(checkout.root)})
self.assertIn("1. Work.", run.calls[1]["stdin"])
self.assertIn("From docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global instructions", run.calls[1]["stdin"])
self.assertEqual({argument(call, "--model") for call in workers}, {"worker-model"})
self.assertEqual({argument(call, "--model") for call in run.calls if call["role"] == "judge"}, {"judge-model"})
self.assertIn("landed-it", run.calls[3]["stdin"])
@@ -348,9 +356,9 @@ class Cycles(unittest.TestCase):
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
self.assertIn("=== cycle 3 ===", run.stdout)
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
self.assertEqual(sorted(copies), ["Stopped: Ctrl-C\n", "Verdict: finished\n", "Verdict: unfinished\n"])
self.assertIn('"text": "landed-it"', copies["Verdict: finished\n"])
self.assertIn('"text": "next chunk"', copies["Stopped: Ctrl-C\n"])
self.assertEqual(sorted(copies), ["<UTC> Stopped: Ctrl-C\n", "<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n", "<UTC> Verdict: unfinished\n\nEvidence:\n> started\n"])
self.assertIn('"text": "landed-it"', copies["<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n"])
self.assertIn('"text": "next chunk"', copies["<UTC> Stopped: Ctrl-C\n"])
self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1)
def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self):
@@ -389,7 +397,7 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.sleeps, [60, 60])
self.assertIn("retrying the judge in a minute: judge down", run.stderr)
self.assertIn("retrying the judge in a minute: the judge returned no reply; it replied: nothing\n", run.stderr)
self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no evidence of type string; it replied: {"structured_output": {"interrupt": false}}')
self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no answer of type string; it replied: {"structured_output": {"interrupt": false}}')
def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self):
checkout = Checkout(self)
@@ -428,10 +436,11 @@ class Cycles(unittest.TestCase):
def test_hands_the_judge_the_tail_of_a_long_transcript(self):
checkout = Checkout(self)
run = checkout.run([worker(say="early " * 20000 + "LATE")])
run = checkout.run([worker(say="early " * 80000 + "LATE")])
self.assertIn("LATE", run.calls[1]["stdin"])
self.assertLess(run.calls[1]["stdin"].count("early"), 20000)
self.assertTrue(run.calls[1]["stdin"].rstrip().endswith("an open PR, a review not yet run, CI not yet reported."))
self.assertEqual(len(run.calls[1]["stdin"]), 400000)
self.assertLess(run.calls[1]["stdin"].count("early"), 80000)
self.assertTrue(run.calls[1]["stdin"].rstrip().endswith("CI not yet reported, an answer not yet recorded."))
def test_skips_a_malformed_transcript_or_stream_line(self):
checkout = Checkout(self)
@@ -474,7 +483,7 @@ class Interrupt(unittest.TestCase):
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"])
[(copy, verdict)] = checkout.archived().items()
self.assertEqual(copy, (checkout.transcripts()[0]).read_text())
self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: interrupt\n\nA or B?\n\nStopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\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\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")
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
session = argument(run.calls[0], "--session-id")
@@ -666,18 +675,19 @@ class Reload(unittest.TestCase):
worker(append=["loop-claude", "\ndef\n"]), judge(),
worker(replace=["loop-claude", "\ndef\n", "\n# edited\n"]), judge(),
worker(append=["loop_claude/nested/edited.py", "# edited\n"]), judge(),
worker(append=["file_writes.py", "# edited\n"]), judge(),
worker(),
])
self.assertEqual(run.code, 130)
self.assertEqual(run.roles(), ["worker", "judge"] * 4)
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} for cycle in (2, 3)])
self.assertIn("=== cycle 4 ===", run.stdout)
self.assertEqual(reloads, [{"cycle_number": cycle, "remaining": "working", "root": str(checkout.root), "task": TASK} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5 ===", run.stdout)
outside = checkout.temp / "outside"
outside.mkdir()
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK}
state = {"cycle_number": 3, "remaining": "", "root": str(checkout.root), "task": TASK}
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)], cwd=outside)
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"]))
self.assertEqual(run.calls[0]["cwd"], str(checkout.root))
+22
View File
@@ -0,0 +1,22 @@
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import markdown_sections
class Sections(unittest.TestCase):
def test_keeps_every_headed_section_with_its_bodies(self):
text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n"
self.assertEqual(markdown_sections.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]})
def test_closes_a_fence_only_on_its_own_marker(self):
text = "## Goals\n````md\n~~~\n## Quoted\n```\n````\n ~~~\n## Also quoted\n ~~~\n1. one\n## Audience\nme\n"
self.assertEqual(list(markdown_sections.sections(text)), ["Goals", "Audience"])
self.assertEqual(list(markdown_sections.sections("```\nquoted:\n```python\n## Inside\n```\n## Goals\n1. one\n")), ["Goals"])
if __name__ == "__main__":
unittest.main()
+2 -1
View File
@@ -7,8 +7,8 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from failure import Failure
import rank_todo
from loop_claude.failure import Failure
from test_python_floor import ROOT
README = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n\n## Audience\n\nMe.\n"
@@ -81,6 +81,7 @@ class Rank(unittest.TestCase):
def test_names_each_item_under_the_bar_that_is_not_exempt(self):
ranked = self.ranked(TODO.replace("`Bar = 9`", "`Bar = 11`"))
self.assertEqual(ranked.under_bar, ["item 2 scores 10.3, under the bar 11; delete it and any item that needs it, or mark it with a reason the bar does not apply"])
self.assertEqual(self.ranked(ranked.text.replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | principle |")).under_bar, [])
def test_reads_goals_and_sub_goals_in_reading_order(self):
self.assertEqual(rank_todo.readme_goals(README), ["1", "2", "2.1"])
+1 -1
View File
@@ -9,8 +9,8 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import statusline
from statusline import CYAN, DIM, GREEN, RED, RESET, YELLOW
import statusline
NOW = datetime.datetime(2026, 10, 2, 12, 0, tzinfo=datetime.timezone.utc)
EPOCH = int(NOW.timestamp())
+1 -1
View File
@@ -2,7 +2,7 @@ import shutil
import subprocess
import unittest
from test_python_floor import ROOT, readme_floor
from test_python_floor import readme_floor, ROOT
class Types(unittest.TestCase):
+40 -9
View File
@@ -1,12 +1,18 @@
# Decisions
## larv-review: a project under the comprehension floor is fixed at the capping dimension
## larv-review: a project under the comprehension floor is fixed at the lowest dimension
2026-09-20, lilleman. Serves goal 4. Across six projects scored with the four seats, Locality or Self-sufficiency capped every seat and Navigation capped none, so a layout fix would not lift a project under the floor. Valid while the scoring run keeps those four seats.
2026-09-20, lilleman. Serves goal 4. Across six projects scored with the four seats, Locality or Self-sufficiency was the lowest dimension at every seat and Navigation at none, so a layout fix would not lift a project under the floor. Valid while the scoring run keeps those four seats.
## loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing
## loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md` and `~/.claude/CLAUDE.md`, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. On 2026-10-01 lilleman decided the judge is to read `docs/decisions.md` and `AGENTS.md` too, so an answer recorded there is not asked again (goal 4.2); `todo.md` item 7 ends the README-only bar. Valid while the worker's self-report stays unreliable.
2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. Valid while the worker's self-report stays unreliable.
2026-10-01, lilleman: the judge reads `docs/decisions.md` and `AGENTS.md` too, so an answer recorded there is not asked again (goal 4.2); its bar becomes whether the README or those files discriminate. 2026-10-03, implemented: when the README's premises or those files answer the worker's question, the judge quotes the answer verbatim and the worker resumes with it. The judge then sees the quote as a `[loop]` line. The worker asking it again shows the quote did not settle it, and the judge sends it to the human. A backstop of three quoted answers per cycle bounds what the judge misses, such as a reworded repeat or a worker asking without end, so the worker cannot loop unattended (goal 4.4); the fourth question that the README's premises or those files answer in one cycle goes to the human with the judge's quote. An interrupt does not reset the count, so every later question those files answer in that cycle also goes to the human. Valid while the worker writes records only in a worktree, as `CLAUDE.md` → "Working with the codebase" has it, so the records the judge reads from the checkout root are merged ones.
2026-10-03, lilleman: the judge is to read `~/.claude/CLAUDE.md` whole too. The worker follows that file, so a question it answers should not reach the human (goal 4.2). Reading the whole file is safe, because the judge may quote only words that appear in it. A list of sections would need keeping current. Implemented the same day.
2026-10-03, lilleman: the judge rules a chunk finished only once every answer the human typed in it is recorded. A finished chunk's session is deleted, and its answers with it, so an answer recorded nowhere would be asked again in a later chunk (goal 4.2). Implemented the same day by claude, which settled two choices the ruling left open. First, an answer counts as recorded where the files the judge reads hold it, `~/.claude/CLAUDE.md` included, or where the transcript shows the worker writing it into `README.md`'s premises, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. A worker's write to `~/.claude/CLAUDE.md` does not count: `CLAUDE.md` → "Maintaining this file" leaves new rules in it to the human. The judge cannot read a code comment or `todo.md`. Yet `CLAUDE.md` → "Working loop", "Ask, don't guess" puts a standing choice made in one place in a comment there. And the human's approval of a release's items, which "Working loop" requires, is the set of rows `todo.md` names for that release. The judge also reads the records once a cycle from the main checkout. That checkout may not yet hold an answer the worker wrote and merged. A judge that refused any of these would hold the chunk open every cycle. Second, only an answer a later chunk could need must be recorded, so an approval such as "merge it" holds nothing open. The worker's resume prompt states the rule, so a worker whose chunk is held open knows it.
## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
@@ -30,7 +36,20 @@
## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02, applying `todo.md`'s bar deleted every place these scoring runs filed except `todo.md` items 13 and 17. The 2026-10-02 runs on PR #196 (`todo.md` as one scored table) scored 7.63, 6.88, 7.25, 6.88, 7.13 at c0dba66; 7.5, 6.88, 7.13, 6.75, 7.0 at 798dfd7; and 7.5, 7.0, 7.0, 6.75, 7.0 at b712076. Under Self-sufficiency, every seat named larv-review §3 and the agents, which a reader follows only with `CLAUDE.md` open. lilleman decided the same day to ship that PR under the floor; the place filed is `todo.md` item 13. The 2026-10-02 run on PR #198 (a usage limit waited out) scored 7.63, 6.88, 7.38, 6.75, 7.13 at 8e85033. Under Self-sufficiency, every seat named larv-review §3, which `todo.md` item 13 covers; under Locality, they named `archive`'s invariants spread over `session.py` and `run.py`, `rank_todo.py` reaching into `premises.sections`, and `stopped` comparing reason strings, each under `todo.md`'s bar and not filed. lilleman decided the same day to ship that PR under the floor. Valid until the next scoring run, which uses the same four seats.
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. Valid while the scoring run keeps its four seats. The decisions to ship under the floor, listed below, stand until `todo.md` item 62 lifts the project to it.
The last scoring run, which the next may not score below (`CLAUDE.md` → "Quality"): PR #215, 2026-10-04, Navigation 7.38, Locality 6.63, Shape 7.0, Self-sufficiency 6.88, overall 6.88.
lilleman decided to ship each of these under the floor on the day listed. Each line gives its last scores (Navigation, Locality, Shape, Self-sufficiency, overall):
- 2026-10-01, `rebuild`, merged at 8585257: 7.38, 6.75, 7.25, 6.5, 6.88.
- 2026-10-01, PR #182: 7.5, 6.5, 6.88, 6.25, 6.38.
- 2026-10-02, PR #191: 7.63, 7.0, 7.25, 6.75, 7.25.
- 2026-10-02, PR #196: 7.5, 7.0, 7.0, 6.75, 7.0.
- 2026-10-02, PR #198: 7.63, 6.88, 7.38, 6.75, 7.13.
- 2026-10-03, PR #202: 7.5, 7.0, 7.0, 6.75, 7.0.
- 2026-10-03, PR #208: 7.5, 7.0, 7.13, 6.63, 6.88.
- 2026-10-04, PR #215: 7.38, 6.63, 7.0, 6.88, 6.88.
## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
@@ -44,13 +63,17 @@
2026-09-30, lilleman. Serves goal 4: no human reads an unattended chunk before it merges, so every change it makes, a nit's wording included, is reviewed. In the 2026-09-30 bench this cost four of nine rounds in one run and drove two passes to the round cap. Valid while a pass is the only reader of a fix before merge.
## review: a pass skips only on a record older than the chunk
## review: a project decision may suspend the scoring run for the plan items it names
2026-09-30, lilleman. Serves goal 4: a record the chunk writes is the chunk's own unreviewed decision, and an unattended run has no human to catch it. Valid while a pass is the only reader of a chunk before merge.
2026-10-04, lilleman. Serves goal 4.4. In a restructure, each step's scoring run measures code the next step deletes. It costs a run and, below the floor, blocks the step, yet says nothing about what the restructure buys. The scoring run after the last step measures that. Valid while such a decision names its items and the plan item that ends it.
## review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
2026-09-30, lilleman. Serves goal 4: a decision the chunk writes is the chunk's own and unreviewed, and an unattended run has no human to catch it. Valid while a pass is the only reader of a chunk before merge.
## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
2026-09-28, lilleman. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole.
2026-09-28, lilleman. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with its outcomes beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole.
## loop-claude: a `claude` that cannot start is a failed worker run, retried
@@ -78,4 +101,12 @@
## todo.md: one table of items scored by the formula and goal weights it states, held to its bar, ranked by `bin/rank_todo.py`
2026-10-02, lilleman. Serves goal 4: findings were filed faster than chunks closed them, so the plan grew without telling what mattered. Each item is scored as `CLAUDE.md` → "Todo items" says; this repo's formula counts value highest and size least. An item under the bar is not kept; this repo's bar started at 10 and was set to 9 the same day, purging the 17 items under it. An Exempt cell keeps a row past the bar where a rule needs it kept. lilleman retired the two decisions whose plans the purge removed: the stats line in the transcript archive, and three benches before a workflow change merges. A finding under the bar is recorded nowhere, so a later review may raise it again, and the run rescores it. That costs one scoring; a ledger of dropped findings would regrow the list the bar caps. larv-review's Round cap rule 5 counts a finding named under the bar as settled, so one raised again holds no pass open. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale. The format is mandatory in every project, as the premises are (goal 4.3); the formula, bar and weights are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. Valid while one human sets the bar and reads the ranking.
2026-10-02, lilleman. Serves goal 4: findings were filed faster than chunks closed them, so the plan grew without telling what mattered. Each item is scored as `CLAUDE.md` → "Todo items" says; this repo's formula counts value highest and size least. An item under the bar is not kept; this repo's bar started at 10 and was set to 9 the same day, purging the 17 items under it. An Exempt cell keeps a row past the bar where a rule needs it kept. lilleman retired the two decisions whose plans the purge removed: the stats line in the transcript archive, and three benches before a workflow change merges. A finding under the bar is recorded nowhere, so a later review may raise it again, and the run rescores it. That costs one scoring; a ledger of dropped findings would regrow the list the bar caps. larv-review's "Round cap" → "Done" counts a finding named under the bar as settled, so one raised again holds no pass open. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale. The format is mandatory in every project, as the premises are (goal 4.3); the formula, bar and weights are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. A 🟡 against a technical principle is exempt as `principle`, because its audience value scores low and the bar would drop every one. A 🟢 against a principle is scored like any other finding. Valid while one human sets the bar and reads the ranking, and while the items marked `principle` stay few enough to rank.
## settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
2026-10-04, lilleman, answering the principles audit of PR #215. Serves goal 4: this setup is meant to run in a sandbox and to work autonomously, so tool access is granted by the sandbox, as "Always grant explicit access to data" in `principles/technical-principles.md` asks. Valid while every machine taking this checkout is such a sandbox.
## the repo may name bender, bender-infra and ai-sandbox
2026-10-04, lilleman, answering the principles audit of PR #215. Serves goal 3, which keeps credentials, transcripts and memory files off the remote; the names of the host, its infrastructure project and the sandbox VM are none of those. Valid while the repo names them without their addresses or credentials.
+2
View File
@@ -1,5 +1,7 @@
# Frontend principles
Applies to a project with a browser frontend.
General principles (KISS, DRY, …) live in `technical-principles.md` and apply here too.
## Foundational stances
+2
View File
@@ -1,5 +1,7 @@
# Logging
Applies to a service that writes logs.
## Levels
Log levels have a standard, RFC5424: { emerg: 0, alert: 1, crit: 2, error: 3, warning: 4, notice: 5, info: 6, debug: 7 }.
+1 -1
View File
@@ -1,6 +1,6 @@
# REST APIs
Conventions for any REST API we build, regardless of product or stack. Existing APIs keep their current shapes until their next major version — reviewers flag deviations on new surfaces, not old ones.
Applies to every REST API we build, regardless of product or stack. Existing APIs keep their current shapes until their next major version — reviewers flag deviations on new surfaces, not old ones.
## URLs & query parameters
+4
View File
@@ -47,6 +47,10 @@
* Explicit over implicit.
- Avoid magic, avoid "clever" solutions, only abstract when the API can clearly describe what is happening.
- Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`).
* Sane defaults, where a default serves better than an explicit ask.
- A default earns its place where most callers want the same value, a wrong guess does no harm, and the caller can see and change it through a `--help` line or a documented option. Anything else is asked for.
- Defaults live at the program's edge: a CLI, a config file, a library's public API. A library still asks for every input that can change between runs, such as data, the clock and randomness; only the code that wires a program together, such as its CLI, defaults those, as "Functional core, imperative shell" asks.
- BANNED: a CLI that refuses to run until given `--data-path` and `--seed`, when nearly every run wants the shipped data and fresh randomness. GOOD: it uses the shipped data and fresh randomness unless a flag overrides them, and `--help` names those flags.
* Functional core, imperative shell.
- Decisions live in pure functions, data in and data out; the shell around them performs the effects and holds no branching of its own.
- Every side effect comes from outside: output, time, randomness, network and storage are injectable, so a test runs exactly the code production runs.
+46 -30
View File
@@ -26,11 +26,13 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de
## 3. Passes
A pass is one kind of review, a row of the table, named by its first column. Its trigger says when it runs on a change it has not seen; its reviewer reports the findings.
| Pass | Reviewer | Trigger |
|------|----------|----------------------------------------|
| Architecture, then the principles audit and the comprehension floor | systems-architect, then principles-auditor and the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats, CLI flags and exit codes); a schema change beyond an additive column; the chunk shipping its release's last item |
| Architecture | systems-architect, then principles-auditor and the scoring run | ships its release's last item, or carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats, CLI flags and exit codes); a schema change beyond an additive column |
| Security | `/security-review` | changes code or config; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto |
| Full security scan | the `claude-security` plugin at high effort: `/claude-security scan this branch's changes at high` | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface |
| Full scan | the `claude-security` plugin at high effort: `/claude-security scan this branch's changes at high` | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface |
| Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour: what the code or its tests do |
| Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on |
| Prose | prose-reviewer | every chunk; a fix, where it touches prose |
@@ -39,37 +41,38 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod
Give a reviewer without Bash the branch diff and `git ls-files`'s output in its prompt: some harnesses grant it Read alone.
**Record, then ask** — for the architecture pass and the full scan:
**Precedent, then ask** — for the architecture pass and the full scan:
1. A record is a decision-log entry, or a planning item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, skip the pass and cite the record.
2. A change that departs from the record is unreviewed, however thorough the record is.
3. Fired and not skipped → ask the user whether to run it, with the evidence and your recommendation; no user reachable → run it.
4. A record or the user's no skips only the architect, never the principles audit or the scoring run: no record older than the chunk checked the code it writes.
- **Skip.** A precedent is a `docs/decisions.md` entry, or a plan item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, skip the pass and cite that entry or item.
- **Departure.** A change that departs from the precedent is unreviewed, however thorough the precedent is.
- **Ask.** Fired and not skipped → ask the user whether to run it, with the evidence and your recommendation; no user reachable → run it. For the full scan, give the evidence and your recommendation, then launch it: the plugin asks the user to confirm its cost, and that prompt is the ask.
- **Audit.** A precedent or the user's no skips only the architect, never the principles audit: no precedent checked the code this chunk writes. The scoring run skips only as "Architecture" → "Suspended" says.
**Round cap.**
1. A round is one launch of a pass's reviewer: the first, each re-entry, and the rerun after the architect's Stage 0 questions.
2. The architecture pass's round is the architect (unless skipped), the principles audit and the scoring run, so a fix to any of their findings reruns the whole round.
3. The external auto-reviewer (§4) is a pass of its own, each review it posts a round.
4. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since.
5. A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings". Resolve that round's 🟢s and ❓s per "Findings" too.
6. A pass takes at most three rounds per chunk. Instead of a fourth, list what is open and ask the user. For the auto-reviewer, ask before the push that would summon its fourth, and hold the fixes unpushed until the answer.
7. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged.
- **Round.** A round is one launch of a pass's reviewer: the first, each re-entry, and the rerun after the architect returns Stage 0 questions ("Architecture" below).
- **Architecture round.** The architecture pass's first round is the architect (unless skipped), the principles audit and the scoring run, which "Architecture" → "Suspended" may skip. A later round relaunches the scoring run, where one ran, and each reviewer whose 🔴 or 🟡 the previous round's fixes answer. Where those fixes carry an architectural decision, the whole round runs again, the architect included.
- **Auto-reviewer.** The external auto-reviewer (§4) is a pass of its own, each review it posts a round.
- **Count.** Close each round with one commit that holds the round's fixes and is titled `Answer <pass> round <n>: …`, `<pass>` being the pass's name in lower case, such as `full scan`. A round that changed nothing gets an empty commit (`git commit --allow-empty`). Push the commits when §4 runs next, where there is a remote. A pass's count is the highest `<n>` among titles holding `Answer <pass> round <n>:` in `git log origin/<default branch>..HEAD` after a `git fetch`, or in `git log <default branch>..HEAD` with no remote. The auto-reviewer's count is the number of its reviews on the PR.
- **Later rounds.** From round 2, prompt an agent under `~/.claude/agents/` with its own last round's findings verbatim and what changed since: `git diff <the commit that round reviewed> HEAD`, since the fixes may be unpushed.
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings". Resolve that round's 🟢s and ❓s per "Findings" too.
- **Cap.** A pass takes at most three rounds per chunk. Instead of a fourth, list what is open and ask the user. For the auto-reviewer, ask before the push that would summon its fourth, and hold the fixes unpushed until the answer.
- **Answer.** A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged.
**Re-entry.**
1. A fix is a change no pass has seen, a 🟢's or ❓'s included.
2. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire, a done pass included, and each pass whose 🔴 or 🟡 they answer; a pass at its cap gets "Round cap" rule 6's ask instead. Then §4.
- **Fix.** A fix is a change no pass has seen, a 🟢's or ❓'s included.
- **Rerun.** A round's fixes re-enter together: run, in table order, each pass whose trigger they fire, a done pass included, and each pass whose 🔴 or 🟡 they answer; a pass at its cap gets "Round cap" → "Cap"'s ask instead. Then §4.
**Findings.**
**Findings.** A reviewer rates each finding 🔴 must fix, 🟡 should fix, 🟢 nit, ❓ question, or 🔀 escalation naming the reviewer whose concern it is.
1. A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". A 🔴 is marked `defect`. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security".
2. A fix that would change a goal, or a decision the repo held before the chunk began, is asked; no user reachable → filed, marked `question`, the goal or decision left as is.
3. A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/CLAUDE.md` → "Decisions: one home, each linked to a goal or a technical principle": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined.
4. A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix.
5. A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test or a record settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed, marked `question`.
6. A 🔀 runs the named pass once the current pass is done.
7. Other reviewers map onto this scale: `/security-review`'s HIGH is 🔴, MEDIUM 🟡, LOW 🟢; what a forge's auto-reviewer marks blocking is 🔴. A finding of theirs repeating one declined or filed does not stand.
- **Outside the chunk.** A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". A 🔴 is marked `defect`. A 🟡 against a file under `~/.claude/principles/` is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security".
- **Goal or decision.** A fix that would change a goal, or a `docs/decisions.md` entry the repo held before the chunk began, is asked; no user reachable → filed, marked `question`, the goal or decision left as is.
- **🔴.** A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/CLAUDE.md` → "Decisions: one home, each linked to a goal or a technical principle": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined.
- **🟡.** A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix.
- **🟢 and ❓.** A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test, a goal or a decision the repo held before the chunk began settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed, marked `question`.
- **🔀.** A 🔀 runs the named reviewer's pass once the current pass is done.
- **Other scales.** Other reviewers map onto this scale: `/security-review`'s HIGH is 🔴, MEDIUM 🟡, LOW 🟢; what a forge's auto-reviewer marks blocking is 🔴. A finding of theirs repeating one declined or filed does not stand.
### Architecture
@@ -78,23 +81,36 @@ Launch systems-architect: review the system as a whole entered through this chan
- **Stage 0 questions returned**: relay them to the user, record the answers in the README, re-run once.
- **BLOCK** → confirm with the user first when the restructure materially reshapes their PR; until confirmed, no later pass runs.
Then the principles audit: one principles-auditor per file in `~/.claude/principles/` and one for the README's goals, each over the whole project in every round.
Then the principles audit: one principles-auditor for the README's goals, and one per file in `~/.claude/principles/` whose `Applies to` line the project meets, judged from the README, `git ls-files` and the branch diff. A file without the line applies to every project. Unsure → launch it.
Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel.
Then the comprehension floor, which the scoring run measures. Four simulated readers — Junior A, Mid A, the maintainability senior and the inherited architect — each read the whole project, not the diff, and score it from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. A seat's overall may not exceed its lowest dimension by more than 1. Each score is the mean of the four seats, to two decimals. Launch the seats per `~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run".
The project's `docs/decisions.md` keeps one entry whose title opens `comprehension floor:`. It holds the last scoring run's scores, and each decision to ship under the floor, with its scores.
The chunk does not merge while either holds:
- **Floor.** Any dimension or the overall is below 7.0.
- **Ratchet.** Any score is below the entry's last scoring run as it stands on the default branch, even within the panel's noise. An equal score passes, and so does every run while the default branch has no entry.
Fix the places the seats name under the lowest dimension and under each dimension that fell. When only the floor holds, the user may decide to ship instead. A decision that lets every chunk ship under the floor, held in the project's `docs/decisions.md` before the chunk began, counts as theirs while it stands. A decision to ship listed in the `comprehension floor:` entry covers only the chunk it names. No user reachable → fix. A fall is never shipped without the user: after three rounds, "Round cap" → "Cap" asks them.
Put each run's five scores in the summary, and replace the entry's last scoring run with them on this branch. List in the entry each decision to ship under the floor, and file its places in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". A project without the entry gets it at its first scoring run, titled `comprehension floor: every dimension and the overall at 7.0 or above` and applying KISS (`~/.claude/principles/technical-principles.md`).
**Suspended.** A decision in the project's `docs/decisions.md`, held before the chunk began, may name plan items to ship without a scoring run. A named item counts as `todo.md` worded it before the chunk began. The decision must name the later plan item whose chunk ends the suspension with a scoring run. A chunk may ship named items only with each other. Such a chunk skips the scoring run, so neither the floor nor the ratchet can block it, and its summary cites the decision. A chunk shipping its release's last item runs the scoring run, even when every item it ships is named.
### Security
`/security-review` over the branch diff is the pass of record.
`/security-review` over the branch diff is the pass of record. Launch a general-purpose subagent that invokes it through the Skill tool, edits nothing, and replies with the skill's report, or that the skill is unavailable. Invoked in your own context, the skill ends your turn on that report.
A verified HIGH inside this chunk's blast radius is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which.
`claude-security` asks the user to confirm a scan's cost, and only the user may answer. The plugin unavailable, its cost prompt unanswered, or no file scanned → say so in the summary; never substitute a hand-rolled pass.
Only the user may answer `claude-security`'s cost prompt. `/security-review` or `claude-security` unavailable, the plugin's cost prompt unanswered, or no file scanned → say so in the summary; never substitute a hand-rolled pass.
**Do not over-read a clean result.** `/security-review` is single-repo and static: it does not trace authorization across services, does not run the application, and deliberately excludes dependency CVEs in third-party libraries — Renovate/Dependabot owns those, per `~/.claude/CLAUDE.md` → "Working with the codebase". Never point an automated reviewer or scan at an untrusted fork's PR content; a PR body is untrusted input to it (CVE-2025-59536, CVE-2026-21852).
### Stability and product-owner
Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates.
Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code.
### Prose
@@ -118,4 +134,4 @@ Launch prose-reviewer with what the diff touched and every section this review c
## 6. Wrap up
Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal or technical principle it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user.
Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, principles files left out with why, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal or technical principle it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user.
+53 -21
View File
@@ -6,7 +6,7 @@
`Bar = 9`
`Next ID = 39`
`Next ID = 72`
| Goal | W |
|---|---|
@@ -25,18 +25,24 @@
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.1.0 | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 3 | 5 | 8 | 9 | 2, 3 | 27.8 |
| 7 | 0.1.0 | decision | **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** | 3 | 4 | 8 | 8 | 4.2 | 19.0 |
| 8 | 0.1.0 | | **Judge a cycle on more than the transcript's last 40,000 characters.** | 4 | 5 | 7 | 8 | 4.2 | 15.8 |
| 13 | 0.1.0 | decision | **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** | 3 | 5 | 6 | 7 | 4.1 | 15.6 |
| 23 | 0.1.0 | | **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** | 3 | 4 | 7 | 8 | 4.4 | 13.5 |
| 60 | 0.1.0 | | **Rerun the scoring run before merge whenever a fix landed after the last scoring run, and count a score under the floor or the ratchet as the scoring run's 🔴.** | 3 | 3 | 6 | 7 | 4.1 | 16.1 |
| 62 | 0.1.0 | defect | **Lift Locality, Self-sufficiency and the overall to the comprehension floor, at the places the seats name.** | 4 | 6 | 6 | 8 | 4.1 | 15.5 |
| 65 | 0.1.0 | | **Archive each judge reply the loop rejects.** | 3 | 4 | 4 | 5 | 2 | 12.9 |
| 21 | 0.1.0 | | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 4.3 | 12.9 |
| 36 | 0.1.0 | | **Ask the user once before a full security scan, folding larv-review's ask into the plugin's cost prompt.** | 2 | 2 | 5 | 5 | 4.2 | 11.9 |
| 49 | 0.1.0 | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 2 | 5 | 6 | 4.3 | 12.5 |
| 12 | 0.1.0 | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 4.1 | 11.7 |
| 59 | 0.1.0 | | **Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.** | 3 | 3 | 6 | 6 | 4.4 | 10.9 |
| 5 | 0.1.0 | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 4.1 | 10.5 |
| 66 | 0.1.0 | principle | **Hold systems-architect's method thresholds only while the comprehension panel finds the flagged code hard.** | 3 | 3 | 4 | 5 | 4.1 | 9.9 |
| 4 | 0.1.0 | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 2 | 9.8 |
| 50 | 0.1.0 | principle | **Grant the bench's runs only the tools a review needs, in place of skipping every permission.** | 2 | 2 | 3 | 4 | 3 | 9.7 |
| 69 | 0.1.0 | principle | **Measure test coverage, so a chunk that lowers it is seen.** | 3 | 4 | 4 | 5 | 4.1 | 9.6 |
| 29 | 0.1.0 | | **Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.** | 2 | 2 | 3 | 5 | 4.1, 4.4 | 9.1 |
| 17 | 0.1.0 | decision | **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** | 1 | 2 | 3 | 4 | 4.1 | 9.0 |
| 68 | 0.1.0 | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 4 | 3 | 5 | 4.1 | 8.6 |
| 67 | 0.1.0 | principle | **Point stability-reviewer at the technical principles in place of its own restatement of them.** | 2 | 3 | 4 | 5 | 4.3 | 8.6 |
| 52 | 0.1.0 | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 6 | 6 | 3 | 5 | 1 | 8.5 |
| 6 | 0.1.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 4 | 5 | 4.1 | 7.4 |
| 51 | 0.1.0 | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 3 | 5 | 3 | 5 | 4.1 | 7.4 |
## Details
@@ -44,23 +50,21 @@
It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read.
2026-10-02, the human: ai-sandbox is the VM `loop-claude` will run on, hosted on the server bender. bender-infra, the infrastructure-as-code project that manages bender, will back up ai-sandbox's data volume once ai-sandbox is rebuilt. The item waits for the human to say the rebuild has landed. Before writing the README line, check that `~/.claude` lives on that volume and that the backup is private and encrypted at rest.
2026-10-02, the human: ai-sandbox is the VM `loop-claude` will run on, hosted on the server bender. bender-infra, the infrastructure-as-code project that manages bender, will back up ai-sandbox's data volume once ai-sandbox is rebuilt. The item waits for the human to say the rebuild has landed; do not remind them. Before writing the README line, check that `~/.claude` lives on that volume and that the backup is private and encrypted at rest.
### 7. Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.
The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 2).
Today it reads only the README's Goals and Audience (`premises.py`) and cannot see an answer recorded in `docs/decisions.md` or `AGENTS.md`, so it can interrupt the human again for a question already answered. Revise the decision "loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing" to match.
### 60. Rerun the scoring run before merge whenever a fix landed after the last scoring run, and count a score under the floor or the ratchet as the scoring run's 🔴.
### 8. Judge a cycle on more than the transcript's last 40,000 characters.
Raised by the systems-architect review of PR #215. A stability, product-owner, prose or auto-reviewer fix reruns no scoring run unless it carries an architectural decision or answers an architecture 🔴 or 🟡. It merges unscored, so the `comprehension floor:` entry records scores for an earlier commit, and the next chunk's ratchet inherits a fall it did not cause. "Round cap" → "Done" and "Re-entry" → "Rerun" count only 🔴 and 🟡, and nothing makes a score under the floor one. A commit that only edits `docs/decisions.md`, `todo.md` or `CHANGELOG.md` needs no rerun.
`judge_prompt` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer.
### 62. Lift Locality, Self-sufficiency and the overall to the comprehension floor, at the places the seats name.
### 13. Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.
Raised by the principles audit of PR #215 against KISS, in `principles/technical-principles.md`, and goal 4.1: the `comprehension floor:` entry in `docs/decisions.md` lists seven decisions to ship under the floor, and 0.1.0 waits on the floor. PR #215's last run put Locality at 6.63 and Self-sufficiency and the overall at 6.88. Its seats named, under Locality: the judge's contract spread over `cycle/judge_reply.py`, `cycle/worker.py` and `cycle/run.py`; `remaining`, which is `Unfinished.evidence` under another name, threaded through `loop/main.py`, `loop/reload.py`'s `LoopRun`, `cycle/run.py` and `worker_args`; the `quoted_answers` cap held by case order in `cycle/states.py`'s `transition` and restated in `run.py`'s `question_for`; the four outcome texts `run.py` builds inline for `archive`. Under Self-sufficiency: `skills/larv-review/SKILL.md`, which needs `CLAUDE.md` → "Vocabulary" open beside it; the archive layout, defined only in `bin/loop_claude/loop/main.py`'s docstring and not at `cycle/archive.py`; `JUDGE_RULES`' precedence in `cycle/judge_reply.py`, restated by `verdict_from`'s branch order and the `Reply` field descriptions; the `sys.path` insert in `bin/loop-claude` that the `from failure import` lines rely on, unstated at the import sites.
Applying one rule of "Round cap", "Re-entry" or "Findings" takes `review-findings.md`, `CLAUDE.md` → "Vocabulary" and the decision log open beside it. The rules cite each other by number ("Round cap" rule 6), so a renumbering breaks a citation silently. Nothing says where a pass's round count is recorded, so a resumed or compacted session loses it.
### 65. Archive each judge reply the loop rejects.
### 23. Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.
On this repo the frontend, REST and logging auditors each read the whole project to report "does not apply", and one 🟢 fix reruns ten whole-project reads.
Goal 2, raised by the principles audit of PR #215: the judge runs with `--no-session-persistence`, and the first two rejected replies reach only stderr, so the archive cannot answer the 3am question of why the loop rejected a verdict.
### 21. Give `settings.json`'s model one writer, and sort its keys.
@@ -68,30 +72,58 @@ Claude Code rewrites `"model"` in this tracked file whenever a model is picked,
Every write Claude Code makes to the file rewrites `"model"`, `claude plugin install` included: Claude Code 2.1.288 turned `"opus"` into `"opus[1m]"`. Each write also puts the keys back in Claude Code's own order, so a sorted file stays sorted only until the next write.
### 36. Ask the user once before a full security scan, folding larv-review's ask into the plugin's cost prompt.
### 49. Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.
When the full scan fires, "Record, then ask" rule 3 asks whether to run it, and `claude-security` then asks the user to confirm its cost.
DRY, in `principles/technical-principles.md`: the list is copied by hand, and sessions work from the copy.
### 12. Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.
The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word.
### 59. Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.
Raised by the product-owner review of PR #211. The resumed worker gets the judge's quote of the work remaining, but a worker that still thinks the chunk done can answer each cycle the same way, and each cycle costs a worker and a judge run (goal 4.4).
### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key.
The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session.
### 66. Hold systems-architect's method thresholds only while the comprehension panel finds the flagged code hard.
KISS, in `principles/technical-principles.md`, which keeps a limit only while readers find the flagged code hard. `agents/systems-architect.md` makes cyclomatic 7 and 24 lines gate rules from the first commit, a 🔴 unless a reason is stated.
### 4. Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.
Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps.
### 50. Grant the bench's runs only the tools a review needs, in place of skipping every permission.
"Always grant explicit access to data", in `principles/technical-principles.md`: `workflow-bench/bench.py` starts claude with `--dangerously-skip-permissions`, and no rule confines it to a sandbox, so a run on the host reaches the host's credentials and other checkouts.
### 69. Measure test coverage, so a chunk that lowers it is seen.
"Test coverage should not decline", in `principles/technical-principles.md`: nothing reports coverage, so a chunk that deletes a test or adds untested code passes unseen.
### 29. Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.
State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it.
### 17. Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.
### 68. Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.
The 2026-10-02 scoring runs on PR #191 named both under Self-sufficiency: the judge's rules use "chunk" and "a release ready to cut" from `CLAUDE.md` with no link, and `--resume`, `--session-id`, `--no-session-persistence`, `--json-schema` and stream-json's result event go unexplained in `worker.py` and `judge.py`.
"Most, if not all, code should have automated tests", in `principles/technical-principles.md`: `compare.blind()` keeps the comparison blind, and a version name it misses invalidates the bench silently.
### 67. Point stability-reviewer at the technical principles in place of its own restatement of them.
DRY, in `principles/technical-principles.md`: `agents/stability-reviewer.md` restates principles in its own words, and the copy has drifted: it asks for "properly randomised UUIDs" where the principle requires UUID v7.
### 52. Record why this checkout lives in Claude Code's own directory, or move it out and link it in.
"One owner per value" and "Prefer the vendor-neutral option", in `principles/technical-principles.md`: git, Claude Code and loop-claude all write `~/.claude`, kept apart only by the `.gitignore` allowlist, and the repo's records live in a vendor directory.
### 6. Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.
Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost.
### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.
"Functional core, imperative shell", in `principles/technical-principles.md`: `archive`, `trust`, `retried`, the worker, `interrupt` and `model_choice` print to stderr themselves, and the tests swap the global stream.
+14 -1
View File
@@ -1,5 +1,18 @@
#!/usr/bin/env python3
"""Run larv-review bench runs: BENCH_SOURCES=<dir of the <case>-main clones, their <case>-main.md reports and comparison.md> bench.py <case>-<version>-<n> ..."""
"""Run larv-review bench runs: BENCH_SOURCES=<dir> bench.py <case>-<version>-<n> ...
The 2026-09-30 bench ran two versions of larv-review, main and rebuild. Each reviewed four real chunks,
the cases, three times; compare.py then rules whether each version reviews at least as well as the
other. The bench's inputs are untracked:
- versions/<version>/ beside this script: a copy of ~/.claude at that version, which each run reads
in place of ~/.claude (run-prompt.md).
- $BENCH_SOURCES/<case>-main/: a clone of the case's project; CASES names the chunk's base and head
commits in it.
- $BENCH_SOURCES/<case>-main.md: main's own review of the case, run on 2026-09-29.
- $BENCH_SOURCES/comparison.md: what each case's real review found, one table row per issue, its ID
led by the case's letter in compare.py's PREFIX.
Each run leaves its clone in <run>/, its report in <run>.md and its claude stream in logs/.
"""
import concurrent.futures
import json
import os
@@ -1,4 +1,4 @@
You judge a bench of two code-review processes, A and B, on one real chunk of work. Each process reviewed the same chunk three times, independently: runs A1–A3 and B1–B3. Rule whether B reviews at least as well as A, and whether A reviews at least as well as B.
You compare two code-review processes, A and B, on one real chunk of work. Each process reviewed the same chunk three times, independently: runs A1–A3 and B1–B3. Rule whether B reviews at least as well as A, and whether A reviews at least as well as B.
Everything is under `{dir}`; read nothing outside it:
@@ -7,7 +7,7 @@ Everything is under `{dir}`; read nothing outside it:
- `<run>/report.md`: the run's own account of its passes, findings and outcomes. Its claims are not evidence.
- `<run>/fixes.diff`: what the run actually changed. This is the evidence.
Judge each run on:
Rate each run on:
1. **Truth coverage**: for each truth issue, caught and fixed ✔, partly ◐, or missed ✘, checked against `fixes.diff`. A filed or declined issue with a sound reason counts ◐.
2. **Other real defects**: a finding the truth lacks that is a real defect in the chunk, fixed or filed.
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Blind-judge each case's six runs: BENCH_SOURCES=<as for bench.py> judge.py <case> ..."""
"""Blind-compare each case's six runs: BENCH_SOURCES=<as for bench.py> compare.py <case> ..."""
import concurrent.futures
import json
import pathlib
@@ -29,11 +29,12 @@ def runs(case, version):
def blind(text):
"""The report, with VERSION_DIR in place of every name that tells which version wrote it."""
return re.sub(r"\S*versions/(main|rebuild)\S*|\b(main|rebuild)\b(?=[`\s]*(process|version))", "VERSION_DIR", text)
def prepare(case):
folder = BENCH / "judge" / case
folder = BENCH / "compare" / case
if folder.exists():
shutil.rmtree(folder)
folder.mkdir(parents=True)
@@ -53,15 +54,15 @@ def prepare(case):
(run / "report.md").write_text(blind(report.read_text()))
(run / "fixes.diff").write_text(bench.git(clone, "diff", head, "chunk") + "\n")
mapping[f"{label}{n}"] = str(report)
(BENCH / "judge" / f"{case}.mapping.json").write_text(json.dumps(mapping, indent="\t") + "\n")
(BENCH / "compare" / f"{case}.mapping.json").write_text(json.dumps(mapping, indent="\t") + "\n")
return folder
def judge(case):
def compare(case):
folder = prepare(case)
ruling = BENCH / "judge" / f"{case}.ruling.md"
prompt = (BENCH / "judge-prompt.md").read_text().format(dir=folder, ruling=ruling)
with (BENCH / "logs" / f"judge-{case}.jsonl").open("w") as out:
ruling = BENCH / "compare" / f"{case}.ruling.md"
prompt = (BENCH / "compare-prompt.md").read_text().format(dir=folder, ruling=ruling)
with (BENCH / "logs" / f"compare-{case}.jsonl").open("w") as out:
subprocess.run(
["claude", "-p", prompt, "--model", "claude-opus-5-5", "--allowedTools", "Read,Grep,Glob,Write", "--output-format", "stream-json", "--verbose"],
cwd=folder, stdout=out, stderr=subprocess.STDOUT)
@@ -70,5 +71,5 @@ def judge(case):
if __name__ == "__main__":
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
for result in pool.map(judge, sys.argv[1:]):
for result in pool.map(compare, sys.argv[1:]):
print(result, flush=True)
+1 -1
View File
@@ -9,7 +9,7 @@ Report: write it to `{report}`.
- `VERSION_DIR/skills/larv-review/SKILL.md` is larv-review. Do not invoke the installed `larv-review` skill.
- Wherever a text cites `~/.claude/<path>`, read `VERSION_DIR/<path>` instead. `VERSION_DIR/CLAUDE.md` replaces `~/.claude/CLAUDE.md`, which you already have loaded: where the two differ, VERSION_DIR's wins.
- Launch every reviewer named `<name>` under `~/.claude/agents/` as a `general-purpose` agent whose prompt opens with the body of `VERSION_DIR/agents/<name>.md` (frontmatter dropped), then the task. A reviewer the process names that has no file there gets the process's own description of it as its prompt.
- `/security-review`: use the Skill tool's `security-review` if it is available; otherwise emulate it with a `general-purpose` agent, told to review the branch diff for exploitable vulnerabilities and report only those at ≥0.8 confidence.
- `/security-review`: launch a `general-purpose` agent that invokes the Skill tool's `security-review`, edits nothing, and replies with the skill's report, or that the skill is unavailable. Where that skill is unavailable, emulate it with a `general-purpose` agent, told to review the branch diff for exploitable vulnerabilities and report only those at ≥0.8 confidence.
## Bench rules