Compare commits

..

76 Commits

Author SHA1 Message Date
lilleman d9ab58b2c5 Answer the third review round 2026-10-02 09:14:32 +02:00
lilleman 8589d3aef8 Answer the second review round 2026-10-02 09:13:13 +02:00
lilleman 426cb82d92 Name the decision's AGENTS.md line its title in the prose reviewer 2026-10-02 09:12:00 +02:00
lilleman 88b5478c1f Answer the first review round 2026-10-02 09:11:52 +02:00
lilleman 7a8df5f2da State each decision whole in its title, so AGENTS.md's index is the decision and docs/decisions.md its background 2026-10-02 09:08:11 +02:00
lilleman e77c6de621 Delete the decisions any reader of the goals, principles or CLAUDE.md would reach anyway 2026-10-02 08:55:44 +02:00
lilleman 8b2d89fa15 Merge pull request 'Keep handoff material in the repo' (#188) from handoffs-in-repo into main 2026-10-02 08:47:43 +02:00
lilleman 43aa6ec4df Answer the second review round 2026-10-02 08:47:00 +02:00
lilleman c729a130a6 Answer the first review round 2026-10-02 08:45:25 +02:00
lilleman 765705e3ca Keep handoff material in the repo, and move the bench scripts the plan points at into workflow-bench/ 2026-10-02 08:43:20 +02:00
lilleman bef4bb0ef8 Merge pull request 'Give larv-review's finding rules one home' (#186) from review-rules-home into main 2026-10-02 07:54:57 +02:00
lilleman a32f3edb1f Answer the prose review's first round 2026-10-02 07:53:44 +02:00
lilleman 4b3f545158 Give larv-review's finding rules one home, and make the small fixes filed against its rules 2026-10-02 07:53:44 +02:00
lilleman c135e2141e Merge pull request 'Plan waiting out a usage limit in loop-claude' (#185) from session-limit-wait into main 2026-10-02 07:51:23 +02:00
lilleman 23efe40404 Answer the prose review's first round 2026-10-02 07:49:15 +02:00
lilleman 13dae8ac2d Plan waiting out a usage limit in loop-claude 2026-10-02 07:48:14 +02:00
lilleman 01a7c9d51b Merge pull request 'Stop the loop when a finished chunk's session cannot be deleted, and give the session one owner' (#184) from session-owner into main 2026-10-02 07:47:49 +02:00
lilleman df2c28e703 Answer the prose review's second round 2026-10-02 07:46:09 +02:00
lilleman ce9eaf6114 Answer the stability review's second round 2026-10-02 07:44:18 +02:00
lilleman d5f5af48b9 Answer the prose review's first round 2026-10-02 07:43:08 +02:00
lilleman f5b3ba0a5d Answer the product-owner review's first round 2026-10-02 07:41:41 +02:00
lilleman 041fb8b98d Name the cause when an OSError has no strerror 2026-10-02 07:40:12 +02:00
lilleman ce9c96c57c Stop the loop when a finished chunk's session cannot be deleted, and give the session one owner 2026-10-02 07:38:18 +02:00
lilleman 2c39de2b48 Merge pull request 'Name each entry shape written_by_human checks, and annotate every parameter in loop_claude' (#183) from readable-types into main 2026-10-01 23:51:48 +02:00
lilleman 4c0b7b5fe7 Answer the stability and prose reviews' first round 2026-10-01 23:50:30 +02:00
lilleman 39acf6dff0 Name each entry shape written_by_human checks, and annotate every parameter in loop_claude 2026-10-01 23:47:03 +02:00
lilleman 70ad9a9caa Merge pull request 'Name the loop's states with one transition function, and inject its side effects' (#182) from loop-state-machine into main 2026-10-01 23:42:14 +02:00
lilleman f8131946ae File the product-owner nits under the exit-contract item 2026-10-01 23:42:12 +02:00
lilleman a6a5f99bfe Answer the prose review's second round 2026-10-01 23:40:49 +02:00
lilleman 1514327d34 Answer the prose review's first round, ship under the floor, and plan giving the judge the decisions 2026-10-01 23:38:06 +02:00
lilleman dbf3c6e27a Answer the stability review's first round 2026-10-01 23:34:41 +02:00
lilleman 9f80bfb9de Use UUID v7s in the unit tests 2026-10-01 23:30:41 +02:00
lilleman fa53ae6137 File what the architecture round found outside the chunk 2026-10-01 23:29:50 +02:00
lilleman 8e221712cb Answer the architect's second round 2026-10-01 23:20:57 +02:00
lilleman 00446be689 Answer the architect's first round 2026-10-01 23:19:10 +02:00
lilleman f385b563f0 Name the loop's states with one transition function, and inject its side effects 2026-10-01 23:12:37 +02:00
lilleman d0ce3b2690 Run sessions on opus without the 1M context 2026-10-01 23:04:58 +02:00
lilleman 6f328d1c40 Merge pull request 'Merge rebuild into main' (#181) from rebuild-merge into main 2026-10-01 23:01:37 +02:00
lilleman 86b9a85b92 Answer the prose review's first round 2026-10-01 23:00:53 +02:00
lilleman 49c91df534 Merge main into rebuild, keeping rebuild's side: main's changes since the fork are ported or superseded 2026-10-01 22:58:37 +02:00
lilleman 2c0e505574 Remove the rebuild's wait-to-merge warnings and the decisions its merge ends 2026-10-01 22:58:32 +02:00
lilleman c26f19bf4b Merge pull request 'Port main's subagent rule and Opus 5.5 model into rebuild' (#180) from port-main into rebuild 2026-10-01 22:55:40 +02:00
lilleman 9f9bb77524 Answer the prose review's first round 2026-10-01 22:53:49 +02:00
lilleman 4ff316884e Port main's subagent rule and Opus 5.5 model into rebuild 2026-10-01 22:52:55 +02:00
lilleman 2a321aeaa8 Merge pull request 'Title each decision by what holds now, and make the small fixes filed against bin/, the README, .gitignore and stability-reviewer' (#179) from index-titles into rebuild 2026-10-01 22:47:19 +02:00
lilleman 4e71611e59 Answer the prose review's second round 2026-10-01 22:46:10 +02:00
lilleman e39f7c3eeb Point todo.md's line references at the lines this chunk moved 2026-10-01 22:44:56 +02:00
lilleman f118809d85 Answer the prose review's first round 2026-10-01 22:44:09 +02:00
lilleman be2d96a808 Answer the product-owner review's first round 2026-10-01 22:39:51 +02:00
lilleman 2f3b2f0f6c Un-ignore bin/loop_claude/ itself, and test that no tracked file is ignored 2026-10-01 22:35:22 +02:00
lilleman 471b86db5e Title each decision by what holds now, and make the small fixes filed against bin/, the README, .gitignore and stability-reviewer 2026-10-01 22:32:44 +02:00
lilleman c260a24ff7 Scope todo.md's panel line to the items it introduces 2026-10-01 22:25:02 +02:00
lilleman 8cc2ad05d0 Plan every remaining item into 0.1.0 2026-10-01 22:22:15 +02:00
lilleman 83d3325471 Merge pull request 'Write larv-review §3's record, round and re-entry rules as numbered rules, and exempt a chunk into rebuild from the scoring run there' (#178) from larv-review-rules into rebuild 2026-10-01 22:19:20 +02:00
lilleman 000c76d8b6 Answer the prose review's third round 2026-10-01 22:17:21 +02:00
lilleman 4c0f593a6a Answer the prose review's second round 2026-10-01 22:16:58 +02:00
lilleman 9dc4d80740 Answer the prose review's first round 2026-10-01 22:16:32 +02:00
lilleman 02216fc6e9 Write larv-review §3's record, round and re-entry rules as numbered rules, and exempt a chunk into rebuild from the scoring run there 2026-10-01 22:14:58 +02:00
lilleman 5876248afe Merge pull request 'File the places the panel on rebuild at 8585257 named under the floor' (#177) from floor-8585257 into rebuild 2026-10-01 22:09:28 +02:00
lilleman 6ddcbaf961 Ratchet each score on its best run on rebuild 2026-10-01 22:08:44 +02:00
lilleman 4a8236e751 Credit written_by_human's least-want count to the three seats asked 2026-10-01 22:06:28 +02:00
lilleman c5ebc54f60 Answer the prose review's second round, and ratchet each score on its best run 2026-10-01 22:06:22 +02:00
lilleman e93359a635 Count the seats each place cites as the reports do 2026-10-01 22:04:40 +02:00
lilleman 2bd29db69c Answer the prose review's first round 2026-10-01 22:04:34 +02:00
lilleman e1852ef390 File the places the panel on rebuild at 8585257 named under the floor 2026-10-01 22:02:35 +02:00
lilleman 8585257e84 Merge pull request 'Ground the judge's quote with markdown emphasis and whitespace ignored' (#176) from grounded-emphasis into rebuild 2026-10-01 21:56:37 +02:00
lilleman 4e0437ee58 Merge pull request 'Let a decision name any technical principle under principles/' (#165) from principle-scope into main 2026-09-30 23:16:30 +02:00
lilleman 7b5fe7d78d Let a decision name any technical principle under principles/ 2026-09-30 23:16:25 +02:00
lilleman cdb120c780 Merge pull request 'Add functional core, imperative shell to the technical principles, and let a decision link one' (#162) from functional-core into main 2026-09-30 22:55:30 +02:00
lilleman e99ae11f74 Add functional core, imperative shell to the technical principles, and let a decision link one 2026-09-30 22:55:22 +02:00
lilleman 8135bef08a Merge pull request 'Ship a rebuild chunk with its worktree's larv-review' (#160) from rebuild-review-rule into main 2026-09-30 21:37:04 +02:00
lilleman 093e75a9af Ship a rebuild chunk with its worktree's larv-review 2026-09-30 21:36:55 +02:00
lilleman 3b3bf1a543 Run this repo on Opus 5.5 2026-09-30 17:02:47 +02:00
lilleman acb95f7ead Merge pull request 'Ground the judge's quote with markdown emphasis and whitespace ignored' (#155) from judge-quote-markdown into main 2026-09-30 16:39:39 +02:00
lilleman 59ef9e209b Ground the judge's quote with markdown emphasis and whitespace ignored 2026-09-30 16:39:33 +02:00
lilleman 8e6b7239b3 Give a subagent the least its job needs, stated in its prompt 2026-09-29 10:59:46 +02:00
47 changed files with 1057 additions and 380 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
{
"model": "claude-fable-5-1"
"model": "claude-opus-5-5"
}
+10 -3
View File
@@ -18,15 +18,22 @@
!agents/
!agents/*.md
!bin/
!bin/*
!bin/loop-claude
!bin/loop_claude/
!bin/loop_claude/**/
!bin/loop_claude/**/*.py
!bin/test_*.py
!docs/
!docs/*.md
!principles/
!principles/*.md
!skills/
!skills/comprehension-panel/
!skills/comprehension-panel/**
!skills/comprehension-panel/*.md
!skills/larv-review/
!skills/larv-review/**
!skills/larv-review/*.md
!workflow-bench/
!workflow-bench/bench.py
!workflow-bench/judge-prompt.md
!workflow-bench/judge.py
!workflow-bench/run-prompt.md
+13 -26
View File
@@ -1,36 +1,23 @@
# Working here
**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. larv-review leaves a PR from `rebuild` into main ready and unmerged.
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 interrupts, not the worker's self-report
- loop-claude: one session per project, at a fixed id from its full path, and a second loop refuses to start
- loop-claude: the trust file is rewritten before an interrupt
- loop-claude: every worktree of the checkout is trusted before an interrupt
- bin/: the Python floor is README's Install prerequisite
- bin/: host python, no container
- 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: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
- bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
- bin/: the tools and their tests run on the host's Python, with no container
- comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it
- vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
- loop-claude: a reload into an older file is unsupported
- loop-claude: a CR-only README.md is reported at line 1
- loop-claude: each project's model lives in loop-claude's own file
- rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole
- review: the round cap counts a pass's rounds per chunk
- review: a 🟢's or ❓'s fix re-enters like any fix
- review: only a record older than the chunk lets a pass skip
- loop-claude: the judge is retried alone, on its own counter
- loop-claude: the judge loads `CLAUDE.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
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
- loop-claude: a loop running main's script stops once at the cut-over
- rebuild: a chunk into `rebuild` takes no comprehension scoring run
- loop-claude: a `claude` that cannot start is a failed worker run, retried
- bin/: mypy checks `loop_claude`'s types in the tests
- rebuild: rebuild's larv-review reviews a chunk into `rebuild`
- review: an ask no user answers leaves the PR unmerged
- review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it
- loop-claude: every claude it starts bypasses permissions inside its sandbox
- stats: a chunk's cost and review numbers are kept in the transcript archive
- bench: a workflow change merges only once three benches rule it better
- chunk: as large as one purpose allows
- loop-claude: the planned stats line goes in the transcript archive, off the remote
- workflow changes: a change merges only once three planned benches rule it better
- review: `/security-review` is the security pass of record
- review: the premises chunk's whole review is the human's approval
+4 -1
View File
@@ -4,14 +4,17 @@
- Run `loop-claude` only in a sandbox with no direct access to production: every claude it starts skips every permission prompt.
- First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does.
- `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone.
- `settings.json`, the agents and the status line run unedited on any machine with README → Install's prerequisites; the status line shows reset times in the machine's own time zone.
- `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one.
- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog.
- `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run.
- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1.
- `loop-claude`'s exit-2 message says what the human is needed for.
- `loop-claude` exits 1 saying why when `git`, or python for a reload, cannot start.
- `loop-claude` shows the judge's reply when it rejects the judge's verdict.
- `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`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `<sha256>.verdict.md`; a transcript it cannot archive exits 1.
- `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.
+5 -5
View File
@@ -79,7 +79,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 decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open.
**A decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **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 decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves 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.
@@ -104,8 +104,9 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`,
## Working with the codebase
- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out.
- Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along.
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app <tool> …`.
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app <tool> …`.
- Tear down test containers after a run.
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create.
- Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match").
- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first.
- Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds.
@@ -128,9 +129,8 @@ The rules every project follows, compose-not-entangle first: `~/.claude/principl
- Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both.
## Handoffs
- One document per project: `~/code/claude-handoffs/<project>_<YYYY-MM-DD>.md`, with its supporting files (scripts, probes, saved sessions) under `~/code/claude-handoffs/<project>/<YYYY-MM-DD>/`, dated the day they were written.
- Each document stands alone — projects move in parallel, so never reference another project's handoff. A fact two of them share (a test site, where credentials live) is stated in each, or kept in a memory file and named there.
- Content: only what the repo cannot hold — probe results, where credentials live. What is done and the next step live in the plan; goals, audience and decisions in `README.md`/`AGENTS.md`. A handoff never restates them: the repo's copy travels with the code and this one does not.
- Write no handoff document. The repo holds everything the next session needs: the plan, the decisions, and every script, sketch or measurement those depend on. A file outside the repo is unreachable from another machine's checkout.
- Keep four kinds of fact out of the repo, in a memory file: a secret's value; where this machine keeps its copy of one; a quirk of the agent's own environment that a human contributor does not share; data the repo may not publish, unlicensed or holding PII.
## Web research
- **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible.
+3 -3
View File
@@ -1,6 +1,6 @@
# Claude Code configuration
My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `statusline.sh`; `CHANGELOG.md` and `todo.md`; and the tools in `bin/`.
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; `statusline.sh`; `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
@@ -20,7 +20,7 @@ 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`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it 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.
Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`, and `jq` and GNU `date` for `statusline.sh`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it 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.
## Release
@@ -30,7 +30,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that co
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → "bin/: host python, no container", "bin/: the Python floor is README's Install prerequisite"): `python3 -m unittest discover -s bin -p 'test_*.py'`
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'`
## Tracking a new file
+1 -1
View File
@@ -6,7 +6,7 @@ tools: Read, Grep, Glob
You check one yardstick against the whole project, never a diff, in every round: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`.
Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. Read the yardstick, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardstick, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
- Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why.
- A departure a `todo.md` item plans away is named with that item, not raised.
+1 -1
View File
@@ -45,7 +45,7 @@ Before anything else, **read the shared principles** at `~/.claude/principles/`.
## Your Output Format
Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. After the verdict:
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict:
**Surface affected**: <one line>
+2 -2
View File
@@ -6,7 +6,7 @@ tools: Read, Grep, Glob
You read the prose as someone who did not write it: you see only what it says, never what the author meant.
The bar: `~/.claude/CLAUDE.md` → "Prose" and "Comments and documentation". Read both each time — they change. Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md.
The bar: `~/.claude/CLAUDE.md` → "Prose" and "Comments and documentation". Read both each time — they change. Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md.
## Checks, in priority order
@@ -14,7 +14,7 @@ Run them in this order. A fix for a later check never breaks an earlier one.
1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence.
2. **Most important first.** Name the document's reader and what they want to know first. Check that the sections run in that order, then the paragraphs within each section, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**.
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a decision to `docs/decisions.md` with its index line in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs ("A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a decision to `docs/decisions.md` with its title in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs ("A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
4. **Short.** Words that do not clearly help 1–3 fail. Fix: **Cut**.
Also report a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
+2 -2
View File
@@ -11,7 +11,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
2. **Read every file 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.
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 documented container tooling (never host runtimes; tear down test containers afterwards). A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script in a temp dir, a targeted test run — before reporting it. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script 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.**
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
- *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity).
@@ -128,7 +128,7 @@ Every PR gets at least this sweep.
## Output Format
Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with:
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with:
- **Location**: File and line/function
- **Issue**: Clear description of the problem
- **Risk**: What could go wrong in production
+2 -2
View File
@@ -6,7 +6,7 @@ import sys
LAUNCHER = pathlib.Path(__file__).resolve()
sys.path.insert(0, str(LAUNCHER.parent))
from loop_claude import paths
from loop_claude import effects, paths
from loop_claude.loop import main
sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd()))
sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd(), effects.system_effects()))
+2 -1
View File
@@ -1,9 +1,10 @@
import json
import pathlib
from loop_claude.claude_code.formats import models_in
def offered_models(folder) -> list[tuple[str, object]]:
def offered_models(folder: pathlib.Path) -> list[tuple[str, object]]:
files = []
for path in folder.glob("*.json"):
try:
+38 -28
View File
@@ -4,7 +4,7 @@ import json
from loop_claude.outcome import Failure
def parse(raw) -> dict | None:
def parse(raw: str | bytes) -> dict | None:
try:
entry = json.loads(raw)
except ValueError:
@@ -12,41 +12,52 @@ def parse(raw) -> dict | None:
return entry if isinstance(entry, dict) else None
def content(entry) -> object:
def content(entry: dict) -> object:
message = entry.get("message")
return message.get("content") if isinstance(message, dict) else None
def parts(entry) -> list:
def parts(entry: dict) -> list:
found = content(entry)
return found if isinstance(found, list) else []
# Alike in the transcript and in stream-json: {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}}
def assistant_parts(entry) -> list:
def assistant_parts(entry: dict) -> list:
return parts(entry) if entry.get("type") == "assistant" else []
def written_by_human(entry) -> bool:
def written_by_human(entry: dict) -> bool:
"""Whether the human wrote a "user" entry; Claude Code writes the rest."""
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
if entry.get("isMeta") or entry.get("promptSource") == "sdk":
if tagged_as_injected(entry):
return False
# {"type": "user", "message": {"content": "<command-name>/model</command-name>\n..."}}
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
# Claude Code tags what it injects, and an entry without promptSource carries no other mark, so a leading < is its own.
if isinstance(text := content(entry), str):
source = entry.get("promptSource")
return source != "system" and (source == "typed" or not text.startswith("<"))
texts = [part_text(part) for part in parts(entry)]
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
text = content(entry)
return string_by_human(entry, text) if isinstance(text, str) else blocks_by_human(parts(entry))
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
def tagged_as_injected(entry: dict) -> bool:
return bool(entry.get("isMeta")) or entry.get("promptSource") in ("sdk", "system")
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
# {"type": "user", "message": {"content": "<command-name>/model</command-name>\n..."}}
def string_by_human(entry: dict, text: str) -> bool:
# Without promptSource, nothing else says who wrote the entry, so a leading < counts as Claude Code's.
return entry.get("promptSource") == "typed" or not text.startswith("<")
# {"type": "user", "message": {"content": [{"type": "text", "text": "merge it"}]}}
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
def blocks_by_human(blocks: list) -> bool:
texts = [part_text(block) for block in blocks]
return bool(texts) and all(text is not None and not text.startswith("[Request interrupted") for text in texts)
def human_text(entry) -> str | None:
def human_text(entry: dict) -> str | None:
"""What the human wrote in the entry, or None where Claude Code wrote it."""
if (queued := queued_human_text(entry)) is not None:
return queued
@@ -58,7 +69,7 @@ def human_text(entry) -> str | 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) -> str | None:
def queued_human_text(entry: dict) -> str | None:
attachment = entry.get("attachment") if entry.get("type") == "attachment" else None
if not isinstance(attachment, dict) or attachment.get("type") != "queued_command" or not isinstance(origin := attachment.get("origin"), dict) or origin.get("kind") != "human":
return None
@@ -66,29 +77,28 @@ def queued_human_text(entry) -> str | None:
# {"type": "text", "text": "ok"}
def part_text(part) -> str | None:
def part_text(part: object) -> str | None:
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
def tool_call(part) -> tuple[object, object] | None:
def tool_call(part: object) -> tuple[object, object] | None:
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
# stream-json's last line: {"type": "result", "subtype": "success", ...}
def ends_stream(event) -> bool:
def ends_stream(event: dict) -> bool:
return event.get("type") == "result"
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
def structured_output(stdout) -> object:
def structured_output(stdout: str) -> object:
return (parse(stdout) or {}).get("structured_output")
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def mark_trusted(config, roots) -> tuple[dict, list[str]] | Failure:
projects = config.get("projects", {}) if isinstance(config, dict) else None
if not isinstance(projects, dict):
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict):
return Failure('not an object whose "projects" is an object')
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
@@ -98,7 +108,7 @@ def mark_trusted(config, roots) -> tuple[dict, list[str]] | Failure:
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def models_in(files) -> list[tuple[str, object]]:
def models_in(files: list[object]) -> list[tuple[str, object]]:
"""The (id, name) of each model in the newest of the parsed catalog files."""
newest: dict = {}
for data in files:
+18 -9
View File
@@ -3,9 +3,11 @@ import glob
import os
import pathlib
import shutil
import sys
import uuid
from loop_claude.outcome import Failure
from loop_claude.paths import Paths
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@@ -17,25 +19,32 @@ class Session:
name: str
def session_for(project, paths) -> Session:
def session_for(project: str, paths: Paths) -> Session:
# "A " is the human's cue in the session picker that the session is the loop's.
name = f"A {project} loop-claude"
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
def transcript_file(session) -> str:
def transcript_file(session: Session) -> str | None:
hit = glob.glob(os.path.join(glob.escape(str(session.claude_code_transcripts)), "*", f"{session.id}.jsonl"))
return hit[0] if hit else ""
return hit[0] if hit else None
def delete_session(session) -> None:
def session_open(session: Session) -> bool:
return transcript_file(session) is not None
def delete_session(session: Session) -> Failure | None:
path = transcript_file(session)
if not path:
return
if path is None:
return None
stem = path.removesuffix(".jsonl")
# <session id>.jsonl, <session id>/subagents/, and from older versions <session id>.superseded-1789290815002/ and <session id>.orphaned-*.jsonl
for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"):
# The transcript goes last: a failed delete leaves a session that session_open still sees, never a new session with this id beside the old one's files.
for sibling in sorted(glob.glob(glob.escape(stem) + "*"), key=lambda sibling: sibling == path):
try:
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
except OSError as failure:
print(f"could not remove {sibling}: {failure}", file=sys.stderr)
return Failure(f"could not delete {sibling}: {failure.strerror or failure}; delete every file and folder matching {stem}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session")
return None
+4 -4
View File
@@ -4,7 +4,7 @@ from loop_claude.claude_code.formats import assistant_parts, human_text, parse,
from loop_claude.outcome import Failure
def read(path) -> list[dict] | Failure:
def read(path: str) -> list[dict] | Failure:
try:
with open(path, "rb") as handle:
return [entry for raw in handle if (entry := parse(raw))]
@@ -12,11 +12,11 @@ def read(path) -> list[dict] | Failure:
return Failure(f"could not read the transcript {path}: {failure.strerror}")
def human_turns(entries) -> int:
def human_turns(entries: list[dict]) -> int:
return sum(1 for entry in entries if human_text(entry) is not None)
def render(entries) -> str:
def render(entries: list[dict]) -> str:
lines = []
for entry in entries:
lines += [line for part in assistant_parts(entry) if (line := part_line(part))]
@@ -25,7 +25,7 @@ def render(entries) -> str:
return "\n\n".join(lines)
def part_line(part, limit=400) -> str:
def part_line(part: object, limit: int = 400) -> str:
if (text := part_text(part)) and text.strip():
return text
if call := tool_call(part):
+2 -1
View File
@@ -1,4 +1,5 @@
import json
import pathlib
import sys
from loop_claude.claude_code.formats import mark_trusted
@@ -7,7 +8,7 @@ from loop_claude.outcome import Failure
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
def trust(config, roots) -> None:
def trust(config: pathlib.Path, roots: list[str]) -> None:
try:
with open(config, encoding="utf-8") as handle:
data = json.load(handle)
+2 -1
View File
@@ -3,9 +3,10 @@ import sys
from loop_claude.file_writes import make_private, replace_file
from loop_claude.outcome import Failure
from loop_claude.paths import Paths
def archive(project, path, note, paths) -> Failure | None:
def archive(project: str, path: str, note: str, paths: Paths) -> Failure | None:
folder = paths.archive / project
try:
with open(path, "rb") as handle:
+8 -8
View File
@@ -1,31 +1,31 @@
import subprocess
import sys
import uuid
from loop_claude import human_needed
from loop_claude.claude_code.transcript import human_turns, read
from loop_claude.claude_code.trust import trust
from loop_claude.effects import Effects
from loop_claude.outcome import Failure, Stop
from loop_claude.paths import Paths
from loop_claude.project.checkout import checkouts
TO = "answer the question above"
def interrupt(root, session_id, model, path, question, paths) -> Stop | None:
def interrupt(root: str, session_id: uuid.UUID, model: str, path: str, question: str, paths: Paths, effects: Effects) -> Stop | None:
print(f"\n{question}", file=sys.stderr)
if stop := human_needed.off_terminal(TO):
if stop := human_needed.off_terminal(TO, effects.on_terminal()):
return stop
trust(paths.claude_json, checkouts(root))
trust(paths.claude_json, checkouts(root, effects))
entries = read(path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
before = human_turns(entries)
try:
subprocess.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
effects.claude_on_terminal(["--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], root)
except OSError as failure:
return Stop(1, f"could not start claude for the interrupt: {failure.strerror}")
entries = read(path)
if isinstance(entries, Failure):
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
if human_turns(entries) <= before:
return human_needed.stop(TO, "the interrupt ended with nothing typed")
return None
return None if human_turns(entries) > before else human_needed.stop(TO, "the interrupt ended with nothing typed")
+27 -21
View File
@@ -1,10 +1,11 @@
import dataclasses
import json
import subprocess
import typing
from loop_claude.claude_code.formats import 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.outcome import Failure, Stop
JUDGE_RULES = (
@@ -28,23 +29,23 @@ JUDGE_RULES = (
)
@dataclasses.dataclass(frozen=True)
class Verdict:
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."})
VERDICT_TYPES = typing.get_type_hints(Verdict)
REPLY_TYPES = typing.get_type_hints(Reply)
JSON_TYPES = {bool: "boolean", str: "string"}
JUDGE_SCHEMA = {
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[VERDICT_TYPES[field.name]]} for field in dataclasses.fields(Verdict)},
"required": list(VERDICT_TYPES),
"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, task, premises, transcript, model) -> Verdict | Stop:
def judge(root: str, task: str, premises: str, transcript: str, model: str, effects: Effects) -> Verdict | Stop:
# 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",
@@ -56,23 +57,25 @@ def judge(root, task, premises, transcript, model) -> Verdict | Stop:
"--tools", "",
]
prompt = judge_prompt(task, premises, transcript)
return retried("judge", lambda: run_judge(root, args, prompt, transcript))
return retried("judge", lambda: run_judge(root, args, prompt, transcript, effects), effects)
def run_judge(root, args, prompt, transcript) -> Verdict | Failure:
def run_judge(root: str, args: list[str], prompt: str, transcript: str, effects: Effects) -> Verdict | Failure:
try:
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
proc = effects.claude(args, root, prompt)
except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}")
if proc.returncode != 0:
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
verdict = verdict_from(structured_output(proc.stdout))
if isinstance(verdict, Verdict) and not grounded(verdict, transcript):
return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else ""))
if isinstance(verdict, Failure):
return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}")
if not grounded(verdict.evidence, transcript):
return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt) else ""))
return verdict
def judge_prompt(task, premises, transcript) -> str:
def judge_prompt(task: str, premises: str, transcript: str) -> str:
return (
f"From README.md:\n{premises}\n\n"
f"The task an agent was given:\n{task}\n\n"
@@ -82,22 +85,25 @@ def judge_prompt(task, premises, transcript) -> str:
)
def verdict_from(output) -> Verdict | Failure:
def verdict_from(output: object) -> Verdict | Failure:
if not isinstance(output, dict):
return Failure("the judge returned no verdict")
for name, kind in VERDICT_TYPES.items():
for name, kind in REPLY_TYPES.items():
if not isinstance(output.get(name), kind):
return Failure(f"the judge's verdict has no {name} of type {JSON_TYPES[kind]}")
if output["interrupt"] and not output["question"].strip():
return Failure("the judge interrupted without a question")
return Verdict(**{name: output[name] for name in VERDICT_TYPES})
# 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"])
def grounded(verdict, transcript) -> bool:
evidence = plain(verdict.evidence)
return evidence != "" and evidence in plain(transcript)
def grounded(evidence: str, transcript: str) -> bool:
quoted = plain(evidence)
return quoted != "" and quoted in plain(transcript)
def plain(text) -> str:
def plain(text: str) -> str:
# The judge drops markdown emphasis and reflows whitespace when it quotes.
return " ".join(text.replace("*", "").replace("_", "").split())
+3 -3
View File
@@ -1,13 +1,13 @@
import sys
import time
import typing
from loop_claude.effects import Effects
from loop_claude.outcome import Failure, Stop
T = typing.TypeVar("T")
def retried(who, attempt: typing.Callable[[], T | Failure]) -> T | Stop:
def retried(who: str, attempt: typing.Callable[[], T | Failure], effects: Effects) -> T | Stop:
failures = 0
while True:
failures += 1
@@ -17,4 +17,4 @@ def retried(who, attempt: typing.Callable[[], T | Failure]) -> T | Stop:
if failures == 3:
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)
time.sleep(60)
effects.sleep(60)
+73
View File
@@ -0,0 +1,73 @@
import dataclasses
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict
@dataclasses.dataclass(frozen=True)
class Working:
"""The worker runs."""
@dataclasses.dataclass(frozen=True)
class Judging:
transcript_path: str
@dataclasses.dataclass(frozen=True)
class Interrupting:
transcript_path: str
question: str
@dataclasses.dataclass(frozen=True)
class Finishing:
transcript_path: str
@dataclasses.dataclass(frozen=True)
class Ended:
"""The cycle is over."""
Active = Working | Judging | Interrupting | Finishing
State = Active | Ended
@dataclasses.dataclass(frozen=True)
class WorkerRan:
transcript_path: str
@dataclasses.dataclass(frozen=True)
class Ruled:
verdict: Verdict
@dataclasses.dataclass(frozen=True)
class Answered:
pass
@dataclasses.dataclass(frozen=True)
class Archived:
pass
Event = WorkerRan | Ruled | Answered | 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()):
return Finishing(transcript_path)
case Judging(), Ruled(Unfinished()):
return Ended()
case Interrupting(transcript_path), Answered():
return Judging(transcript_path)
case Finishing(), Archived():
return Ended()
raise ValueError(f"no transition from {state} on {event}")
+55 -28
View File
@@ -1,12 +1,15 @@
import dataclasses
import typing
from loop_claude.claude_code.session import Session, delete_session, transcript_file
from loop_claude.claude_code.session import Session, delete_session, session_open, transcript_file
from loop_claude.claude_code.transcript import read, render
from loop_claude.cycle.archive import archive
from loop_claude.cycle.interrupt import interrupt
from loop_claude.cycle.judge import Verdict, judge
from loop_claude.cycle.judge import judge
from loop_claude.cycle.retry import retried
from loop_claude.cycle.states import Active, Answered, Archived, Ended, Event, Finishing, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition
from loop_claude.cycle.worker import run_worker, worker_args
from loop_claude.effects import Effects
from loop_claude.outcome import Failure, Stop
from loop_claude.paths import Paths
from loop_claude.project.models import Models
@@ -14,6 +17,7 @@ from loop_claude.project.models import Models
@dataclasses.dataclass(frozen=True)
class Cycle:
effects: Effects
models: Models
paths: Paths
premises: str
@@ -23,33 +27,56 @@ class Cycle:
task: str
def run_cycle(cycle) -> Stop | None:
if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, bool(transcript_file(cycle.session))))):
return stop
path = transcript_file(cycle.session)
if not path:
return Stop(1, f"claude left no transcript for session {cycle.session.id}")
verdict = judge_through_interrupts(cycle, path)
if isinstance(verdict, Stop):
return verdict
if verdict.finished:
if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths):
return Stop(1, failure.reason)
delete_session(cycle.session)
def run_cycle(cycle: Cycle) -> Stop | None:
state: State = Working()
while not isinstance(state, Ended):
event = step(cycle, state)
if isinstance(event, Stop):
return event
state = transition(state, event)
return None
def judge_through_interrupts(cycle, path) -> Verdict | Stop:
# The interrupt appends to this transcript, so each pass judges and archives it anew.
while True:
entries = read(path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
verdict = judge(cycle.root, cycle.task, cycle.premises, render(entries), cycle.models.judge)
if isinstance(verdict, Stop) or not verdict.interrupt:
return verdict
if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{verdict.question}", cycle.paths):
return Stop(1, failure.reason)
if stop := interrupt(cycle.root, cycle.session.id, cycle.models.worker, path, verdict.question, cycle.paths):
return stop
def step(cycle: Cycle, state: Active) -> Event | Stop:
match state:
case Working():
return work(cycle)
case Judging(transcript_path):
return rule(cycle, transcript_path)
case Interrupting(transcript_path, question):
return ask(cycle, transcript_path, question)
case Finishing(transcript_path):
return close(cycle, transcript_path)
case _:
typing.assert_never(state)
def work(cycle: Cycle) -> WorkerRan | 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):
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 rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
entries = read(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)
return verdict if isinstance(verdict, Stop) else Ruled(verdict)
def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop:
# The interrupt appends to this transcript, so it is archived at each question.
if failure := archive(cycle.project, transcript_path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{question}", 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()
def close(cycle: Cycle, transcript_path: str) -> Archived | Stop:
if failure := archive(cycle.project, transcript_path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths):
return Stop(1, failure.reason)
if failure := delete_session(cycle.session):
return Stop(1, failure.reason)
return Archived()
+20
View File
@@ -0,0 +1,20 @@
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 -14
View File
@@ -1,24 +1,23 @@
import subprocess
from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse
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.outcome import Failure
def run_worker(root, args) -> Failure | None:
def run_worker(root: str, args: list[str], effects: Effects) -> Failure | None:
try:
proc = subprocess.Popen(["claude", *args], cwd=root, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
proc = effects.stream_claude(args, root)
except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}")
with proc:
done = False
for raw in proc.stdout or ():
event = parse(raw) or {}
done = done or ends_stream(event)
for part in assistant_parts(event):
if line := part_line(part, 160):
print(line, flush=True)
code = proc.wait()
done = False
for raw in proc.lines():
event = parse(raw) or {}
done = done or ends_stream(event)
for part in assistant_parts(event):
if line := part_line(part, 160):
print(line, flush=True)
code = proc.wait()
if code < 0:
return Failure(f"claude killed by signal {-code}")
if code:
@@ -26,7 +25,7 @@ def run_worker(root, args) -> Failure | None:
return None if done else Failure("claude exited 0 without a result event")
def worker_args(task, session, model, resuming) -> list[str]:
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)]
else:
+53
View File
@@ -0,0 +1,53 @@
import dataclasses
import os
import subprocess
import sys
import time
import typing
class Streaming(typing.Protocol):
"""A started claude whose stream-json lines arrive as it works."""
def lines(self) -> typing.Iterable[str]: ...
def wait(self) -> int: ...
@dataclasses.dataclass(frozen=True)
class Effects:
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
claude_on_terminal: typing.Callable[[list[str], str], int]
execv: typing.Callable[[str, list[str]], None]
git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
input: typing.Callable[[str], str]
on_terminal: typing.Callable[[], bool]
python: typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
sleep: typing.Callable[[float], None]
stream_claude: typing.Callable[[list[str], str], Streaming]
class Popened:
def __init__(self, args: list[str], cwd: str) -> None:
self.proc = subprocess.Popen(["claude", *args], cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
def lines(self) -> typing.Iterable[str]:
with self.proc:
yield from self.proc.stdout or ()
def wait(self) -> int:
return self.proc.wait()
def system_effects() -> Effects:
return Effects(
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
claude_on_terminal=lambda args, cwd: subprocess.run(["claude", *args], cwd=cwd).returncode,
execv=os.execv,
git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True),
input=input,
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True),
sleep=time.sleep,
stream_claude=Popened,
)
+5 -3
View File
@@ -1,10 +1,12 @@
import json
import os
import pathlib
import typing
from loop_claude.outcome import Failure
def make_private(folder) -> None:
def make_private(folder: pathlib.Path) -> None:
mask = os.umask(0o077)
try:
os.makedirs(folder, exist_ok=True)
@@ -12,11 +14,11 @@ def make_private(folder) -> None:
os.umask(mask)
def replace_json(path, data, **dump) -> Failure | None:
def replace_json(path: pathlib.Path, data: object, **dump: typing.Any) -> Failure | None:
return replace_file(path, json.dumps(data, **dump).encode())
def replace_file(path, data) -> Failure | None:
def replace_file(path: pathlib.Path, data: bytes) -> Failure | None:
staged = f"{path}.{os.getpid()}"
try:
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600
+3 -5
View File
@@ -1,13 +1,11 @@
import sys
from loop_claude.outcome import Stop
def stop(to, but) -> Stop:
def stop(to: str, but: str) -> Stop:
return Stop(2, f"the human is needed to {to}, but {but}")
def off_terminal(to) -> Stop | None:
if sys.stdin.isatty() and sys.stdout.isatty():
def off_terminal(to: str, on_terminal: bool) -> Stop | None:
if on_terminal:
return None
return stop(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
+33 -27
View File
@@ -10,12 +10,13 @@ on the terminal, every worktree first marked trusted in ~/.claude.json. An unfin
its session next cycle; the next chunk starts a fresh session.
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude
leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a
reload with unreadable state, or 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 verdict misses or
mistypes a field, interrupts without a question, or quotes nothing in the transcript.
Exit 1: no task, git cannot start or finds no checkout, no premises, a models file it cannot read or
write, claude leaves no transcript or one it cannot read or archive, a finished chunk's session it
cannot delete, claude cannot start for an interrupt, python cannot start for a reload, a reload whose
loop run it cannot read, or 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 verdict misses or mistypes
a field, interrupts without a question, or quotes nothing in the transcript.
Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a
terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any
open session.
@@ -34,20 +35,24 @@ A change to bin/loop-claude or bin/loop_claude/**/*.py takes effect at the next
loop-claude --help succeeds.
"""
import dataclasses
import pathlib
import sys
import typing
from loop_claude.claude_code.session import session_for
from loop_claude.cycle.steps import Cycle, run_cycle
from loop_claude.loop.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint
from loop_claude.effects import Effects
from loop_claude.loop.reload import RELOAD_FLAG, LoopRun, decode_handed, exec_if_edited, fingerprint
from loop_claude.outcome import Stop
from loop_claude.paths import Paths
from loop_claude.project.checkout import checkout_root, project_name
from loop_claude.project.models import project_models
from loop_claude.project.premises import read_premises
def main(argv, env, paths, launcher, cwd) -> int:
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
try:
stop = run_loop(argv, env, paths, launcher, cwd)
stop = run_loop(argv, env, paths, launcher, cwd, effects)
except KeyboardInterrupt:
stop = Stop(130, "")
if stop.reason:
@@ -55,35 +60,36 @@ def main(argv, env, paths, launcher, cwd) -> int:
return stop.code
def run_loop(argv, env, paths, launcher, cwd) -> Stop:
state = loop_state(argv, cwd)
if isinstance(state, Stop):
return state
def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> Stop:
loop_run = loop_run_from(argv, cwd, effects)
if isinstance(loop_run, Stop):
return loop_run
baseline = fingerprint(launcher)
project = project_name(state.root, paths.code)
project = project_name(loop_run.root, paths.code)
session = session_for(project, paths)
while True:
exec_if_edited(launcher, baseline, state)
state = dataclasses.replace(state, cycle_number=state.cycle_number + 1)
premises = read_premises(state.root)
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
return stop
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
premises = read_premises(loop_run.root)
if isinstance(premises, Stop):
return premises
models = project_models(project, paths, env)
models = project_models(project, paths, env, effects)
if isinstance(models, Stop):
return models
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
if stop := run_cycle(Cycle(models=models, paths=paths, premises=premises, project=project, root=state.root, session=session, task=state.task)):
print(f"\n=== cycle {loop_run.cycle_number} ===", flush=True)
if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project=project, root=loop_run.root, session=session, task=loop_run.task)):
return stop
def loop_state(argv, cwd) -> LoopState | Stop:
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
if argv[:1] != [RELOAD_FLAG]:
task = " ".join(argv)
if task in ("", "-h", "--help"):
return Stop(0 if task else 1, __doc__.strip())
root = checkout_root(cwd)
return root if isinstance(root, Stop) else LoopState(0, root, task)
state = decode_state(argv[1], LoopState) if len(argv) == 2 else None
if not (state and state.root and state.task):
return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
return state
root = checkout_root(cwd, effects)
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 reload cannot read the loop run from {argv[1:]}; rerun loop-claude <task>")
return loop_run
+19 -12
View File
@@ -1,24 +1,27 @@
import dataclasses
import hashlib
import json
import os
import subprocess
import pathlib
import sys
import typing
from loop_claude.effects import Effects
from loop_claude.outcome import Stop
RELOAD_FLAG = "--reloaded"
T = typing.TypeVar("T")
# A field change stops a running loop at its next reload: the new script rejects the old fields.
@dataclasses.dataclass(frozen=True)
class LoopState:
class LoopRun:
"""One loop-claude run; a reload hands it to the new script as JSON on argv."""
cycle_number: int
root: str
task: str
def decode_state(handed, kind: type[T]) -> T | None:
def decode_handed(handed: str, kind: type[T]) -> T | None:
try:
fields = json.loads(handed)
except ValueError:
@@ -31,7 +34,7 @@ def decode_state(handed, kind: type[T]) -> T | None:
return kind(**fields)
def fingerprint(launcher) -> str:
def fingerprint(launcher: pathlib.Path) -> str:
digest = hashlib.sha256()
for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]:
try:
@@ -42,11 +45,15 @@ def fingerprint(launcher) -> str:
return digest.hexdigest()
def exec_if_edited(launcher, baseline, state) -> None:
def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, effects: Effects) -> Stop | None:
if fingerprint(launcher) == baseline:
return
trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True)
if trial.returncode != 0:
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
return
os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))])
return None
try:
trial = effects.python([str(launcher), "--help"])
if trial.returncode != 0:
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
return None
effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
except OSError as failure:
return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude <task>")
return None
+1 -1
View File
@@ -3,7 +3,7 @@ import dataclasses
@dataclasses.dataclass(frozen=True)
class Failure:
"""A step failed and its caller decides: `retried` reruns a worker or judge run until it fails three times running; anything else becomes a Stop or a warning."""
"""A step failed, for reason; its caller decides what follows."""
reason: str
+2 -1
View File
@@ -1,5 +1,6 @@
import dataclasses
import pathlib
import typing
@dataclasses.dataclass(frozen=True)
@@ -12,7 +13,7 @@ class Paths:
models_file: pathlib.Path
def paths_from(home, env) -> Paths:
def paths_from(home: pathlib.Path, env: typing.Mapping[str, str]) -> Paths:
claude = home / ".claude"
return Paths(
archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
+13 -6
View File
@@ -1,22 +1,29 @@
import subprocess
import pathlib
from loop_claude.effects import Effects
from loop_claude.outcome import Stop
def checkout_root(cwd) -> str | Stop:
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True)
def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop:
try:
found = effects.git(["rev-parse", "--show-toplevel"], str(cwd))
except OSError as failure:
return Stop(1, f"could not start git: {failure.strerror}")
if found.returncode != 0:
return Stop(1, found.stderr.strip())
return found.stdout.strip()
def checkouts(root) -> list[str]:
def checkouts(root: str, effects: Effects) -> list[str]:
found = [root]
listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True)
try:
listing = effects.git(["worktree", "list", "--porcelain"], root)
except OSError:
return found
if listing.returncode == 0:
found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")]
return sorted(set(found))
def project_name(root, code) -> str:
def project_name(root: str, code: pathlib.Path) -> str:
return root.removeprefix(f"{code}/").lstrip("/")
+30 -16
View File
@@ -1,11 +1,15 @@
import dataclasses
import json
import pathlib
import sys
import typing
from loop_claude import human_needed
from loop_claude.claude_code.catalog import offered_models
from loop_claude.effects import Effects
from loop_claude.file_writes import replace_json
from loop_claude.outcome import Stop
from loop_claude.outcome import Failure, Stop
from loop_claude.paths import Paths
@dataclasses.dataclass(frozen=True)
@@ -14,24 +18,24 @@ class Models:
worker: str
def project_models(project, paths, env) -> Models | Stop:
def project_models(project: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> Models | Stop:
judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL")
if judge and worker:
return Models(judge, worker)
chosen = project_model(project, paths)
chosen = project_model(project, paths, effects)
if isinstance(chosen, Stop):
return chosen
return Models(judge or chosen, worker or chosen)
def project_model(name, paths) -> str | Stop:
def project_model(name: str, paths: Paths, effects: Effects) -> str | Stop:
saved = paths.models_file
models = read_models(saved)
if isinstance(models, Stop):
return models
if saved_model := models.get(name):
return saved_model
chosen = ask_model(name, saved, paths.model_catalog)
chosen = ask_model(name, saved, paths.model_catalog, effects)
if isinstance(chosen, Stop):
return chosen
# Reread: another loop may have saved its project while this one waited on the human.
@@ -44,7 +48,7 @@ def project_model(name, paths) -> str | Stop:
return chosen
def read_models(saved) -> dict[str, str] | Stop:
def read_models(saved: pathlib.Path) -> dict[str, str] | Stop:
try:
with open(saved, encoding="utf-8") as handle:
models = json.load(handle)
@@ -57,8 +61,8 @@ def read_models(saved) -> dict[str, str] | Stop:
return models
def ask_model(name, saved, folder) -> str | Stop:
if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}"):
def ask_model(name: str, saved: pathlib.Path, folder: pathlib.Path, effects: Effects) -> str | Stop:
if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}", effects.on_terminal()):
return stop
offered = offered_models(folder)
print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr)
@@ -68,14 +72,24 @@ def ask_model(name, saved, folder) -> str | Stop:
print(f" no model catalog cached in {folder}", file=sys.stderr)
while True:
try:
answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip()
answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ")
except EOFError:
print(file=sys.stderr)
return human_needed.stop(f"pick {name}'s model", "the input ended")
if not answer:
continue
if not (offered and answer.isdecimal()):
return answer
if 1 <= int(answer) <= len(offered):
return offered[int(answer) - 1][0]
print(f"pick 1 to {len(offered)}", file=sys.stderr)
picked = model_picked(answer, offered)
if isinstance(picked, Failure):
print(picked.reason, file=sys.stderr)
elif picked:
return picked
def model_picked(answer: str, offered: list[tuple[str, object]]) -> str | Failure | None:
"""The model the answer picks, a Failure naming the numbers to pick from, or None to ask again."""
answer = answer.strip()
if not answer:
return None
if not (offered and answer.isdecimal()):
return answer
if 1 <= int(answer) <= len(offered):
return offered[int(answer) - 1][0]
return Failure(f"pick 1 to {len(offered)}")
+2 -2
View File
@@ -3,7 +3,7 @@ import pathlib
from loop_claude.outcome import Stop
def read_premises(root) -> str | Stop:
def read_premises(root: str) -> str | Stop:
try:
found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8"))
except OSError as failure:
@@ -22,7 +22,7 @@ def read_premises(root) -> str | Stop:
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
def sections(text) -> dict[str, list[str]]:
def sections(text: str) -> dict[str, list[str]]:
blocks: list[tuple[str | None, list[str]]] = []
fenced = False
for line in text.splitlines():
+10
View File
@@ -0,0 +1,10 @@
import subprocess
import unittest
from test_python_floor import ROOT
class Gitignore(unittest.TestCase):
def test_ignores_no_tracked_file(self):
ignored = subprocess.run(["git", "ls-files", "-ci", "--exclude-standard"], capture_output=True, check=True, cwd=ROOT, text=True).stdout
self.assertEqual(ignored, "")
+255 -19
View File
@@ -2,18 +2,23 @@ import dataclasses
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import time
import unittest
import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude import file_writes
from loop_claude.claude_code import formats, transcript
from loop_claude.cycle import judge
from loop_claude import file_writes, paths
from loop_claude.claude_code import formats, session, transcript
from loop_claude.cycle import interrupt, judge, retry, states, steps, worker
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished
from loop_claude.effects import Effects
from loop_claude.loop import main, reload
from loop_claude.outcome import Failure, Stop
from loop_claude.project import premises
from loop_claude.project import checkout, models, premises
CWD = pathlib.Path("/c")
@@ -30,6 +35,223 @@ def queued(prompt, kind):
return {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": kind}, "prompt": prompt}}
class FakeEffects:
"""Effects that record each call and answer from a script, one answer per call."""
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True):
self.calls = []
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
self.terminal = on_terminal
def effects(self):
return Effects(
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
claude_on_terminal=lambda args, cwd: self.answer("claude_on_terminal", args),
execv=self.execv,
git=lambda args, cwd: self.answer("git", args),
input=lambda prompt: self.answer("input", prompt),
on_terminal=lambda: self.terminal,
python=lambda args: self.answer("python", args),
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
stream_claude=lambda args, cwd: self.answer("stream_claude", args),
)
def answer(self, seam, what):
self.calls.append((seam, what))
answer = self.scripts[seam].pop(0)
if isinstance(answer, BaseException):
raise answer
return answer(what) if callable(answer) else answer
def execv(self, path, args):
self.calls.append(("execv", args))
raise OSError(2, "No such file or directory")
def made(self, seam):
return [what for called, what in self.calls if called == seam]
def uuid7():
# Python 3.11, the floor, has no uuid.uuid7.
random = int.from_bytes(os.urandom(10))
return uuid.UUID(int=int(time.time() * 1000) << 80 | 7 << 76 | (random >> 62 & 0xFFF) << 64 | 2 << 62 | random & (1 << 62) - 1)
def ran(stdout="", code=0, stderr=""):
return subprocess.CompletedProcess([], code, stdout, stderr)
def judged(verdict, evidence="working"):
reply = {"evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict == "interrupt" else ""}
return ran(json.dumps({"structured_output": reply}))
class Worker:
"""A worker claude: writes a line to the session's transcript, then streams a result."""
def __init__(self, home):
self.home = home
def __call__(self, args):
flag = "--session-id" if "--session-id" in args else "--resume"
path = self.home / "projects" / "-fake" / f"{args[args.index(flag) + 1]}.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "a") as handle:
handle.write(json.dumps(assistant({"type": "text", "text": "working"})) + "\n")
return Streamed(0)
class Streamed:
def __init__(self, code):
self.code = code
def lines(self):
return [json.dumps({"type": "result"}) + "\n"]
def wait(self):
return self.code
class Transitions(unittest.TestCase):
def test_each_state_moves_on_its_events_and_only_on_them(self):
legal = (
(states.Working(), states.WorkerRan("/t"), states.Judging("/t")),
(states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")),
(states.Judging("/t"), states.Ruled(Finished("e")), states.Finishing("/t")),
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Ended()),
(states.Interrupting("/t", "q"), states.Answered(), states.Judging("/t")),
(states.Finishing("/t"), states.Archived(), states.Ended()),
)
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.Finishing("/t"), 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())
for state in every_state:
for event in every_event:
if (state, event) not in [(state, event) for state, event, _ in legal]:
with self.subTest(state=state, event=event), self.assertRaises(ValueError):
states.transition(state, event)
class Cycles(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.home = pathlib.Path(temp.name)
self.paths = paths.paths_from(self.home, {})
self.session = session.session_for("proj", self.paths)
def cycle(self, fake):
return steps.Cycle(effects=fake.effects(), models=models.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project="proj", root=str(self.home), session=self.session, task="Do it.")
def archived_verdicts(self):
return sorted(path.read_text() for path in (self.paths.archive / "proj").glob("*.verdict.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(steps.run_cycle(self.cycle(fake)))
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"])
self.assertIsNone(session.transcript_file(self.session))
def test_an_unfinished_chunk_keeps_its_session_and_the_next_cycle_resumes_it(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
self.assertIsNone(steps.run_cycle(self.cycle(fake)))
self.assertTrue(session.transcript_file(self.session))
self.assertIsNone(steps.run_cycle(self.cycle(fake)))
workers = fake.made("stream_claude")
self.assertIn("--session-id", workers[0])
self.assertIn("--resume", workers[1])
self.assertFalse((self.paths.archive / "proj").exists())
def test_an_interrupt_is_archived_answered_and_judged_again(self):
def answer(args):
with open(session.transcript_file(self.session), "a") as handle:
handle.write(json.dumps(human("the second")) + "\n")
return 0
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()])
self.assertIsNone(steps.run_cycle(self.cycle(fake)))
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\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])
@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)
(folder / "subagents").mkdir(parents=True)
folder.chmod(0o500)
self.addCleanup(folder.chmod, 0o700)
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
stop = steps.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(), ["Task: Do it.\n\nVerdict: finished\n"])
def test_stops_when_the_worker_leaves_no_transcript(self):
fake = FakeEffects(streams=[Streamed(0)])
self.assertEqual(steps.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}"))
class Retried(unittest.TestCase):
def test_retries_a_minute_apart_and_stops_on_the_third_failure(self):
fake = FakeEffects()
results = [Failure("one"), "done"]
self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), "done")
self.assertEqual(fake.calls, [("sleep", 60)])
fake = FakeEffects()
self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects()), Stop(1, "the judge failed three times running: no"))
self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)])
class Interrupts(unittest.TestCase):
def test_stops_off_a_terminal_before_starting_claude(self):
fake = FakeEffects(on_terminal=False)
stop = interrupt.interrupt("/r", uuid7(), "m", "/t", "Which one?", paths.paths_from(pathlib.Path("/h"), {}), fake.effects())
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"))
self.assertEqual(fake.calls, [])
def test_stops_when_nothing_was_typed_in_the_handover(self):
with tempfile.TemporaryDirectory() as home:
path = pathlib.Path(home, "t.jsonl")
path.write_text(json.dumps(human("a")) + "\n")
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
stop = interrupt.interrupt(home, uuid7(), "m", str(path), "Which one?", paths.paths_from(pathlib.Path(home), {}), fake.effects())
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
class ModelPrompt(unittest.TestCase):
OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")]
def test_reads_a_number_as_the_offered_model_and_anything_else_as_a_name(self):
self.assertEqual(models.model_picked(" 2 ", self.OFFERED), "claude-haiku-4-5")
self.assertEqual(models.model_picked("opus", self.OFFERED), "opus")
self.assertEqual(models.model_picked("3", []), "3")
self.assertEqual(models.model_picked("3", self.OFFERED), Failure("pick 1 to 2"))
self.assertIsNone(models.model_picked(" ", self.OFFERED))
def test_asks_again_until_an_answer_picks_a_model(self):
with tempfile.TemporaryDirectory() as empty:
fake = FakeEffects(inputs=["", "my-model"])
self.assertEqual(models.ask_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), "my-model")
self.assertEqual(len(fake.made("input")), 2)
fake = FakeEffects(inputs=[EOFError()])
self.assertEqual(models.ask_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended"))
class WorkerArgs(unittest.TestCase):
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
opened = session.session_for("proj", paths.paths_from(pathlib.Path("/h"), {}))
fresh = worker.worker_args("Do it.", opened, "m", False)
self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id))
self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude")
resumed = worker.worker_args("Do it.", opened, "m", True)
self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id))
self.assertNotIn("Do it.", " ".join(resumed))
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"
@@ -61,6 +283,7 @@ class HumanTurns(unittest.TestCase):
human("<command-name>/model</command-name>"),
{**human("<3 merge it"), "promptSource": "typed"},
{**human("<task-notification>done</task-notification>"), "promptSource": "system"},
{**human([{"type": "text", "text": "<task-notification>done</task-notification>"}]), "promptSource": "system"},
{**human("peer message"), "isMeta": True},
{**human("the loop's own prompt"), "promptSource": "sdk"},
human([{"type": "text", "text": "[Request interrupted by user]"}]),
@@ -98,40 +321,53 @@ class MarkTrusted(unittest.TestCase):
class Grounded(unittest.TestCase):
def test_every_verdict_must_quote_the_transcript(self):
def verdict(evidence):
return judge.Verdict(evidence=evidence, finished=False, interrupt=False, question="")
self.assertTrue(judge.grounded(verdict("Needs you: x"), "so.\n\nNeeds you: x\n"))
self.assertFalse(judge.grounded(verdict("invented"), "the transcript"))
self.assertFalse(judge.grounded(verdict(""), "the transcript"))
self.assertFalse(judge.grounded(verdict(" "), "the transcript"))
self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n"))
self.assertFalse(judge.grounded("invented", "the transcript"))
self.assertFalse(judge.grounded("", "the transcript"))
self.assertFalse(judge.grounded(" ", "the transcript"))
transcript = "done.\n\n**Your step:**\n```\n./run.sh\n```\nRun it."
self.assertTrue(judge.grounded(verdict("Your step:\n```\n./run.sh\n```\nRun it."), transcript))
self.assertTrue(judge.grounded(verdict("Your step: ``` ./run.sh ``` Run it."), transcript))
self.assertFalse(judge.grounded(verdict("**"), transcript))
self.assertTrue(judge.grounded("Your step:\n```\n./run.sh\n```\nRun it.", transcript))
self.assertTrue(judge.grounded("Your step: ``` ./run.sh ``` Run it.", transcript))
self.assertFalse(judge.grounded("**", transcript))
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "", "finished": True, "question": ""}), judge.Verdict(evidence="", finished=True, interrupt=False, question=""))
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 verdict has no interrupt of type boolean"))
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's verdict 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 verdict"))
class LoopState(unittest.TestCase):
class LoopRuns(unittest.TestCase):
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "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"})]):
with self.subTest(handed=handed):
self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>"))
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the reload cannot read the loop run from {handed}; rerun loop-claude <task>"))
def test_decodes_a_state_whose_annotations_are_strings(self):
@dataclasses.dataclass(frozen=True)
class Stringly:
count: "int"
name: "str"
self.assertEqual(reload.decode_state('{"count": 1, "name": "n"}', Stringly), Stringly(1, "n"))
self.assertIsNone(reload.decode_state('{"count": "1", "name": "n"}', Stringly))
self.assertEqual(reload.decode_handed('{"count": 1, "name": "n"}', Stringly), Stringly(1, "n"))
self.assertIsNone(reload.decode_handed('{"count": "1", "name": "n"}', Stringly))
def test_stops_when_the_reload_cannot_start_python(self):
with tempfile.TemporaryDirectory() as root:
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>"))
class Checkouts(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.checkouts("/r", fake.effects()), ["/r"])
@@ -139,7 +375,7 @@ 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(os.path.join(root, "in-the-way"), b"data"), Failure("Is a directory"))
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"])
+7 -3
View File
@@ -300,6 +300,10 @@ class Premises(unittest.TestCase):
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.stderr.strip(), f"README.md in {checkout.root}: Is a directory - no premises.")
(checkout.temp / "fake-bin" / "git").unlink()
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.stderr.strip(), "could not start git: No such file or directory")
def test_names_the_session_by_the_checkout_relative_to_code_or_else_to_the_root(self):
checkout = Checkout(self)
@@ -373,13 +377,13 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.code, 130)
self.assertEqual(run.sleeps, [60, 60, 60, 60])
run = checkout.run([worker(), judge(exit=1, stderr="judge down"), judge(stdout="{}"), judge(verdict={"interrupt": False})])
run = checkout.run([worker(), judge(exit=1, stderr="judge down"), judge(stdout=""), judge(verdict={"interrupt": False})])
self.assertEqual(run.code, 1)
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"])
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 verdict", run.stderr)
self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge's verdict has no evidence of type string")
self.assertIn("retrying the judge in a minute: the judge returned no verdict; it replied: nothing\n", run.stderr)
self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s verdict has no evidence of type string; it replied: {"structured_output": {"interrupt": false}}')
def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self):
checkout = Checkout(self)
+1 -1
View File
@@ -11,5 +11,5 @@ class Types(unittest.TestCase):
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line")
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+26 -66
View File
@@ -4,118 +4,78 @@
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.
## loop-claude: a judge decides interrupts, not the worker's self-report
## 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
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-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`'s "Give the judge the project's recorded decisions" ends the README-only bar. Valid while the worker's self-report stays unreliable.
## loop-claude: one session per project, at a fixed id from its full path, and a second loop refuses to start
## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the checkout's full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Until `todo.md`'s "Key a project on its checkout's full path" lands, the id is the checkout's path relative to `~/code`, or to `/` outside it, and a second loop is not refused, so a checkout outside `~/code` mirroring a path inside it shares its id. Valid while claude takes `--session-id` and resumes by it.
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md`'s "Key a project on its checkout's full path" lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it.
## loop-claude: the trust file is rewritten before an interrupt
## loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 4. A write by another claude inside `trust`'s read-modify-write window is lost. 2026-09-30, lilleman: Claude Code owns and writes that file, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md`'s "Move what `loop-claude` writes out of `~/.claude.json`" ends it.
2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 4. A write by another claude inside `trust`'s read-modify-write window is lost.
## loop-claude: every worktree of the checkout is trusted before an interrupt
2026-09-24, lilleman, extending it to every worktree. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Valid while resume re-enters a recorded worktree and trust is kept per path.
2026-09-24, lilleman. Serves goal 4. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Stands until `todo.md`'s "Move what `loop-claude` writes out of `~/.claude.json`" ends it. Valid while resume re-enters a recorded worktree and trust is kept per path.
2026-09-30, lilleman: Claude Code owns and writes that file, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md`'s "Move what `loop-claude` writes out of `~/.claude.json`" ends it.
## bin/: the Python floor is README's Install prerequisite
## bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
2026-09-26, larv-review. Serves goal 1. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a call newer than the floor, like 3.12's `itertools.batched`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while `uv` can fetch the floor interpreter and no machine taking the checkout ships an older Python.
## bin/: host python, no container
## bin/: the tools and their tests run on the host's Python, with no container
2026-09-24, larv-review. Serves goals 1 and 4. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run on the same host Python the tools meet. Valid while claude runs on the host.
## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it
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; the places the last run named are filed in `todo.md` under 0.1.0, and a later scoring run may not lower any dimension. 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. 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. Valid until the next scoring run, which uses the same four seats.
## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
2026-09-24, larv-review. Serves goal 4. Three seats of the 2026-09-24 panel found the words only in the changelog; a definition at each rule lands one reader and misses the next, so the section is the one landing place and each file using the words links it once, and `bin/test_citations.py` fails on a citation no heading or bold lead answers, so the pointer's rot is visible. `loop-claude --help` restates chunk, cycle, interrupt and premises, since a terminal reader has no link to follow. Valid until the next scoring run.
## loop-claude: a reload into an older file is unsupported
2026-09-26, lilleman. Serves goal 4. A running loop whose `bin/loop-claude` or `bin/loop_claude/` on disk is rolled back to a version with an older handover fails in that older file, or, older than the handover itself, runs `--reloaded <state>` as its task; this version cannot change either; the human who rolled it back reruns `loop-claude <task>`. Valid while nobody but the developer runs it: other team members running it while it is still developed reopens this.
## loop-claude: a CR-only README.md is reported at line 1
2026-09-26, larv-review. Serves goal 4. The line of a non-UTF-8 byte counts `\n`, so a file with classic-Mac `\r` endings reports line 1 whatever line an editor shows; no machine the audience runs writes such a file. Valid while the audience is the author's own machines.
## loop-claude: each project's model lives in loop-claude's own file
## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
2026-09-26, lilleman. Serves goal 4. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. Valid while Claude Code keeps rewriting the settings' model from inside a session.
## rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole
## review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human
2026-09-28, lilleman. Serves goal 4. Three scoring runs held Locality at 6 while about thirty chunks fixed the places the seats named, and two blind judges scored main's loop-claude 5 and its review process 4 against 7 for sketches designed from the target result. Other sessions run on `~/.claude` main throughout, so every rebuild chunk merges into `rebuild`, never main, and `rebuild` reaches main only when it passes the comprehension floor and **the human has explicitly approved the whole and merges it themselves**. The ⚠️ warning stands in `AGENTS.md`, atop `todo.md` and on its last item on purpose, 2026-09-28, lilleman: a premature merge lands under every session running on main, so a reader of any one of them must meet it. Valid until the rebuild merges.
2026-09-28, lilleman. Serves goal 4. One counter per pass per chunk, so no fix bounces between two passes without end. Valid while one human answers the ask, in the session or from the unmerged PR.
## review: the round cap counts a pass's rounds per chunk
2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask, in the session or from the unmerged PR.
## review: a 🟢's or ❓'s fix re-enters like any fix
## review: a fix for a 🟢 or ❓ re-enters review like any fix
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: only a record older than the chunk lets a pass skip
## review: a pass skips only on a record older than the chunk
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.
## loop-claude: the judge is retried alone, on its own counter
2026-09-28, lilleman, for the rebuild. Serves goal 4. A failed verdict reruns the judge on the same transcript; rerunning the worker would spend a worker run on a judge's fault. Valid while a judge run costs far less than a worker run.
## loop-claude: the judge loads `CLAUDE.md`
2026-09-28, lilleman, for the rebuild. Serves goal 4. The judge rules on chunks, releases and premises, which `CLAUDE.md` → "Vocabulary" and "Working loop" define; `--bare` would leave it the prompt's words alone. Valid while those definitions live in `CLAUDE.md`.
## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
2026-09-28, lilleman, for the rebuild. 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.
## loop-claude: a loop running main's script stops once at the cut-over
2026-09-29, lilleman. Serves goal 4. The rebuild's `LoopState` lacks main's failure count, so a loop running main's script exits 1 at its first reload into the rebuild, telling the human to rerun `loop-claude <task>`. No code exists only for the cut-over: one rerun costs a one-human audience less. Valid until the rebuild merges.
## rebuild: a chunk into `rebuild` takes no comprehension scoring run
2026-09-28, lilleman, confirming larv-review's reading of the rebuild decision above. Serves goal 4. The floor and its ratchet gate `rebuild` into main, scored by the plan's last item; the chunks before it pass through half-moved states a per-chunk run would block. Valid until the rebuild merges.
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.
## loop-claude: a `claude` that cannot start is a failed worker run, retried
2026-09-28, larv-review, declining a product-owner nit to exit at once when `claude` is missing. Serves goal 4. Claude Code's updater repoints `~/.local/bin/claude` at each new version under running loops, and a start that meets it mid-update fails with the same error as a broken install; the retry costs two minutes on the second and saves an unattended loop on the first. Valid while Claude Code updates by repointing its link.
## bin/: mypy checks `loop_claude`'s types in the tests
2026-09-29, lilleman. Serves goal 4. An unchecked annotation goes stale when a body gains a return type, and a reader trusts it; the suite already needs `uv`, which fetches a pinned mypy. Valid while `loop_claude` carries annotations.
## rebuild: rebuild's larv-review reviews a chunk into `rebuild`
2026-09-30, lilleman. Serves goal 4. A blind judge ruled it at least as good as main's on all four cases of the 2026-09-30 bench. Valid until the rebuild merges.
## review: an ask no user answers leaves the PR unmerged
2026-09-30, claude, for the rebuild. Serves goal 4: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix under the floor, fix a finding no goal lets the run decline — the run takes it; a ❓ or a prose fix changing a goal or a decision is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves.
## review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it
2026-09-30, lilleman. Serves goal 4: `@larvit/log`'s chunks each passed their per-diff reviewers, and a whole-project audit that day still found its functional core and state machines not followed and two semver breaks planned; what grows over many chunks shows in no diff. Valid while the other passes review a diff.
2026-09-30, claude. Serves goal 4: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix under the floor, fix a finding no goal lets the run decline — the run takes it; a ❓, or a fix changing a goal or a decision, is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves.
## loop-claude: every claude it starts bypasses permissions inside its sandbox
2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names.
## stats: a chunk's cost and review numbers are kept in the transcript archive
## loop-claude: the planned stats line goes in the transcript archive, off the remote
2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost. Each line names another project and its chunk, so the file stays off this repo's remote. `loop-claude` writes the line: the tokens, cycles and interrupts it counts, and the review's numbers from the summary larv-review ends with. Valid while the transcript archive stays off the remote.
## bench: a workflow change merges only once three benches rule it better
## workflow changes: a change merges only once three planned benches rule it better
2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. One bench ruling it worse closes the PR, since quality comes first (goal 4.1), and `docs/workflow-learnings.md` keeps what the PR changed and why it lost. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number.
## chunk: as large as one purpose allows
## review: `/security-review` is the security pass of record
2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. Purpose caps a chunk, never a line count. Tiny items are the exception: up to ten, a few lines each, share one chunk whatever their purposes and passes, since the review's fixed cost dwarfs them. Valid until the stats or a bench show that larger chunks lower what reviews catch.
2026-09-20, lilleman. Serves goal 4.1. Its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. Valid while `/security-review` ships both.
## review: the premises chunk's whole review is the human's approval
2026-09-20, lilleman. Serves goal 4.1. A reviewer's finding on that chunk could only be declined by citing the goals the chunk exists to write. Valid while every decline must name a goal or a technical principle.
+1 -1
View File
@@ -9,7 +9,7 @@
"~/code"
]
},
"model": "opus[1m]",
"model": "opus",
"disableClaudeAiConnectors": true,
"statusLine": {
"type": "command",
+37 -11
View File
@@ -9,7 +9,7 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchr
**Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. Resolve the tooling from the remote per `~/.claude/CLAUDE.md` → "Git, commits, and PRs"; on any other forge, achieve the same intents through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary.
Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/.claude/skills/larv-review/review-findings.md.
Words: `~/.claude/CLAUDE.md` → "Vocabulary". What a reviewer reports: ~/.claude/skills/larv-review/review-findings.md; how you resolve it: §3 → "Findings".
**An ask** holds only what it asks about; the rest runs on while it waits. No user reachable (a headless run) → finish the rest, then leave the PR unmerged with the question and your recommendation in the summary, unless the ask's rule names another branch.
@@ -17,7 +17,7 @@ Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/.
- Not a git repo → say so and stop.
- Someone else's PR, or the user asked for opinions only → one stability run, report its findings, done.
- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal is reviewed like any chunk.
- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval; a later change to a goal is reviewed like any chunk.
- Issue trackers are project-specific — the project's own docs say whether it has one. When it does and the work has a ticket, follow that tracker's conventions for assignment and status.
## 2. Ship the branch (idempotent — skip whatever already exists)
@@ -28,20 +28,46 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de
| 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); a schema change beyond an additive column; the chunk shipping its release's last item |
| 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 |
| 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 (`/claude-security` → "Scan changes") | 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 |
A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other.
A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work.
**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: cite the record and skip it. The architecture pass's principles audit and scoring run are excepted: they run whenever the pass fires, unasked, since no record older than the chunk checked the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it.
**Record, then ask** — for the architecture pass and the full scan:
**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. 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; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. 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, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged.
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.
**Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4.
**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 or filed 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.
**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.
**Findings.**
1. A finding outside the chunk's change is filed in `todo.md`, under a release, whatever its pass or severity. 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, the goal or decision left as is.
3. A 🔴 is fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`. 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, its reason and the goal or technical principle it rests on go to `docs/decisions.md`. 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.
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.
### Architecture
@@ -50,13 +76,13 @@ 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. A finding outside the chunk is filed in `todo.md`; a 🔴 on a decision is asked, since the decision is the user's.
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 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`. 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.
### Security
`/security-review` over the branch diff is the pass of record: its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse.
`/security-review` over the branch diff is the pass of record.
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.
@@ -70,12 +96,12 @@ Launch the reviewer with the change — product-owner-reviewer also with the ext
### Prose
Launch prose-reviewer with what the diff touched and every section this review cited — a reviewer's finding, your decline or the implementer's decision quoted it — each with the code it governs, and say whether the architecture pass ran. Its fixes land in this chunk, except one changing a goal or a decision: that is asked; no user reachable → filed in `todo.md`, the prose left as is; a split or index bigger than the chunk is a `todo.md` item naming the section and what the hunt costs.
Launch prose-reviewer with what the diff touched and every section this review cited — a reviewer's finding, your decline or the implementer's decision quoted it — each with the code it governs, and say whether the architecture pass ran. Fix what the chunk touched. A finding on a cited section the chunk did not touch, or on any other prose file, is outside the chunk. A split or index bigger than the chunk is filed as a `todo.md` item naming the section and how long a reader searches it.
## 4. Gate
1. Run the project's test suite locally unless the last stability round already left it verified green.
2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3.
2. Watch the forge's checks until every one passes. A red check is a finding.
3. No CI configured → the gate is local tests only; note it in the summary.
4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix.
5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its rounds, §3 → "Round cap". Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit.
+5 -16
View File
@@ -2,22 +2,15 @@
Words: `~/.claude/CLAUDE.md` → "Vocabulary".
A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `todo.md` first: a finding declined in the one or filed in the other is not raised again, unless the decline works against a goal or a technical principle and names no `todo.md` item ending it.
A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `todo.md` first: a finding declined or disproved in `docs/decisions.md`, or filed in `todo.md`, is not raised again, unless the decline works against a goal or a technical principle and names no `todo.md` item ending it.
## Severity
- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed; outside the chunk, filed in `todo.md`; or shown factually wrong, with what disproved it recorded in `docs/decisions.md`. Never declined.
- 🟡 **should fix** — worse than it needs to be. Fixed, declined, or — outside the chunk — filed in `todo.md`.
- 🟢 **nit** — fixed, answered, declined in the summary with its reason, or filed in `todo.md`.
- 🔴 **must fix** — a goal, a principle or correctness broken.
- 🟡 **should fix** — worse than it needs to be.
- 🟢 **nit**.
- ❓ **question** for the author: a finding you could not confirm goes here, not above.
- 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line. The orchestrator runs it.
A 🟢 or ❓ is answered where the code, a test or a record settles it: the summary quotes what.
Other reviewers map onto this scale, and a finding of theirs repeating one declined or filed does not stand:
- `/security-review`: HIGH is 🔴, MEDIUM 🟡, LOW 🟢.
- A forge's auto-reviewer: what it marks blocking is 🔴.
- 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line.
## Verdict
@@ -31,7 +24,3 @@ A review's first line, derived from the findings:
- Handed no earlier findings: surface everything.
- Handed an earlier round's findings: verify each 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem.
## Declining
A 🟡 may be declined where the reason is sound, consistent with the goals and the technical principles, and confidence is very high. The decline, its reason and the goal or technical principle it rests on go to `docs/decisions.md`. 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", which also says where the user's reply to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix.
+33 -25
View File
@@ -2,44 +2,52 @@
## 0.1.0
**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole.
### Under the comprehension floor
The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`.
The panels on `rebuild` at 8585257 and on PR #182 named these under Self-sufficiency and Locality, the two dimensions under the floor. Scores: `docs/decisions.md` → "comprehension floor".
- **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below the last run. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds.
- **Name `loop_claude`'s modules and words by what each holds.** The 2026-10-01 panel misread `formats.py` (it holds every Claude Code shape, `mark_trusted` and `models_in` included), `steps.py`, `outcome.py` and `human_needed.py`. "Project", "transcripts", "verdict" and "model" each name two or three things. Goal 4.1.
- **State in `reload.py` why a loop reloads its own script, and tie each exit-1 clause of `--help` to the `Stop` that produces it.** Two seats found the reload's purpose nowhere in the code, and one could keep the exit contract true only by grepping every `Stop(1`. Name what a reload could not read, and its likely cause, in both `--help` and the reload's error: "loop run" is defined nowhere a reader looks. Goal 4.1.
## 0.2.0
### The rest
- **Make the small fixes filed against `bin/`, the README and `.gitignore`.** Goals 1, 3 and 4.1.
- Name `jq` and GNU `date` under README → Install, or stop `statusline.sh` needing them. Without `jq` the status line aborts. Under BSD `date` the reset times vanish. Either way CHANGELOG's "runs on any machine unedited" is false.
- Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean. Today a stray log of `loop-claude` output in `bin/` would be committed, transcript text included.
- Show the judge's reply when its verdict is rejected. Its stdout is discarded today, so a judge that failed three times running leaves nothing to diagnose.
- Return a `Stop` when `git` or `os.execv` fails. `checkout.py:7,15` and `reload.py:52` end in a traceback today.
- `outcome.Failure`'s docstring: say what a failure is, without naming `retried`. A value type does not name its consumer.
- **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so a failed exit or Ctrl-C loses the transcript. Goal 2.
- **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. `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. Goal 4.1.
- **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** 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 "a judge decides interrupts, not the worker's self-report" to match. Goal 4.2.
- **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so after a failed exit or Ctrl-C the transcript stays unarchived until the chunk finishes, and is never archived if it does not. Goal 2.
- **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_name` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. Goal 4.1.
- **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1.
- **Make `loop-claude`'s loop a tested state machine with its side effects injected.** Functional core, imperative shell. Goal 4.1.
- Inject the side effects: `time.sleep`, `subprocess`, `input()`, `isatty` and `os.execv`. Split `project_model` and `interrupt` into decisions and effects.
- Give a project's loop state named states and one transition function. Today fresh, resuming, awaiting the human and finished come from whether a transcript exists, two verdict booleans and an open `while True` in `steps.py`.
- Make two `Verdict`s unrepresentable: one with both `interrupt` and `finished`, and one with a question and no interrupt. `steps.py:49` ignores `finished` when `interrupt` is set.
- Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments. Only the pure helpers are tested today, because nothing reaches the loop's flow without the effects.
- **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. Goal 4.1.
- **Make the small changes filed against the review's rules.** Goals 4.1 and 4.4.
- larv-review §3: name CLI flags and exit codes among the external contracts that fire the architecture pass, or record that they do not. The product-owner row names the CLI; the architecture row does not.
- `review-findings.md`: give a 🟡 shown factually wrong the 🔴's way out. Today it can only be fixed, declined on a goal, or filed.
- Make the contributor a standing member of every project's audience. A project drops them only where 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.
- Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop". Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`.
- **Clean up the rules, skills, agents, plan and decision log.** Goal 4.1.
- Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, and each decision valid "until the rebuild merges".
- `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and three runs have passed. Put the floor's rule first and its runs' scores in a table.
- larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds.
- `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and every run since has passed it. Put the floor's rule first and its runs' scores in a table.
- `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need.
- `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each.
- **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. Goal 4.1.
- **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:80` 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. Goal 4.2.
- **Make the small fixes filed by the 2026-10-01 principles audit against `bin/`.** Goal 4.1.
- Prefix each diagnostic `loop-claude` prints with its level, `warning:` at the least, so a run's output can be grepped for what needs fixing.
- Have `make_private` return a `Failure` like `replace_file` beside it.
- Check the catalog `name` in `models_in` as well as `id`.
- Name `part_line`'s limits 160 and 400, rename `Popened`, and give `human_needed.stop(to, but)` and `TO` names that read without the caller.
- Sort `worker_args`' flags and the globs in `catalog.py` and `session.py`.
- Write `"bypassPermissions"` once for every claude `loop-claude` starts.
- Keep the judge's evidence and model in each archived `.verdict.md`.
- Move the test helpers `ROOT` and `readme_floor` out of `test_python_floor.py`, which two other tests import them from.
- **Inject output and storage into `Effects`, and test what each step prints.** `print` and `open` are called directly across `bin/loop_claude/`, so the stderr lines of the CLI contract can be checked only through the black-box tests. Goal 4.1.
- **Read transcript and stream entries into typed values where they are read.** `transcript.read` and `run_worker` pass raw `dict`s, so about ten accessors in `formats.py` re-check shapes deep inside and mypy cannot check `render`, `human_turns` or `run_worker`. Goal 4.1.
- **Measure test coverage in the suite, and fail on a drop.** Nothing measures it, so "Test coverage should not decline" cannot be held. Goal 4.1.
- **Give the reviewer agents only the tools they need.** `systems-architect.md`, `product-owner-reviewer.md` and `stability-reviewer.md` have no `tools:` line, so each can edit the branch it reviews; `review-findings.md` says a reviewer edits nothing. Goal 4.1.
- **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** `test_gitignore.py` checks only that every tracked file is allowlisted; a widened negation such as `!*.json` would un-ignore `.credentials.json`. Goal 3.
- **Archive a finished chunk's subagent transcripts before `delete_session` removes them.** Today only `<id>.jsonl` is copied, so every reviewer's full run in an unattended chunk is lost. Goal 2.
- **Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row.** No machine has it enabled, so every chunk that fires the pass skips it. Goal 4.1.
- **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 4.4.
- **Give `settings.json`'s model one writer.** Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice. Goal 4.3.
- **Rewrite `statusline.sh` in Python, and test it.** It needs `jq` and GNU `date` on every machine, `eval`s jq output, has three near-identical usage blocks and no test. Goal 1.
- **Say in `systems-architect.md` that a REST API's `/v1/` prefix is not versioning machinery to defer.** Its "defer the versioning story" can be read against `principles/rest-apis.md`, which requires the prefix from the start. Goal 4.3.
- **Judge a cycle on more than the transcript's last 40,000 characters.** `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. Goal 4.2.
- **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4.
- Have `loop-claude` write the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts.
- End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the line: agents launched and rounds per pass; findings per pass by severity, inside the chunk's diff and outside it; and the comprehension scores when the panel ran.
- **Write a `workflow-review` skill that reads the stats and files each change it proposes to the workflow as a plan item, and have `AGENTS.md` run it on the chunk shipping a release's last item.** The workflow is `CLAUDE.md`, `principles/`, the skills, the agents and `loop-claude`. The skill's signals: findings outside the chunk's diff and comprehension scores per release, both from the stats; fixes after merge, from git; and the human's corrections, from the archived transcripts. Goal 4.4.
- **Bench about one chunk in ten against an open PR that changes the workflow, and have a blind claude rule which run better serves this repo's goal 4.** Redo the chunk under the PR, from the commit it started from. The ruling claude is not told which run is which. `loop-claude` picks the chunk at random, small diffs and big ones alike; with no such PR open, no bench runs. The same outcome with less code and prose, in the chunk or in the workflow, also counts as better. The PR merges only once three benches rule it better. A bench that rules it worse closes the PR and records, in `docs/workflow-learnings.md`, what the PR changed and why it lost. The ruling and both runs' numbers go on the chunk's stats line. Start from the 2026-09-30 bench's scripts: `~/code/claude-handoffs/claude-config/2026-09-30/bench/`. Needs the stats line. Goals 4.1 and 4.4.
- **Bench about one chunk in ten against an open PR that changes the workflow, and have a blind claude rule which run better serves this repo's goal 4.** Redo the chunk under the PR, from the commit it started from. The ruling claude is not told which run is which. `loop-claude` picks the chunk at random, small diffs and big ones alike; with no such PR open, no bench runs. The same outcome with less code and prose, in the chunk or in the workflow, also counts as better. The PR merges only once three benches rule it better. A bench that rules it worse closes the PR and records, in `docs/workflow-learnings.md`, what the PR changed and why it lost. The ruling and both runs' numbers go on the chunk's stats line. Start from `workflow-bench/`, written for the 2026-09-30 bench's four fixed cases. Needs the stats line. Goals 4.1 and 4.4.
- **Bring the project to the comprehension floor on the four-seat panel.** Every dimension and the overall must reach 7.0, and none may fall below its best run on `rebuild`. A dimension under the floor gets its places filed under "Under the comprehension floor".
- **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** Today a worker or judge that hits a usage limit fails three times a minute apart, and the loop exits 1, so an unattended loop dies at every limit. The transcript line Claude Code writes for it, marked `"error":"rate_limit"`, holds the reset time: `You've hit your session limit · resets 7:40pm (Europe/Stockholm)`. Sleep until 2 minutes past it. The judge runs without a transcript, so find what its JSON reply carries on a limit. Where no reset time can be read, retry every 10 minutes: a retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests. Print when the next try is due, and update `--help`'s exit 1. Goal 4.
+84
View File
@@ -0,0 +1,84 @@
#!/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> ..."""
import concurrent.futures
import json
import os
import pathlib
import shutil
import subprocess
import sys
import time
BENCH = pathlib.Path(__file__).resolve().parent
SOURCES = pathlib.Path(os.environ["BENCH_SOURCES"])
CASES = {
"cjk": ("151bf38^", "6c49912"),
"35b": ("692433b", "1d369ec"),
"brlan": ("59ce55b^", "92e466a"),
"mypy": ("89a66d3", "b32d131"),
}
ATTEMPTS = 4
def git(repo, *args):
return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True).stdout.strip()
def fresh_clone(case, dest):
if dest.exists():
shutil.rmtree(dest)
source = SOURCES / f"{case}-main"
base_ref, head_ref = CASES[case]
base = git(source, "rev-parse", base_ref)
head = git(source, "rev-parse", head_ref)
subprocess.run(["git", "clone", "-q", "--no-local", str(source), str(dest)], check=True)
git(dest, "checkout", "-q", "-B", "chunk", head)
for branch in git(dest, "for-each-ref", "--format=%(refname:short)", "refs/heads").split():
if branch != "chunk":
git(dest, "branch", "-D", branch)
for tag in git(dest, "tag").split():
git(dest, "tag", "-d", tag)
git(dest, "remote", "remove", "origin")
git(dest, "reflog", "expire", "--expire=now", "--all")
git(dest, "gc", "-q", "--prune=now")
return base, head
def rate_limit_reset(log):
resets = [0]
for line in log.read_text().splitlines():
if '"status":"rejected"' in line:
resets.append(json.loads(line)["rate_limit_info"]["resetsAt"])
return max(resets)
def run(name):
case, version, _ = name.split("-")
clone = BENCH / name
report = BENCH / f"{name}.md"
for attempt in range(1, ATTEMPTS + 1):
if report.exists():
return f"{name}: done"
base, head = fresh_clone(case, clone)
prompt = (BENCH / "run-prompt.md").read_text().format(
version_dir=BENCH / "versions" / version, base=base, head=head, case=case, report=report)
log = BENCH / "logs" / f"{name}.{attempt}.jsonl"
log.parent.mkdir(exist_ok=True)
with log.open("w") as out:
subprocess.run(
["claude", "-p", prompt, "--dangerously-skip-permissions", "--model", "claude-opus-5-5", "--output-format", "stream-json", "--verbose"],
cwd=clone, stdout=out, stderr=subprocess.STDOUT)
if report.exists():
return f"{name}: done on attempt {attempt}"
time.sleep(max(1200, rate_limit_reset(log) + 120 - time.time()))
return f"{name}: FAILED after {ATTEMPTS} attempts"
def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
for result in pool.map(run, sys.argv[1:]):
print(result, flush=True)
if __name__ == "__main__":
main()
+23
View File
@@ -0,0 +1,23 @@
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.
Everything is under `{dir}`; read nothing outside it:
- `truth-issues.md`: what the chunk's real review found and fixed, one row per issue.
- `truth.diff`: the real review's fixes.
- `<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:
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.
3. **Damage**: a change that makes the chunk worse — a regression, a false claim written, a needless churn of lines outside the chunk.
4. **Cost**: agents launched and rounds, from the report.
Then, per process, weigh the three runs together: what it catches reliably (two or more runs), what it catches by luck (one run), and its spread. A difference one run makes is variance, not the process.
Write your ruling to `{ruling}`:
1. A table per run: each truth issue's mark, other real defects, damage, cost.
2. Per process: reliable catches, lucky catches, damage, cost range.
3. **Ruling**: one line each — `B at least as good as A: yes|no` and `A at least as good as B: yes|no` — each followed by the decisive evidence, citing runs and diff lines. "No" needs a difference that holds across runs, not one run's miss.
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Blind-judge each case's six runs: BENCH_SOURCES=<as for bench.py> judge.py <case> ..."""
import concurrent.futures
import json
import pathlib
import random
import re
import shutil
import subprocess
import sys
import bench
BENCH = bench.BENCH
TRUTH_END = {"cjk": "160c2a7", "35b": "a4b6b48", "brlan": "8f6e22d", "mypy": "628ee30"}
PREFIX = {"cjk": "C", "35b": "B", "brlan": "R", "mypy": "M"}
def runs(case, version):
"""The version's first three runs as (report, clone), main's 2026-09-29 run last."""
found = []
for n in range(1, 4):
report = BENCH / f"{case}-{version}-{n}.md"
if report.exists():
found.append((report, BENCH / f"{case}-{version}-{n}"))
if version == "main":
found.append((bench.SOURCES / f"{case}-main.md", bench.SOURCES / f"{case}-main"))
return found[:3]
def blind(text):
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
if folder.exists():
shutil.rmtree(folder)
folder.mkdir(parents=True)
source = bench.SOURCES / f"{case}-main"
head = bench.git(source, "rev-parse", bench.CASES[case][1])
(folder / "truth.diff").write_text(bench.git(source, "diff", head, TRUTH_END[case]) + "\n")
rows = [line.split("|")[1:3] for line in (bench.SOURCES / "comparison.md").read_text().splitlines()
if re.match(rf"\| {PREFIX[case]}\d+ \|", line)]
(folder / "truth-issues.md").write_text("".join(f"-{i.strip()}: {t.strip()}\n" for i, t in rows))
groups = ["main", "rebuild"]
random.shuffle(groups)
mapping = {}
for label, version in zip("AB", groups):
for n, (report, clone) in enumerate(runs(case, version), 1):
run = folder / f"{label}{n}"
run.mkdir()
(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")
return folder
def judge(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:
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)
return f"{case}: {'ruled' if ruling.exists() else 'FAILED'}"
if __name__ == "__main__":
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
for result in pool.map(judge, sys.argv[1:]):
print(result, flush=True)
+31
View File
@@ -0,0 +1,31 @@
You are one run of a bench comparing two versions of the larv-review process. Review the chunk in this repository (your working directory) exactly as the process below says, then write a report.
VERSION_DIR = {version_dir}
Chunk: commits `{base}..chunk` on branch `chunk` (head at start: `{head}`). Case `{case}`.
Report: write it to `{report}`.
## The process
- `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.
## Bench rules
- Launch every agent in the foreground (`run_in_background: false`): background agents die when this headless turn ends.
- No remote and no forge: skip the PR, CI, the external auto-reviewer and the merge; review locally.
- Do not run the repo's test suites. A targeted probe is fine, in the repo's own container tooling.
- Skip the comprehension floor's scoring run; say so in the report.
- No human is reachable. Where the process names a no-human branch, take it; where it names none, take your recommendation and list the question in the report.
- Commit each round's fixes on `chunk`, messages prefixed `{case} - review: `. Touch nothing outside this repository except the report.
## Report
Sections, in order:
1. **Passes**: a table of each pass, run or skipped, and why.
2. **Findings**: per pass and round, each finding's severity, location, one-line summary and outcome (fixed in `<sha>`, answered, declined, filed, disproved).
3. **Questions for the human**: each ask you could not put, with your recommendation.
4. **Totals**: agents launched per pass, rounds per pass, commits.
5. **Ambiguities**: every place the process text was unclear, contradicted itself, or could not be followed, and how you read it.