Compare commits

...

102 Commits

Author SHA1 Message Date
lilleman 64914c0177 Move compose-not-entangle into the technical principles, down to functions 2026-10-01 17:46:03 +02:00
lilleman 1d93e78307 Updated goals 2026-10-01 17:32:57 +02:00
lilleman 44c24d43cc Merge pull request 'Name the sandbox loop-claude runs in, and git as its seam to production' (#167) from sandbox-install into rebuild 2026-09-30 23:43:26 +02:00
lilleman c20a12391f Cover the interrupt in the sandbox rule, name the forge as the seam, and tell the changelog 2026-09-30 23:43:00 +02:00
lilleman 5076d7f06f Name the sandbox loop-claude runs in, and git as its seam to production 2026-09-30 23:41:23 +02:00
lilleman 3e20310afc Merge pull request 'Record the human's answers to the rebuild's principles audit' (#166) from user-answers-audit into rebuild 2026-09-30 23:36:53 +02:00
lilleman d5a85c9b9f Say what holds until each todo item lands, and what the credentials sentence decides 2026-09-30 23:36:24 +02:00
lilleman 87024023f4 Record the audit answers: a full-path session with one loop at a time, keeping out of ~/.claude.json, the sandbox's bypassPermissions, and continuous archiving 2026-09-30 23:34:15 +02:00
lilleman 35be6ea509 Merge pull request 'Audit every principle and goal over the whole project in the architecture pass' (#164) from architecture-pass-principles into rebuild 2026-09-30 23:33:09 +02:00
lilleman ce21270052 File the rebuild's principles audit 2026-09-30 23:20:11 +02:00
lilleman 080fdb94b2 Let a decline rest on a technical principle, and untangle the 🔴 bullet and the record exception 2026-09-30 23:16:09 +02:00
lilleman fec886273a Carry the todo.md condition and the technical principles into review-findings, and run the audit unasked in every round 2026-09-30 23:14:33 +02:00
lilleman a79efe2429 Audit every principle and goal over the whole project in the architecture pass, and fire it on a release's last chunk 2026-09-30 23:12:23 +02:00
lilleman 89dcce731a Merge pull request 'Add functional core, imperative shell to the technical principles, and let a decision link one' (#163) from functional-core-rebuild into rebuild 2026-09-30 22:56:20 +02:00
lilleman 888206cac5 Add functional core, imperative shell to the technical principles, and let a decision link one 2026-09-30 22:55:33 +02:00
lilleman 4bc8aae9c8 Merge pull request 'File keeping larv-review's prose fixes to what the chunk touched' (#161) from review-scope into rebuild 2026-09-30 22:29:20 +02:00
lilleman c2211afb7c File keeping larv-review's prose fixes to what the chunk touched 2026-09-30 22:29:14 +02:00
lilleman a9883e653a Merge pull request 'Let rebuild's larv-review review a chunk into rebuild' (#159) from rebuild-reviews-rebuild into rebuild 2026-09-30 21:37:04 +02:00
lilleman 47e2bcdbd7 Delete main's rebuild-review paragraph in the merge to main 2026-09-30 21:36:40 +02:00
lilleman e4c17b7fd4 Drop the how-to from the decision entry 2026-09-30 21:36:11 +02:00
lilleman 7072cccd1d Let rebuild's larv-review review a chunk into rebuild 2026-09-30 21:35:09 +02:00
lilleman beec48bb10 Merge pull request 'Drop the finished bench item: a blind judge ruled rebuild's larv-review at least as good as main's on all four cases' (#158) from bench-judged into rebuild 2026-09-30 20:49:15 +02:00
lilleman a53a807340 Drop the finished bench item: a blind judge ruled rebuild's larv-review at least as good as main's on all four cases 2026-09-30 20:49:05 +02:00
lilleman 46d8c777c5 Merge pull request 'Source a list or threshold a consumer relies on' (#157) from research-sourced-lists into rebuild 2026-09-30 16:44:54 +02:00
lilleman a2ffd7e3ce Source a list or threshold a consumer relies on 2026-09-30 16:44:08 +02:00
lilleman 30279ad5f7 Merge pull request 'Plan carrying main's judge-quote fix into the rebuild' (#156) from judge-quote-todo into rebuild 2026-09-30 16:39:54 +02:00
lilleman 16ccca5e0a Plan carrying main's judge-quote fix into the rebuild 2026-09-30 16:39:47 +02:00
lilleman 7f041d8fa3 Merge pull request 'Decline a nit in the summary alone, and define answered' (#154) from declined-nit into rebuild 2026-09-30 15:47:12 +02:00
lilleman a17eb7e395 Decline only a 🟡 in the decision log, and word the nit and summary lines one way 2026-09-30 15:46:28 +02:00
lilleman 826676c1eb Decline a nit in the summary alone, and define answered 2026-09-30 15:44:45 +02:00
lilleman 97e1a0dbf7 Merge pull request 'Run the comprehension floor when the architecture pass is skipped by record' (#153) from floor-skip into rebuild 2026-09-30 15:43:41 +02:00
lilleman 650e18bb46 Attach the scoring run's exception to the skip 2026-09-30 15:43:39 +02:00
lilleman 884dc232a0 Except the scoring run from a skip by record, in the skip and in the round 2026-09-30 15:42:45 +02:00
lilleman 0b739a1d8a Run the comprehension floor when the architecture pass is skipped by record 2026-09-30 15:41:56 +02:00
lilleman d5323eb186 Word the no-human branches' nits 2026-09-30 15:40:09 +02:00
lilleman eaf5911b03 Hold an unanswered Stage 0 and BLOCK, say what the cap's no does, and word the no-human branches one way 2026-09-30 15:39:37 +02:00
lilleman b78885e22f Give every ask in larv-review a no-human branch 2026-09-30 15:37:58 +02:00
lilleman 104fec4b58 Route a pass fired and not skipped to the ask, and place 'before the chunk began' 2026-09-30 15:34:56 +02:00
lilleman e57f80d66e Let only a record older than the chunk skip a pass 2026-09-30 15:34:20 +02:00
lilleman 5c0613d297 Let prose-reviewer read what a finding needs, and drop what it cannot judge 2026-09-30 15:02:02 +02:00
lilleman 4257077b38 Give the prose pass its own reviewer agent, prose-reviewer 2026-09-30 15:00:57 +02:00
lilleman 10c8b819ae Pin which round addresses a done pass's nits, and file whether a diff-only prose rerun counts as a round 2026-09-30 11:54:42 +02:00
lilleman 698ec912a5 Say a re-entry reopens a done pass, and name the ❓ in the decision's title 2026-09-30 11:54:18 +02:00
lilleman a4594e18ac Re-enter a nit's fix like any fix, so prose fixes are reviewed too 2026-09-30 11:53:24 +02:00
lilleman 14d3017b4b Define a behaviour change once, in the stability row 2026-09-30 11:38:16 +02:00
lilleman 45e3391696 Exempt a behaviour-neutral nit fix from re-entry per fix, and file what the cap's ask grants 2026-09-30 11:37:25 +02:00
lilleman 8c6c71b54e Word the nit re-entry decision's premise as the rule 2026-09-30 11:36:30 +02:00
lilleman f935e80f99 Re-enter a nit's fix only where it changes behaviour, and give a capped pass the cap's ask 2026-09-30 11:36:21 +02:00
lilleman 2d21690c46 Let the README hold how a goal is met 2026-09-30 11:32:49 +02:00
lilleman 31746d5090 Drop the architect's vagueness bar and say where a goal is met 2026-09-30 11:32:00 +02:00
lilleman 507b41d24b State goals as one-line aims read like slogans, with no vagueness bar 2026-09-30 11:28:07 +02:00
lilleman c3535dbd1d Ask for goals short enough to read as slogans 2026-09-30 11:18:54 +02:00
lilleman 4de52d52aa File goals as one-line aims first, and bench larv-review against not degrading, ruled by a judge 2026-09-30 11:17:20 +02:00
lilleman a1c705cb7b File the places the bench found in rebuild's larv-review 2026-09-30 08:33:48 +02:00
lilleman 507c3beca5 Name the pass table's column Trigger, define a pass, and plan benching the rebuilt larv-review 2026-09-29 18:48:20 +02:00
lilleman 628ee30f2a Run mypy without a cache and name the floor once 2026-09-29 15:50:49 +02:00
lilleman b32d131a0c Record mypy checking loop_claude's types 2026-09-29 15:47:52 +02:00
lilleman 6e643cc87c Pass mypy on loop_claude 2026-09-29 15:47:41 +02:00
lilleman 099e9e19a5 Pin mypy passing on loop_claude at the Python floor 2026-09-29 15:46:09 +02:00
lilleman 89a66d37a0 File checking loop_claude's annotations in the gate 2026-09-29 12:25:37 +02:00
lilleman d13658967a Annotate the return type of every function in loop_claude 2026-09-29 12:23:37 +02:00
lilleman 0842135b87 Name the agents prompted with earlier findings 2026-09-29 12:20:25 +02:00
lilleman 2de5141d89 Prompt only a reviewer agent with earlier findings, and drop restatements of when a pass is done 2026-09-29 12:20:03 +02:00
lilleman 2f9ee68660 Define a round, its prompt and when its pass is done under larv-review's Round cap alone 2026-09-29 12:19:05 +02:00
lilleman 6f6972949f Leave the round's definition to its 0.1.0 item, and ratchet the floor per scoring run 2026-09-29 12:17:30 +02:00
lilleman 738a82a283 File the places the panel on rebuild at 2c74bbc named under the floor 2026-09-29 12:16:41 +02:00
lilleman 2c74bbcbba Point the Test line at both bin/ decisions, and correct the floor entry's example 2026-09-29 12:11:23 +02:00
lilleman 411ec14c6c Say in the README why the tests run on the host and need uv 2026-09-29 12:10:17 +02:00
lilleman d38b354538 Say why a leading < marks Claude Code's entry and why a trust failure only warns 2026-09-29 12:08:50 +02:00
lilleman fa49aacbd4 Drop prose restating what its link or its own file already says 2026-09-29 12:07:11 +02:00
lilleman 277beec2c8 Sort main's imports after the move, and file sorting imports on their first binding 2026-09-29 12:03:44 +02:00
lilleman 7f1142cc76 Name the cycle's module steps.py, and group main and reload under loop/ 2026-09-29 11:57:43 +02:00
lilleman 830ba331ca Group a cycle's modules under cycle/, apart from claude_code/ 2026-09-29 11:55:53 +02:00
lilleman aba2a98d7e Name formats.py's samples by what they are, put Session's lifetime on Session, and file the prose pass's places 2026-09-29 11:53:46 +02:00
lilleman c2be13efd5 Name formats.models_in by what it returns, and read the catalog in one function 2026-09-29 11:50:16 +02:00
lilleman 29495b1e7d Read the model catalog in claude_code/catalog.py 2026-09-29 11:48:54 +02:00
lilleman 5e84736672 Keep formats.py to Claude Code's shapes, with paths and file reads at their callers 2026-09-29 11:47:23 +02:00
lilleman 969bb26668 Tell a user entry the human wrote apart with one predicate 2026-09-29 11:43:59 +02:00
lilleman d9ba36732f Route a nit's fix through Re-entry 2026-09-29 11:41:49 +02:00
lilleman a8a3ac9cf1 Re-enter a round's fixes together, run an escalation's fixes as a re-entry, and file the CLI gap in the architecture trigger 2026-09-29 11:41:10 +02:00
lilleman 1f259cd728 Route a fix through larv-review's Re-entry in one read 2026-09-29 11:40:04 +02:00
lilleman ea29be4046 Name sections' list blocks 2026-09-29 11:38:03 +02:00
lilleman 69b093d1a7 Build premises.sections without filling found through an alias 2026-09-29 11:36:43 +02:00
lilleman e7b0479092 Hand run_cycle and judge_through_interrupts one cycle context 2026-09-29 11:33:49 +02:00
lilleman 7604ec4fa7 Declare LoopState beside decode_state, as the state a reload carries 2026-09-29 11:31:07 +02:00
lilleman 9d7eaa5453 Tighten the cut-over decision 2026-09-29 11:12:19 +02:00
lilleman 917f150fd1 Say in --help that a run is retried within its cycle, and drop the cut-over from the changelog 2026-09-29 11:10:19 +02:00
lilleman d4d8621ab4 Stop a loop running main's script once at the cut-over, and tick off the item 2026-09-29 11:07:44 +02:00
lilleman fb221787d6 Retry the worker and the judge through one counter, in retry.py 2026-09-29 11:02:57 +02:00
lilleman 6c09cadfa3 Pin the worker retried within its cycle and reload state without a failure count 2026-09-29 11:01:40 +02:00
lilleman aefd6e2fb0 File the places the panel on rebuild at 2f9ab2f named under the floor 2026-09-29 10:47:31 +02:00
lilleman 2f9ab2fb7d Name human_needed.py for the exit-2 stops it holds 2026-09-29 10:41:11 +02:00
lilleman f602b94aff Name the field claude_code_transcripts and build Session by keyword 2026-09-29 10:38:47 +02:00
lilleman 99d9996b75 Rename Paths.projects and Session.projects to claude_transcripts 2026-09-29 10:36:30 +02:00
lilleman f5970686e1 Count a Stage 0 rerun as its own round, and keep the Vocabulary link bare 2026-09-29 10:34:20 +02:00
lilleman cb4be72b2a Define a round once, in larv-review's Round cap 2026-09-29 10:33:34 +02:00
lilleman 75ad040204 Say when a failed run stops being retried 2026-09-29 10:32:02 +02:00
lilleman 80edf5e695 State in outcome.py what the loop does with each outcome 2026-09-29 10:31:48 +02:00
lilleman d9058d2d7e Resolve decode_state's field types from string annotations too 2026-09-29 10:29:08 +02:00
lilleman b69b37b334 Name the records mark_trusted adds 2026-09-29 10:27:03 +02:00
lilleman f4f996f124 Drop the unit assertion the black-box test covers 2026-09-29 10:26:36 +02:00
lilleman 4aaad015f6 Return the updated ~/.claude.json from mark_trusted 2026-09-29 10:24:57 +02:00
43 changed files with 469 additions and 355 deletions
+9 -2
View File
@@ -6,7 +6,7 @@ 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
- 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
@@ -18,9 +18,16 @@ Decisions live in `docs/decisions.md`:
- 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: the archive keeps the raw transcript, and a failed archive stops the loop
- loop-claude: the rebuild keeps main's `--reloaded` state
- 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
+2
View File
@@ -2,6 +2,7 @@
## Unreleased
- 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.
- `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.
@@ -9,6 +10,7 @@
- `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` 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.
+10 -16
View File
@@ -9,11 +9,12 @@ Shorter is better, none is best — chat output, commit messages, comments, docs
- **gate** — the merge gate: the checks a PR passes before it merges.
- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them.
- **plan** — `todo.md`.
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`.
- **release** — a semver version the human cuts.
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
- **round cap** — the rounds one pass may take per chunk.
- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap".
- **session** — a Claude Code session: one id, what `claude --resume` continues.
- **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them.
- **worker** — the headless claude that runs the task in a cycle, in the chunk's session.
@@ -28,19 +29,12 @@ Shorter is better, none is best — chat output, commit messages, comments, docs
- After every change to this file, re-read the whole thing and restructure it: merge overlapping rules, cut prose that restates a rule, move rules to the section they belong in, drop what's now covered elsewhere. Same information, more compact.
## 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.
- Default to `WebSearch`/`WebFetch`. When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw <url> [options]` (see its README). Don't use claude-in-chrome for this.
## Compose, do not entangle
**The core design rule — it is what keeps a system from turning into spaghetti**, in the network, in the code, in the data, and in the tooling. Two things that can stand alone must stand alone, joined by a narrow seam you can name. Never by one reaching through the other.
## Technical principles
Apply it as a question to any design that routes A through B, or has A reach into B: **does A still work when B is absent, broken, half-deployed, or swapped for something else?** If not — and especially if A is what you would use to *fix* B — the design is wrong however tidy the diagram looks.
- **Services & networking.** A deploy trigger, health probe, backup job or admin path gets its own way in. One routed through the application it operates on fails in exactly the state it exists for. BANNED: a deploy webhook reached through the app's own reverse proxy. GOOD: its own listener, answering while the app is down.
- **Code & modules.** Dependencies point one way: callers may know the service, the service must never know its callers. Business logic — and its comments — must not name or assume the delivery mechanism (controller, HTTP, request validation, route), because a service may have many consumers (controller, queue worker, CLI, another service). BANNED: `// The controller's validator guarantees these fields`. GOOD: caller-agnostic phrasing ("callers must supply X"), or just let the guard + type signature speak.
- **Data & state.** One owner per piece of state, reached through that owner. Two components writing the same table, file or volume are one component with a seam nobody declared.
- **Tooling & tests.** A test, script or pipeline stage that passes only because another one ran first is entangled: state what it needs and get it, or make it independent.
- **Vendors & records.** A supplier is a component like any other, so the question above is the whole test: prefer the option tying us to none, and where one is genuinely needed — a capability only it has, or a vendor that is the target itself — know what leaving costs (`~/.claude/principles/technical-principles.md`). Documentation the project owns is the case with no excuse. BANNED: the decision log in `.claude/rules/`, where swapping tools takes the project's reasoning with it. GOOD: `docs/decisions.md`, with a path-scoped rule pointing at it.
- **Proximity is not a reason.** Reusing a listener, config file, table, module or service *because it is already there*, when the new thing has no relationship to it, is how this gets in. If you cannot name the seam, there isn't one.
The design rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before designing or reviewing code.
## One spelling per goal
@@ -54,7 +48,7 @@ Apply it as a question to any design that routes A through B, or has A reach int
How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise.
- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered and specific enough that a design decision can be derived from them; the audience names who depends on this and what they may rely on. The check is those two headings in `README.md`, run at the start of every chunk: the same content in `AGENTS.md`, in `docs/`, or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. A repo missing either, or holding a version too vague to settle a decision, has no premises and gets one chunk that writes them and takes approval **before any planned work**, `todo.md` included.
- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered aims, one line each, reading like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal never describes what the code does today; how it is met lives further down the README and names the goal it serves. The audience names who depends on this and what they may rely on. The check is those two headings in `README.md`, run at the start of every chunk: the same content in `AGENTS.md`, in `docs/`, or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. A repo missing either has no premises and gets one chunk that writes them and takes approval **before any planned work**, `todo.md` included.
- **Without premises nothing merges and no work is reported as done**: the only output is that chunk, or a statement that the premises are missing. Without them only: a security fix — which passes even where it alters an interface — a bot's dependency bump, and a repair restoring behaviour the repo already claims: a red gate, a failing build, a false claim fixed per "A false claim is a bug". None of them decides direction. Anything else that adds capability, alters an interface, or picks between options is planned work and waits. Once written they stand; a later question they do not settle is the ask rule below, never reopened premises.
- **The plan is ordered as semver releases** — every item sits under the release that ships it. A `todo.md` in any other shape gets that shape as this chunk, approval taken.
- **An empty earliest unreleased release with nothing shipped toward it is planned as this chunk**: weigh the unscheduled items against the goals, write the order, take approval before any code.
@@ -108,9 +102,9 @@ How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise.
**Negation, history and limitations: name the action, or say nothing.** Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**.
**The inversion: 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 not a goal — 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.
**The inversion: 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.
**Every decision links to a goal.** An entry names the goal it serves; one that cannot is a missing goal, and an entry already in the repo with no goal behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how.
**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 — the ask rule above says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it.
**Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link. Don't summarize what's behind the link or restate the identifier's own name.
@@ -132,7 +126,7 @@ Default to NO comment. Delete one that is any of:
### README
**A README covers what a reader needs *before* opening the code**: how to build, test, run, and deploy it, and cross-cutting decisions no single file owns. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift.
**A README covers what a reader needs *before* opening the code**: how it meets its goals, how to build, test, run, and deploy it, and cross-cutting decisions no single file owns. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift.
**"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all, and adding a section is a deliberate act you must justify. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it.
@@ -160,5 +154,5 @@ Default to NO comment. Delete one that is any of:
- Commit message and PR title: **one line**, prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context.
- PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title).
- 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.
- Releases follow semver read strictly (`~/.claude/principles/technical-principles.md`): a minor only adds; a consumer's current code, data and scripts survive it unchanged.
- Releases follow semver read strictly (`~/.claude/principles/technical-principles.md`).
- Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else.
+5 -5
View File
@@ -4,10 +4,10 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for ins
## Goals
1. Share this configuration between my computers.
2. Keep it, and the transcripts of unattended runs, backed up.
1. Make my claude setup shareable between computers.
2. Keep my claude setup and the transcripts of unattended runs, backed up.
3. Leak nothing to the remote — no credentials, no transcripts, no memory files.
4. Run work chunks unattended, interrupting me only when a decision is mine.
4. Supply tools like agents, skills and scripts to make working with claude code more effective and with less interruptions.
## Audience
@@ -15,7 +15,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`.
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.
## Release
@@ -25,7 +25,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, with `uv` on `PATH`: `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/: host python, no container", "bin/: the Python floor is README's Install prerequisite"): `python3 -m unittest discover -s bin -p 'test_*.py'`
## Tracking a new file
+13
View File
@@ -0,0 +1,13 @@
---
name: principles-auditor
description: "Use this agent for larv-review's architecture pass: one yardstick checked against the whole project."
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.
- Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why.
- A departure a `todo.md` item plans away is named with that item, not raised.
- A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the `todo.md` item that ends it. Weigh it hard: that it was decided is no reason.
+1 -1
View File
@@ -18,7 +18,7 @@ You consider internal logic **only** when it directly affects an external surfac
## Your Review Method
Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` (URL/query conventions, error envelope, pagination, versioning, OpenAPI requirement) and `frontend.md` (intuitive-over-fancy, broad device support, progressive enhancement, semantic HTML, responsive design). `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change.
Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` and `frontend.md`. `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change.
1. **Identify the change surface**: Read the recent changes and pinpoint what external behavior is affected. If the change is purely internal with no external impact, say so plainly and stop — don't manufacture concerns.
+28
View File
@@ -0,0 +1,28 @@
---
name: prose-reviewer
description: "Use this agent for larv-review's prose pass."
tools: Read, Grep, Glob
---
You judge prose as a reader who did not write the change: you do not know what it means to say, so you can see whether it says it.
Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. The bar: `~/.claude/CLAUDE.md` → "Comments and documentation" and "Prose"; per paragraph the default verdict is delete. Read both each time — they change.
## Scopes
The prompt hands you these; past them, read only what a finding needs checking against.
1. **What the diff touched** — every markdown line and every comment it adds or changes.
2. **What the review cited** — each section the prompt names, with the code it governs. A cited section is load-bearing.
3. **Every prose file the repo owns**, when the prompt says the architecture pass ran: the sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk.
## Findings
Name the fix with each:
- **Delete** — a type, a test name, a spec or the code already says it.
- **Move** — a decision to `docs/decisions.md` with its one-line index in `AGENTS.md`; a goal to the README.
- **Move back** — a pointer standing where a definition belongs ("A pointer is not a definition"): inline the definition, leave the reasoning where it is.
- **Split or index** — load-bearing but unfindable: a section long enough that a reader who knows the answer is inside it still has to search. Sub-headings, or an index at its head.
Also a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
+1 -1
View File
@@ -9,7 +9,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
## First Steps
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
2. **Read every file in the shared principles** at `~/.claude/principles/` — not just `technical-principles.md`, also `frontend.md`, `logging.md`, and `rest-apis.md`. These are mandatory org guidelines, shared with the systems-architect (same principles, code-level lens here); all code MUST comply. Map the relevant file(s) to the change (frontend PR → `frontend.md`; API PR → `rest-apis.md`; etc.). Re-read each time — they change. Flag violations prominently.
2. **Read every file in the shared principles** at `~/.claude/principles/` — 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.
5. **Two passes minimum, then hunt absences.**
+7 -8
View File
@@ -1,12 +1,12 @@
---
name: systems-architect
description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing, vague, or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n<example>\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n<commentary>\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n<commentary>\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n<commentary>\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n<commentary>\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent drafts the missing goals and priorities and asks the user to confirm them before evaluating fitness.\\n</commentary>\\n</example>"
description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n<example>\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n<commentary>\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n<commentary>\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n<commentary>\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n<commentary>\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent drafts the missing goals and priorities and asks the user to confirm them before evaluating fitness.\\n</commentary>\\n</example>"
---
You are an elite Systems Architect with decades of experience designing software systems that endure for as long as their horizon demands. Your philosophy is uncompromising on fundamentals: clarity, simplicity, and deliberate structural choices trump short-term convenience every time. You design systems people will read, understand, and extend for their whole recorded lifetime.
## Core Philosophy
**Fitness for purpose decides what "best" means.** There is no best architecture in the abstract — only the best fit for the project's explicit goals and their priority order (time-to-market, throughput, operability, cost, team skills, and so on). This judgment runs all the way down: the overall solution idea, the programming language, and the major frameworks — not just how components are arranged internally. You cannot call any design "best" until the goals and priorities exist and are consistent. If they are missing, vague, or contradictory, fixing them is the first task (Stage 0).
**Fitness for purpose decides what "best" means.** There is no best architecture in the abstract — only the best fit for the project's explicit goals and their priority order (time-to-market, throughput, operability, cost, team skills, and so on). This judgment runs all the way down: the overall solution idea, the programming language, and the major frameworks — not just how components are arranged internally. You cannot call any design "best" until the goals and priorities exist and are consistent. If they are missing or contradictory, fixing them is the first task (Stage 0).
**The external contract ranks second only to the goals.** The API between this project and those who depend on it is the hardest part to change later; internal structure can be re-cut cheaply, a published contract cannot. Design and scrutinize it before internal arrangement (see The External Contract). Apply the same test to every major decision: sort one-way doors (published contracts, data models, storage, sync-vs-async, distribution boundaries) from two-way doors — scrutinize one-way doors hardest and commit to them as late as sound; decide two-way doors fast.
@@ -56,9 +56,9 @@ You work in distinct stages. Never skip stages. Never collapse them. Goals, audi
### Stage 0: Establish goals, audience, scale & domain language (do this first)
You cannot judge whether an implementation is the best one without a yardstick. The yardstick is five artifacts: **the audience** (who this is for — concrete roles, not "users"), **the problem statement** (what hurts without this), **the goals and their priority order** (including which failure classes are intolerable — the correctness targets the test machinery is priced against), **the scale & horizon** (expected load and data volume in orders of magnitude, team and consumer count, and the intended lifetime — throwaway experiment / MVP / production / long-lived platform — with a promotion event, the one that graduates it and forces re-review), and **the domain glossary** — the ubiquitous language: each core domain concept, one name, one line of meaning. Every name in the design must come from it.
- **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy — the same set the stability-reviewer enforces at code level, applied here through an architectural lens), the relevant ticket, and any design docs. What isn't written down is a question for the user.
- **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, measurable, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name?
- **Fix first if broken.** Unless the purpose and goals are abundantly clear, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead.
- **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy), the relevant ticket, and any design docs. What isn't written down is a question for the user.
- **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name?
- **Fix first if broken.** Unless the purpose and goals are stated and consistent, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead.
Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary. Only once these are recorded in the README do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies.
@@ -134,7 +134,6 @@ You review the seams that make verification possible and the strategy that uses
- **The external contract is executably pinned.** Contract tests fail when a published shape breaks — the lock on that one-way door. Price them like the versioning machinery (The External Contract): zero consumers outside your control, defer; many, mandatory.
- **Load targets come from Stage 0.** Load and performance tests verify the recorded scale numbers; no recorded scale, nothing to verify — fix Stage 0 first (a rig for unrecorded load is "Hunt the imagined requirement" wearing a QA hat). Data and traffic are production-shaped — a load run against a 1000-row database measures nothing. Runs are scheduled outside the merge gate (see Delivery); determinism here means a repeatable method against fixed thresholds, not identical latencies.
- **Post-deploy production suites are a designed capability.** Tagged, idempotent synthetic traffic against external surfaces only (API, UI), built once and run twice: post-deploy smoke and scheduled monitoring. It asserts liveness of the deployed surface, not logic — logic determinism lives in the pre-merge suites. Self-cleaning means expendable-by-design: a synthetic tenant or TTL-tagged data reaped out-of-band, never teardown-in-the-test, and never a delete endpoint added to the contract only for tests. Side effects are sandboxed by design — a synthetic checkout must never charge a real card — and the synthetic marking propagates through every downstream sink (telemetry, billing, analytics) so real signals stay uncontaminated; a tag that dies at the API edge is a missing seam.
- **Depth scales with the recorded horizon; the seams do not.** E2e breadth, load rigs, and post-deploy suites are ceremony — price them by horizon, blast radius, and the intolerable failures Stage 0 records. An injected clock and a pure core are fundamentals — scale-invariant (Core Philosophy: rigor follows the horizon).
## Delivery (the path to production is architecture)
@@ -149,7 +148,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d
## Reviewing Existing Work (periodic alignment)
You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. Stage 0 blocks review as much as design: if the project's purpose and goals are not abundantly clear from its docs, this run's output is the clarifying questions plus a short draft to confirm — not a review; the review happens in a later invocation, once the answers are recorded in the README.
You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review.
**Verdict and severities: ~/.claude/skills/larv-review/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon).
@@ -187,7 +186,7 @@ This is where unjustified duplication and accidental complexity get caught. Run
6. **Price the reasoned complexity too.** Essential-looking complexity has a requirement behind it. For each hotspot that survives the steps above, name that requirement, then sketch the design without it. When a much simpler near-equivalent exists, report the trade as a finding: the simpler shape, the exact functionality delta, and the complexity saved. A requirement nobody has priced is not a decision — offer the trade once, plainly, and let the owner accept or reject it.
7. **Hunt the imagined requirement.** The step above prices complexity a real requirement forces; this one removes complexity no requirement forces. For every abstraction, indirection, configuration point, and layer of generality, name the present, Stage 0-recorded requirement it serves. An interface with one implementation, a plugin system with one plugin, a cache or shard — or a load-testing rig — for load nobody recorded, a canary rig for a blast radius nobody recorded, "in case we swap the database" — speculative generality is the over-engineered twin of copy-paste drift: complexity nobody's requirement chose. The future that justifies flexibility must be a recorded goal or horizon, not the author's imagination — and the shorter the horizon, the harder this step cuts. Rate removals with the same severity as unreasoned duplication.
Respect documented deliberate deviations — a stated trade-off is a valid reason (`docs/decisions.md`). Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system.
Respect documented deliberate deviations — a stated trade-off is a valid reason (`docs/decisions.md`), unless it works against a goal or a technical principle and names no `todo.md` item ending it. Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system.
## Communication Style
+2 -1
View File
@@ -6,6 +6,7 @@ import sys
LAUNCHER = pathlib.Path(__file__).resolve()
sys.path.insert(0, str(LAUNCHER.parent))
from loop_claude import main, paths
from loop_claude import 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()))
+14
View File
@@ -0,0 +1,14 @@
import json
from loop_claude.claude_code.formats import models_in
def offered_models(folder) -> list[tuple[str, object]]:
files = []
for path in folder.glob("*.json"):
try:
with open(path, encoding="utf-8") as handle:
files.append(json.load(handle))
except (OSError, ValueError):
continue
return models_in(files)
+30 -75
View File
@@ -1,40 +1,10 @@
"""Every Claude Code format loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it."""
import enum
import glob
"""Claude Code's JSON shapes loop-claude handles, each under a sample of it, as Claude Code 2.1.284 writes it."""
import json
import os
from loop_claude.outcome import Failure
class UserEntryKind(enum.Enum):
"""Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind."""
COMMAND = enum.auto()
CTRL_C = enum.auto()
EMPTY = enum.auto()
HUMAN = enum.auto()
META = enum.auto()
NON_TEXT = enum.auto()
SDK_PROMPT = enum.auto()
def locations(home):
return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects"
# <projects>/-home-me-code-log/<session id>.jsonl
def transcript_path(projects, session_id):
hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl"))
return hit[0] if hit else ""
# <session id>.jsonl, <session id>/subagents/, and from older versions <session id>.superseded-1789290815002/ and <session id>.orphaned-*.jsonl
def session_files(transcript):
return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*")
def parse(raw):
def parse(raw) -> dict | None:
try:
entry = json.loads(raw)
except ValueError:
@@ -42,51 +12,45 @@ def parse(raw):
return entry if isinstance(entry, dict) else None
def content(entry):
def content(entry) -> object:
message = entry.get("message")
return message.get("content") if isinstance(message, dict) else None
def parts(entry):
def parts(entry) -> 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):
def assistant_parts(entry) -> list:
return parts(entry) if entry.get("type") == "assistant" else []
def user_entry_kind(entry):
def written_by_human(entry) -> bool:
"""Whether the human wrote a "user" entry; Claude Code writes the rest."""
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
if entry.get("isMeta"):
return UserEntryKind.META
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
if entry.get("promptSource") == "sdk":
return UserEntryKind.SDK_PROMPT
if entry.get("isMeta") or entry.get("promptSource") == "sdk":
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 UserEntryKind.COMMAND if source == "system" or (source != "typed" and text.startswith("<")) else UserEntryKind.HUMAN
return source != "system" and (source == "typed" or not text.startswith("<"))
texts = [part_text(part) for part in parts(entry)]
if not texts:
return UserEntryKind.EMPTY
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
if None in texts:
return UserEntryKind.NON_TEXT
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
if any(text.startswith("[Request interrupted") for text in texts):
return UserEntryKind.CTRL_C
return UserEntryKind.HUMAN
return bool(texts) and all(text is not None and not text.startswith("[Request interrupted") for text in texts)
def human_text(entry):
def human_text(entry) -> 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
if entry.get("type") != "user" or user_entry_kind(entry) is not UserEntryKind.HUMAN:
if entry.get("type") != "user" or not written_by_human(entry):
return None
text = content(entry)
return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry))
@@ -94,7 +58,7 @@ def human_text(entry):
# 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):
def queued_human_text(entry) -> 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
@@ -102,54 +66,45 @@ def queued_human_text(entry):
# {"type": "text", "text": "ok"}
def part_text(part):
def part_text(part) -> 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):
def tool_call(part) -> 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):
def ends_stream(event) -> bool:
return event.get("type") == "result"
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
def structured_output(stdout):
def structured_output(stdout) -> object:
return (parse(stdout) or {}).get("structured_output")
# ~/.claude.json: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def trust_records(config):
projects = config.setdefault("projects", {}) if isinstance(config, dict) else None
# 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):
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")
return projects
def mark_trusted(projects, roots):
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
for path in untrusted:
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
return untrusted
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
return {**config, "projects": {**projects, **marked}}, untrusted
# <model catalog>/*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def catalog(folder):
newest = {}
for path in folder.glob("*.json"):
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError):
continue
# 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]]:
"""The (id, name) of each model in the newest of the parsed catalog files."""
newest: dict = {}
for data in files:
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models = newest
models: object = newest
for key in ("catalog", "config", "models"):
models = models.get(key) if isinstance(models, dict) else None
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
+15 -13
View File
@@ -1,38 +1,40 @@
import dataclasses
import glob
import os
import pathlib
import shutil
import sys
import uuid
from loop_claude.claude_code.formats import session_files, transcript_path
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@dataclasses.dataclass(frozen=True)
class Session:
id: uuid.UUID
name: str
projects: pathlib.Path
def session_for(project, paths):
"""Exists while its transcript does."""
id: uuid.UUID
claude_code_transcripts: pathlib.Path
name: str
def session_for(project, 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(uuid.uuid5(NAMESPACE, name), name, paths.projects)
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
def transcript_file(session):
return transcript_path(session.projects, session.id)
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
def transcript_file(session) -> str:
hit = glob.glob(os.path.join(glob.escape(str(session.claude_code_transcripts)), "*", f"{session.id}.jsonl"))
return hit[0] if hit else ""
def delete_session(session):
def delete_session(session) -> None:
path = transcript_file(session)
if not path:
return
for sibling in session_files(path):
# <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")) + "*"):
try:
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
except OSError as failure:
+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):
def read(path) -> 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):
return Failure(f"could not read the transcript {path}: {failure.strerror}")
def human_turns(entries):
def human_turns(entries) -> int:
return sum(1 for entry in entries if human_text(entry) is not None)
def render(entries):
def render(entries) -> 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):
return "\n\n".join(lines)
def part_line(part, limit=400):
def part_line(part, limit=400) -> str:
if (text := part_text(part)) and text.strip():
return text
if call := tool_call(part):
+9 -8
View File
@@ -1,26 +1,27 @@
import json
import sys
from loop_claude.claude_code.formats import mark_trusted, trust_records
from loop_claude.claude_code.formats import mark_trusted
from loop_claude.file_writes import replace_json
from loop_claude.outcome import Failure
def trust(config, roots):
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
def trust(config, roots) -> None:
try:
with open(config, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError) as failure:
print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr)
return
projects = trust_records(data)
if isinstance(projects, Failure):
print(f"could not read {config}: {projects.reason}", file=sys.stderr)
marked = mark_trusted(data, roots)
if isinstance(marked, Failure):
print(f"could not read {config}: {marked.reason}", file=sys.stderr)
return
untrusted = mark_trusted(projects, roots)
updated, untrusted = marked
if not untrusted:
return
if failure := replace_json(config, data, indent=2):
print(f"could not write {config}: {failure.reason}", file=sys.stderr)
if unwritten := replace_json(config, updated, indent=2):
print(f"could not write {config}: {unwritten.reason}", file=sys.stderr)
return
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
-41
View File
@@ -1,41 +0,0 @@
from loop_claude.archive import archive
from loop_claude.claude_code.session import delete_session, session_for, transcript_file
from loop_claude.claude_code.transcript import read, render
from loop_claude.claude_runs.interrupt import interrupt
from loop_claude.claude_runs.judge import judge
from loop_claude.claude_runs.worker import run_worker, worker_args
from loop_claude.outcome import Continue, Failure, Stop
def run_cycle(root, project, task, premises, models, paths):
session = session_for(project, paths)
resuming = bool(transcript_file(session))
if failure := run_worker(root, worker_args(task, session, models.worker, resuming)):
return failure
path = transcript_file(session)
if not path:
return Stop(1, f"claude left no transcript for session {session.id}")
verdict = judge_through_interrupts(root, project, task, premises, models, session, path, paths)
if isinstance(verdict, Stop):
return verdict
if verdict.finished:
if failure := archive(project, path, f"Task: {task}\n\nVerdict: finished", paths):
return Stop(1, failure.reason)
delete_session(session)
return Continue()
def judge_through_interrupts(root, project, task, premises, models, session, path, paths):
# 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(root, task, premises, render(entries), models.judge)
if isinstance(verdict, Stop) or not verdict.interrupt:
return verdict
if failure := archive(project, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict.question}", paths):
return Stop(1, failure.reason)
if stop := interrupt(root, session.id, models.worker, path, verdict.question, paths):
return stop
@@ -5,7 +5,7 @@ from loop_claude.file_writes import make_private, replace_file
from loop_claude.outcome import Failure
def archive(project, path, note, paths):
def archive(project, path, note, paths) -> Failure | None:
folder = paths.archive / project
try:
with open(path, "rb") as handle:
@@ -17,7 +17,7 @@ def archive(project, path, note, paths):
# The copy lands last, so a copy on disk always has its verdict beside it.
if not copy.exists():
for dest, data in ((copy.with_suffix(".verdict.md"), f"{note}\n".encode()), (copy, raw)):
if failure := replace_file(dest, data):
return Failure(f"could not archive the transcript: {dest}: {failure.reason}")
if unwritten := replace_file(dest, data):
return Failure(f"could not archive the transcript: {dest}: {unwritten.reason}")
print(f"transcript: {copy}", file=sys.stderr)
return None
@@ -1,7 +1,7 @@
import subprocess
import sys
from loop_claude import human
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.outcome import Failure, Stop
@@ -10,9 +10,9 @@ from loop_claude.project.checkout import checkouts
TO = "answer the question above"
def interrupt(root, session_id, model, path, question, paths):
def interrupt(root, session_id, model, path, question, paths) -> Stop | None:
print(f"\n{question}", file=sys.stderr)
if stop := human.off_terminal(TO):
if stop := human_needed.off_terminal(TO):
return stop
trust(paths.claude_json, checkouts(root))
entries = read(path)
@@ -27,5 +27,5 @@ def interrupt(root, session_id, model, path, question, paths):
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(TO, "the interrupt ended with nothing typed")
return human_needed.stop(TO, "the interrupt ended with nothing typed")
return None
@@ -1,12 +1,11 @@
import dataclasses
import itertools
import json
import subprocess
import typing
from loop_claude.claude_code.formats import structured_output
from loop_claude.outcome import Failure
from loop_claude.retry import stop_or_sleep_a_minute
from loop_claude.cycle.retry import retried
from loop_claude.outcome import Failure, Stop
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
@@ -45,7 +44,7 @@ JUDGE_SCHEMA = {
}
def judge(root, task, premises, transcript, model):
def judge(root, task, premises, transcript, model) -> 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",
@@ -57,29 +56,23 @@ def judge(root, task, premises, transcript, model):
"--tools", "",
]
prompt = judge_prompt(task, premises, transcript)
for failures in itertools.count(1):
verdict = run_judge(root, args, prompt)
if isinstance(verdict, Failure):
reason = verdict.reason
elif not grounded(verdict, transcript):
reason = f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else "")
else:
return verdict
if stop := stop_or_sleep_a_minute("judge", failures, reason):
return stop
return retried("judge", lambda: run_judge(root, args, prompt, transcript))
def run_judge(root, args, prompt):
def run_judge(root, args, prompt, transcript) -> Verdict | Failure:
try:
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
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}")
return verdict_from(structured_output(proc.stdout))
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 ""))
return verdict
def judge_prompt(task, premises, transcript):
def judge_prompt(task, premises, transcript) -> str:
return (
f"From README.md:\n{premises}\n\n"
f"The task an agent was given:\n{task}\n\n"
@@ -89,7 +82,7 @@ def judge_prompt(task, premises, transcript):
)
def verdict_from(output):
def verdict_from(output) -> Verdict | Failure:
if not isinstance(output, dict):
return Failure("the judge returned no verdict")
for name, kind in VERDICT_TYPES.items():
@@ -100,5 +93,5 @@ def verdict_from(output):
return Verdict(**{name: output[name] for name in VERDICT_TYPES})
def grounded(verdict, transcript):
def grounded(verdict, transcript) -> bool:
return verdict.evidence.strip() != "" and verdict.evidence in transcript
+20
View File
@@ -0,0 +1,20 @@
import sys
import time
import typing
from loop_claude.outcome import Failure, Stop
T = typing.TypeVar("T")
def retried(who, attempt: typing.Callable[[], T | Failure]) -> T | Stop:
failures = 0
while True:
failures += 1
result = attempt()
if not isinstance(result, Failure):
return result
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)
+55
View File
@@ -0,0 +1,55 @@
import dataclasses
from loop_claude.claude_code.session import Session, delete_session, 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.retry import retried
from loop_claude.cycle.worker import run_worker, worker_args
from loop_claude.outcome import Failure, Stop
from loop_claude.paths import Paths
from loop_claude.project.models import Models
@dataclasses.dataclass(frozen=True)
class Cycle:
models: Models
paths: Paths
premises: str
project: str
root: str
session: Session
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)
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
@@ -5,14 +5,14 @@ from loop_claude.claude_code.transcript import part_line
from loop_claude.outcome import Failure
def run_worker(root, args):
def run_worker(root, args) -> Failure | None:
try:
proc = subprocess.Popen(["claude", *args], cwd=root, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}")
with proc:
done = False
for raw in proc.stdout:
for raw in proc.stdout or ():
event = parse(raw) or {}
done = done or ends_stream(event)
for part in assistant_parts(event):
@@ -26,7 +26,7 @@ def run_worker(root, args):
return None if done else Failure("claude exited 0 without a result event")
def worker_args(task, session, model, resuming):
def worker_args(task, session, model, resuming) -> list[str]:
if resuming:
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session.id)]
else:
+4 -4
View File
@@ -4,7 +4,7 @@ import os
from loop_claude.outcome import Failure
def make_private(folder):
def make_private(folder) -> None:
mask = os.umask(0o077)
try:
os.makedirs(folder, exist_ok=True)
@@ -12,11 +12,11 @@ def make_private(folder):
os.umask(mask)
def replace_json(path, data, **dump):
def replace_json(path, data, **dump) -> Failure | None:
return replace_file(path, json.dumps(data, **dump).encode())
def replace_file(path, data):
def replace_file(path, data) -> Failure | None:
staged = f"{path}.{os.getpid()}"
try:
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600
@@ -27,5 +27,5 @@ def replace_file(path, data):
except OSError as failure:
if os.path.exists(staged):
os.remove(staged)
return Failure(failure.strerror)
return Failure(failure.strerror or str(failure))
return None
@@ -3,11 +3,11 @@ import sys
from loop_claude.outcome import Stop
def needed(to, but):
def stop(to, but) -> Stop:
return Stop(2, f"the human is needed to {to}, but {but}")
def off_terminal(to):
def off_terminal(to) -> Stop | None:
if sys.stdin.isatty() and sys.stdout.isatty():
return None
return needed(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
return stop(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
View File
@@ -12,10 +12,10 @@ Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "V
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. 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.
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 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.
@@ -36,24 +36,16 @@ loop-claude --help succeeds.
import dataclasses
import sys
from loop_claude.cycle import run_cycle
from loop_claude.outcome import Continue, Failure, Stop
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.outcome import Stop
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
from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint
from loop_claude.retry import stop_or_sleep_a_minute
@dataclasses.dataclass(frozen=True)
class LoopState:
cycle_number: int
failures: int
root: str
task: str
def main(argv, env, paths, launcher, cwd):
def main(argv, env, paths, launcher, cwd) -> int:
try:
stop = run_loop(argv, env, paths, launcher, cwd)
except KeyboardInterrupt:
@@ -63,12 +55,13 @@ def main(argv, env, paths, launcher, cwd):
return stop.code
def run_loop(argv, env, paths, launcher, cwd):
def run_loop(argv, env, paths, launcher, cwd) -> Stop:
state = loop_state(argv, cwd)
if isinstance(state, Stop):
return state
baseline = fingerprint(launcher)
project = project_name(state.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)
@@ -79,24 +72,17 @@ def run_loop(argv, env, paths, launcher, cwd):
if isinstance(models, Stop):
return models
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
match run_cycle(state.root, project, state.task, premises, models, paths):
case Stop() as stop:
return stop
case Failure(reason):
state = dataclasses.replace(state, failures=state.failures + 1)
if stop := stop_or_sleep_a_minute("worker", state.failures, reason):
return stop
case Continue():
state = dataclasses.replace(state, failures=0)
if stop := run_cycle(Cycle(models=models, paths=paths, premises=premises, project=project, root=state.root, session=session, task=state.task)):
return stop
def loop_state(argv, cwd):
def loop_state(argv, cwd) -> LoopState | 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, 0, root, task)
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>")
@@ -4,16 +4,26 @@ import json
import os
import subprocess
import sys
import typing
RELOAD_FLAG = "--reloaded"
T = typing.TypeVar("T")
def decode_state(handed, kind):
# A field change stops a running loop at its next reload: the new script rejects the old fields.
@dataclasses.dataclass(frozen=True)
class LoopState:
cycle_number: int
root: str
task: str
def decode_state(handed, kind: type[T]) -> T | None:
try:
fields = json.loads(handed)
except ValueError:
return None
shape = {field.name: field.type for field in dataclasses.fields(kind)}
shape = typing.get_type_hints(kind)
if not isinstance(fields, dict) or fields.keys() != shape.keys():
return None
if any(type(fields[name]) is not type_ for name, type_ in shape.items()):
@@ -21,7 +31,7 @@ def decode_state(handed, kind):
return kind(**fields)
def fingerprint(launcher):
def fingerprint(launcher) -> str:
digest = hashlib.sha256()
for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]:
try:
@@ -32,7 +42,7 @@ def fingerprint(launcher):
return digest.hexdigest()
def exec_if_edited(launcher, baseline, state):
def exec_if_edited(launcher, baseline, state) -> None:
if fingerprint(launcher) == baseline:
return
trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True)
+2 -5
View File
@@ -1,17 +1,14 @@
import dataclasses
@dataclasses.dataclass(frozen=True)
class Continue:
pass
@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."""
reason: str
@dataclasses.dataclass(frozen=True)
class Stop:
"""loop-claude exits with code, printing reason."""
code: int
reason: str
+5 -8
View File
@@ -1,27 +1,24 @@
import dataclasses
import pathlib
from loop_claude.claude_code.formats import locations
@dataclasses.dataclass(frozen=True)
class Paths:
archive: pathlib.Path
claude_code_transcripts: pathlib.Path
claude_json: pathlib.Path
code: pathlib.Path
model_catalog: pathlib.Path
models_file: pathlib.Path
projects: pathlib.Path
def paths_from(home, env):
def paths_from(home, env) -> Paths:
claude = home / ".claude"
claude_json, model_catalog, projects = locations(home)
return Paths(
archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
claude_json=claude_json,
claude_code_transcripts=claude / "projects",
claude_json=home / ".claude.json",
code=home / "code",
model_catalog=model_catalog,
model_catalog=claude / "cache" / "model-catalog",
models_file=claude / "loop-claude-models.json",
projects=projects,
)
+3 -3
View File
@@ -3,14 +3,14 @@ import subprocess
from loop_claude.outcome import Stop
def checkout_root(cwd):
def checkout_root(cwd) -> str | Stop:
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True)
if found.returncode != 0:
return Stop(1, found.stderr.strip())
return found.stdout.strip()
def checkouts(root):
def checkouts(root) -> list[str]:
found = [root]
listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True)
if listing.returncode == 0:
@@ -18,5 +18,5 @@ def checkouts(root):
return sorted(set(found))
def project_name(root, code):
def project_name(root, code) -> str:
return root.removeprefix(f"{code}/").lstrip("/")
+11 -11
View File
@@ -2,8 +2,8 @@ import dataclasses
import json
import sys
from loop_claude import human
from loop_claude.claude_code.formats import catalog
from loop_claude import human_needed
from loop_claude.claude_code.catalog import offered_models
from loop_claude.file_writes import replace_json
from loop_claude.outcome import Stop
@@ -14,7 +14,7 @@ class Models:
worker: str
def project_models(project, paths, env):
def project_models(project, paths, env) -> Models | Stop:
judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL")
if judge and worker:
return Models(judge, worker)
@@ -24,13 +24,13 @@ def project_models(project, paths, env):
return Models(judge or chosen, worker or chosen)
def project_model(name, paths):
def project_model(name, paths) -> str | Stop:
saved = paths.models_file
models = read_models(saved)
if isinstance(models, Stop):
return models
if chosen := models.get(name):
return chosen
if saved_model := models.get(name):
return saved_model
chosen = ask_model(name, saved, paths.model_catalog)
if isinstance(chosen, Stop):
return chosen
@@ -44,7 +44,7 @@ def project_model(name, paths):
return chosen
def read_models(saved):
def read_models(saved) -> dict[str, str] | Stop:
try:
with open(saved, encoding="utf-8") as handle:
models = json.load(handle)
@@ -57,10 +57,10 @@ def read_models(saved):
return models
def ask_model(name, saved, folder):
if stop := human.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}"):
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}"):
return stop
offered = catalog(folder)
offered = offered_models(folder)
print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr)
for number, (model_id, label) in enumerate(offered, 1):
print(f" {number}. {label} ({model_id})", file=sys.stderr)
@@ -71,7 +71,7 @@ def ask_model(name, saved, folder):
answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip()
except EOFError:
print(file=sys.stderr)
return human.needed(f"pick {name}'s model", "the input ended")
return human_needed.stop(f"pick {name}'s model", "the input ended")
if not answer:
continue
if not (offered and answer.isdecimal()):
+13 -9
View File
@@ -3,7 +3,7 @@ import pathlib
from loop_claude.outcome import Stop
def read_premises(root):
def read_premises(root) -> str | Stop:
try:
found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8"))
except OSError as failure:
@@ -22,15 +22,19 @@ def read_premises(root):
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
def sections(text):
found, current, fenced = {}, None, False
def sections(text) -> dict[str, list[str]]:
blocks: list[tuple[str | None, list[str]]] = []
fenced = False
for line in text.splitlines():
fenced ^= line.startswith("```")
if not fenced and line.startswith("## "):
current = []
found.setdefault(line.strip()[3:], []).append(current)
blocks.append((line.strip()[3:], []))
elif not fenced and line.startswith("# "):
current = None
elif current is not None and line.strip():
current.append(line)
return {name: ["\n".join(body) for body in bodies] for name, bodies in found.items()}
blocks.append((None, []))
elif blocks and line.strip():
blocks[-1][1].append(line)
found: dict[str, list[str]] = {}
for name, body in blocks:
if name is not None:
found.setdefault(name, []).append("\n".join(body))
return found
-11
View File
@@ -1,11 +0,0 @@
import sys
import time
from loop_claude.outcome import Stop
def stop_or_sleep_a_minute(who, failures, reason):
if failures == 3:
return Stop(1, f"the {who} failed three times running: {reason}")
print(f"retrying the {who} in a minute: {reason}", file=sys.stderr)
time.sleep(60)
+22 -3
View File
@@ -1,3 +1,4 @@
import dataclasses
import json
import os
import pathlib
@@ -7,9 +8,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude import file_writes, main
from loop_claude import file_writes
from loop_claude.claude_code import formats, transcript
from loop_claude.claude_runs import judge
from loop_claude.cycle import judge
from loop_claude.loop import main, reload
from loop_claude.outcome import Failure, Stop
from loop_claude.project import premises
@@ -85,6 +87,15 @@ class Parse(unittest.TestCase):
self.assertIsNone(formats.parse("[1, 2]"))
class MarkTrusted(unittest.TestCase):
def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self):
config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}}
handed = json.dumps(config)
self.assertEqual(formats.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"]))
self.assertEqual(json.dumps(config), handed)
self.assertEqual(formats.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"]))
class Grounded(unittest.TestCase):
def test_every_verdict_must_quote_the_transcript(self):
def verdict(evidence):
@@ -106,10 +117,18 @@ class Verdict(unittest.TestCase):
class LoopState(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, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]):
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>"))
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))
class ReplaceFile(unittest.TestCase):
+6 -5
View File
@@ -366,6 +366,8 @@ class Cycles(unittest.TestCase):
self.assertIn("retrying the worker in a minute: claude exited 1", run.stderr)
self.assertIn("claude exited 0 without a result event", run.stderr)
self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude killed by signal 9")
self.assertNotIn("=== cycle 2 ===", run.stdout)
self.assertEqual(argument(run.calls[1], "--resume"), argument(run.calls[0], "--session-id"))
run = checkout.run([worker(exit=1), worker(exit=1), worker(), judge(), worker(exit=1), worker(exit=1)])
self.assertEqual(run.code, 130)
@@ -646,17 +648,16 @@ class Reload(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge"] * 4)
self.assertIn("keeping the running script", run.stderr)
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
self.assertEqual(reloads, [{"cycle_number": cycle, "failures": 0, "root": str(checkout.root), "task": TASK} for cycle in (2, 3)])
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK} for cycle in (2, 3)])
self.assertIn("=== cycle 4 ===", run.stdout)
outside = checkout.temp / "outside"
outside.mkdir()
state = {"cycle_number": 3, "failures": 2, "root": str(checkout.root), "task": TASK}
run = checkout.run([worker(exit=1)], argv=["--reloaded", json.dumps(state)], cwd=outside)
self.assertEqual((run.code, run.sleeps), (1, []))
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK}
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)], cwd=outside)
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"]))
self.assertEqual(run.calls[0]["cwd"], str(checkout.root))
self.assertIn("=== cycle 4 ===", run.stdout)
self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude exited 1")
run = checkout.run([], argv=["--reloaded", "{}"])
self.assertEqual((run.code, run.calls), (1, []))
+7 -3
View File
@@ -9,11 +9,15 @@ ROOT = pathlib.Path(__file__).resolve().parents[1]
FLOOR = re.compile(r"Python 3\.(\d+) or newer")
def readme_floor() -> tuple[int, int] | None:
named = FLOOR.search((ROOT / "README.md").read_text(encoding="utf-8"))
return (3, int(named.group(1))) if named else None
class PythonFloor(unittest.TestCase):
def test_the_suite_passes_on_the_python_the_readme_names_as_floor(self):
named = FLOOR.search((ROOT / "README.md").read_text(encoding="utf-8"))
self.assertIsNotNone(named, "README.md's Install names `Python 3.N or newer`")
floor = (3, int(named.group(1)))
floor = readme_floor()
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if sys.version_info[:2] == floor:
self.skipTest("this run is on the floor")
if shutil.which("uv") is None:
+15
View File
@@ -0,0 +1,15 @@
import shutil
import subprocess
import unittest
from test_python_floor import ROOT, readme_floor
class Types(unittest.TestCase):
def test_mypy_passes_on_loop_claude_at_the_floor(self):
floor = readme_floor()
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)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+38 -10
View File
@@ -8,29 +8,29 @@
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.
## loop-claude: one session per project, at a fixed id
## loop-claude: one session per project, at a fixed id from its full path, and a second loop refuses to start
2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. 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 session name, so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside 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.
## loop-claude: the trust file is rewritten before an interrupt
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. Valid while no flag skips the dialog.
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.
## loop-claude: every worktree of the checkout is trusted before an interrupt
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. 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.
## bin/: the Python floor is README's Install prerequisite
2026-09-26, larv-review, carrying the floor the 2026-09-26 stability round assumed and verified its f-string fix under. 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 3.11-only call like `contextlib.chdir`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while no machine taking the checkout ships an older Python.
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
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 the same way. Valid while claude runs on the host.
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, and 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c; the places the last run named are filed in `todo.md` under 0.1.0, and a later chunk 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; 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.
## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
@@ -54,7 +54,15 @@
## 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.
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
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
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
@@ -68,9 +76,9 @@
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: the rebuild keeps main's `--reloaded` state
## loop-claude: a loop running main's script stops once at the cut-over
2026-09-28, lilleman, for the rebuild. Serves goal 4. A loop running main's script reloads into the rebuilt one at its next cycle boundary and carries on; `decode_state` accepts only JSON whose keys and value types match `LoopState` exactly, so renaming, adding, dropping or retyping a field breaks that reload, and no code exists only for the cut-over. Valid until the rebuild merges.
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
@@ -79,3 +87,23 @@
## 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.
## 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.
+13
View File
@@ -5,12 +5,20 @@
# Principles
* Compose, do not entangle — the core design rule, at every level from services down to functions.
- Two things that can stand alone stand alone, joined by a narrow seam you can name; never by one reaching through the other. The test, for any design routing A through B or having A reach into B: does A still work when B is absent, broken, half-deployed or swapped for something else? If not — and especially if A is what you would use to fix B — the design is wrong however tidy the diagram looks.
- Services and networking: a deploy trigger, health probe, backup job or admin path gets its own way in, since one routed through the application it operates on fails in exactly the state it exists for. BANNED: a deploy webhook reached through the app's own reverse proxy. GOOD: its own listener, answering while the app is down.
- Modules: dependencies point one way. Callers may know the service; the service never knows its callers, and neither it nor its comments name or assume the delivery mechanism (controller, HTTP, request validation, route), because a queue worker, a CLI or another service may call it too. BANNED: `// The controller's validator guarantees these fields`. GOOD: "callers must supply X", or the guard and the type signature alone.
- Functions: a function takes what it needs as arguments and returns what it produces. One that works only after another has set up shared state, or leaves state for the next to find, is entangled with it. BANNED: `validate(conf)` that fills defaults `send(conf)` relies on. GOOD: `send(withDefaults(conf))`.
- Tests and tooling: a test, script or pipeline stage that passes only because another ran first is entangled; it states what it needs and gets it.
- Proximity is not a reason. Reusing a listener, config file, table, module or service because it is already there, when the new thing has no relationship to it, is how entanglement gets in. If you cannot name the seam, there is none.
* Make invalid states unrepresentable.
- Example: using a time-only type in the database when we actually want to store a time of day introduces risk for errors.
* Always store timestamps as full ISO datetime in UTC.
- Always communicate timestamps as full ISO datetime in UTC from APIs with database access.
* Always grant explicit access to data, both read and write.
* One owner per value; a reader can name every writer.
- At every scale, from a variable to a table, file or volume: two components writing the same one are one component with a seam nobody declared.
- The test: from the code in front of them, can a reader list every writer to this value, and the order those writers run in?
- BANNED: a record passed to 24 functions, 13 of which mutate it and return nothing. GOOD: one type owns the value, the rest call it and take a result.
- BANNED: `fill(set)` then `adjust(set)`, where swapping the two lines changes the output. GOOD: `const filled = fill(); const adjusted = adjust(filled);`
@@ -32,6 +40,10 @@
- Example set order.client_firstname instead of order.client_id and fetching firstname from the clients table.
* Explicit over implicit.
- Avoid magic, avoid "clever" solutions, only abstract when the API can clearly describe what is happening.
* Functional core, imperative shell.
- Decisions live in pure functions, data in and data out; the shell around them performs the effects and holds no branching of its own.
- Every side effect comes from outside: output, time, randomness, network and storage are injectable, so a test runs exactly the code production runs.
- BANNED: `new Date(entry.msTimestamp ?? Date.now())` in a formatter; a test swapping `globalThis.fetch`. GOOD: the clock is a parameter, defaulted to the system clock only where the program is wired together.
* Deterministic order wherever order carries no meaning.
- Sort it, on a key that does not move: the name a line introduces, never where it came from. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to.
* Keep It Simple, Stupid (KISS).
@@ -41,6 +53,7 @@
* All critical flows should have good traces, from where something was initiated until it completed.
- Use traceparent OTLP and standardized logging for this.
* Prefer the vendor-neutral option, and know what leaving would cost.
- A supplier is a component like any other, so compose-not-entangle's test is the whole test.
- Where two options do the job, the one that ties us to no supplier wins by default — dependency, protocol, format, service, provider and storage alike. Choosing neutral is usually free; it is the leaving that is expensive, so the test is what an exit costs and whether anyone has priced it.
- Sidestep deliberately, never by drift: a capability only that vendor has, or a vendor that is the target itself (an integration we build, a format we implement). Record which of the two it is and what the tie buys.
- Do not buy portability nobody asked for. An abstraction over one implementation, "in case we swap X", is speculative generality rather than neutrality — prefer the neutral thing, do not build a layer to preserve the option.
+19 -27
View File
@@ -11,11 +11,13 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchr
Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/.claude/skills/larv-review/review-findings.md.
**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.
## 1. Preconditions
- 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, or too vague to settle a decision → 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. Only what that section lets through without them reaches review.
- **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. Only what that section lets through without them reaches review.
- 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)
@@ -24,31 +26,33 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de
## 3. Passes
| Pass | Reviewer | Runs on a change it has not seen that… |
| Pass | Reviewer | Trigger |
|------|----------|----------------------------------------|
| Architecture, then the comprehension floor | systems-architect, then 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; more than ~400 non-generated lines of code or ~5 modules |
| 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 |
| 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 | you, and a fresh-context agent | every chunk; a fix, where it touches prose |
| 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 pass whose trigger does not fire is skipped, and the summary says so. A 🔀 escalation fires the named pass's trigger once the current pass is done, and runs forward from there as a re-entry does.
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.
**Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → 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: 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.
**Re-entry.** A fix is a change the passes have not seen. The pass whose findings it answers runs again, per the findings document's rounds; beyond it, classify the fix by the widest thing it touches — the first row whose trigger it fires, none sending it to §4 — and run forward from that row through §4, each later pass only where its trigger fires too.
**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.
**Round cap.** A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human. A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 launch and its rerun. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent. The external auto-reviewer (§4) is a pass of its own, each review it posts a round: after its third, ask the human before any push that would summon a fourth.
**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.
### Architecture
Launch systems-architect: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts.
- **Stage 0 questions returned** (goals/audience/horizon unrecorded): relay them to the user, record the answers in the README, re-run once. No user → skip the pass, carry the questions into the summary.
- **BLOCK** → confirm with the user first when the restructure materially reshapes their PR.
- **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 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`. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel.
Then the 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 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
@@ -62,23 +66,11 @@ The full-scan plugin is not enabled by default; unavailable → say so in the su
### Stability and product-owner
Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches — prompted per the findings document's rounds. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates.
Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates.
### Prose
Two scopes:
1. **What the diff touched** — every markdown line and every comment it adds or changes. Judge these yourself.
2. **What this review cited** — any section of the repo's prose a reviewer quoted to justify a finding, you quoted to justify a decline, or the implementer quoted to explain a decision. A cited section is load-bearing, and if anyone had to hunt for it, that is the finding. Judge these with a **fresh-context agent**, never yourself: whoever just wrote the code already knows the answer and cannot see what the prose adds. Hand it the section and the code that section governs, and nothing else.
In a chunk whose architecture pass ran, the fresh-context agent reads every prose file the repo owns: the only sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk.
The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph the default verdict is delete.
- **Delete** — a type, a test name, a spec or the code already says it. In this chunk.
- **Move** — a decision goes to `docs/decisions.md` with its one-line index; a goal goes to the README. In this chunk.
- **Move back** — the opposite fault, and the one a deletion-only pass never catches: a pointer standing where a definition belongs ("A pointer is not a definition", same section). Inline the definition and leave the reasoning where it is.
- **Split or index** — load-bearing but unfindable: a section long enough that a reader who knows the answer is inside it still has to search for it. Sub-headings, or an index at its head. Bigger than the chunk → 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. 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.
## 4. Gate
@@ -86,7 +78,7 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph
2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3.
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 findings follow the findings document like any reviewer's. 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. **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. Goal alignment, then merge
@@ -97,4 +89,4 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph
## 6. Wrap up
Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs declined vs open — each decline with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user.
Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal or technical principle it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user.
+8 -7
View File
@@ -2,16 +2,18 @@
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.
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.
## Severity
- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`; never declined.
- 🔴 **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** — never holds a pass.
- 🟢 **nit** — fixed, answered, declined in the summary with its reason, or filed in `todo.md`.
- ❓ **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 🟢.
@@ -27,10 +29,9 @@ A review's first line, derived from the findings:
## Rounds
- Surface everything in round 1.
- From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each earlier 🔴 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.
- A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round, unless a fix changes behaviour: that takes one.
- 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 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal 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 an answer to a ❓ lands. Never a silent drop, and never a decline argued from convenience or the size of the fix.
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.
+24 -9
View File
@@ -6,18 +6,33 @@
The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`.
The places the panel on `rebuild` at 7f9de5c named (`docs/decisions.md`), capping dimension first:
- **Make `mark_trusted` return the updated `~/.claude.json`, so `trust` writes what it was handed and `formats.py` mutates nothing.** Three seats: `trust_records` `setdefault`s into the config and `trust` writes `data` changed through an alias.
- **Make `decode_state` check the fields' types without relying on the annotations being runtime types.** Two seats: `from __future__ import annotations` in `main.py` would fail every reload.
- **State once, in `outcome.py`, that a `Failure` is retried and a `Stop` exits.** Three seats inferred it from `run_loop`.
- **Define a round once, in larv-review's "Round cap", and link it from `review-findings.md` → "Rounds", the Vocabulary and the auto-reviewer's step.** All four seats held §3, "Rounds" and the Vocabulary open together to settle whether a launch counts.
- **Give `project` one meaning: rename `Paths.projects` and `Session.projects` for Claude Code's transcript directory.** Two seats: it also names the package, the key and `~/.claude.json`'s object.
- **Name `human.py` for the exit-2 stops it holds.** One seat looked there for the prompts, which live in `models.py` and `interrupt.py`.
- **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the last run, and open its PR into main for the human.** ⚠️ Leave that PR ready and unmerged: only the human merges it, after approving the whole rebuild. A dimension under the floor gets its places filed above this item.
- **Carry main's #155 into `grounded()`: match the judge's quote with markdown emphasis and whitespace ignored.** The judge drops a bold line's closing `**` when quoting it; `rebuild` still rejects that, so merging it into main would bring back loops stopping on a correct verdict.
- **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the last run, and open its PR into main for the human.** ⚠️ Leave that PR ready and unmerged: only the human merges it, after approving the whole rebuild. A dimension under the floor gets its places filed above this item. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds.
## 0.2.0
- **Sort `bin/`'s imports on their first binding, per `CLAUDE.md` → "Code style", and keep that rule in one place.** Today they sort by path, so a module move reorders unchanged lines; `CLAUDE.md` and `principles/technical-principles.md` each state the sort key, neither says how case sorts, and "host packages" names no Python group.
- **Reword `CLAUDE.md` → "One spelling per goal" so a copy in code is derived from its owner, and drop the README-caveat sentence and the scope list.** A prose pass found "reject at load" fits only copied config, and the scope list reads as excluding internal code.
- **Name CLI flags and exit codes among larv-review's external contracts, or record that they do not fire the architecture pass.** A prose pass found the product-owner row names the CLI and the architecture row does not.
- **Show the judge's reply when `loop-claude` rejects its verdict.** Its stdout is discarded, so a judge that failed three times running leaves nothing to diagnose.
- **Back up `loop-claude`'s transcript archive to a destination other than this repo's remote.**
- **Make the contributor a standing member of every project's audience, dropped only where `## Audience` says maintainability does not matter.** `CLAUDE.md`'s premises rule states it; larv-review's comprehension floor names the contributor as the reader it serves, so the floor gates every chunk while the contributor stands and a project that drops them skips it.
- **Give `docs/decisions.md`'s comprehension-floor and vocabulary entries a premise that has not already expired, with the floor's rule first and its runs' scores as a table, and give the rebuild entry's warning placement its own heading and index line.** A prose pass found both "Valid until the next scoring run" outlived by three runs.
- **Move larv-review's reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`.** A prose pass found rejected alternatives at the rule.
- **Cut `comprehension-panel`'s run history and the restated description, `systems-architect.md`'s "one home" line, and split its Reasonability Review steps 4 and 5.** A prose pass found them carrying nothing the instructions need.
- **Keep `outcome.Failure`'s docstring to what a failure is, without naming `retried`.** A value type naming its consumer.
- **Give a 🟡 shown factually wrong the 🔴's way out in `review-findings.md`.** Today it can only be fixed, declined on a goal, or filed.
- **Say in `AGENTS.md` that only the rebuild's last chunk opens `rebuild`'s PR into main.** Today it reads as every chunk doing so.
- **Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop".** Its fixes land "in this chunk", cited sections and the sweep run when the architecture pass ran included. The 2026-09-30 bench's costliest rebuild runs sprawled outside the chunk: deleted README facts, 13 mypy rounds where main took 6–7 for the same fixes. On 35b, rebuild's one clear win took 6–11 agents to main's 8–16. `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`
- **Give principles-auditor and prose-reviewer a way to list the project's files.** Their `tools: Read, Grep, Glob` left only Read in the 2026-09-30 audit run, so each read what imports and `.gitignore` named and said which files it could not reach.
- **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:80` cuts the session, which 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 (goal 4).
- **Name `jq` and GNU `date` under README → Install, or drop them from `statusline.sh`.** Without `jq` the status line aborts; under BSD `date` the reset times vanish, so CHANGELOG's "runs on any machine unedited" is false.
- **Inject `loop-claude`'s side effects: `time.sleep`, `subprocess`, `input()`, `isatty` and `os.execv`, and split `project_model` and `interrupt` into decisions and effects.** Functional core, imperative shell; the loop's flow has no tests because nothing reaches it without the effects.
- **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.
- **Give a project's loop state named states and one transition function.** Fresh, resuming, awaiting the human and finished come today from whether a transcript exists, two verdict booleans and an open `while True` in `steps.py`.
- **Make a `Verdict` with both `interrupt` and `finished`, or a question without an interrupt, unrepresentable.** `steps.py:49` ignores `finished` when `interrupt` is set.
- **Return a `Stop` when `git` or `os.execv` fails.** `checkout.py:7,15` and `reload.py:52` end in a traceback.
- **Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean.** A stray log of `loop-claude` output in `bin/` would be committed with transcript text in it.
- **Archive the transcript as each cycle ends, so a failed exit or Ctrl-C loses nothing.** Today only an interrupt or a finish archives, against goal 2.
- **Key a project on its checkout's full path — its session, archive folder and models entry — and refuse to start while another session on that id is active.** `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share a session, an archive folder and a models entry, and one loop can resume or delete the other's session.
- **Move what `loop-claude` writes out of `~/.claude.json`, and bring each case that must stay to the human.** Claude Code owns and writes that file, and `trust`'s read-modify-write loses a write landing in its window.