`~/.claude` is a checkout of this repo, so an `AGENTS.md` here would load into every other project's sessions. Where a rule names a project's `AGENTS.md`, read it here as:
- the project principles, the title of each decision no project principle covers, and the working rules: the head of `docs/decisions.md`, before `# Decisions`;
- the scoring-run values: `skills/comprehension-panel/seat-prompts.md` → "claude-config's values".
-The checkout holds `CLAUDE.md`, `AGENTS.md`, `settings.json`, `statusline.sh`, agents, skills and principles; credentials, transcripts and memory files never sync.
-`loop-claude <task>` runs a project's next chunk cycle after cycle, interrupting only for a decision that is yours or a release ready to cut.
-`loop-claude` exits 1 when the worker or the judge fails three times running, saying why: the worker's exit code, the signal that killed it, or an exit 0 without a result event; a verdict missing a field or quoting nothing in the transcript.
-`loop-claude` exits 2 when an interrupt gets no answer, saying why: stdin or stdout is not a terminal, or nothing was typed. Rerunning resumes the session.
-`loop-claude` archives each session's transcript under `~/.claude/loop-claude-transcripts/`, one folder per project; `LOOP_CLAUDE_TRANSCRIPTS` overrides the root.
-`loop-claude` runs at the checkout root wherever inside the checkout it is started.
-`loop-claude` says why when it cannot read `~/.claude.json` before an interrupt, and the interrupt then lands in Claude Code's trust dialog.
-`loop-claude` takes an edit to itself at the next cycle boundary once the edited file answers `--help`, and exits 1 when the edited file cannot read the running loop's state.
-`loop-claude --help` names the Claude Code version its transcript, session and trust handling were observed on; check it first when an upgrade breaks a cycle.
-`loop-claude` runs the model each project's settings pick; `LOOP_CLAUDE_WORKER_MODEL` and `LOOP_CLAUDE_JUDGE_MODEL` override it.
-`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.
-`mutate-changes` mutates a Python script from its own folder where a test beside it imports it by its file name, as in `import run_harness`, so mutmut finds the tests' calls to it. A crash inside mutmut now becomes one report line that names mutmut's error, not a traceback, and the other folders still report.
-do-epic starts an issue in Jira as its chunk starts: it assigns the issue to the account it works as, unless someone else holds it, and the new settings `jira-start-transition` and `jira-sprint-board` in its `config.toml` move the issue and add it to a board's active sprint.
-Load no MCP server in the bench's headless `claude -p` judge and in the reviewer-merge trials' new-findings call either, so text an outsider wrote cannot reach one. A new check fails any Python file that passes `--tools` more often than `--strict-mcp-config`.
-Load no MCP server in the six headless `claude -p` calls that deny the model tools, so text an outsider wrote cannot reach one.
-`do-epic` starts an epic's runnable issues in order of score alone, not in Jira's backlog order. It scores each open issue that holds no scores, the ones people filed included, and comments on the issue why.
-do-epic and `todo-item add` file issues as the Jira issue types the settings `jira-finding-type` and `jira-review-type` name, Task by default, and refuse before filing where the Jira project lacks the type, naming the types it has.
-do-epic names the team's own label for each repo, from the `[label-repos]` table, when it tells a chunk's worker how to file a finding or a release review, and keeps `repo:<name>` for a repo the table doesn't name.
-do-epic records a repo pick, and the summary of each sub-task it files, in the team's own spelling: a label from the `[label-repos]` table of its config, and a `sub-task-summary` template with `{label}` and `{Summary}`.
-Add `do-epic <EPIC-KEY> --dry-run`, which prints every Jira write planning would make and each chunk that would start, and makes none of them.
-The stability reviewer checks each parser that splits text on a separator or strips a suffix against a value that holds the separator, and reports a row the parse misplaces or drops.
## 0.14.0
-`loop-claude`'s judge stops, naming how much to cut the records by, rather than judge a prompt that leaves it less than the transcript's last 50,000 characters. A file the project's config names for two records is read once.
- Under `merge = "human"`, `loop-claude` and `chunk-preflight` pass over an item whose ready pull request awaits a person's merge, and `loop-claude` stops, naming those pull requests, once every item left awaits one.
- do-epic reads two new settings from a project's config: `jira-unblocking-statuses` names the statuses at which an issue unblocks the issues it blocks, and `jira-automation-moves-issues` leaves the move out of "In Progress" to the team's own automation.
- The prose standard asks that a sentence about several named things holds for each of them.
-`do-epic` resumes a chunk parked on `your merge` when its pull request no longer merges into its base, so the worker runs `chunk-pr merge` again to level the branch; a finished chunk in that state stays open until its pull request merges.
-`larv-review prepare-scoring` takes the scoring run's project values from the checkout's `skills/comprehension-panel/seat-prompts.md` where the working-rules file holds no "Scoring run" section, not only where that file is missing.
## 0.13.0
- Fix loop-claude stopping after a finished chunk: its judge may now quote the worker's task as evidence, so the loop starts the next chunks instead of exiting.
- Add the project setting `merge = "human"`, for a team that merges its own pull requests: `chunk-pr merge` then marks the pull request ready and leaves the merge to a person, and a do-epic chunk parks, shown as `awaits your merge`, until the pull request is merged.
- do-epic reads a team's own repo labels: a `[label-repos]` table in `~/.claude-projects/do-epic/config.toml` maps each such label to its repo, such as `twu-4 = "tenant-web-ui-4"`, and do-epic reads a mapped label as it reads `repo:<name>`. An issue a person filed a sub-task under is no longer split by repo: its sub-tasks run instead, each under a label of its own, and the team closes the issue.
- do-epic --file takes --blocked-by <KEY> and --parent <KEY>, so a chunk files the next pull request of a change as an issue that waits for the one before it; a chunk's first prompt says when to use them.
## 0.12.0
- loop-claude asks a headless claude whether a worker that went quiet before its result is stuck, and prints the verdict and appends it to stuck-workers.md, without killing anything.
- loop-claude stops the background shells that hold a worker after its final result, once they have been quiet for a few minutes, and records each stop
- Add `do-epic-e2e`, a command that runs `do-epic` end to end against a sandbox epic on a real Jira site and deletes the epic afterwards.
-`do-epic <EPIC-KEY>` plans the epic before it starts chunks: it files a sub-task per repo under an open issue that changes several repos, labels each other unlabelled issue with where it is worked, asking on the terminal where the repo rule leaves that unclear, and puts the scored issues it filed in order of score.
- loop-claude compacts a waiting worker's session 10 minutes before its hour-long prompt cache expires, where no answer to an interrupt has come and the context holds at least 60k tokens, so the resume doesn't write the whole context again.
- do-epic gives a `do-epic-human` issue that blocks another its own window: it DMs you once through the notifier of one of the epic's repos, takes no running slot, and polls until you close the issue in Jira, when the issues it held up may start.
- do-epic tells an epic chunk's worker how its repo ships the change: a bullet under the repo's changelog where the repo publishes something, none where its plan is in Jira, and no `--finish` for `chunk-pr merge`.
-`do-epic <EPIC-KEY> --status` says which chunk asks you a question, and since when each parked chunk has awaited its gate.
- do-epic moves a chunk's issue to done in Jira when the chunk finishes, and the split item it belongs to once its last sub-task is done, so no finished chunk starts again and the chunks it blocks start. It moves them by the transition `jira-finish-transition` and `jira-finish-status` name, so set both; without them a finishing chunk stops with that reason.
- Describe do-epic in the README: its entry under Tools, and its machine settings and `repo-rule.md` under Set up a project.
- do-epic finishes an epic: once none of its issues is open, a finishing chunk files a release review of each repo the epic changed, as an issue labelled `do-epic-release-review`, and asks you to confirm each goal. `do-epic <EPIC-KEY> --close-epic` then posts the summary piped in as a comment on the epic and closes it in Jira, by the transition `jira-finish-transition` names, to the status `jira-finish-status` names.
- do-epic parks a chunk whose pull request waits on its checks, an approval or a new review: the chunk frees its place for the next one, its tmux window says what it awaits, and its worker goes on when the gate opens or a reviewer comments, even after a reboot. `do-epic <EPIC-KEY> --status` prints what each open issue does.
- A chunk that `do-epic` runs files a finding about an epic goal as an issue of the epic, with `do-epic <EPIC-KEY> --file`, and records a decision in the epic's description, with `--record-decision`; its judge reads the epic's Scoring and Decisions before the repo's records.
- Added `do-epic <EPIC-KEY>`: it runs the chunks of one Jira epic, each in its own window of the tmux session `epic-<EPIC-KEY>`. As many run at once as the line `**Max parallel chunks:** 2` in the epic's description allows, one without it; a repo takes as many as its `parallel-chunks`, and none while loop-claude runs chunks in it. loop-claude in turn starts no chunk in a checkout where do-epic runs one.
- Refuse in rule-hook a Bash or Monitor command that waits forever: a sleeping loop with no time or count cap, and a `pgrep -f` or `pkill -f` whose pattern its own command line matches.
- A project's config may list its team's convention files in `coding-conventions`, which larv-review's reviewer agents read beside the principles and the standards, the team's rule winning where they conflict. larv-review opens the pull request after its own review where a push to the branch starts CI, and files an item to add a mutation tool where `mutate-changes` covers none of a language. The technical principles gain rules for tests on a shared environment, "Never mock a service your own team runs" and "Don't loosen a type when refactoring"; stability-reviewer checks a change that stores a value differently; and every finding of an outside reviewer now changes the setup, a deterministic tool first.
- do-epic's epic backends rank a child issue just before another, in Jira and in memory, and do-epic can re-rank Jira's backlog to an epic's ranking: it moves only the issues the loop filed, so each issue a person filed keeps its place, and it stops at the first rank Jira refuses and names it. Nothing calls it yet.
- Comprehension seats run as the `comprehension-seat` agent under `agents/`, which starts without `CLAUDE.md` and the skill and agent listings, and `larv-review prepare-scoring` no longer takes `--preloaded`; after updating, launch each seat with `subagent_type: comprehension-seat`.
- do-epic splits an epic item that changes several repos into one Jira sub-task per repo, each labelled `repo:<name>`, with a headless claude call predicting the repos from the code; the item is marked `split-by-repo` and counts as done once every sub-task is, and an issue a person filed gets a comment for the team in the epic's language. The epic backends gain `comment`, in the Jira backend and the in-memory one.
- do-epic's epic backends read each issue's scores, its blockers and whether the loop filed it, in the Jira backend and the in-memory one; the Jira backend marks each issue it files as the loop's. Nothing calls it yet.
- The technical principles now forbid a test that decides at run time whether to check anything, by a conditional skip, early return or catch around its assertions, and stability-reviewer flags one.
- do-epic's scorer orders an epic's items by score, then by Blocked by: an item's Moves names a goal as `epic 1.1`, `code health` or `repo 2`, and the epic's achieve goals outweigh the achieve goals of every repo. Nothing calls it yet.
-`todo-item add` and `todo-item edit --detail` refuse a detail whose `Touches:` list touch-predictions cannot read, and `rank_todo.py --check` fails on each item holding one, so rule-hook refuses a commit of such a plan: after updating, run `~/.claude/bin/rank_todo.py --check` in each project and fix each list it names.
- loop-claude hands each worker's claude a Bash output ceiling of 6,000 characters that saves a longer result to a file, rule-hook refuses a Read of a session transcript under ~/.claude/projects, and review-replay takes --bash-ceiling and --read-limit to test such a limit against archived review rounds.
- do-epic picks each epic item's repo, or that it is Claude's work or a human task, by repo-rule.md and a headless claude call, records the pick as a label on the issue and reads it back without a new call; where the rule leaves it unclear it returns a question for the human. The epic backends gain a label write.
- judge-replay <model> --offline replays every archived verdict through a "?" rule, a decision table and a classifier trained on the archive, with no judge call, and counts the interrupts each misses.
- do-epic finds an epic repo's checkout and project config by the repo's name, and clones a missing checkout from the host and owner of the epic's other repos, asking the human where they differ or the clone fails.
- do-epic reads its machine-wide settings from ~/.claude-projects/do-epic/config.toml and its repo rule from repo-rule.md beside it, and refuses to start while either is missing or misspelt.
-`project-record save` now writes a goals file kept as a Jira epic's description, except a change to `## Goals` or `## Audience`, which stays an edit in Jira.
- Add do-epic's epic backend: one interface that reads a Jira epic's child issues and their sub-tasks, with labels, assignee, status and parent, and files new ones, met by a Jira backend and an in-memory fake that pass the same contract tests.
- Fix for an outside reviewer's comment on a PR now ends with a change to the setup that would have caught it, in claude-config first, then the principles and standards, then the project.
- larv-review reruns the pass that raised a 🟡 when the fix removes or loosens an assertion, changes an expected value, or skips, deletes or guards a test. Other 🟡 fixes still rerun no pass.
- Add `markdown-section <file> <fragment>`, which prints the section of a markdown file under the heading the fragment picks, to the next heading of its level or a higher one. It fails, listing the headings, where several hold the fragment.
- loop-claude and subagent-rung run an L 3 task one rung above the project's rung and an L 4 task two above it: on an Opus 5.5 project, Fable 5.2 at low and at medium.
- Add `larv-review round-title <pass>`, which prints a review round commit's title prefix with the 🔴, 🟡 and misread counts taken from the round's report. rule-hook refuses a round commit whose counts differ from that report, where the report exists and can be counted; a report must head each finding `### 🔴` or `### 🟡`, optionally followed by ` [misread]`.
- Add `workflow-bench/handoff_bench.py`, a bench of how a worker's step to a stronger model hands over the chunk, on six archived L 3 chunks. Sonnet 5.5 left five unfinished at its budget. On those, Opus 5.5 resuming Sonnet 5.5's session passed two and was partial on three, for a mean $0.68; a fresh session with a brief passed one and was partial on four, for $0.78. So a stepped worker still resumes its session.
- todo-item edit --blocked-by sets the "is blocked by" links of a Jira issue the loop filed.
- A `Touches:` list in the description of a Jira issue is read as one in `todo.md` is, a path or name that holds a backtick included: the Jira description spells it in backticks with no padding spaces, and the prediction reader takes that spelling too.
-`todo-item edit --detail` and `project-record save` leave a Jira description or a Confluence page exactly as it is, with its block ids and spacing paragraphs, where the text saved is the text a read showed. An unedited save over a page a teammate saved since still refuses.
- Add `compress-archives`, which gzips each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them. The tools that read those folders read a gzipped file by its plain name. A new crontab line in the README's Install section runs it daily.
- review-replay and judge-replay keep each run, with its prompt, claude's exit code and stream, and the report they print, in a `replays/<tool>-<arguments>-<UTC stamp>/` folder of loop-claude's archive, so a replay that decided a rung can be checked and re-priced later; claude's json replies are now stream-json, whose last line is the reply.
- loop-claude's archive keeps each judge run's prompt and json reply in a judge/ folder beside its chunk's transcripts, and names the run on a `Judge run:` line of the outcome it produced; judge-replay replays a verdict on its archived prompt where the archive holds one.
- A plan kept as a Jira epic takes no changelog bullet: `todo-item finish` there needs neither `--changelog` nor `--no-changelog`, and refuses `--changelog`, since the issues' history is the changelog.
## 0.11.0
-`adf_codec.convert` can now convert ADF to markdown and back without losing a block's `localId` or the empty paragraphs Jira uses for spacing, so a Jira or Confluence document read and saved back unedited comes back identical: `markdown_to_adf_lossless`, `adf_to_markdown_lossless` and `adfs_to_markdown_lossless`. No tool calls them yet.
- A config whose `plan` names a Jira epic must now set `jira-score-formula` and `jira-score-bar`, and fails to load without them. `todo-item add` scores the item by them, refuses one under the bar unless it is exempt, and ranks the new issue among the issues the loop filed: questions first, then security findings, then by score. A person's issues keep their rank.
-`todo-item edit` and `move` work on a plan kept in a Jira epic. They change only an issue the loop filed, and never a link. Of an issue a person filed, `edit` sets only the scores, and posts the new `--comment` on the issue to tell the team why; a plan in a file takes the flag and keeps no comment.
- A release someone else cut while it still held plan items no longer stops the loop: those items count as the next release's, `chunk-preflight` tells the worker to move them there, and `loop-claude` routes on them. Where the plan names no later release and `todo.md` named none since the cut, the loop still asks which release they belong to.
-`project-record open` now writes the copy of a record kept outside a file under a folder of the worktree that ran it, `~/.local/state/project-record/<key>/<worktree>/`, so two chunks of one project no longer overwrite each other's unsaved edit. It also removes the folders of worktrees git no longer lists.
-`chunk-pr merge` merges the chunks of one project on a machine one at a time, and `--finish <ID>` finishes each plan item in the chunk's turn, so `todo.md` and `CHANGELOG.md` no longer conflict between open chunks. A pull request that waits for an approval leaves the queue while it waits, and merge stops where a reviewer's comment waits for an answer.
-`loop-claude` runs each chunk in its own window of one tmux session per project, `loop-<key>`, and needs tmux 3.2 or later. Up to the config's new optional `parallel-chunks` chunks run at once, 1 by default; a chunk starts beside the others only where its item's `Touches:` prediction overlaps none of theirs. `loop-claude <task>` starts the windows and attaches to the session, and as a chunk finishes, its loop starts the next. A window whose chunk waits for you ends its name in ` ?` and rings the bell, and the question's DM names the window. A stopped chunk keeps its window and its items until you run `loop-claude <task>` again. A chunk's claude session is named after its window, as `A <key> loop-claude item-372`. A commit in the config's folder now takes only the file it changed, as `git commit -m <title> -- <file>`. To upgrade, finish or stop every running loop-claude before `deploy-release` moves `~/.claude` to this release: a loop that reloads into it starts its project's windows afresh, and leaves its chunk's open claude session in the session picker.
-`todo-item finish` finishes an item of a plan kept in a Jira epic: it moves the item's issue by the workflow transition, and to the status, that the config's new optional settings `jira-finish-transition` and `jira-finish-status` name, both as Jira shows them. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither.
- Reviewers and loop-claude's judge read the review standards from the folder a project's config sets as `standards`, in place of `~/.claude/skills/larv-review/standards/`. The setting is required. To upgrade, add `standards = "~/.claude/skills/larv-review/standards"` to every config under `~/.claude-projects/` right after `deploy-release` moves `~/.claude` to this release, and not before.
- A project's config may keep each of its five records on a Confluence Cloud page: set, for example, `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, with the credentials in the config's `env-file`. `decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic. The loop reads and writes the page as markdown, so a save replaces a mention or a macro on it with plain text. It never overwrites a teammate's edit: where someone saved the page since the loop read it, `project-record save` refuses and the loop asks you.
-`todo-item add` files an item into a plan kept in a Jira epic: a Task under the epic, under the project's Fix Version for the release, labelled `security` for a security finding and linked to each item that blocks it. Editing an issue still happens in Jira.
- An item of the next release may predict the files and parts it will touch, under a `Touches:` line in its detail. `chunk-preflight` then names the items that may start chunks at once, and the new `touch-predictions record` keeps each prediction beside what the merged chunk touched, in the record a project's config places with `touch-predictions`.
- CLAUDE.md, the todo-items rule, and loop-claude's worker and judge prompts and `--help` define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan.
- Reviewers without a shell read the plan from a listing that larv-review writes into the review folder, whichever store holds it.
- A project's config may set `tooling-on-host = true`, so the loop runs a legacy project's language runtime, package manager, tests and task runner directly on the host.
- A project's config may set `readability-floor` to a number from 1 to 10: the comprehension score under which code health is very important. It is 7.0 where left out.
- A project whose plan is a Jira epic can keep its goals and audience in an epic's description too: set `goals-and-audience = "jira:https://<site>/browse/<KEY>"`. The loop only reads it, and `project-record open goals-and-audience` prints a file holding its text.
- A project with a Jira plan can name each chunk's branch, worktree, commits and pull request by the issue key, as in `ABC-123` and `ABC-123 - …`. The README shows the three templates to set.
- A read of a plan in a Jira epic converts every issue description in one `adf_codec` container run, however many issues the epic holds. The codec builds its image inside one of the machine's heavy slots that `run-heavy` shares, so sessions reading at once build it once.
- A project config may name its plan as `jira:https://<site>/browse/<KEY>`: the plan is then read from the open child issues of that Jira Cloud epic, in backlog order, with the credentials in the config's `env-file`. Such a plan is only read so far: file, edit and finish its issues in Jira.
- A new `adf_codec` package converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back with `@larvit/adf-codec` 0.3.1. It runs in a pinned Node container with a memory limit and no network, and returns adf-codec's error codes as a `Failure`. No tool calls it yet.
- The new `todo-item list [--release <version>]` prints the plan's items in the plan's order, `todo-item edit <ID>` sets an item's cells or detail, and `todo-item move <ID> --release <version>` moves it to another release; each change ranks the plan. Agents now read and change the plan's items only with `todo-item`, and the tools read the plan as it stands through one store, `bin/plan_store`, so a later backend can keep a plan outside `todo.md`. `todo-item list --release` with a bad version exits 2, and `finish <ID> --no-changelog` also drops an item no chunk built.
- A project's config may name the language its prose is written in (`language`) and templates for its commit titles, pull request titles and branch names (`commit-title`, `pull-request-title`, `branch`), in which `{id}` stands for the plan item's ID and `{summary}` for the one-line summary. The tools and the prose reviewer follow them. On a branch that fits the `branch` template, rule-hook's new `commit-title` rule refuses a commit title that doesn't fit, and `chunk-pr` such a pull request title. While a project's config holds a fault, rule-hook refuses every commit there.
-`chunk-pr merge` waits for a human's approval of the pull request where the project's config sets `wait-for-approval = true`: it merges once GitHub reports the pull request approved, and gives up after 90 minutes. It reads approvals on GitHub only. Set it for a client whose pull requests need another person's approval.
- The technical principles ask for code in files and folders before `// --- name ---` banner comments. They also ask for an entry point a newcomer finds at once: the root holds it, the README and the files a tool reads only from there.
- In a client project, the loop reads the team's own `CLAUDE.md` and `AGENTS.md` and proposes each change that aligns them with this setup in a pull request of its own. Where the team declines or doesn't answer, the loop follows the team's rule unless it breaks a project goal, and records the conflict as a decision in the `decisions` record.
- The new `project-record open <record>` prints the file in which an agent reads and edits one of a project's five records (`decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`), and `project-record save <record>` stores the edit. Every tool now reads and writes a record the same one way, so that a later release can keep a record outside files. No config needs a change.
-`loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link.
- rule-hook's `run-heavy` rule also refuses a heavy command run through `uv run`, `poetry run`, `sudo` or `doas` outside `run-heavy`, such as `uv run mutmut run` or `sudo docker build`. Run it as `~/.claude/bin/run-heavy uv run mutmut run`.
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
- A project's config names the service for loop-claude's DMs: `notifier = "mattermost"` or `"slack"`, with the bot's token and the recipient in the `env-file`. To upgrade, move the Mattermost keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, name it as `env-file` and add `notifier = "mattermost"`. A project with no `notifier` gets no DM, and `~/.claude/.env` is no longer read. A failure names each missing key and holds no token.
-`mattermost-dm` is now `notify`, which sends through the project's `notifier`; `notify --help` names the keys.
## 0.10.1
- The routing ladder is now a file, `bin/model_routing/routing-ladder.json`, and a project may run on a ladder of its own: a `routing-ladder.json` in its config's folder, `~/.claude-projects/<key>/`, replaces the shipped ladder whole for that project, and loop-claude says so as each cycle starts. loop-claude, `subagent-rung` and rule-hook read the project's ladder; the routing figures, `judge-replay` and `review-replay` read the shipped one. `subagent-rung` now reads the config of the checkout it runs in, and exits 1 where that config or the ladder holds a fault; loop-claude stops on a faulty ladder as it does on a faulty config. `loop-claude --help` shows the file's shape, and README → Install → "Set up a project" says when to write one.
## 0.10.0
- The loop commits each change it makes to a file in the config's folder, such as a plan kept there, in that folder's git repo, titled as it titles its commits in the checkout. rule-hook ranks the plan on such a commit; before, it refused the commit.
- Every tool, prompt, rule and skill reads and writes the plan, `AGENTS.md`, the records and the changelog at the paths the project's config names. A plan outside the checkout is read as it stands; the tools that need a file's commits say what they leave undone for it, and the loop goes on.
- loop-claude, `rank_todo.py`, `todo-item` and rule-hook's `todo.md` checks now fail in a checkout no config names: write a config for each project, with `goals-and-audience = "checkout:README.md"` where its goals stay in its README. They read the goals and audience from the file that setting names, in place of `README.md`. `larv-review reviewer-header` names it on a `Goals and audience:` line, and the reviewers read it from there. A client's project can keep the file, named `goals.md`, in its config's folder, and void code health there as a README can.
- Reviewers read the technical principles from the folder a project's config sets as `principles`, in place of `~/.claude/principles/`. `larv-review reviewer-header` names the folder on a `Technical principles:` line and fails where no config sets it, or the folder is missing or empty. Write a config for each project before its next review; a project that keeps today's principles sets `principles = "~/.claude/principles"`.
- A project can now have a config, `~/.claude-projects/<key>/config.toml`, that names its checkout and the path of every file the loop keeps for it. `project-config` prints those paths, and fails naming each setting a config leaves out. README → Install → "Set up a project" shows how to write one. Every project needs one, as the first bullet says.
- larv-review takes an item as a floor item only where its tagline opens with `Reach the comprehension floor:`. A tagline that quotes the floor elsewhere, such as in a decision title, no longer makes its chunk due a scoring run. Reword each open floor item's tagline in every project's `todo.md` to open with the phrase.
## 0.9.0
- larv-review skips stability round 2 where round 1 reported a 🔴 and every 🔴 and 🟡 asked only that a named mutant be killed or a named failing test pass, once the tests and the mutation command run clean on the fixes.
-`review-replay` now qualifies a rung whose share of a pass's archived findings is no more than 10 points below the mean of two replays on the project's rung, over at least 8 rounds, where it misses no 🔴 that both found. It used to demand every finding the project's rung found again, which the project's rung itself failed. It tries the project's model at each lower effort first, then the ladder below. Its run on the prose pass of Opus 5.5 projects qualified no rung: Opus 5.5 at low effort found 49% against a bar of 66%.
- loop-claude records beside each verdict, interrupt and quoted answer the claude-config release and commit that ran it, the tokens the worker, each subagent and the judge spent, by model and kind, with the list prices in force, and any typed answer of yours the judge quotes as reversing a choice the worker took on its own recommendation; `score-outcomes` counts those reversals per finished chunk.
-`larv-review prepare-scoring` makes a scoring run's worktree and writes each seat's prompt; `record-scoring` removes both once it has recorded the run.
-`deploy-release` moves a checkout whose `settings.json` differs from the release only by a `/model` pick or the key order Claude Code writes, and then says to pick the model again.
-`chunk-pr merge` waits for the pull request's checks itself, allowing a minute for them to report, and no longer takes `--gate-passed`. `wait-for <file> [<pattern>]` waits for a line in a background job's log or report.
-`chunk-pr sync` merges origin's default branch into the chunk's branch, unless the branch already holds it, then runs the rank check on `todo.md`.
-`chunk-pr ready <title>` sets the pull request's final title as it marks the pull request ready.
-`bin/run-tests` runs this repo's test suite as README.md → Test says, prints each failing test with its error and pytest's summary line, and saves the whole log to a file whose path it prints.
-`command-patterns [<version>] --calls <file>` saves each Bash call of the release's chunks as a JSON line, with its chunk, pattern, seconds, sizes and text.
-`todo-item show <ID>` prints an item's table row and detail from `todo.md`.
- A reviewer under `agents/` can start without `CLAUDE.md`: `omitClaudeMd: true` in its frontmatter drops the file, a `SubagentStart` hook hands it the "Shared goal", "Prose" and "Vocabulary" sections, and `larv-review reviewer-header` names the project's principles file. `review-replay <pass> <model> --omit-claude-md` replays each round three times unchanged and once without `CLAUDE.md`, and a reviewer passes where it missed no more findings without the file than an unchanged replay missed. Five of the six reviewers pass and start without it: principles-auditor, stability-reviewer, prose-reviewer, product-owner-reviewer and systems-architect.
- Add `workflow-bench/advisor_bench.py`, a bench of the advisor tool on six archived L 1 and L 2 chunks. Sonnet 5.5 alone passed all six, as Opus 5.5 at medium did, for 41% less, and its advisor ran in one of six runs, so workers stay without it.
- loop-claude's judge on an Opus 5.5 project now runs on Opus 5.5 at xhigh in every chunk, never at medium: in replays medium sometimes closed a chunk whose worker had asked a question the README or records answer, where xhigh quoted the answer. The judge never runs on Fable 5.2 either, since each Fable 5.2 rung replayed missed an interrupt. `judge-replay` now also replays each rung above the project's that a review climbs to, and reports what each misses.
## 0.8.0
- The routing ladder now tops out at Fable 5.2, ordered by the Artificial Analysis Intelligence Index read 2026-11-11: Sonnet 5.5 at high, Opus 5.5 at medium, Fable 5.2 at low and medium, Opus 5.5 at xhigh, Fable 5.2 at high and max. On an Opus 5.5 project, L 4 workers, E + I 5 reviews and a worker's first escalation now run on Fable 5.2 at low, where they ran on Opus 5.5 at high; E + I 6 reviews on Fable 5.2 at medium, where they ran on Opus 5.5 at xhigh; E + I 7 on Opus 5.5 at xhigh, where they ran on Opus 5.5 at max; and E + I 8 on Fable 5.2 at high, where they ran on Fable 5.1 at max. On a Sonnet 5.5 project, E + I 6, 7 and 8 reviews now run on Fable 5.2 at low, Fable 5.2 at medium and Opus 5.5 at xhigh, where they ran on Opus 5.5 at high, xhigh and max. The judge climbs with the reviews. A Fable 5.2 project starts on Fable 5.2 at low. Update `~/.claude` while no loop is mid-chunk: a chunk that stepped up to Opus 5.5 at high or max, or Fable 5.1 at max, finds its rung gone and restarts on its item's rung.
- loop-claude now sends you a Mattermost DM from a bot for each question it asks, each release ready to cut, each routing call and each stop but Ctrl-C, where `~/.claude/.env` names the server, the bot's token and your username. `bin/mattermost-dm` sends one by hand; `mattermost-dm --help` names the keys. A DM that fails is one line on loop-claude's terminal, and the loop goes on.
- larv-review's worker now runs the project's tests and static analysis, and checks the docs for each name its change touches, before each stability round, and hands stability-reviewer the commit that passed; the reviewer doesn't run them again on it.
- stability-reviewer, product-owner-reviewer and systems-architect have one-line descriptions, which shrinks the agent listing every session carries.
-`mutate-changes` mutation-tests the lines a branch changes, running cargo-mutants, Infection, mutmut or Stryker by each file's language, and prints each mutant that no test kills. Where a project's README documents no mutation command of its own, larv-review now runs it before each stability round and hands stability-reviewer the mutants that survive.
- loop-claude now asks each worker to name the items its chunk takes on one line, as in `Chunk items: 12 (L 3, E + I 5), 14 (L 2, E + I 4)`, and scores them from `todo.md` on the default branch. That line, not the judge, now sets the items loop-inbox lists, and how far an item beyond the one the chunk was routed on lifts the worker, its reviewers and the judge. The judge still reports escalations and whether a release is ready to cut.
-`~/.claude` holds no `AGENTS.md` any more, so each session in your projects starts about 3,600 tokens smaller, and a session in `~/code/claude-config` loads its `CLAUDE.md` once instead of twice.
- A project's `AGENTS.md` may group decision titles into project principles, and each new decision is checked against them: a principle covers it, it breaks one, or it suggests a new one for you to approve.
- The prose reviewer now holds prose to the negation rule: write `doesn't cost anything`, never `costs nothing`, after any verb or its preposition.
-`rule-hook` now checks files at `git commit`: each file that differs from HEAD or is untracked and not ignored, even one the commit leaves out. It holds each to `action-pin`, `image-pin`, `ignorefile-sorted` and `no-ai-attribution`, so a file a Bash command wrote is checked as an Edit or Write is. A `# rule-override` line in the file or the command overrides a breach.
-`chunk-pr merge` now refuses while a scoring run the plan calls is unrecorded on the branch, and `larv-review needs-scoring-run` calls one after a release is cut with none.
## 0.7.0
- README's test, CI and mutation-test commands now have their own section, README → Test.
-`rule-hook overrides` now lists the chunk's overrides when a file or folder shares the branch's name. It used to exit saying it could not read the reflog.
-`chunk-pr clean` removes a merged chunk's worktree and local branch and fast-forwards the main checkout. It leaves a main checkout with uncommitted files, another branch or commits of its own as it was, and says why.
-`review-replay` now replays each round at the commit with the newest author time at or before the round's time, and takes the clone's base the same way by the time the chunk began. It took the first such commit in log order, so a commit authored early but merged late, such as a dependency bump, could win over the commits the round reviewed.
- The shared goal every project pursues, code health, now asks that code stay easy to read, change safely and debug, tomorrow and after seven years of development.
-`rank_todo.py` now lets an item that adds a test, a gate leg or a probe name the maintain goal it guards, by how much more confident the project becomes that the goal holds, 1 to 10. Each point is worth 0.5.
-`chunk-preflight` now quotes the detail of each item that may join the chunk, so a worker no longer opens `todo.md` to read it.
-`command-patterns [<version>]` prints a table of the shell command patterns a release's chunks ran.
-`deploy-release --cut` reports each step as it finishes, waits for the checks `main`'s protection requires and names them, deletes the merged release branch, and ends on one line saying the release is cut.
- CI runs the test suite on every pull request, and `main` merges nothing until it passes.
-`larv-review reviewer-header <pass> [--rerun]` writes the branch diff and the places into the chunk's review folder and prints the header of a reviewer's prompt: the pass, its next round, the PR, the worktree, the branch, the merge base of HEAD and the default branch, and the paths of the report, the diff and the places.
-`chunk-pr open|ready|merge` opens a chunk's pull request as a draft, marks it ready and merges it, with `gh` or `tea` as the remote needs. It merges only with `--gate-passed`, by the first merge method the repository allows. `larv-review` and `CLAUDE.md` now tell workers to use it.
-`score-outcomes` now gives, where most of the chunks it counts for L hold no 🔴, the share of chunks with a 🔴 at each L in place of L's rank correlation by 🔴 findings.
-`todo-item add` now files an item in `todo.md` with one command. It takes `Next ID` as the item's ID, raises `Next ID`, writes the row and the detail it reads from stdin, and ranks the file.
-`todo-item finish <ID>` now removes a finished item's row and detail from `todo.md`. With `--changelog <bullet>`, it also adds that bullet first under `CHANGELOG.md` → `## Unreleased`. Where a `CHANGELOG.md` exists, it refuses to run without `--changelog <bullet>` or `--no-changelog`, so no bullet is left out by mistake.
- A worker whose review rules its work below standard now fixes it on its own rung where the fix changes only prose, a comment or docstring included. It hands the fix to a higher rung only where code, config or tests change.
-`loop-claude`'s judge now sends a question you answered earlier in the chunk back to the worker, quoting your answer, unless the question ends with the words of your answer that leave it open. You are asked only about what your answer left open.
-`score-outcomes` now shows, beside what each finished item's chunk measured, the size of the files and folders its tagline or detail names in backticks: how many files, and how many lines, as they stood before its chunk.
-`workflow-bench/bench.py` now prints a failed run, such as a failed clone, as a `<run>: FAILED: …` line beside the other runs' results, in place of stopping at the first failure.
- A scoring run under the comprehension floor of 7.0 now leaves a plan item meant to reach it. `larv-review record-scoring` follows its `Floor:` line with a `Next:` line. It says to file one ambitious refactor aimed at the lowest dimension, or to refresh the one `todo.md` already holds. The item's tagline holds `comprehension floor`, so its own chunk runs a scoring run. It goes into the release after the chunk's, so the floor doesn't hold up any release (larv-review §3 → "Floor item"). An item already in `todo.md` whose tagline holds those words counts as the open one: drop or reword it if it isn't such a refactor.
-`loop-claude` now interrupts you less. A worker takes its own recommendation on a choice no rule reserves for you, and records it, and the judge answers an ask that carries a recommendation by quoting the rule that says so. You are still asked about a goal, a release's planned items and its cut, a change to the routing ladder, and whatever another rule asks your approval for; `CLAUDE.md` → "Working loop", "Ask, don't guess" lists them.
- This setup's own plan now ranks items by `Score = 100 * V / (2**S + 32)`, up from 8: F, a chunk's fixed cost, is 32, about one size-5 change, fitted to ten finished chunks' tokens, so small items rank lower against large ones. `docs/decisions.md` holds the fit.
-`loop-claude` now keeps the cycle it last measured the routing figures at, and each routing call it raised, in `routing-state.json` at the archive's root, and reads them back from there in place of `routing-figures.md` and `routing-calls-raised.md`. The two markdown files hold what they held before. From them, loop-claude now reads only a `Reset` line in `routing-calls-raised.md`, which still resets the figures. The first loop to close a cycle after the upgrade measures the figures at once. If the figures still make a call raised since the latest reset, it puts that call to you once more.
-`loop-claude` and the routing figures no longer read a `Worker:` line written as a sentence, as versions before 0.4.0 archived. A rerun routes a chunk whose archive still ends in one afresh, and the figures leave it out of the routed chunks and charge its dollars to a row named by the sentence.
-`score-outcomes` no longer credits a chunk's measurements to an item the chunk removed from `todo.md` without building it. Remove such an item in a commit whose title opens `Drop item 69: <why>`, or `Drop items 69, 70 and 71: <why>`, and `score-outcomes` leaves it out. Items dropped before this release still count as shipped.
- rule-hook's `todo-rank-check` now checks a branch of this setup's repo with that branch's own `bin/rank_todo.py`, so a branch that changes `todo.md`'s shape commits without an override. Any other repo is still checked with `~/.claude`'s.
## 0.6.0
-`deploy-release --cut`, run in `~/code/claude-config`, now cuts a release. Once the next release holds no item in `todo.md` and its release review has landed, it renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request: it opens the pull request, waits for its checks and merges it fast-forward only. Then it tags the merged commit, pushes the tag and moves `~/.claude` to it. Where a step fails it stops with git's or the forge's reason, and a rerun continues. Nobody can push to `main` on the remote any more, so the old manual steps under README → Release no longer work. Cut 0.6.0 itself from the clone, `~/code/claude-config/bin/deploy-release --cut`, since `~/.claude` still holds 0.5.0.
- The routing figures now count what `loop-claude`'s judge costs. `loop-claude` archives each judge run's cost, from claude's reply, in a `Judge cost:` line beside the verdict or rejection, and `routing-figures.md` adds it to its dollars by project, rung and tool, and under the subagent type `judge`. Before, the judge's cost was left out. Chunks archived before this change, and a judge run that failed, add none.
- In a repo with no tag, `chunk-preflight` now counts the newest version under a dated `CHANGELOG.md` heading, such as `## 0.0.1 - 2026-10-03`, as the last cut. A later release in `todo.md` reads as next, the unreleased commits are those after the commit that added that heading, and a `Release review of` commit counts only for a release after it. A heading without a date doesn't count, and a tag always wins. Before, such a repo was sent to review a release it had already cut.
-`rule-hook` no longer hangs, or reads without end, on an Edit, MultiEdit or Write whose `file_path` is a FIFO or a device: it reads only a regular file.
- A `loop-inbox` ask file now stores when the loop asked as an ISO UTC datetime, such as `2026-11-04T09:30:00Z`, in place of seconds since the epoch. Restart any `loop-inbox` running when you deploy: one started before doesn't list the new asks. A `loop-claude` running then reloads itself at its next cycle, and `loop-inbox` doesn't list a question it asks before that; answer such a question on the loop's terminal.
- Each chunk's first worker prompt now holds a reading rule: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context. Where the 20 chunks after it take more review rounds, unfinished verdicts, findings, misread findings, dollars or hours than the 20 before, a later release drops it.
-`rule-hook`'s `round-cap` now refuses a round commit whose title names no larv-review pass, such as `Answer architectur round 1:`. Before, a misspelled pass got a count of its own, so its rounds never reached the cap.
- A routing call from `loop-claude`'s figures now opens claude in the setup's development clone, `~/code/claude-config`, not in `~/.claude`. Recording the answer there no longer leaves `~/.claude` with changes that stop `deploy-release` from moving it.
- Where the default branch's tags cannot be read, `chunk-preflight` now says so, with git's reason, and that it cannot tell which release is next, and `loop-claude` routes the chunk on the project's rung. Before, both read such a branch as one with nothing cut, so `chunk-preflight` could report an empty plan where a release review was due.
- A branch that changes `workflow-bench/run-prompt.md` or `compare-prompt.md` now counts as changing config, as a skill does: its reviewers run on the rung its items pick, not on the project's rung.
-`deploy-release` now stops with git's own error where git cannot refresh the checkout's index. Before, it went on and could refuse with a wrong report of uncommitted changes.
## 0.5.0
- A bare run of `chunk-preflight` now only prints the facts. It no longer adds the worktree `<checkout>-item-<ID>` and the branch `item-<ID>`, or runs `reading-cost`, `larv-review places` and its other checks in that worktree. `chunk-preflight --worktree` does all that, and `loop-claude` now passes it. Before, every run that found an item added the worktree and branch, and you had to remove them after a run made only to read the facts.
## 0.4.1
- A release review now fixes the findings of its architecture and principles passes in the release it reviews. Before, it filed each one in `todo.md`, so the release held the drift the review had found. It files only three kinds of finding, each under the release being reviewed: one whose fix needs a human answer, marked `question`; one whose fix adds a feature; and one whose fix the five rounds cannot finish. Until each is done, the release isn't ready to cut.
- In a repo with no tag yet, `chunk-preflight` now calls a release finished once `todo.md` files no item under it: its release review is due, and no later release's item is taken. Before, it lost sight of such a release.
- In a run `loop-claude` started, `rule-hook` now refuses a `/security-review` or `/claude-security` Skill call that the worker makes in its own context on a rung below the project's. It also refuses one from any subagent whose prompt doesn't open with `You are the security pass for this chunk.`, since that subagent's rung is unchecked. The refusal says to invoke the skill from a subagent on the project's rung, its prompt opening with that sentence. Before, only an Agent call that launched the security pass was held to that rung.
-`loop-claude` and `loop-inbox` no longer write `~/.claude.json`. Each claude they open on a terminal, for `/talk`, a release ready to cut or a routing call, now has `CLAUDE_CODE_SANDBOXED=1` set, so Claude Code skips its trust dialog. Before, they marked the checkout and each worktree trusted in that file, and a write Claude Code made at the same moment could be lost. Claude Code doesn't document the variable: where a version drops it, the trust dialog comes back.
## 0.4.0
-`~/.claude` now holds only a release, and this repo is developed in a clone, `~/code/claude-config`. A new tool, `deploy-release`, moves `~/.claude` to the newest `v*` tag and prints `CHANGELOG.md`'s section for each version it moved past. It refuses while a tracked file there has an uncommitted change the new tag doesn't hold, such as a hook Claude Code wrote into `settings.json`, or where the move would drop commits no release holds; a model picked with `/model` is no such change. To switch a machine over:
1. Stop any `loop-claude` running in `~/.claude`, and finish or move its open chunk.
2. Clone this repo to `~/code/claude-config`, and run `git config filter.settings.clean bin/settings_filter.py` there.
3. Run `~/code/claude-config/bin/deploy-release`. Where `~/.claude` is on a branch, it refuses until a release holds that branch's commits.
4. Run loop-claude for this repo from `~/code/claude-config`. It asks for the project's model, since the project is new to it.
- larv-review's architecture and principles passes now run only in a new release review: the chunk that runs once a release holds no item and changes are unreleased, before the release is ready to cut. Each reads the whole project, may refactor boldly and takes up to five rounds; their fixes take the stability, security, overrides and prose passes, two rounds each. No other chunk runs either pass, so a chunk that changes code no longer waits on the principles audit. Between releases, the product-owner pass now also reviews changes to routes, request and response shapes, events, webhooks, published file formats, CLI flags and exit codes, which the architecture trigger used to cover. The comprehension check's paired ruling moves to the release review too.
-`chunk-preflight` now reports a release review due where it reported a release ready to cut, until a commit titled `Release review of <release>` follows the newest `v*` tag on the default branch. Open the review's branch with that commit.
- rule-hook's `round-cap` and `larv-review round-count` allow the architecture and principles passes five rounds.
- Haiku 5.5 is off the routing ladder, which now runs from Sonnet 5.5 at high to Fable 5.1 at max. A Sonnet 5.5 project's L 1 and L 2 workers now run on Sonnet 5.5 at high, where they ran on Haiku 5.5 at max: such a chunk took more than two hours and 3.1 million output tokens on a README change. A review replay can now lower a pass only to Sonnet 5.5 at high. `subagent-rung`, `review-replay` and `judge-replay` treat Haiku 5.5 as a model off the ladder.
- larv-review runs fewer reviews on changes that hold no code:
- A fix for a 🟡 no longer reruns the pass that found it. Only a 🔴 fix does, with each pass whose re-entry row the fix meets.
- A comment counts as prose in every file, config included, so a comment in a workflow or compose file fires only the prose pass. Markdown an agent follows counts as config: `CLAUDE.md`, `AGENTS.md`, and files under `agents/`, `principles/`, `rules/` or `skills/`.
- A branch that changes only other Markdown, such as `README.md`, `docs/` and `todo.md`, runs the prose pass, and the product-owner pass where an outside reader lands on the change. Its reviewers run on the project's rung, whatever its items' E + I. loop-claude's prompt says so, and rule-hook's `reviewer-rung` allows it.
- A `todo.md` row or detail that a chunk files from a finding, re-scores or moves between releases is no longer reviewed. The chunk that ships the item reads it.
- New tool `loop-inbox` lists the interrupts of every loop-claude on the machine, oldest first, in one terminal. Each entry shows the loop's checkout, how long it has waited and the question's first lines. Pick one to answer the question as on the loop's terminal, except that Enter alone goes back; `/talk` opens claude in loop-inbox's terminal. Of a pasted answer, only the first line is sent, and the rest is dropped. The loop takes the first answer, from its terminal or loop-inbox, so it works as before with no loop-inbox running. A loop that ends drops off the list, even one killed outright. A loop whose claude is already open, such as for a release ready to cut or the routing calls, is listed but answered in that claude. A loop asking for its project's model, as on a project's first run, asks on its own terminal only. Below the questions, loop-inbox lists every running loop, with the ID and tagline of each `todo.md` item its chunk takes. Link it onto `PATH` as README → Install shows.
- Ctrl-C in a claude that `loop-claude` opens on its terminal, for `/talk`, a release ready to cut or the routing calls, now reaches only that claude. Before, it also stopped `loop-claude`, which closed that claude a quarter second later.
-`reading-cost` now lists the files a chunk read in the worktree `chunk-preflight` made, `<checkout>-item-<ID>`. It listed none, since no transcript command names that worktree.
-`larv-review ruling-base` now finds the last measured commit when run in a subfolder of a checkout. Before, it found no change to the comprehension history there and fell back to the merge base.
-`score-outcomes` now counts each finished chunk's later fixes: the later chunks on the default branch that fixed code it shipped, each a defect that review let through. A later chunk counts where a change of it rewrites or removes lines that `git blame` traces to the earlier chunk: its whole change where it ships a `todo.md` item marked `defect` or `security`, or one of its round commits whose title counts both a 🔴 and a finding a reviewer marked `[misread]`. Each finished item shows the count beside its guessed scores, and a new list, after the misread findings, names the chunks that fixed each one, newest first. `routing-figures.md` shows the mean per rung, over the chunks whose later fixes are known, in a new column of the routed-chunks table. To find them, loop-claude now reads each archived project's checkout, and the figures name each project whose default branch it could not read.
-`loop-claude` now opens every message it prints with the machine's local time, as in `2026-10-28 11:46:01`, so you can see when each happened, such as how long a question has waited. A message of several lines, such as a question, carries the time on its first line only. The `retrying at …` time of a usage-limit wait now also shows seconds, and no longer names the zone.
- larv-review now gives each review pass at most two rounds per chunk, where it gave three and then asked for more, and no longer asks: the fixes answering a pass's second round merge once the gate passes. rule-hook's new `round-cap` rule refuses a round commit that would take a pass past round 2, such as `Answer stability round 3: …`, and takes no override. It counts the pass's earlier round commits on the branch, so a third commit titled round 2 is refused too. `larv-review round-count` marks a pass at two rounds as at the cap.
- rule-hook has a new rule, `repeat-read`, and now runs before each Read call too. It blocks a Read, or a Bash `cat`, `head` or `sed -n '<A>,<B>p'` of one file, when every line it asks for is already in the agent's context, and the block names those lines. The rule takes no override.
- A line is in context when an earlier read's result in the agent's own transcript showed it since the last compaction, as the file holds it now. A subagent is judged on its own transcript, not its session's.
- A read goes through when it asks for a line no earlier read showed, or one that changed since. A Bash output that Claude Code cut short shows no lines.
- A Read also goes through until the agent has read the file with Read or written it with Edit, MultiEdit or Write, and again once the file changed after that. Edit, MultiEdit and Write refuse the file until then, and a Bash read does not count.
- Where the context lacks lines the transcript shows, as after Claude Code cleared old tool results, `grep -n '' <file> | sed -n '<A>,<B>p'` reads them.
- Install the latest stable Python, today 3.14, as `python3`: the tools and their tests no longer support 3.11 to 3.13. A full test run now takes about 29 s, where it took about 3.3 minutes. It runs once, on that Python, in four pytest-xdist workers, where it used to rerun the whole suite on 3.11.
-`routing-figures.md` now reports dollars by project, subagent type, rung and tool, in place of tokens. Cache reads are included; the tokens left them out, though they were about a quarter of the cost. The dollars are what each worker transcript's last `cost-state` entry records for each model, split across the messages of the worker and its subagents in proportion to their cost at list prices. The judge's runs are not counted, since the archive doesn't hold them.
- larv-review's principles pass now launches one auditor per round, which checks the README's goals, code health and every principles file that applies, so it reads the project once per round. It used to launch one auditor for the goals with code health and one for each principles file, each reading the whole project. Its report is `principles-round-<n>.md`, like every other pass's.
- A session running larv-review now enters the chunk's worktree with `EnterWorktree` before the first review pass, so `/security-review` and the full scan read the branch's diff. Run from the checkout root, they used to find it empty.
-`loop-claude` now stops with exit 2 when the judge rules one chunk unfinished 6 cycles running, so a worker and a judge that disagree can no longer cycle unattended without end. Rerunning resumes the chunk and gives it 6 more cycles.
- larv-review now launches a round's reviewers in up to three waves, each wave's reviewers in one message, in place of one reviewer at a time: first the architect, then the principles auditor with the security and overrides passes, then the stability, product-owner and prose passes. Each wave now lasts as long as its slowest reviewer, where a round used to last as long as all its reviewers one after another.
- loop-claude's worker, and every subagent it launches, now run with a 200k auto-compact window, handed as `CLAUDE_CODE_AUTO_COMPACT_WINDOW`: Claude Code compacts their context at about 170k tokens, where it used to let it grow to about 967k. loop-claude's judge no longer reads a compaction summary as words you typed. `CLAUDE.md` has a new section, "Compact instructions", saying what a summary keeps.
- On Linux, `run-heavy` now caps the memory of a container its command makes with `docker run` or `docker create`. A container that sets no limit gets a memory limit and a swap limit, both the slot's share: three quarters of the machine's memory, split across the heavy slots. A container that sets one of the two limits keeps it, and gets the other as large. This covers containers a project's own scripts start, which rule-hook can't see. A `docker compose` service, and a docker named by its full path, get no cap. rule-hook's `docker-run-memory` now lets a `docker run` under run-heavy pass.
- rule-hook has a new rule, `docker-run-memory`. It blocks a `docker run` or `docker create` that lacks a memory limit or a swap limit, such as `--memory 4g --memory-swap 4g`, sized to what the work needs. `--memory-swap -1`, unlimited swap, counts as none. `CLAUDE.md` asks for the same limits on a container a script or a compose file starts, which rule-hook can't see. rule-hook's `run-heavy` rule also now reads docker's `--tlscacert`, `--tlscert`, `--tlskey` and buildx's `--builder` as options that take a value, and reads `docker container run` as a run: `docker --tlscacert ca.pem build .` was not blocked outside run-heavy before.
- Reviewers now mark a 🔴 or 🟡 `[misread]` where it arose because the implementer misread code that had already shipped. A round's commit title now counts the marked findings, as in `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, and rule-hook's `round-title-counts` blocks a round title without that count. `score-outcomes` shows the count on each finished item, and lists it after the medians for each chunk whose round titles carry it, newest first. A chunk whose round titles predate this change reads as unknown.
- Sessions running at once no longer starve the machine. A new tool, `run-heavy <command>`, runs a heavy command, such as a full gate, mutation tests, an e2e run or a `docker build`, once it holds one of the machine's heavy slots: one per 4 CPUs, shared by every session. `CLAUDE.md` has every session run its heavy commands under it, and rule-hook blocks a `docker build` or a mutation run outside it. loop-claude now waits to start a worker while less than a quarter of the machine's memory is available.
- larv-review's skill now says a commit answering the external auto-reviewer takes no `Answer <pass> round` title, and that `larv-review round-count` doesn't list the auto-reviewer. A worker who followed the skill used to get a "not a pass" warning.
- loop-claude's first prompt for a chunk that no plan item routed now also names the rung on which the worker launches its reviews for an item it takes in, as the prompt after a step-up or an unfinished verdict already did.
-`loop-claude --help` now describes routing in two short paragraphs for the person running the loop. The rules it used to repeat are now stated once, in the code that enforces them.
- loop-claude now archives the route on each `Worker:` line as a JSON record, such as `{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 12}`, and reads it back field by field. The line used to be a sentence, such as `claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5`, which loop-claude parsed back word for word: rewording the sentence in the code would have made every archived line unreadable, and a rerun would have routed the open chunk afresh. A rerun and the routing figures still read the sentences archived since loop-claude routed on L. A rerun that finds a `Worker:` line it can't read now says so on stderr. The judge's reply now names the levels the worker took in `highest_likelihood_taken_in` and `highest_escape_and_impact_taken_in`, in place of `bundled` and `bundled_escape_and_impact`.
- A chunk now takes every unblocked item of its release that fires the same review passes, whatever its purpose: one PR title no longer has to state what the items achieve together. An item with R above 5 ships alone. `chunk-preflight` says so for such an item, and never lists one as an item that may join another.
- A branch whose name is not UTF-8 now shows no branch in the status line, in place of a name with replacement characters.
- A new technical principle, "About seven things per level", sets soft limits on what a reader takes in at once: the parameters and branches of a function, the methods of a class, the files and folders in a folder, the sections of a document and the components of a system. Aim for four or five of the things that act on each other, such as parameters. Things found by name, such as files named by locale, may run far past seven. Crossing a limit asks you to group the things or record why they stay. The systems-architect reviewer now reads its limits from this principle. It rates a unit that crosses a limit with no recorded reason a 🟡, where it used to be a 🔴, and no longer asks for the limits as merge-gate rules.
- The comprehension panel's base worktree and a build probe's output now go in a folder under the chunk's review folder in `~/.local/state/larv-review/`. Both used to go in a session scratchpad, which loop-claude's headless sessions don't have.
- rule-hook now reads `git > out commit -m x` as one git commit, as the shell runs it. A redirect used to split a command in two, so such a commit escaped `commit-one-line`, `round-title-counts` and `todo-rank-check`.
-`larv-review needs-scoring-run` now calls a scoring run for the release `chunk-preflight` names as next, not for the earliest release in the plan. It also counts a change as unreleased the way `chunk-preflight` does: an entry under `CHANGELOG.md` → `## Unreleased`, or, where there is no such section, a commit after the newest `v*` tag (any commit when there is none). Before, a chunk that moved the next release's last items to a later release without shipping them called a scoring run, while `chunk-preflight` called that release unplanned.
- README → Install now says that every machine taking this checkout must be a sandbox with no direct access to a production environment, since `settings.json` runs Claude Code in auto mode with the dangerous-mode prompt skipped. Before, it asked for a sandbox only for `loop-claude`.
## 0.3.0
- A task scored L 1 now routes its worker, or a delegated subagent such as a search, one rung below the project's rung, as L 2 does; it used to go two rungs below. On an Opus 5.5 project that is Sonnet 5.5 at high, not Haiku 5.5 at max: chunks started on Haiku 5.5 took more review rounds and unfinished verdicts.
- loop-claude's worker now starts with `ScheduleWakeup` disallowed. A worker that scheduled a wakeup kept `claude -p` running after its turn ended, so loop-claude neither ran the judge nor asked you, and the chunk stalled until someone killed the worker.
- Every project's audience now includes the contributor, the person who reads the code to change it. A README doesn't list them; only its `**Void:** code health` line drops them. larv-review's comprehension check now measures how hard the project is for them to read.
-`score-outcomes` now also measures projects that merge by rebase: each run of commits that share one commit time counts as a chunk. Add `docs/score-anchors.md` to those projects too. A chunk that was pushed or fast-forwarded may hold only part of its pull request, so the medians and rank correlations leave it out.
-`settings.json` no longer carries a model: each machine keeps the one you pick with `/model`. Git's clean filter `bin/settings_filter.py` drops `"model"` and sorts the keys, so neither a pick nor Claude Code's key order can reach a commit. Update now starts with `git add settings.json`: without it, Update's `git checkout -f` drops the machine's model. On upgrade, on each machine:
1. Turn the filter on in `~/.claude`: `git config filter.settings.clean bin/settings_filter.py`.
2. Pick a model with `/model`. Until you do, Claude Code runs its default model; this repo set `opus` before.
- larv-review's "Re-entry" is now one table of which passes a fix reruns, and the pass table's triggers say only when a pass first runs. The rule is unchanged; a fix for a 🟢, a ❓ or a prose finding still reruns no pass.
## 0.2.0
- Every project now shares one achieve goal, code health: the code is easy to understand and change safely. `CLAUDE.md` → "Shared goal" states it, with its signal and counter-signal. `rank_todo.py` ranks it first among a project's achieve goals. A project's overall is the overall mean of the newest scoring run in `docs/comprehension-history.md`, averaged with every other run on its commit. While that overall is under 7.0, or no run has measured the project, code health weighs four times as much as it does at 7.0 or above. An item's Moves cell names it as in `code health by 6`. A README voids it with `**Void:** code health, since <reason>.` under `## Goals`, and `rank_todo.py` then refuses an item that names it. `larv-review record-scoring` re-ranks `todo.md` after it appends a run, and exits 1 where `rank_todo.py` would, keeping the run. Expect items that make code easier to read to rank higher in every project. On upgrade:
1. Move every machine to this release before any of them ranks a plan another machine shares: an older `rank_todo.py` scores it without code health and rejects a `code health` cell.
2. Void code health in each project that opts out of the comprehension check, or `rank_todo.py` refuses its plan.
3. Run `rank_todo.py` in each project that keeps code health. It re-scores every item, so until then `rank_todo.py --check` fails, and rule-hook holds the project's next `todo.md` commit.
4. In each project whose README restates code health as a goal of its own, file an item to drop that goal and point the Moves cells citing it at `code health`. Dropping it renumbers the goals after it, so the same item repoints every Moves cell and decision citing them; `rank_todo.py` cannot tell a cell left pointing at the wrong goal.
-`stability-replay <model>` is now `review-replay <pass> <model>`, and replays any pass an agent under `agents/` reviews, such as `review-replay prose claude-opus-5-5`. It now tries every rung below the project's, down to the ladder's lowest. Its runs on the prose and stability passes of Opus 5.5 projects found no rung below the project's that finds every 🔴 and 🟡 the project's rung finds: Sonnet 5.5 at high missed 12 of 27 prose findings and 11 of 20 stability findings. So every pass stays where it runs. A rung a future run finds lowers only its pass, once `REPLAYED` in `bin/model_routing/ladder.py` names it, and only where the chunk's E + I steps no review up and the worker runs no higher than the project's rung; there it may run below the worker's rung.
-`chunk-preflight` names the release it finds finished and ready to cut, or to be planned first, wherever todo.md has named that release since the last cut.
- Each reviewer under `agents/` now writes its full report to a file that larv-review names in the reviewer's prompt, in a folder per chunk under `~/.local/state/larv-review/`. It returns only its verdict and one line per finding, so a review takes less of the worker's context. The worker reads a finding's full entry before it fixes or answers a 🔴 or 🟡. Each reviewer now holds Write. `rule-hook` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`; no override waives this rule. Each chunk's folder stays after the merge, so `review-replay` can replay a round that reads an earlier round's report. It replays on a copy of the folder.
-`loop-claude` asks an interrupt's question on its own terminal and resumes the worker headless with your one-line answer, so the loop no longer waits for you to leave a claude session. Type `/talk` instead to open the worker's session in claude, as every interrupt did before, to read the diff or discuss first. A release ready to cut opens that session at once. Pressing Enter on an empty answer stops the loop, exit 2. Keys typed before the question shows are dropped, and a pasted answer keeps only its first line; type `/talk` for a longer one. The judge counts that answer as yours, like one typed in claude: the chunk stays open until the answer is recorded, where a later chunk could need it.
-`todo.md` may mark a renamed release in a `## Renamed` section, one line per rename, such as `- 0.2.1 renamed to 0.3.0`. `chunk-preflight` and `loop-claude` then skip that release when they pick the next one, and larv-review's scoring-run trigger calls no run for it. Without the mark, a release named since the last tag whose items all moved to other releases reads as finished: `chunk-preflight` says it is ready to cut and the loop stops for you, and the trigger calls a scoring run. `rank_todo.py` fails on a `## Renamed` line of another shape, and on an item filed under a release it marks. Before you move a machine to this release, add the line to the `todo.md` of every project that renamed a release since its last tag, or its loop stops for that release's cut.
- When a worker's run ends with a question and a request for a higher rung, `loop-claude` now steps the worker one rung up as the judge interrupts, or as it answers the question with a quote from `README.md` or another file it may quote. The judge must quote a passage showing that the escalation trigger the run cites fired. Before, the step was lost for an answered question, and the worker carried on from the answer on its old rung. The step has the same limits as the step on an unfinished verdict. An escalation trigger that fired before the worker's last step-up doesn't step it again, so one trigger buys one step. A trigger that fires after the step steps the worker again, in the same cycle or a later one. A chunk left open across the upgrade to this release starts with no step-up on record, so a trigger that already stepped its worker may step it once more. The archive's interrupt and quoted-answer outcomes now name the worker's rung.
- A scoring run due because a release's items ran out costs four more seats: it is done twice on one head. `larv-review agreement` compares how often Mid A and the inherited architect vote alike in paired rulings with how often their overall scores move the same way between the two runs. After 10 such pairs it gives a verdict, and on `Assumption fails:` larv-review asks you whether to keep the paired ruling.
-`workflow-bench/bench.py` gives each run a fixed list of allowed tools. Before, it skipped every permission check. A run may launch agents, run `/security-review`, edit its clone (not the clone's `.git/` or `.claude/`) and its report, and read its clone and the copy of `~/.claude` it benches. For git it gets one command, `workflow-bench/review_git.py`, and no bare `git`. The wrapper runs `log`, `diff`, `show`, `status`, `ls-files`, `add` and `commit -m` on the run's clone, whatever the working directory. It allows only the options it lists for each, and refuses an argument that names a path outside the clone. git runs with no global or system config, hook, pager or editor. A run loads no settings or MCP servers from `~/.claude` or from the case's clone, so their hooks and extra directories do not apply to it. Every other call is denied. Expect a benched review that needs another git command, or to run a project's code or tests, to say in its report that it could not.
- Every goal in `README.md` → Goals is marked `**Maintain:**`, a state to hold, or `**Achieve:**`, a direction to pursue. Each achieve goal has a signal, a counter-signal and a one-line reason under it. A change that breaks a maintain goal is redesigned or dropped, whatever it scores: `rules/todo-items.md` says so, and larv-review's goal alignment step no longer merges such a PR. `rules/goals-and-audience.md` states the form for every project's README. Expect larv-review to stop a PR on a maintain goal where it asked you before.
- Reshape every project's `todo.md` to the new shape below: until it is reshaped, that is the project's only work, as it is while README.md lacks Goals and Audience, and `rank_todo.py` says so. First move every machine to this release: an older release rejects the new formula, so it fails on every reshaped `todo.md`. Then mark the README's goals `**Maintain:**` or `**Achieve:**`, score each item's L, E and I, and set a bar on the new scale below the score of every item to keep, since the old bar would drop most items. Until then, an old-shape `todo.md` still ranks by its own formula and weights.
-`todo.md` ranks items by value per cost: this setup's own plan uses `Score = 100 * V / (2**S + 8)`, where 8 is a chunk's fixed cost, about one size-3 change, and `rank_todo.py --help` shows it. A Moves column replaces A, G and Goals, naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`. V sums each named goal's weight times its move. `rank_todo.py` weighs each achieve goal 0.97 times the one above it in README.md, so a goal far down the list still counts almost as much as the first and the goal weights table goes. The weights sum to 1: 5 achieve goals weigh 0.212 down to 0.188, 15 weigh 0.082 down to 0.053. An item names the most specific goal it moves, never a goal beside its own sub-goal. `rules/todo-items.md` and `rank_todo.py --help` show the new shape.
- L, E and I replace C, and set R. L is the chance the change holds a defect, from 1 to 4; E the chance a defect escapes tests and review, from 1 to 3; I the damage it would do, from 1 to 5, counting every project and session that runs the change. `rules/todo-items.md` defines each level in words, and `rank_todo.py` writes R as L + E + I − 2, at least 7 when I is 5 and at least 5 when I is 4. The table's score columns are `| L | E | I | R | S |`. `score-outcomes` takes `L E I S`, and reports how well L, E and I each order finished chunks by review rounds and 🔴 findings.
-`loop-claude` routes a chunk's worker on its item's L, from two rungs below the project's rung at L 1 to one above it at L 4. It routes the reviewers on the highest E + I among the chunk's items, counting each item the worker takes in: one rung above the project's for each point past 4, never below the worker's rung. It runs the judge of an Opus 5.5 project on the rung that highest E + I picks, never below the project's, and keeps it there when the worker steps up. The comprehension seats and the security pass stay on the project's rung. rule-hook holds each reviewer launch to the reviewers' rung, which it works out from the E + I `loop-claude` hands the worker in `LOOP_CLAUDE_ESCAPE_AND_IMPACT`. A delegated task's subagent takes the rung its L picks: `subagent-rung` takes L in place of R + C. Until a project reshapes its `todo.md`, every chunk there runs on the project's rung. Expect reviews of items whose defects would escape far or break much to cost more, and escalation from an item of L 4 to reach Fable 5.1 only with your yes.
- An item that restores a maintain goal the project breaks today is exempt as `defect`, and its Moves may name that maintain goal, weighed as the heaviest achieve goal. A defect ranks by its score like any item. Only two kinds rank ahead of the rest of their release: questions first, since an answer may change other items, then security items.
- The stability reviewer applies `principles/technical-principles.md` as written, in place of its own copies of it. Its test-data check now asks for UUID v7, where it asked for randomised UUIDs.
- larv-review's principles audit is a pass of its own, and runs on every chunk that changes code, config or tests, not only on one with an architectural decision. A chunk of prose or planning alone skips it.
-`rule-hook` refuses an Agent call that launches a reviewer, a comprehension seat or the security pass on a rung below the one `loop-claude` names for it, and takes no override: pass the model and effort the refusal names.
-`score-outcomes` lists a project's score anchors: the shipped items its `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured. `rules/todo-items.md` has a scorer compare a new item with them, and says how to choose two or three per level. Add the file to each project that merges with merge commits; elsewhere, score by the level descriptions in `rules/todo-items.md`.
-`loop-claude` archives each judge reply it rejects in the chunk's `<sha256>.outcomes.md`, with the reason and the reply as json. Before, such a reply reached only stderr, so a run that exited 1 overnight could not say what the judge had returned. stderr now prints only the reason; the reply is in outcomes.md. If archiving fails, `loop-claude` exits 1.
-`loop-claude` routes each chunk on `todo.md` as the default branch holds it, freshly fetched: merge a `todo.md` edit before the chunk it should route starts. Where `todo.md` holds no item for the next release, the earliest release it has named since the newest tag, no item routes the chunk, and the worker is told that release is finished and ready to cut, or, where no work has landed since the tag, to be planned first. Before routing, `loop-claude` runs the new `bin/chunk-preflight` and quotes what it prints in the worker's first prompt: the chunk's mechanical facts, which `chunk-preflight --help` lists. The preflight also makes the chunk's worktree, `<checkout>-item-<ID>` beside the checkout on the branch `item-<ID>`, or continues the one already there, and leaves an uncommitted figure in that worktree's `docs/reading-cost.md` for the chunk to commit. It stops a fetch, forge CLI or tool after 60 seconds, or after the seconds `CHUNK_PREFLIGHT_TIMEOUT` sets. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. Expect the worker to start editing sooner.
## 0.1.0
-`todo.md`'s items table has a Blocked by column, right after Release, listing the IDs of the items that must be done before an item starts, such as `12, 14`. Move every machine to this release before any of them ranks a plan another machine shares: an older release reads the new table as no plan. `rank_todo.py` ranks each blocker above every item it blocks, drops an ID once that item leaves the table, and adds the column to a table without it. It does not turn a line such as "Needs 12" in an item's detail into a Blocked by cell; move each into the column by hand. It now fails on text beside the table under `## Items`, such as a line naming items to take first: put an order in the scores or the column. It reads the table's cells by column name, and fails on a column it does not know rather than drop it. `loop-claude` routes a chunk on the next release's first item that is neither marked `question` nor blocked by an item still in the table, which is the item the worker takes, so the first cycle runs on that item's rung.
- The new `bin/stability-replay <model>` replays archived stability reviews of the projects run on the model, each on the code it reviewed, first on the project's rung and then on each rung below, and prints the lowest rung that, like each rung above it, finds every 🔴 and 🟡 finding the project's rung finds. It shares its search with `judge-replay`, which now tries rungs from the project's rung down, where it tried them from the cheapest up. Its first run, on Opus 5.5 projects, found none: Sonnet 5.5 at high missed 13 of the 29 findings the project's rung found again. So the stability reviewer stays on the project's rung while the worker runs below it.
- A `todo.md` item you tell a session to keep is marked `owner` in its Exempt cell, and stays whatever its score.
- A `loop-claude` worker hands a task that proves too hard for its rung to a subagent one rung up, edits included, when a trigger fires: a re-score of the item on the project's rung or above picks a higher rung, the same failing test or finding survives two fix attempts, or a review pass reports a 🔴 in round 2 or later. Each further trigger climbs one more rung, to at most two rungs above the rung the chunk's `todo.md` item picks, unless you agree. `CLAUDE.md` states the rule, and `loop-claude`'s prompt names the rungs a trigger opens. The worker opens the subagent's prompt with `Escalation trigger <n>:`, and `routing-figures.md` counts the escalations by trigger. Expect a chunk that gets stuck to spend more on the stuck part, and fewer unfinished verdicts.
- A loop-claude worker may end its run asking for a higher rung, citing an escalation trigger. Once the judge quotes the transcript passage that shows the trigger fired, the next cycle resumes the worker one rung up, up to two rungs above the rung the chunk's `todo.md` item picks. The archive quotes that passage under `Escalation:` in the unfinished verdict.
- A reviewer that rules a chunk's work below standard, with systems-architect's BLOCK or a finding against larv-review's `standards/quality.md`, may ask to rerun one rung up, as may a comprehension seat whose vote in a paired ruling `record-ruling` counts as worse. The worker relaunches it once, on the rung `loop-claude`'s prompt names. A relaunched reviewer gets the report that asked and confirms or dismisses each of its findings. The relaunch's report stands in place of the one that asked, in the same round, so it adds no round. The ruling that stands is a fourth escalation trigger in `CLAUDE.md`. Expect a chunk whose work falls below standard to spend more on its review and its fix.
- A session or subagent below the project's rung, the cheapest rung of the project's model, no longer scores or reshapes `todo.md`: it drafts each new item and each change to a filed item, and before its next commit one subagent on the project's rung or above applies and scores the drafts and sets their release. It may still remove finished items. `rules/todo-items.md` states the rule. `CLAUDE.md` has a session launch a subagent that files or scores items on the rung the new `bin/subagent-rung --plan <model> <R+C>` prints, never below the project's rung, and `loop-claude`'s prompt to a worker below that rung names the command. Expect one extra subagent in a chunk that files items while its worker runs below the project's rung.
-`loop-claude` runs the judge of an Opus 5.5 project on the rung the chunk's `todo.md` item picks, never below Opus 5.5 at medium effort, the project's rung. Before, the judge ran at the effort `settings.json` sets, xhigh. A replay of 39 archived verdicts found every cheaper rung missing verdicts. The judge keeps its rung when the worker steps up or takes in another item, and runs on the project's rung when no item routed the chunk. A project on another model keeps its judge at its settings' effort. Each verdict in the archive now names the judge's rung on a `Judge:` line. The new `bin/judge-replay <model>` replays the judge on archived verdicts and prints the lowest rung that, like each rung above it, returns them. Expect the judge to cost less on items of R + C 12 or less, and more on items of R + C 15 or more.
- Every 20 cycles across all projects, `loop-claude` measures every finished chunk in its archive, with no model run, and writes the figures to `routing-figures.md` at the archive's root: tokens by project, subagent type, rung and tool, and, for each chunk a `todo.md` item routed, grouped by the rung it started on: its review rounds past each pass's first, its unfinished verdicts and its subagents' rungs. It interrupts you, with `claude` on the project's model on the terminal in `~/.claude`, when chunks routed onto a rung took more review rounds or unfinished verdicts than chunks routed onto the next rung up, each rung with 5 chunks or more, or when 5 or more subagents of one type wrote reports longer than the tool results they read. Each call is raised once, then listed in `routing-calls-raised.md` beside the figures; the next chunk of this repo files a `todo.md` item for it. Off a terminal, the calls are said on stderr and the loop goes on. They are raised at the next measurement on a terminal. After a routing change, a `- <UTC time> Reset` line in that file makes the figures count only chunks finished after it, and lets its calls be raised again. Expect a pause of about ten seconds at each measurement.
- A session delegates a task to a subagent only when it needs just the task's conclusion, such as a search across many files, and keeps edits in its own thread. It scores the task's R and C as for a `todo.md` item, and launches the subagent on the model and effort that the new `bin/subagent-rung <model> <R+C>` picks from the project's model, such as `model sonnet, effort high`. `CLAUDE.md` states the rule. Expect searches to run on cheaper models, and less of each session's context to fill with search output.
-`loop-claude` routes each chunk's worker on a ladder of model and effort rungs, from Haiku 5.5 at low effort to Fable 5.1 at max, when the project's model is on it. As a chunk starts, the R + C of `todo.md`'s top item in the next release picks the rung: 11–12 picks one rung above the project's rung, so Opus 5.5 at high for an Opus 5.5 project, and so on up to four rungs. An item of R + C 10 or less runs the worker at or below the project's model's cheapest rung, which for Opus 5.5 is medium effort, below the xhigh `settings.json` sets. While the worker runs below the project's model's cheapest rung, it launches every reviewer, comprehension seat and security pass, the full scan included, in a subagent on that rung. While it runs above that rung, it launches each comprehension seat and the security pass on that rung. It steps up one rung after every second unfinished verdict on a chunk, and to a higher rung when it takes in an item of higher R + C. Each cycle's header, and each finished or unfinished verdict, stop and step-up in the archive, name the worker's rung; a rerun resumes an open chunk on the latest rung archived for it. `docs/decisions.md` → `routing:` gives the ladder, its source and the bands. Expect a chunk on an easy item to cost much less than under xhigh, and perhaps to take more review rounds, and one on an item of R + C 15 or more to cost more.
- A session reads `todo.md` up to `## Details`, and the details of only the items its chunk takes. It reads a `docs/decisions.md` entry only where the entry's title leaves open what it needs. Both rules are in `CLAUDE.md`, so they hold from a session's start. The decisions rule replaces one in `rules/decisions.md`, which loads only once a session has opened `docs/decisions.md` or `AGENTS.md`. A chunk's opening line now counts the unreleased changes instead of listing them. Expect fewer tokens read before a chunk's first commit.
- larv-review's stability and product-owner reviewers report only a defect, a requirement of the plan or the goals that the change breaks, a breach of a technical principle, or for stability a hard place the change touches; the stability reviewer leaves the style of comments to the prose reviewer, which now also reads help and error text. Each architect finding names a concrete later change the PR makes harder, and one that names none is dropped. The prose pass runs only on a chunk that changes prose a reader reads, such as docs, comments, help text or `todo.md`, and skips a code-only chunk. Expect fewer findings and fewer review rounds.
- Every `todo.md` item carries a C score, how hard the change is to get right, from 1 to 10, in a column after S. C stays out of the score. `rank_todo.py` fails on an items table without the column, and the rule hook then blocks committing that `todo.md`. Before the next commit that changes a project's `todo.md`, add the column and score every item's C, as `rank_todo.py --help` shows.
- The new `bin/score-outcomes` shows what finished chunks measured beside the R, S and C their items were guessed at: lines and files changed, review rounds, and 🔴 and 🟡 findings. It reads them from the default branch's merge commits, so a project that merges by squash or fast-forward shows none. Given a guess, it lists the 5 finished items guessed nearest. It always reports, for each score, the median outcome at each guessed value, once 10 chunks that each shipped one item record it: R against 🔴 findings, S against lines changed, C against review rounds past each pass's first. A session filing or editing an item runs it and scores R, S and C from what it shows.
- larv-review round commits now carry the round's 🔴 and 🟡 counts, `Answer stability round 1: 1 🔴, 2 🟡; …`, and the rule hook's new `round-title-counts` rule blocks a round title without them.
- The stability reviewer mutation-tests the lines each change adds or modifies: it makes small changes to that code, such as flipping a comparison. For each test to add or strengthen, it reports one 🟡 naming the changes that test would catch. It uses the project's documented mutation command, or else cargo-mutants, Infection, mutmut or Stryker. The technical principles replace "Test coverage should not decline" with "Every mutant of a changed line fails a test, unless the mutant leaves behaviour unchanged", and say what a valuable test is: it checks behaviour through the unit's interface, and fails when that behaviour breaks. README → "Tools" gives the mutmut command for `bin/`. Expect longer stability passes and more 🟡s about tests. In a project whose README documents no mutation command, the reviewer picks and installs a tool on each run; document one there to make the runs consistent.
- Each new `loop-claude` worker session's prompt now quotes the README's Goals and Audience. A line above them says that the chunk's `todo.md` items, or else the task, set its scope, and that the goals only choose how to deliver it. A session outside the loop reads Goals and Audience before starting a chunk, as `CLAUDE.md` now says.
- A session no longer reads the technical principles before writing code. It writes the simplest change that solves its item, test first wherever a test can check the change, and reads a principle only when the item changes it, a finding names it, or a decision or `todo.md` item it writes cites it. larv-review's reviewers hold the change to the principles, and a finding against one names it. Expect more findings from the prose and stability reviewers, since sessions no longer load the rules for comments and READMEs.
- The rules for comments and READMEs, "Quality" and the examples behind "Prose" moved to `skills/larv-review/standards/`, which the prose and stability reviewers and `loop-claude`'s judge read. `CLAUDE.md` keeps a short core of "Prose"; sorting where order carries no meaning lives only in the technical principles.
- A session no longer points out a preference you have repeated or asks you to write it up, and no longer restructures `CLAUDE.md` and `rules/` after changing them.
- A `todo.md` item names a release whose version bump fits the item under strict semver: a major for a change to what exists (a minor before 1.0.0), a minor for an addition, a patch for a fix.
-`CLAUDE.md` keeps only the rules no file path can scope. The rules for `todo.md` items, decisions and a README's Goals and Audience moved to files under `rules/`. Claude Code loads each one when a session reads or writes a matching file. `loop-claude`'s judge reads them beside `CLAUDE.md`.
- A README no longer holds cross-cutting decisions; `docs/decisions.md` does.
- A technical principle, "Prefer deep modules": a module puts a small, intuitive interface in front of a lot of hidden work, and hides how it works but never what it depends on. It wins over "Explicit over implicit" unless hiding the work makes it harder for someone new to the project to tell what a call does. "Functional core, imperative shell" moves up to second place, a core rule beside "Compose, do not entangle" that no other principle overrides. The systems architect holds every module to it.
- A hook blocks each Bash, Edit, MultiEdit and Write call that breaks a rule a program can check: a commit message that is not one line passed with `-m`, a Claude or Anthropic attribution, a container image short of a full patch version, an Action pinned to anything but a semver tag, an unsorted block in an ignore file, and a commit of a `todo.md` that `rank_todo.py --check` rejects. `CLAUDE.md` states those rules only where the hook cannot check them; `~/.claude/bin/rule-hook --help` states what it checks. A call overrides a rule with `# rule-override <rule>: <reason>`. larv-review's new overrides pass, run before stability, accepts or rejects each override the chunk logged, and the PR body lists each with its ruling; a rejected override means the chunk keeps the rule. An override that touches a credential, a security rule or a production system, or cannot be undone, is asked of you.
- A project may opt out of larv-review's architect, product-owner pass or comprehension check in every chunk, through a `docs/decisions.md` entry titled `review opt-out: …` that names the goal that skipping them serves. A project without such an entry is reviewed as before. Opting out of the comprehension check also skips the scoring run due at a release's end. The principles audit always runs.
- A README goal states the project's aim and intent, and no longer names a step of the work, such as "kill weak candidates early". Such steps go in a method section further down the README and name the goal they serve.
- The stability reviewer keeps its scratch work in a directory it creates for the run, deletes that directory afterwards, and deletes nothing else.
- larv-review's mechanical rules run in the new, tested `bin/larv-review`: the paired ruling's base (`ruling-base`), each pass's round count (`round-count`, which ignores case in a round's commit title, counts a repeated round number as a round of its own, and says to ask you before another round once a pass is at or past the cap), the scoring run's trigger (`needs-scoring-run <item ID>...`), and the vote count, means and history format (`record-ruling <votes file>` and `record-scoring <scores file> [<item ID>...]`, which append to `docs/comprehension-history.md` and refuse a second entry on what a seats file's first line reads; `record-scoring` refuses a run the plan does not call, and prints `Floor:` naming each mean under the comprehension floor of 7.0), and the places seats found hard since the newest scoring run (`places`). The skill says when to run each and what its answer means. A seats file line the tool cannot read fails the run, so a mistyped vote never counts as same. The base search compares the history before and after each merged change, so it no longer depends on how a line is worded. A release whose last plan item moves to another release is due a scoring run too, once work has landed towards it. A seats file must name commits the checkout holds. When origin cannot be fetched, the tool reads it as last fetched and says so.
- The new `bin/metric-bench` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest: cognitive complexity, length, shared state and change spread, each scored by how well it ranks the named functions above the rest. No metric enters review yet.
- larv-review runs a comprehension check, which records how hard the project is to read and blocks no merge. It runs once per chunk, after every pass, on the branch as review left it. Where the architecture pass ran, Mid A and the inherited architect read that commit beside the last measured commit: the default branch's newest merged change that added a ruling or a scoring run to `docs/comprehension-history.md`. They vote better, same or worse on each dimension and overall: `Navigation same, Locality worse, Shape same, Self-sufficiency same, Overall better`. When their overall votes differ, the maintainability senior and Junior A vote too. A ruling needs a lead of two or more votes, else it is same. Each place a seat names opens with the dimensions it moves, such as `Locality, Shape: `, or the run fails, and a vote that no place opens with counts as same. Four seats score the project from 1 to 10 when a chunk ships or removes a release's last plan item, or ships an item naming the comprehension floor of 7.0. A project whose own `docs/decisions.md` or `AGENTS.md` still says the floor or a worse ruling blocks a merge keeps that rule; edit it there to stop blocking.
- larv-review reruns fewer passes after a fix. A fix reruns the pass whose 🔴 or 🟡 it answers, plus stability when the fix changes behaviour, security when it opens an untrusted-input boundary or touches authn/authz, secrets or crypto, and architecture when it carries an architectural decision. From round 2, a reviewer agent reviews only the answers to its previous round's findings: each fix, and each dismissal with its reason. A fix from another pass that re-enters it gets a first-round review, limited to the fix's lines. On those answers it reports only a fix or a dismissal that is plainly wrong or worse than the change it answered, so a pass should converge in its second round. A fix for a 🟢, a ❓ or any prose finding reruns no pass, and prose takes one round.
- larv-review runs one security pass on each change: the full scan alone when it runs, else `/security-review`.
- larv-review runs the new `bin/reading-cost`, which measures each chunk `loop-claude` finished from its archive: the new input tokens the worker and its subagents took in before the worker's first commit, and the files git tracks that they read most. It appends each figure the project's `docs/reading-cost.md` lacks. Once 10 chunks are measured, and the last 5 chunks' median is above the 5 before them, larv-review files one plan item naming the files read most, or refreshes it. The chunk that ships it runs `reading-cost --reset`, so the trend counts only chunks that finished after it.
- larv-review appends every paired ruling and scoring run to the project's `docs/comprehension-history.md`: the commit the seats read, a ruling's base, each seat's vote or scores, and the places each seat named. The PR summary gives each ruling with its base and votes. The seats do not read the history.
- The architect and the stability reviewer get the places seats found hard since the newest scoring run, from the new `larv-review places`: that run's places, and each later ruling's places a seat voted worse. Each reports, as a 🟡, a place the change touches without making it easier to read; the chunk fixes it or says in the PR summary why not. A session filing a `todo.md` item reads the places too, and an item touching one says to make it easier to read.
- The README's goals put quality with the fewest interrupts first, as goal 1; sharing the setup, backups and leaking nothing follow as goals 2–4.
- larv-review skips the comprehension check for a chunk whose plan items a project decision names. The decision also names the later item whose check ends the suspension. The skipped chunk's summary cites the decision. A chunk that ships or removes a release's last plan item, or ships an item naming the floor, still gets the scoring run.
- README → Install and Update give the commands that check the latest tag out into `~/.claude`: on a new machine, whether or not Claude Code has already created the directory, and on one already on an older tag.
- A session commits changes Claude Code made to `settings.json` only once their diff holds no credential, and asks you to move any credential out of the file first.
- A technical principle, "Sane defaults, where a default serves better than an explicit ask". A default suits a value most callers want, does no harm when wrong, and can be seen and changed. It lives at the program's edge, such as a CLI; a library still asks for data, the clock and randomness.
- larv-review's principles audit reads only the files under `~/.claude/principles/` that apply to the project, launching a file's auditor when unsure. A file's `Applies to` line says what it covers; one without the line covers every project. The summary names each file left out. After its first round, the architecture pass reruns only the reviewers whose 🔴 or 🟡 the fixes answer, unless the fixes carry an architectural decision.
- When `loop-claude`'s judge rules a chunk unfinished, the resumed worker is shown the passage the judge quoted as the work remaining. A loop started before this change exits 1 at its next reload; rerun it.
- larv-review's architecture pass and full security scan get short names, `Architecture` and `Full scan`. Each round's commit is titled with its pass's name in lower case: `Answer full scan round 1: …`.
-`loop-claude`'s judge reads your `~/.claude/CLAUDE.md` beside the project's `AGENTS.md` and `docs/decisions.md`. It no longer interrupts for a choice that file settles, and it answers the worker's questions from it.
-`loop-claude`'s judge holds a chunk open until each answer you typed in it that a later chunk could need is recorded. An answer counts as recorded once the README's goals or audience, `AGENTS.md`, `docs/decisions.md` or `~/.claude/CLAUDE.md` hold it. It also counts once the transcript shows the worker writing it into the README's goals or audience, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. The worker writing to `~/.claude/CLAUDE.md` does not count, since new rules there are yours. The resumed worker is told this rule.
-`loop-claude` archives each answer the judge quotes, with the question it answers and its UTC time, in `<sha256>.outcomes.md`.
- larv-review keeps its three-round cap across a resumed session. It closes each review round with a commit naming the pass and the round, empty when the round changed nothing, and counts rounds from the branch's own commits.
- larv-review runs `/security-review` in a subagent, so the run goes on to the next pass without you prompting it.
- larv-review asks once before the full security scan: it states the evidence and its recommendation, and `claude-security`'s cost prompt is the ask.
-`loop-claude` accepts the judge's quote of the transcript when it elides with an ellipsis and the transcript holds each fragment in order. The transcript the judge reads, and the worker's printed output, show tool input with its non-ASCII characters as written, so the judge can quote it.
- Unless another Exempt reason fits, larv-review marks a `todo.md` item filed from a 🟡 finding against `~/.claude/principles/` with `principle`, an Exempt reason that keeps it whatever its score.
-`loop-claude`'s judge reads the project's `AGENTS.md` and `docs/decisions.md` beside the README's goals and audience, and does not interrupt for a choice they settle. When the worker asks a question that the README or those files answer, the worker resumes with the judge's quote of the answer, which `loop-claude` prints. A quote they do not hold word for word is dropped, and the question goes to you. So does a question asked again after its answer. The fourth question they answer in one cycle goes to you too, with the quote. The judge reads as much of the transcript's end as fits a 400,000-character prompt, up from the last 40,000 characters. `loop-claude` exits 1 when `AGENTS.md` or `docs/decisions.md` cannot be read or is not UTF-8.
- A project's decision log is `docs/decisions.md` alone, the one file the judge, `rank_todo.py` and the reviewers read.
-`loop-claude` waits out a usage limit and retries: 2 minutes past the reset, or every 10 minutes when the reset time is unknown. A limit is not a failure, and restarts the count of three failures in a row. It prints what claude said about the limit and when the next try is due.
- Add the official plugin marketplace and install every plugin `settings.json` enables (README → Install): `claude-security`, `code-review` and `rust-analyzer-lsp`, which needs `rust-analyzer` on `PATH` for Rust projects. With `claude-security`, larv-review's full security scan runs once you confirm its cost; an unattended larv-review reports the scan as not run. `settings.json` silences the plugin's scan tip after `git push`.
- systems-architect and product-owner-reviewer can no longer edit what they review; stability-reviewer keeps its shell to run tests, and loses Claude Code's file-editing tools.
- Every project's `todo.md` takes one shape, and larv-review's gate checks it: one table of items, each scored by the formula and goal weights the file states and held to its bar, an item under the bar dropped unless its Exempt cell says why. `bin/rank_todo.py` ranks the table, and `rank_todo.py --help` shows a valid file.
- 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 unedited on any machine with README → Install's prerequisites; the status line shows reset times in the machine's own time zone.
-`loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one.
-`loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog.
-`loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run.
-`loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1.
-`loop-claude`'s exit-2 message says what the human is needed for.
-`loop-claude` exits 1 saying why when `git`, or python for a reload, cannot start.
-`loop-claude --help` lists each exit cause on its own line, and when an edit to `loop-claude` breaks its reload, the exit-1 message names what the edited script could not read.
-`loop-claude` shows the judge's reply when it rejects the judge's verdict.
-`loop-claude` retries a failed worker within its cycle.
-`loop-claude` counts an interrupt reply starting with `<` as typed.
-`loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed.
-`loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and failures included, in one folder per chunk. Each distinct transcript is kept once, named by its SHA-256. Beside it, `<sha256>.outcomes.md` holds the verdict, with the transcript passage the judge rested it on, and why the loop stopped. The verdict and the stop each open with their UTC time. The subagents' transcripts and the session's other files go in the chunk folder's `session/` subfolder. `loop-claude` exits 1 when it cannot archive.
-`loop-claude` exits 1 when it cannot delete a finished chunk's session, naming what to delete before rerunning; the next chunk would otherwise resume it.
-`loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600.
Shorter is better, none is best — chat output, commit messages, comments, docs and code alike. Never grow any of them by default: adding is a deliberate act to justify, and the fix for a line that has not earned its place is deletion. If the information is already in the code or the project `README.md`, skip it. Use **English** everywhere.
## Vocabulary
- **chunk** — the unit of work: the smallest PR-able change.
- **cycle** — one worker run and the judge's verdict on it, in `loop-claude`.
- **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.
- **looping reviewer** — a reviewer rerun in rounds until no 🔴 and no 🟡 stand: stability, product-owner and a forge's auto-reviewer.
- **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 loop of a looping reviewer may take; a 🔴 or 🟡 open past it stops the loop at `needs input`.
- **session** — a Claude Code session: one id, what `claude --resume` continues.
- **trigger** — a sign that a change carries an architectural decision the decision log does not hold, so the architecture pass is warranted; `larv-review` §2 lists them.
## Prose
- **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone.
- **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader doing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`.
## Maintaining this file
- When you spot a pattern in how I work that isn't written here — a preference I've repeated, a correction I've given more than once, a convention you inferred from my code — tell me and ask me to write it up here. Don't add it silently, and don't just keep it in a memory file.
- 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
- 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.
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.
## One spelling per goal
- When two spellings reach the same result, make one work and reject the other. Supporting both needs a stated reason, written down.
- Reject the redundant spelling as early as possible — at load, parse or compile, not at use — and have the error name the spelling to use instead: `token {p} renders a level that {p.first} reads a path into; name the fields you want instead`.
- Where the two spellings can *disagree*, this is a correctness rule. A caveat in the README does not close it.
- Applies to data formats, config, CLI flags and public APIs alike.
## Working loop
How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise.
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. A rule names a project's files by their usual paths: `todo.md`, `AGENTS.md`, `CHANGELOG.md` and the files under `docs/`. Each is where the project's config puts it, which `~/.claude/bin/project-config` prints and `chunk-preflight`'s facts quote. Where the config names a Jira epic as the plan, the plan is the epic's open child issues. Read and edit a project record in the file `~/.claude/bin/project-record open <record>` prints, and run `project-record save <record>` after each edit. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
- **`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.
- **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.
- **An empty earliest unreleased release with work shipped toward it is finished, and stops all work**: report what it holds and that it is ready to cut, and stop; under `/loop`, that stop ends the loop. Only a security fix still lands, into it. Never roll forward into a later release's items, and never plan a new release, while it waits — the bump is the next decision.
- **A release is the human's.** The version bump and the publishing credentials are the human's whatever any other rule says; prepare everything around it so the release is one decision.
- **Open every chunk with one line**: the last version cut, what is unreleased (`CHANGELOG.md`'s`## Unreleased`, else the log since the last tag), and the release this chunk ships into; a repo that publishes nothing says so once.
- **One chunk at a time**; split a milestone into sub-items in `todo.md` before starting it. A finding inside the chunk is fixed in the chunk; outside it, it becomes a `todo.md` item under a release.
- **A done item leaves `todo.md`; its release heading stays until the version is cut.** Where the repo publishes something a consumer takes — a package, an image, an API — the line is reworded for that consumer and moves to `CHANGELOG.md` under `## Unreleased`; a CHANGELOG is written for the public, never for the next agent. Everywhere else the line is simply deleted, because git history is already the record.
- **Ship every chunk with `/larv-review`.**
- **Ask, don't guess — and fix the goals rather than the question.** Before asking, check whether the goals already settle it; where they nearly do, propose the goal change and show what falls out of it for the instance, because one answered question settles one instance and a goal settles the class. Every answer lands where its kind belongs, and nowhere else: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. Where an answer is more than one of these, the goal wins — write the goal, and record a decision only for what it still leaves open. Never in chat alone.
- **Until the goals file has a`## Goals` and an `## Audience`section, writing them is the only work.** Not even planning. In a README both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as`AGENTS.md` or`docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
- **Keep a plan in `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
- **Read and change the plan's items only with `~/.claude/bin/todo-item`**, which lists, shows, files, edits, moves and finishes them; `todo-item --help` says how. It reads a plan in Jira as it does a file. There it edits and moves only an issue the loop filed; of an issue a person filed it sets only the scores, with `--comment` telling the team why. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` §3 → "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one.
- **Where someone cut a release that still holds items, those items are the next release's.** Move them there as the chunk's first change and say so in its opening line; where `todo-item` cannot move an item, such as an issue a person filed in a Jira plan, ask the human in the chunk's summary to move it. Where the plan names no later release, ask the human which one they belong to.
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` →`## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that doesn't publish anything says so once.
- **A client project's `CLAUDE.md` and `AGENTS.md` in its repo belong to its team.** Read both at the start of each chunk there. Propose each change that aligns them with this setup in a pull request of its own, never inside a chunk's; the one edit a chunk makes there is a decision's title in `AGENTS.md`. Until the team accepts a proposal, and after it declines or doesn't answer, follow the team's rule unless it breaks one of the project's goals. Record each such conflict as a decision in the `decisions` record, as`rules/decisions.md` asks: which rule you follow, why, and the open proposal's PR. Then nobody is asked twice.
- **Read the goals file's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and each item that may join it with its L, E + I, S, tagline and detail; run `todo-item` only for what they leave out. Otherwise run `~/.claude/bin/todo-item list`, which prints every item's row in the plan's order, without details. Then read the details of only the items the chunk takes, with `~/.claude/bin/todo-item show <ID>`, which prints an item's row and detail. `AGENTS.md` lists the project principles and the title of each decision no project principle covers. Read an entry in `docs/decisions.md` only where the project principle or the title leaves open what the chunk or the review needs. Print one entry with `~/.claude/bin/markdown-section <file> <fragment of its title>`, where `<file>` is what `~/.claude/bin/project-record open decisions` prints.
- **Work one chunk at a time, and put every item that can share its review into it.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The items need not share a purpose. An item whose risk R, in the plan, is above 5 ships alone: it joins no chunk, and none joins it. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need not fire the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in the plan before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
- **Ask, don't guess.** Three choices are always the human's: a goal; a release, meaning the items planned into it and when it is cut; and a change to loop-claude's routing ladder, its rungs included. Any other rule that asks the human's approval reserves that choice too. Ask about a reserved choice. For any other choice, first check whether the goals already answer it. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Otherwise take the option you would recommend, and record it with its reason: in the item's detail, or, where it governs later work, as the next sentence says. A recommendation you can give a reason for is not a guess. Ask only where you have no recommendation. Write every answer once, where it belongs, never only in chat: a goal in the goals file, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the goals file, and record as a choice only what the goal leaves open.
- **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the goals file's `## Audience`, picks it.
- **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. Take its expected values from the item, never from the code. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file in the principles folder the project's config sets (`~/.claude/bin/project-config principles` prints it) only when the item changes it, a finding or a record you write names it, or you decline a finding.
- **Change the setup for each finding an outside reviewer raises on a PR, deterministic tools first.** An outside reviewer is a forge's auto-reviewer or a human, not one of larv-review's reviewer agents. For each finding of theirs, whether you fix it or decline it, ask why our review didn't raise it first, and change the setup so it would; a fix that only answers the comment leaves the same gap open for the next chunk. Put the change in the first place that fits:
1. A deterministic tool that would have caught it, such as a rule-hook rule, a gate check, a linter setting or `mutate-changes`: a tool catches the fault every time, and a reviewer only when it notices.
2. A technical principle or a review standard, where a rule was missing or too vague: in claude-config's files, or in the project's own principles folder.
3. Anything else: the reviewers' agents, `larv-review`'s text, or the project's own settings or `AGENTS.md`. A client repo's `AGENTS.md` changes by a proposal of its own, per "A client project's `CLAUDE.md` and `AGENTS.md`" above.
Change claude-config's files where every project gains, and the project's own only where the gap is that project's alone. In claude-config, the change is a fix of the chunk. In another project, a change to the project's own files is a fix of the chunk too, and a change to claude-config's is an item in claude-config's plan: start a worktree of claude-config off `origin/main`, run `todo-item add` in it, commit the plan file, and ship it as a pull request of its own with `chunk-pr`, since claude-config's default branch may not take a direct push. Describe the gap without the client's name, code or comment text. File a change too big for the chunk as its own item. Where no setup gap caused the finding, as when the finding is wrong, say so in the chunk's summary rather than inventing a change.
- **Remove a finished item from the plan, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. `~/.claude/bin/todo-item finish <ID>` removes the item with its detail, and adds the bullet you pass with `--changelog <bullet>`; it refuses while a decision cites the item. A plan kept in Jira takes no bullet, since the issues' history is its changelog: `finish` there refuses `--changelog`. A chunk finishes its items as it merges, through `chunk-pr merge --finish <ID>`, which takes the same flags (`larv-review` §5).
- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision.
- **Open each plan item or ticket with a bold one-sentence tagline**, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and doesn't say anything about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- **File a security finding the moment it is found.** A security finding — a leaked credential, secret or PII, an auth bypass, an injection — goes under the next release, marked `security`, naming the exposure and the path it reaches. `~/.claude/bin/rank_todo.py` ranks it first in its release, after only the open questions, which wait for me. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
## Shared goal
Every project pursues the achieve goal below, ranked above every achieve goal its goals file states. A project whose code nobody will maintain voids it with one line under `## Goals`, before the numbered goals: `**Void:** code health, since <reason>.` So does a project that opts out of the comprehension check, since the goal then has no signal. An item's Moves cell names it as in `code health by 6`, and `rank_todo.py --help` says how much it weighs.
**Achieve:** Code health: the code stays easy to read, change safely and debug, tomorrow and after seven years of development.
- Signal: the comprehension panel's overall score rises, always. Under the project's readability floor it is very important. The floor is 7.0, unless the project's config sets `readability-floor`.
- Counter-signal: defects keep reappearing in functionality that already shipped, or reviewers raise blockers because the implementer misunderstood the current system.
- Why: a score that rises while changes still misread the code measures the wrong thing.
Fewer items shipped per release is a price this goal accepts, not a counter-signal.
## Prose
Everything written — chat, commit messages, comments, docs, code — is in **English**. Where a project's config names another `language`, which `~/.claude/bin/project-config language` prints, the prose that project's readers see is in that language instead: its docs, comments, commit messages, pull requests and tracker text. These stay English: chat, names in code, a reviewer's report, and what a tool reads, which is the fixed words of a title, such as `Answer <pass> round <n>:`, `todo.md`'s table, and a record's headings, such as `## Unreleased`. Prose meets four priorities, in this order. When two pull against each other, the higher one wins.
1.**Easy to understand.** A reader with little time gets it on one read: one idea per sentence, and each term explained before it is used.
2.**Most important first**, judged by what the reader wants to know first.
3.**Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it.
4.**Short.** Cut whatever does not clearly help 1–3.
Write the thing, not an introduction to it. State what holds and stop; name a rejected alternative only where that stops a reader choosing it.
Write negations as people say them: after a verb, or after its preposition, write `doesn't <verb> anything` or `anyone`, never `<verb> nothing` or `no one`. BANNED: `stops nothing`, `depends on no one`, `so answering in time costs nothing`. GOOD: `doesn't stop anything`, `doesn't depend on anyone`, `so answering in time doesn't cost anything`.
Reviewers hold prose to the full rules, with examples: `prose.md` in the project's review standards, which "Topic rules" below defines.
## Public API specs
- Text in public API specs (OpenAPI `description`/`title` fields, in a spec file or in code, and the generated api-docs) is read by external consumers. Never leak internal references: no ticket IDs, internal URLs, repo/system code-names, "see ticket X". Describe behaviour in consumer terms. GOOD: `Deprecated alias for paymentAccountId`. BANNED: `…will be removed (ABC-123)`.
- Internal code comments, by contrast, *may* cite a ticket for a footgun or constraint.
## Topic rules
Claude Code loads a rule file when a session writes a file its `paths:` frontmatter matches, or reads one with the Read tool or `head -n`, never `sed`. After a write, it loads only once the write is done. Read a rule file before you create a file it covers.
- The decision log: `~/.claude/rules/decisions.md`.
- Goals and audience: `~/.claude/rules/goals-and-audience.md`.
- Plan items, their scores and Exempt reasons: `~/.claude/rules/todo-items.md`. Read it before you file, score, edit or move an item: a session that runs `todo-item` never opens `todo.md` itself, so the rule doesn't load.
The rules only reviewers apply, for quality, comments, READMEs and prose, are the project's review standards: the folder its config sets as `standards`, which `~/.claude/bin/project-config standards` prints.
## Working with the codebase
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app <tool> …`.
- Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match").
- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out.
-Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds.
-Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.)
## Handoffs
- One document per project: `~/code/claude-handoffs/<project>_<YYYY-MM-DD>.md`, with its supporting files (scripts, probes, saved sessions) under `~/code/claude-handoffs/<project>/<YYYY-MM-DD>/`, dated the day they were written.
- Each document stands alone — projects move in parallel, so never reference another project's handoff. A fact two of them share (a test site, where credentials live) is stated in each, or kept in a memory file and named there.
- Content: only what the repo cannot hold — probe results, where credentials live. What is done and the next step live in the plan; goals, audience and decisions in `README.md`/`AGENTS.md`. A handoff never restates them: the repo's copy travels with the code and this one does not.
## Tests
- Write tests first for the behaviour we want, then implement until they pass.
- Changing tests and changing other code are two separate processes — be very careful about doing both at once.
- Use properly randomised UUID v7s — never `aaaa-0000`-style placeholders.
-Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along.
-Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host, unless the project's config sets `tooling-on-host = true` or a decision puts them there. Example: `docker compose run --rm app <tool> …`.
- Tear down test containers after a run.
- Give every container you start a memory limit and a swap limit, as large as its work needs: `--memory 4g --memory-swap 4g` on `docker run`, or `mem_limit` and `memswap_limit` in a compose file, scripts included. rule-hook checks only the `docker run` and `docker create` in your Bash commands.
- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run the command in the background, since run-heavy's wait can outlast the Bash tool's timeout; `~/.claude/bin/wait-for <file> [<pattern>]` waits for a line in a log the command writes.
- Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's L as for a plan item; a task that changes no file, such as a search, is L 1. `<model>` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits:
1. A reviewer, a comprehension seat or the security pass: those loop-claude's prompt gives it. Given none, pass no model or effort, so it runs on your model.
2. An escalated task, below: the rung loop-claude's prompt names for escalation, or case 3's rung where the subagent files or scores plan items and that rung is higher.
3. A subagent that files or scores plan items: what `~/.claude/bin/subagent-rung --plan <model> <L>` prints, which is never below the project's rung.
4. Any other: what `~/.claude/bin/subagent-rung <model> <L>` prints.
- Escalate a task that proves too hard for your rung. Four escalation triggers say so:
1. A re-score of the item's L, made on the project's rung or above, picks a rung above yours.
2. The same failing test or finding survives two fix attempts.
3. A pass reports a 🔴 in round 2.
4. A review rules the work below standard: systems-architect's BLOCK, a finding against the review standards' `quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up"). It doesn't fire where the fix changes only prose (`larv-review` §3 says what is prose): fix that on your own rung.
## Code style
-Indent with hard tabs by default. A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation.
-Reuse before adding. Extend an existing test with an assertion rather than writing a new one.
-Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first.
- Sort a compound line on the name it introduces, never on an incidental field: an import on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group.
- Prefer a standalone Python script with a `#!/usr/bin/env python3` shebang over a shell script — it runs identically across systems where shell dialects/builtins differ. Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded.
- DTOs, enums, and value objects are pure data — no logic. They stand in for the structs/records a language lacks.
- Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`).
- Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. Domain decisions and branching belong in the service layer — an entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code.
- Signal failures with a result value carrying an optional error, not by throwing. A function that both returns a result and throws for some inputs has two error channels; collapse to one. Reserve exceptions for truly unrecoverable states at boundaries, never for control flow the caller is meant to handle.
- A cast (`x as Foo`) asserts what the compiler could not check and stops it checking — so when the type later changes, nothing tells you. Derive the real type instead: infer it, name the return type, or parse the input once into a typed shape. Where a value genuinely arrives untyped (HTTP body, `JSON.parse`, DB row), the boundary owes a **type guard validating the fields it claims**; past that boundary everything is typed. `as unknown as T` and non-null `!` are the same defect wearing a hat. BANNED: `const user = body as User` — one rename and it is a silent lie. GOOD: `function isUser(v: unknown): v is User` checking each field, then `if (!isUser(body)) return { error: … }`.
When one fires, hand the hard part, edits included, to a subagent on the rung loop-claude's prompt names, one above yours. Open the subagent's prompt with the marker loop-claude's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung loop-claude's prompt names. Ask the human before going higher. Where loop-claude's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread.
-Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`~/.claude/bin/larv-review review-folder` prints it), and removes no image or file it did not create.
-Check `README.md` first for build, test, install, and codegen commands, and fix one that misbehaves in the same change. Refresh `README.md` whenever you change what it describes, keeping it true, not longer.
-Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest or a `docker run` line, pin a container image to its full patch version and a GitHub Action to a semver tag.
## Naming files & folders
- Name by what's inside, not by catch-all. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. Use explicit names: `e2e-tests/`, `db-migrations/`, `release-tooling/`.
- Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`.
- Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`.
## Comments and documentation (`README.md`, `AGENTS.md`, `docs/`, API specs)
**One bar for all of it.** A comment or a paragraph earns its place by saying what a competent reader of THIS codebase could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. The fix for a redundant one is deletion, not trimming — two copies drift, and the doc copy is the one nobody updates. Once it has earned its place, make it short and information-dense. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show.
**A false claim is a bug — fix it where you find it.** Docs, comments and what a program prints — `--help`, an error, a log line — assert checkable things: a command, a resolution rule, a path, a limit. Verify one before you repeat or build on it. When it is wrong, correct it in the same change: the claim — or the code, when consumers already rely on what the claim promises. Never work around it or record the discrepancy elsewhere.
**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.
**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.
**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; N copies drift, whether they are comments or READMEs. Don't summarize what's behind the link or restate the identifier's own name.
**A pointer is not a definition.** A definition the reader needs to follow the code — what a unit counts, what a term means, what invariant a cache rests on — sits at the code in one line. A pointer to it (`see AGENTS.md §11`) cannot be checked against the code beside it, so it rots invisibly. A pointer carrying rationale — a rejected alternative, the premise behind a standing choice — is correct and stays.
### Comments
The rules below govern prose comments; doc comments a tool consumes — docstrings, godoc, JSDoc types — are outside them.
Default to NO comment. Delete one that is any of:
1. A **restatement** of the adjacent code. BANNED: `// Sanitized + bounded to 1000 chars` above `mb_substr(json_encode(LogSanitizer::body($x)), 0, 1000)`.
2. A **cross-cutting convention** used elsewhere (sanitization, the 1000-char Loki cap, "log so the source is recoverable"). Project-wide facts live in ONE doc, never repeated at call sites.
3. A **justification of self-evident code** (a log line is self-evidently for observing its value).
4. A **file preamble or arrangement rationale**: what a file holds, why it exists, why two things share it, why a check sits beside what it judges, why an order was chosen. The file name and the declarations are the index; a choice with no effect on the running program belongs in the commit that made it.
**What stays is one terse line, and only where the code cannot show it.** GOOD: `# Pinned to 7.x: hurl 8's jsonpath change breaks the nth-filter asserts.` A second line belongs in the commit message or the ticket. The one exception is a paragraph for an invariant a reader must hold before touching the code below; it stays with the code it guards.
**Density is a review signal.** Prose comment lines much past ~10% of a file's non-blank lines mean something is wrong — narrating comments, or code that fails to carry its own meaning. A defect to investigate, not a style preference.
### 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.
**"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.
### Todo items (`todo.md`, tickets, plans)
- Write each item as the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `Accept undefined in MetadataValue and drop such keys on output`. BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, at the top of the list under its own `## Security` heading, naming the exposure and the path it reaches. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
### Package README (what someone finds on npm or GitHub)
- The public API is the contract, so the README documents it: options, results, events, everything exported. The rule against narrating a file or test case still holds.
- Order sections by what a new developer wants first: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts.
- Headline plus short, clear instruction, nothing else. No meta-prose ("things to keep in mind", "you may want to know"). An intro is a line or two that points at the in-depth section.
- Keep every documented behaviour, as terse facts, bullets and tables rather than paragraphs. Where the README is the only record of a behaviour, cutting it is a decision to ask about, not a tidy-up.
- Write for the app developer using the package; gloss a domain term once, on first use.
- Top: badges (package version, CI), a one-line tagline that is also the package manifest's description, a feature list, a one-line table of contents. Near the bottom: a table of everything exported.
- A guide for migrating from an older major goes in `MIGRATION.md`, linked from one line in the README.
### Public API specs
- Text in public API specs (OpenAPI `description`/`title` fields and the generated api-docs) is read by external consumers. Never leak internal references: no ticket IDs, internal URLs, repo/system code-names, "see ticket X". Describe behaviour in consumer terms. GOOD: `Deprecated alias for paymentAccountId`. BANNED: `…will be removed (ABC-123)`.
- The opposite of internal code comments, which *may* cite a ticket for a footgun/constraint.
## Git, commits, and PRs
-Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything below applies to both.
- Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`.
- When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it.
-Mark no commit, PR, issue comment or file as the work of Claude, Anthropic or an agent.
- 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.
- Where the project's config names a `commit-title`, `pull-request-title` or `branch` template, fill it instead of following the formats in this section. `{summary}` is the one line that says what the change does, without a ticket ID, and `{id}` is the ID of the chunk's first item. A chunk without a plan item, such as a release review, works on a branch that doesn't fit the `branch` template, and its titles are the summary alone. `~/.claude/bin/project-config --help` describes the templates, and `chunk-preflight`'s facts quote them. A title a tool reads, such as `Answer <pass> round <n>: …`, `Drop item <ID>: …` or `Release review of <release>`, is the template's `{summary}`.
- When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it.
- 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.
-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.
-Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`.
-Branch for a plan item without a ticket: `item-<ID>`, in the worktree `<checkout>-item-<ID>` beside the checkout, as `chunk-preflight` makes them. Under a `branch` template, `chunk-preflight` names both by the template.
-Where the project's config keeps a file in the config's folder, `~/.claude-projects/<key>/`, such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Two chunks may commit there at once, so commit only that file: `git commit -m <title> -- <file>`, after `git add <file>` where it is new. Where git finds `index.lock` held, the other chunk is committing: try again. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title.
- Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both.
- On GitHub and Gitea, open a chunk's pull request as a draft, mark it ready and merge it with `~/.claude/bin/chunk-pr`, which picks `gh` or `tea` from the remote; `chunk-pr --help` says how. Once it has merged, run `chunk-pr clean` in the chunk's worktree: it removes the worktree and the branch and fast-forwards the main checkout.
## Handoffs
- Write no handoff document. The repo holds everything the next session needs: the plan, the decisions, and every script, sketch or measurement those depend on. A file outside the repo is unreachable from another machine's checkout.
- Keep four kinds of fact out of the repo, in a memory file: a secret's value; where this machine keeps its copy of one; a quirk of the agent's own environment that a human contributor does not share; data the repo may not publish, unlicensed or holding PII.
## Web research
- **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible.
- When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw <url> [options]` (see its README). Don't use claude-in-chrome for this.
## Compact instructions
Claude Code reads this section by its heading when it compacts a conversation. Keep in the summary:
- what remains before the chunk is finished;
- the task loop-claude gave, and each plan item the chunk takes with its L and E + I;
- the worktree, branch and PR;
- the rung loop-claude named for each review launch, rerun and escalated subagent;
- each review pass's rounds so far, each open 🔴 and 🟡, and how the answered ones were answered;
- every question the human answered, with the answer;
- each escalation trigger that fired;
- for a reviewer or comprehension seat, every finding and place it has drafted.
## Vocabulary
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from the premises or the judge's records.
- **gate** — the merge gate: the checks a PR passes before it merges.
- **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`. Read it in the file `~/.claude/bin/project-record open goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder, or in a Jira epic's description, whose `## Goals` and `## Audience` the loop only reads.
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer there, or `/talk` to open the worker's session there with `claude --resume`. A release ready to cut opens that session at once. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
- **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/`, then those in the project's review standards.
- **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling.
- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them.
- **place** — the smallest addressable unit, such as a function or a section heading, that a seat names with its `path:line` when it judges how hard the project is to read there.
- **plan** — where the project keeps its items, as the `plan` setting of its config names it: a `todo.md` at a path, or a Jira epic.
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's goals file, with code health ("Shared goal") first among the goals unless the goals file voids it.
- **project's rung** — the cheapest rung on loop-claude's routing ladder of the project's model, which is the model loop-claude's prompt names as the project's, or else your own.
- **project record** — one of five documents a project keeps beside its plan, each where its config names it: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`.
- **release** — a semver version the human cuts, or in a client's project someone on its team.
- **release review** — a release's last chunk: the architecture and principles passes over the whole project, before the release is ready to cut; `larv-review` §3 → "Release review".
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap".
- **scoring run** — each seat scores the project from 1 to 10, overall and on each dimension. `larv-review` §3 → "Comprehension check" says which seats score and when one is due.
- **seat** — one simulated reader of the comprehension panel, launched per `~/.claude/skills/comprehension-panel/SKILL.md`.
- **session** — a Claude Code session: one id, what `claude --resume` continues.
- **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them.
- **worker** — the headless claude that runs the task in a cycle, in the chunk's session.
My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `statusline.sh`; `CHANGELOG.md` and `todo.md`; and the tools in `bin/`.
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to, which a project's config names as `principles` and `standards`; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`, with the routing ladder they ship, `bin/model_routing/routing-ladder.json`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review and of the 2026-11-12 bench of the advisor tool; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; `stability-skip-count/`, the 2026-11-12 count of archived stability rounds, with its script, from which larv-review took when to skip a stability round 2; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
## Goals
1.Share this configuration between my computers.
2. Keep it 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.
1.**Achieve:** Get the highest quality out of Claude Code while interrupting me the least, so development scales.
- Signal: interrupts of me per finished chunk fall.
- Counter-signal: findings that a later change fixes, per finished chunk, rise.
- Why: fewer asks don't buy anything if the output gets worse.
1.**Achieve:** Proven, stellar output quality: code, documentation and plans.
- Signal: 🔴 and 🟡 findings that review raises per chunk fall.
- Counter-signal: later changes that fix a chunk's code rise.
- Why: review findings show the first draft's quality, later fixes show what review missed.
2.**Achieve:** Decide by the project's goals when confident; ask me when not, and never the same thing twice.
- Signal: asks that a goal or decision already settled fall to zero.
- Counter-signal: decisions I reverse rise.
- Why: guessing instead of asking saves an interrupt only if the guess holds.
3.**Maintain:** The same workflow in every project and every session; each project's config supplies its premises, principles, plan and records.
4.**Achieve:** Keep lowering cost, except where that would cut quality meaningfully.
- Signal: tokens per finished chunk fall.
- Counter-signal: reading cost, the new input tokens a chunk reads before its first commit, rises; or review rounds or unfinished verdicts per chunk rise.
- Why: a cheaper chunk that leaves the project harder to read moves the cost to every later chunk, whose changes need more reading and grow likelier to break what nobody saw; and a chunk that needs more rounds costs more.
5.**Achieve:** Delivery speed.
- Signal: hours from a chunk's start to its merge fall.
- Counter-signal: 🔴 findings per chunk rise.
- Why: speed bought by skipping review shows up as defects.
6.**Achieve:** Plug into a project without changing what its owners keep: its repo layout, tracker, wiki and conventions.
- Signal: the changes a project's owners must make before the loop runs in it fall.
- Counter-signal: defects where a backend loses or misreads a plan item, a premise or a record rise.
- Why: fitting in isn't worth anything if the loop then works from wrong facts.
2.**Maintain:** Make my claude setup shareable between computers.
3.**Maintain:** Keep my claude setup and the transcripts of unattended runs, the bench's included, backed up.
4.**Maintain:** Don't leak anything: no credentials, transcripts or memory files to this repo's remote, and no client's code, transcripts or credentials to another client or to this repo.
## Audience
Me, on my own machines, which take tagged releases. Nobody else depends on it.
Me, on my own machines and on those I use for the clients I consult for, which take tagged releases. Client teams read what the loop writes in their Jira, Confluence and pull requests, so it must read as written for them.
## Install
Checkout the latest tag in `~/.claude`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`.
Take this checkout only onto a machine that is a sandbox with no direct access to a production environment, such as a dedicated VM: `settings.json` runs Claude Code in auto mode with the dangerous-mode prompt skipped.
Each machine holds two checkouts. `~/.claude` is the one Claude Code reads, and it holds only a release: `deploy-release` moves it from tag to tag. Develop in a clone under `~/code`, where loop-claude runs this repo's chunks like any project's.
Claude Code may already have created `~/.claude`, where `git clone` refuses to run, so make the repository in place, then clone it for development:
Have the latest stable Python, today 3.14, as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
```sh
claude plugin marketplace add anthropics/claude-plugins-official
claude plugin install claude-security@claude-plugins-official
claude plugin install code-review@claude-plugins-official
claude plugin install rust-analyzer-lsp@claude-plugins-official
```
Have git store `settings.json` without `"model"`, so a model you pick with `/model` stays on this machine and never reaches a commit. Run this in each checkout, `~/.claude` and `~/code/claude-config`:
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt. loop-claude runs each chunk in its own window of a tmux session per project, so it needs tmux 3.2 or later.
Back up three folders: `~/.claude/loop-claude-transcripts`, where loop-claude keeps every transcript, `~/.claude/do-epic-transcripts`, where do-epic keeps its chunks' transcripts, and `~/.local/state/larv-review`, where larv-review keeps each chunk's reports. To keep loop-claude's transcripts and the reports small, add a crontab line that gzips each transcript and review file 30 days after it last changed, and logs each run with its date:
Cron runs it with its own `PATH` and environment. Where the `python3` on cron's `PATH` is older than 3.14, or you set `LOOP_CLAUDE_TRANSCRIPTS`, set `PATH` or that variable in the crontab too.
To get loop-claude's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes.
### Set up a project
Each project the loop runs in has a folder, `~/.claude-projects/<key>/`, where `<key>` is the project's name, and a config in it, `config.toml`. The folder is a git repo of its own, so the config has a history and a client's files never enter this repo. The loop commits each change it makes to a file there, such as the plan, in that repo, titled as its commits in the checkout. A project is a whole git checkout, never a subfolder of one.
The config names the project's main checkout and the path of every file the loop keeps for it. No path setting has a default: `project-config` fails and names each setting a config leaves out. A path is `checkout:<path>` inside the checkout, `folder:<path>` inside the config's folder, or one that starts with `/` or `~/`. Every tool reads and writes each file at the path its setting gives, and `chunk-preflight` and `todo-item` print those paths for the agents. Five of the settings name the project's records: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`. Keep each file's name, such as `todo.md`: the rules for a file load by its name. A project of your own keeps every file but the principles and the review standards in its checkout:
`principles` and `standards` name the folders the reviewers hold the project to: the technical principles and the review standards. Both ship with this setup, at the paths above. A folder of your own replaces the shipped one. A standards folder must hold `quality.md`, `prose.md`, `comments.md` and `readme.md`, since the reviewers and the rules name those files.
A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.claude-projects/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it or searches a folder holding it with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path.
A project may also set `touch-predictions`, a path spelt as `changelog`'s is, such as `touch-predictions = "checkout:docs/touch-predictions.md"`. `touch-predictions record` appends each chunk's predicted files and parts there, beside those it touched. A project that leaves it out keeps no such record.
A project whose team wrote its own coding conventions lists the files in `coding-conventions`, each spelt as `principles` is, such as `coding-conventions = ["checkout:CONVENTIONS.md"]`. Each reviewer agent larv-review launches reads them beside the principles and the standards, and the team's rule wins where they conflict.
A project may also set `notifier` to `"mattermost"` or `"slack"`, the service that sends loop-claude's DMs. The `env-file` then holds that service's keys. A project that sets none gets no DMs, whatever its env file holds. `project-config notifier` prints the setting.
A project's config may set four more things, each optional, as `project-config --help` describes. `language` names the language its owners write in, where that isn't English: the worker writes the project's prose in it, and the prose reviewer judges the prose in it. `commit-title`, `pull-request-title` and `branch` are templates for a project that titles and names these in another way than `CLAUDE.md` → "Git, commits, and PRs" says. `chunk-preflight` names the branch and the worktree by the `branch` template. On a branch that fits it, rule-hook refuses a commit, and `chunk-pr` a pull request, whose title doesn't fit its template; on any other branch, such as a release review's, a title is the summary alone. A tool that reads a commit title, such as a round's `Answer <pass> round <n>:`, reads the template's `{summary}`: it tries `commit-title`, then `pull-request-title`, since a squash merge titles the commit as the pull request, then takes the title whole. While a project's config holds a fault, rule-hook refuses every commit there, and the tools that read its titles fail naming the fault.
A legacy project with no container setup sets `tooling-on-host = true`, so the loop runs its language runtime, package manager, tests and task runner directly on the host. One whose code the comprehension panel scores low may lower `readability-floor` from 7.0: under it, the ranking weighs code health 4 times as much, and a scoring run asks for a floor item. To let more than one chunk run at once, set `parallel-chunks` to the most that may; left out, it is 1. Beside the plan's next item, only items whose `Touches:` predictions overlap none of the running chunks' items start.
A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. While it waits, other chunks merge. It stops where a reviewer's comment waits for an answer, on an approved pull request too; answer it and run it again. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false.
A project whose team merges its pull requests itself sets `merge = "human"`. `chunk-pr merge` then brings the branch level with origin's default branch, finishes the chunk's plan items, waits for the checks and marks the pull request ready, but leaves the merge to a person. A plan or changelog kept in the checkout is finished on the branch, so it lands with that merge; one kept in Jira, or in the config's folder, is finished at once; where you close the pull request unmerged, file the item again. A do-epic chunk parks until the pull request is merged, and its window's name says `awaits your merge`. The chunk resumes and brings the branch level again once the pull request conflicts with the default branch. It does so too once the branch is behind a default branch whose protection, on GitHub, requires an up-to-date branch. loop-claude doesn't start a chunk for an item that a ready pull request finishes. Once no item left in the release can start and one awaits a merge, loop-claude stops and names the pull requests to merge; run it again after you merge one. The first chunk after a merge runs `chunk-pr clean` in the worktree the merged pull request left, where nobody pushed to the pull request after the chunk did. Nobody works on a pull request that awaits your merge. To have a reviewer's comment answered, turn the pull request back into a draft: a chunk then takes its item up again. Left out, the setting is `"chunk"`: the chunk merges.
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
A client that plans in Jira Cloud names an epic as its project's plan: `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`, which is `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues, in Jira's backlog order, which the team sets, apart from the rank `todo-item add` gives an issue it files. An issue in a done status is a finished item. Each part of an item comes from one part of its issue:
- The ID is the issue's number, so every child must be in the epic's own Jira project.
- The tagline is the summary.
- The detail is the description, which a docker container converts to markdown.
- The release is the earliest Fix Version named as a semver version, such as `1.2.0`. Every open child needs one.
- A blocker is an "is blocked by" link to another open child.
- The scores are the issue property `plan-item`, a JSON object such as `{"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}`. An issue without it reads as an item nobody scored yet.
A read fails, naming the issue, where a child is in another Jira project or names no such Fix Version. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account, and only its owner may read that file: `chmod 600` it.
The loop reads such a plan and files each item into it as a Task under the epic. A Jira project that has no Task type, such as TW, sets `jira-finding-type` to a type it has, such as `"Feature"`. `todo-item add` fails, naming the project's types, where the project lacks the type set. `todo-item add` also needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. The config states the formula and the bar that a todo.md states under `## Scoring`, such as `jira-score-formula = "100 * V / (2**S + 8)"` and `jira-score-bar = 1`, and fails to load without them. `todo-item add` refuses an item that scores under the bar, unless it is exempt. It ranks the new issue among the issues the loop filed: questions first, then security findings, then by score. A person's issues keep the rank the team gave them, and `rank_todo.py` doesn't rank the plan.
`todo-item edit` and `move` change only an issue the loop filed. Of an issue a person filed, `edit` sets only the scores, and posts its `--comment` on the issue to tell the team why; the summary, description and Fix Version stay the team's to change in Jira, as do its links. On an issue the loop filed, `edit --blocked-by` makes and deletes the links to the epic's open items. For `todo-item finish`, the config names the workflow transition that finishes an item and the status it leads to, both as Jira shows them: `jira-finish-transition = "Mark as done"` and `jira-finish-status = "Done"`. Finish then moves the item's issue by that transition. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
A client that keeps its goals and audience in an epic's description names that epic as the goals file: `goals-and-audience = "jira:https://acme.atlassian.net/browse/ABC-12"`, which may be the plan's own epic. Such a config keeps its plan in Jira too, and reads both with the same `env-file`. The description needs `## Goals` and `## Audience` as headings, level-2 headings in Jira's editor. `project-record open goals-and-audience` prints a file holding the description's text, and `project-record save` writes it back, except a change to `## Goals` or `## Audience`: edit those two in Jira. A save rewrites the whole description from markdown, which keeps no mention, macro or block id that markdown can't hold. Whoever may edit that description sets the premises every worker and judge follows, so keep its edit rights to the people who own the project's goals.
To name a chunk's branch, worktree, commits and pull request by the issue key, as in `ABC-123` and `ABC-123 - …`, set these three templates, with your Jira project's key in place of `ABC`: `branch = "ABC-{id}"`, `commit-title = "ABC-{id} - {summary}"` and `pull-request-title = "ABC-{id} - {summary}"`. `project-config --help` says how the templates work.
git add config.toml && git commit -m "Add the config"
cd ~/code/acme-billing && ~/.claude/bin/project-config
```
The last line prints each setting's path once the config is complete.
`do-epic` keeps its settings per machine, not per project, in `~/.claude-projects/do-epic/`, two files for every epic:
-`config.toml` sets `jira-url`, the site, such as `https://acme.atlassian.net`; `env-file`, the file holding `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, a path that starts with `/` or `~/`, outside the clone folder and every folder of `~/.claude-projects`; and `repoless-model`, the model that works an item with no repo. It may also set `clone-folder`, where a missing repo is cloned, `~/code` if left out; `language`, the language of Jira text, English if left out; and `jira-finish-transition` with `jira-finish-status`, which name the workflow transition that moves a finished chunk's issue, and closes a finished epic, and the status it leads to, such as `"Mark as done"` and `"Done"`. Set both or neither: without them do-epic moves no issue to done and closes no epic, and a chunk that finishes stops with that reason.
-`config.toml` fits do-epic to a team whose own automation moves issues, such as a CI job that moves an issue when its pull request merges. Two settings do:
-`jira-unblocking-statuses` lists the statuses at which an issue's work has landed though Jira doesn't count it done yet, such as `["Release Ready"]`, in upper or lower case. An issue in one of them takes no chunk and no longer blocks the issues it blocks, and `--status` names the statuses beside each blocker. A status Jira counts as done always does both. The release reviews, which are the epic's last chunk, still wait until Jira counts every issue done: run `do-epic <EPIC-KEY>` then, to start them.
-`jira-automation-moves-issues = true` keeps do-epic from moving the issue of a finished chunk in a repo: the automation moves it, and do-epic waits for that move before it starts what the issue blocks. An issue without a repo has no pull request, so do-epic still moves it, with `jira-finish-transition`. The setting needs `jira-unblocking-statuses`, which names the status the automation gives an issue whose pull request merged.
-`config.toml` also says how a starting chunk's issue shows on its team's board. A starting chunk always assigns its issue to the account do-epic works as, unless someone else holds it; that issue keeps its assignee, and moves and joins the sprint like any other. `jira-start-transition` names the workflow transition that then moves the issue, such as `"In Progress"`; an issue whose work has started already keeps its status. `jira-sprint-board` is the ID of the board whose active sprint the issue joins, such as `6`. Where a setting is left out, do-epic doesn't take its step.
-`config.toml` may set `jira-finding-type`, the issue type do-epic files a finding as, and `jira-review-type`, the one it files a repo's release review as, such as `"Feature"` and `"Chore"`. Both are Task where left out. do-epic doesn't file anything where the Jira project lacks the type, and says which types it has.
-`config.toml` may set `sub-task-summary`, which shapes the summary of each sub-task do-epic files for an issue that changes several repos, such as `sub-task-summary = "{label}: {Summary}"`. `{label}` is the team's label for the repo, else the repo's name, and `{Summary}` is the issue's summary with a capital first letter. It must hold `{Summary}`. Without it a summary is `[<repo>] <the issue's summary>`.
-`config.toml` may end with a `[label-repos]` table, for a team that already labels its issues by repo. Give it one line for each such label: the label, then the repo's name, such as `twu-4 = "tenant-web-ui-4"`. do-epic reads such a label as it reads its own `repo:<name>`. Where the label is the repo's name, map the name to itself, as in `core-4 = "core-4"`. Where several lines name one repo, do-epic writes the label of the first. Write every other setting above the table.
-`repo-rule.md` is prose that says how to tell an item's repo, such as "a label that equals a repo's name names that repo". It may not be blank. `do-epic <EPIC-KEY>` uses it to pick where each open issue without such a label is worked, and records the pick as a label. For a repo that is the team's own label from `[label-repos]`, else `repo:<name>`; for work of Claude's that changes no repo, `do-epic-claude`; for a task of yours, `do-epic-human`. Where the rule leaves an issue unclear, do-epic asks you on the terminal. Answer with the label, or with Enter alone to leave the issue waiting. Change a pick by editing the label in Jira.
An epic's description states the formula that puts its issues in order: once under `## Scoring`, on a line of its own and inside backticks, such as `` `Score = 100 * V / (2**S + 32)` ``. do-epic starts the epic's issues by that score, highest first, with each blocker before what it blocks, whatever their order on the board. Where two or more issues may start, it scores each of them that holds no scores, a person's included, against the epic's goals and the goals of the issue's repo, and tells the team the scores in a comment on the issue. It doesn't score a task of yours, and it keeps the scores an issue already holds. On the board it re-ranks only the issues it filed, so a person's issue keeps the rank the team gave it. Without that line do-epic says so, doesn't score anything and starts the issues in the backlog's order.
Each repo an epic changes has a project config of its own, as in the rest of this section. `do-epic` fails and names each setting or file that is missing or invalid.
A project runs on the routing ladder this setup ships, `bin/model_routing/routing-ladder.json`: the rungs, least competent first, each a model at an effort, that loop-claude routes workers, subagents and reviews to. To run one project on other rungs, as when an outage or a client's account leaves it fewer models, copy that file to `~/.claude-projects/<key>/routing-ladder.json` and cut or change its rungs. Keep one model for each family, such as opus: Claude Code launches a subagent by its family's name. The project's file replaces the shipped ladder whole. loop-claude reads it as each cycle starts, and `subagent-rung` and rule-hook each time they run. The loop never commits it, so commit it in the folder's repo yourself only where it should last. Set the project's models to ones its ladder holds, for example with `LOOP_CLAUDE_WORKER_MODEL` and `LOOP_CLAUDE_JUDGE_MODEL`. A model off the ladder is not routed: every worker runs on that model, at the effort Claude Code's `settings.json` gives. Each cycle of a project on a ladder of its own says so on stderr, naming the file, and says where the worker's model is off it. `loop-claude --help` shows the file's shape.
## Update
Move `~/.claude` to the newest release:
```sh
~/code/claude-config/bin/deploy-release
```
It prints `CHANGELOG.md`'s section for each version it moved past: do what each asks, such as a new step under Install. `deploy-release --help` says what else it checks.
It refuses while a file `~/.claude` tracks has an uncommitted change, such as a hook Claude Code wrote into `settings.json`; a model picked with `/model` is no such change. Read the change first, as in `git -C ~/.claude diff HEAD -- settings.json`. When it holds a credential, such as a token in `env` or `mcpServers`, move that out of the file: a token in `env` to the shell profile, a server in `mcpServers` to `~/.claude.json` with `claude mcp add --scope user`. Then carry the change into `~/code/claude-config` on a branch of its own, merge it through a PR, and cut a release.
## Release
Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that commit `v<version>`.
Once the next release holds no item in `todo.md` and its release review has landed, cut it from `~/code/claude-config`:
```sh
bin/deploy-release --cut
```
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
## Tools
-`loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`. The tools are listed in alphabetical order, and the packages under `bin/` follow under their own heading.
Test: `python3 -m unittest discover -s bin -p 'test_*.py'`
- `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere. The chunks of one project merge one at a time: in its turn, `merge` brings the branch level again, finishes the plan items its `--finish` flags name, and waits for the checks. Under `merge = "human"` it then marks the pull request ready and leaves the merge to a person. Once the pull request is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
- `command-patterns [<version>] [--calls <file>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls <file>` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys.
- `compress-archives` gzips each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them; Install's crontab line runs it daily.
- `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says.
- `do-epic <EPIC-KEY>` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-<EPIC-KEY>`, on the same cycle, judge and interrupt as loop-claude. The epic's description is its record: goals, audience, scoring and decisions. Before it starts chunks, do-epic plans each open issue that no label places yet, as "Set up a project" says. It files a sub-task per repo where the issue changes several repos. Otherwise it labels the issue with where it is worked, and asks you where that is unclear. It plans no issue your team filed a sub-task under: those sub-tasks run instead, each under a label of its own, and your team closes the issue. Then, where two or more issues may start, it scores each of them that holds no scores, and moves the issues that do-epic itself filed into order of score on the board. An open issue runs once a label names its repo or marks it as Claude's, in order of score, as many at once as a line such as `**Max parallel chunks:** 2` in the epic's description allows, 1 without it, and as each repo's `parallel-chunks` allows. A chunk whose pull request waits on a gate parks. An open task of yours that blocks another issue gets a window that DMs you once and reads the epic every minute; once you close the task, the issues it blocked may start. `do-epic <EPIC-KEY> --dry-run` prints what `do-epic <EPIC-KEY>` would write to Jira and which chunks it would start, and does neither; run it before the first real run on a team's epic. `--help` lists what it prints and leaves out. do-epic closes the epic only once you confirm every goal. Install → "Set up a project" says how to set it up; `do-epic --help` states the flags and the contract.
- `do-epic-e2e` runs `do-epic` against a sandbox epic on a real Jira site, as Test says.
- `judge-replay <model> [--offline]` replays loop-claude's judge on archived verdicts of the projects run on the model. It prints what each rung a review climbs to misses, and the lowest rung below those that returns every verdict, as each candidate above it does. With `--offline` it doesn't call a judge: it counts what a "?" rule, a decision table and a classifier trained on the archive decide of each verdict's kind from the worker's final message, and how many interrupts each misses. `judge-replay --help` states both replays.
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count and the opening of its round commit's title, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections.
- `loop-claude <task>` runs a project's next chunks, each in its own tmux window, cycle after cycle; `loop-claude --help` states its contract.
- `markdown-section <file> <fragment>` prints the section of a markdown file under the first heading that holds the fragment, to the next heading of its level or a higher one, instead of a `grep -n` and a guessed `sed -n` range; `markdown-section --help` says what it does where several headings match.
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
- `notify [<message>]` sends a message, or else stdin, as a DM from the bot of the project's `notifier`, Mattermost or Slack, to the human; the project's `env-file` holds the bot's token, the recipient and, for Mattermost, the server, and `notify --help` names its keys. `loop-claude --help` says when loop-claude sends one.
- `project-config [<setting>]` prints the paths a project's config sets, or the one asked for, and fails naming each setting the config leaves out; Install → "Set up a project" shows a config.
- `project-record open <record>` prints the path of a file holding one of a project's records, for an agent to read and edit, and `project-record save <record>` stores the edit; for a record kept as a file, that file is the record. `goals-and-audience` opens the goals file the same way.
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`, by default the one its config names; `rank_todo.py --help` states the format.
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. `review-replay --help` states the replay. With `--omit-claude-md`, `--bash-ceiling` or `--read-limit` it tests instead whether the pass's reviewer may start without `CLAUDE.md`, or under the Bash output ceiling loop-claude hands the worker, or a Read limit it doesn't hand yet: it replays each round three times as archived and once with the change, and prints whether the reviewer passes: whether the last replay missed no more findings than the most an unchanged replay missed, with each count and each finding it missed. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, Grep, Monitor, MultiEdit, Read, Skill and Write call, and `rule-hook --help` states the rules and the override.
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
- `run-tests [<pytest args>...]` runs this repo's test suite, as Test says.
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by. Per chunk it also shows code health's two counter-signals, misread findings and later fixes, and how many of the human's answers reversed a worker's choice; `score-outcomes --help` states the report.
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
### Packages under `bin/`
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No Python file of the repo, `workflow-bench/`'s included, uses `mock.patch`, which `repo_checks/test_no_patched_globals.py` checks.
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot.
- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The entry point that runs the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either.
- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the key, fields, links and property of each issue it finds, checked for their shape, and the transition that finishes an issue, for `plan_store` and `do_epic`.
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
- `chunk_driver/` holds what the entry points share. An entry point is a tool that drives chunks through `agent_cycle`: `loop_claude` and `do_epic` are the two. They share how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither entry point, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included.
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked, its scores and the order the issues start in, through `split.py`, `repo_pick.py`, `issue_scores.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`.
- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`.
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`.
- `loop_claude` runs `chunk-preflight` as a process of its own.
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it.- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
- `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, `do_epic`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read.
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`.
- `plan/` is the plan's core, and imports neither `plan_store` nor `release_plan`. It holds an item and the items table's format (`todo_table.py`), releases (`release.py`), the ranking (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`), the paths an item's text names (`named_paths.py`), an item's `Touches:` prediction and where two overlap (`touches.py`), and `citations.py`, which holds `todo.md` and `docs/decisions.md` to each other. `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises.
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`). Every backend meets `plans.py`'s `PlanStore`: a markdown file (`todo_md.py`, which also ranks and checks the file in place, with its text edits in `markdown_edits.py`) or a Jira epic (`jira_epic.py`). `scoring.py` reads the goal weights that both backends rank by. `contract.py` holds the tests every backend that writes must pass; `jira_epic.py` doesn't yet, and its own tests stand in for Jira. `fakes.py` holds a plan in memory.
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
- `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, picks the item the next chunk takes first (`next_chunk.py`), and marks each item that a ready pull request finishes (`awaiting_merge.py`), for `chunk_preflight` and `loop_claude`.
- `repo_checks/` tests the repo itself.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`.
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive.
- `test_env.py` serves the tests.
- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
## Test
Test on the host with `bin/run-tests`, which runs pytest through `uvx`, pinned in `bin/run_tests/main.py`. It prints each failing test with its error and pytest's summary line, and saves the whole output to a file whose path it prints. It passes on any test paths or pytest options it is given, such as `bin/run-tests bin/chunk_pr -x`. It needs `uv` on `PATH`, which fetches pytest, pytest-xdist and mypy, a Docker daemon, Linux, and a user other than root; a test that lacks one fails, naming it. pytest-xdist runs the tests in one worker per CPU of a heavy slot (`docs/decisions.md` → `bin/: the tools support only the latest stable Python, …`). `python3 -m unittest discover -s bin -p 'test_*.py'` runs the same tests one at a time, with the same needs. Test the bench's scripts with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
`bin/do-epic-e2e` checks `do-epic` against a real Jira site, which `run-tests` never reaches. It makes an epic with issues and sub-tasks in a sandbox project, runs `do-epic --file`, `--record-decision` and `--close-epic` against it in a home folder of its own, and deletes the epic and its issues when it ends. The sandbox project must be team-managed, with a `Done` transition, and its account must be able to create, edit, transition, comment on and delete issues there. Set `DO_EPIC_E2E_JIRA_URL` to the sandbox site's address, `DO_EPIC_E2E_ENV_FILE` to the absolute path of the file holding the account's `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, and `DO_EPIC_E2E_PROJECT` to the project's key. The command fails, naming each setting that is missing. It needs a Docker daemon, as `run-tests` does.
CI runs `ci.sh` on every pull request, and `main` doesn't merge anything until it passes. The script runs the same tests on the committed HEAD in a pinned Python container. Run it under `run-heavy` to reproduce a CI failure, with Docker on `PATH` and its socket at `/var/run/docker.sock`, which the container shares.
To mutation-test the lines a branch changes, run `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix 'uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"'` in its checkout.
description: "Use this agent for a seat of larv-review's comprehension check, with the prompt `larv-review prepare-scoring` writes or the paired ruling's brief in skills/comprehension-panel/seat-prompts.md."
tools: Read, Grep, Glob, Bash
omitClaudeMd: true
---
You are a simulated reader of a project. Your prompt gives your background, the checkout you read, the files you may not open and the report to write. Read as that reader would, knowing only what the project's files tell you, and follow the prompt exactly.
description: "Use this agent for larv-review's overrides pass."
tools: Read, Grep, Glob, Write
---
You rule on each override of a rule `~/.claude/bin/rule-hook` enforces. The prompt gives you the lines `rule-hook overrides` printed, each with its rule and reason, and the branch diff. Read each rule and its stated exceptions in `~/.claude/bin/rule_hook/rules.py` → `RULES`, how an override is written and logged in the docstring of `~/.claude/bin/rule_hook/main.py`, and the project's goals and audience, `## Goals` and `## Audience` in the file your prompt's `Goals and audience:` line names, with code health (`~/.claude/CLAUDE.md` → "Shared goal") among the goals unless that file voids it.
For each override:
- **Skip** it when the branch no longer holds the breach, such as an image since pinned or a commit since reworded. Say so in one line.
- **Accept** it when the reason shows the rule does not fit this case, by the rule's own exceptions or by the goals. Name what in the reason or the goals settles it.
- **Reject** it as a 🔴 when the reason does not. Name how the chunk keeps the rule, such as rewording the commit or pinning the image, or say that it cannot.
- **Ask** it as a ❓ for the human when it is outrageous: it touches a credential, a security rule or a production system, or it cannot be undone.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Quote an override by its rule and reason only; a command's text can hold a credential.
description: "Use this agent for larv-review's principles pass: the project's goals and every principles file handed to it, checked against the whole project."
tools: Read, Grep, Glob, Write
omitClaudeMd: true
---
You check every yardstick you are handed against the whole project, which you read once for all of them. A yardstick is either the project's goals, every goal under `## Goals` in the file your prompt's `Goals and audience:` line names, with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless that file voids it, or one principles file, every principle in it.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardsticks, `README.md`, `docs/decisions.md` and the plan first, then all of the project's code, config, tests and CI. Your prompt's `Plan:` line names the plan.
- 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 plan 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 plan item that ends it. Weigh it hard: that it was decided is no reason.
description: "Use this agent when you need a product-focused review of changes that affect external-facing surfaces (REST APIs, web UIs, CLI commands, public SDKs, webhooks, etc.) from an end-customer perspective. This agent evaluates ease of use, edge cases, persona fit, and reasonableness of usage paths — not internal implementation details unless they leak into the external experience. Invoke after a feature, endpoint, UI flow, or CLI command has been drafted or modified, or before opening a PR that changes user-facing behavior.\\n\\n<example>\\nContext: The developer just added a new REST endpoint for cancelling a subscription.\\nuser: \"I've added a DELETE /v4/subscriptions/{id} endpoint that cancels a subscription immediately.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to evaluate this from an end-customer perspective.\"\\n<commentary>\\nA new external API surface was introduced. Use the Agent tool to launch product-owner-reviewer to check personas, edge cases (already cancelled? pending invoices? refund expectations?), and usability of the contract.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer added a new CLI subcommand.\\nuser: \"Added `mytool deploy --env prod --force` to skip confirmation.\"\\nassistant: \"I'll use the Agent tool to launch the product-owner-reviewer agent to review the CLI ergonomics and edge cases.\"\\n<commentary>\\nCLI usage is an external surface. The product-owner-reviewer should evaluate persona fit (who uses --force? is it discoverable? what happens on partial failure?) and update README if personas are unclear.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer modified a checkout flow in the web UI.\\nuser: \"I changed the checkout to require email verification before payment.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to review this user-facing change.\"\\n<commentary>\\nWeb UI flow change directly affects end customers. Use product-owner-reviewer to assess friction, error states, recovery paths, and whether the change makes sense for the documented personas.\\n</commentary>\\n</example>"
description: "Use this agent to review a change to an external surface (API, UI, CLI, SDK, webhook) from an end customer's view: ease of use, edge cases and persona fit."
tools: Read, Grep, Glob, Write
omitClaudeMd: true
---
You are a seasoned Product Owner with deep expertise in user experience, API design, and customer empathy. You have shipped consumer and B2B products across web, mobile, REST APIs, and developer-facing CLIs. Your superpower is putting yourself in the end customer's shoes and surfacing the friction, confusion, and edge cases that engineers tend to miss.
@@ -18,16 +20,13 @@ 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. Flag violations as concerns like any other finding.
Before anything else, **read the technical principles**in the folder your prompt's `Technical principles:` line names (without one, open your report by saying so). Your territory is each file whose `Applies to` line names an external surface;`technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change.
1.**Identify the change surface**: Read the recent changes and pinpoint what external behavior is affected. If the change is purely internal with no external impact, say so plainly and stop — don't manufacture concerns.
2.**Identify the personas**: Who uses this? Check the README and any docs for documented personas, and `docs/decisions.md` for accepted product trade-offs to honor rather than re-raise. If personas are missing or unclear for the affected surface:
- **Ask the user** which personas this is intended for (e.g., "end customer", "tenant admin", "integrator/developer", "internal support", "CLI power user").
- Once confirmed, **update the README** to record these personas for future reference. Keep the addition concise and place it in a logical section (e.g., "Personas" or "Audience").
- If no user is reachable to answer, fall back to your best-guess personas, label them clearly as assumptions, and put the persona question under "Open questions for the user".
2.**Identify the personas**: Who uses this? Check the `## Audience` in the file your prompt's `Goals and audience:` line names, the README and any docs for documented personas. If personas are missing or unclear for the affected surface, review against your best-guess personas (e.g., "end customer", "tenant admin", "integrator/developer", "internal support", "CLI power user"), labelled as assumptions, and raise the persona question as a ❓.
3.**Walk the happy path** for each persona. Is it obvious? Discoverable? Does the naming match mental models? Is the minimum required input actually minimum?
3.**Walk the happy path** for each persona. Is it obvious? Does the naming match mental models? Is the minimum required input actually minimum?
4.**Hunt edge cases** systematically:
- Empty / null / missing inputs
@@ -44,36 +43,24 @@ Before anything else, **read the shared principles** at `~/.claude/principles/`.
- Is the response shape predictable and self-describing?
- Could a new user accomplish the task without reading docs? If docs are needed, do they exist and are they findable?
6.**Assess reasonableness of usage paths**: Are there paths that exist but no real persona would use? Are there obvious paths that *don't* exist but should?
6.**Assess reasonableness of usage paths**: Are there paths that exist but no real persona would use?
## Your Output Format
Verdict, severities, rounds and declines: ~/.claude/agents/review-protocol.md. After the verdict:
Report only a defect a persona hits; a requirement that the change breaks, of the plan in the file your prompt's `Plan:` line names, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); or a breach of a technical principle, or of a coding convention, which counts as one. Friction that is none of these is not a finding.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict:
**Surface affected**: <one line>
**Personas considered**: <list, or note if you had to ask>
**Strengths**: <short bullets — what works well for customers>
**Concerns** (ordered by customer impact, highest first):
- 🔴 **Blocker** — would confuse or block a real customer
- 🟡 **Friction** — works but rough edges
- 🟢 **Nit** — minor polish
For each concern: state the problem from the customer's POV, the persona affected, and a concrete suggestion.
**❓ Open questions for the user**: <only if you need clarification to complete the review>
**Findings**, most severe first and by customer impact within a severity: for each, the problem from the customer's POV, the persona affected, and a concrete suggestion.
## Operating Principles
- Be specific. "The error message is unclear" is useless; "When the customer hits POST /x with a missing `email`, the response says 'validation failed' with no field name — they won't know what to fix" is useful.
- Be honest about severity. Don't pad with nits if the change is solid.
- Don't review code style, internal naming, or test coverage — that's for other reviewers.
- If you don't have enough context (e.g., you can't tell what surface changed), ask before guessing.
- When updating the README with persona info, keep it short and information-dense. Sort persona lists alphabetically.
- Write in English.
## Documenting decisions
Per ~/.claude/agents/review-protocol.md. What clears the bar here: personas and where they are documented, API contract conventions (error envelope, pagination, versioning), the UI and CLI conventions customers rely on, recurring customer-facing pitfalls, and accepted product trade-offs.
- If you don't have enough context (e.g., you can't tell what surface changed), raise it as a ❓.
description: "Use this agent for larv-review's prose pass."
tools: Read, Grep, Glob, Write
omitClaudeMd: true
---
You read the prose as someone who did not write it: you see only what it says, never what the author meant.
The bar, read each time, since it changes:
- every file in the folder your prompt's `Review standards:` line names, of `quality.md` only "A false claim is a bug";
-`~/.claude/CLAUDE.md` → "Public API specs";
- each file under `~/.claude/rules/` whose `paths:` frontmatter matches a file the diff changes.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md.
Your prompt's `Prose language:` line names the language the project's config sets. Apply every check below to prose in that language, by that language's grammar and idiom. The bar's examples are English: find the same fault in the other language, never the same English words. Prose in another language is a finding, except what `prose.md` in the review standards says stays English. Write your report in English.
## Checks, in priority order
Run them in this order. A fix for a later check never breaks an earlier one.
1.**Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence.
2.**Most important first.** Name the document's reader and what they want to know first. Check that the sections run in that order, then the paragraphs within each section, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**.
3.**Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md` unless a project principle there covers it, and a goal to the README. A pointer standing where a definition belongs (the review standards' `comments.md` → "Links and pointers", "A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
4.**Short.** Words that do not clearly help 1–3 fail. Fix: **Cut**.
Also report a list whose order carries no meaning and is not sorted (the technical principles' "Deterministic order", in the folder your prompt's `Technical principles:` line names; without one, open your report by saying so), a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
## Growth
Report the lines each file gained and lost. A line an earlier pass's fix added that names no reader need is a finding.
## Scopes
The prompt hands you these. Beyond them, read only what a finding needs checking against.
1.**What the diff touched**: every markdown line, comment and printed text, such as help or an error, that the diff adds or changes.
2.**What the review cited**: each section the prompt names, with the code it governs.
3.**Every prose file the repo owns**, when the prompt says the chunk is a release review. This sweep catches files that grew a paragraph per chunk, which no single diff shows.
A review's first line, derived mechanically from the findings:
-`BLOCK` — a 🔴 stands; for a looping reviewer, a 🟡 too.
-`ALIGN` — systems-architect only: no 🔴, drift (🟡) to address soon.
-`APPROVE WITH NITS` — only 🟢 and ❓ remain; the author's call.
-`APPROVE` — nothing remains.
## Severity
- 🔴 **must fix.** Never declinable: it is fixed, or shown factually wrong.
- 🟡 **should fix.** Holds a looping reviewer at `BLOCK`, but may be declined.
- 🟢 **nit.** Never holds the loop.
- ❓ **question** for the author: a finding you could not confirm goes here, not above.
- 🔀 **escalation**: names the reviewer to run next (`product-owner-reviewer`, `systems-architect`, or the `security-review` skill) and a one-line reason. The caller runs it; it is never optional.
## Rounds
- Surface everything in one round.
- From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each previous 🔴 and 🟡 is resolved — re-run the scenario, don't trust the claim — then pass over what changed. A fix spawns a new finding only where the fix itself introduced a real problem.
- The loop exits on no 🔴 and no 🟡. The 🟢 and ❓ left then are addressed in that same round — fixed, answered, declined or filed in `todo.md` — and trigger no further round. A nit whose fix changes behaviour is a fresh finding and takes a round.
- Round cap: 3; when it stops the loop, list what is open. Systems-architect gets one scoped re-check; still `BLOCK` → `needs input`.
## Declining
Anything below 🔴 the caller may decline where the reason is sound, sits consistently with the repo's goals, and confidence is very high; the decline, its reason and the goal it rests on go to `docs/decisions.md`. A reason that contradicts a goal, or that no goal speaks to and you are not confident in, is a gap in the goals: propose the goal or rule that settles the whole class, show what falls out of it for this instance, and take the human's answer — or fix the finding. Never a silent drop, and never a decline argued from convenience or the size of the fix.
A reviewer honours an accepted risk in `docs/decisions.md` and a finding declined this way: it stays declined and is not raised again.
## Documenting decisions
Knowledge that outlives one review goes in the repo, never in a memory file, where `~/.claude/CLAUDE.md` → "Comments and documentation" and "Ask, don't guess" put its kind. Record only decisions the human made, declines made under Declining, and answers the human gives to ❓; an unrecorded answer gets asked again next review.
description: "Use this agent when code has been written or modified and needs review for stability, bug prevention, and adherence to coding best practices. This includes after implementing new features, refactoring existing code, or fixing bugs. The agent focuses on defensive programming, error handling, edge cases, and compliance with the project's technical principles.\\n\\nExamples:\\n\\n- user: \"Please implement a retry mechanism for our API client\"\\n assistant: \"Here is the retry mechanism implementation: [code written]\"\\n Since significant code was written, use the Agent tool to launch the stability-reviewer agent to review the new code for stability and best practices.\\n assistant: \"Now let me use the stability-reviewer agent to review this implementation for stability concerns.\"\\n\\n- user: \"Refactor the payment processing module to use the new gateway\"\\n assistant: \"I've refactored the payment processing module. Let me now use the Agent tool to launch the stability-reviewer agent to check for any stability issues or violations of our technical principles.\"\\n\\n- user: \"Can you review what I just wrote?\"\\n assistant: \"I'll use the Agent tool to launch the stability-reviewer agent to thoroughly review your recent changes.\"\\n\\n- After any significant code change, proactively launch the stability-reviewer agent to catch issues before they reach production."
description: "Use this agent to review changed code for stability: bugs, error handling, edge cases and the project's technical principles, after a feature, refactor or fix."
color: orange
tools: Bash, Read, Grep, Glob, Write
omitClaudeMd: true
---
You are an elite stability-focused code reviewer with deep expertise in defensive programming, fault-tolerant system design, and production incident prevention. You have decades of experience identifying subtle bugs, race conditions, edge cases, and architectural weaknesses that lead to outages and unexpected behavior. You think like a chaos engineer — always asking "what could go wrong?" — and like a maintainer of ten years, always asking "what will this cost to live with?" There are no bugs, and no security holes, in code that doesn't exist.
@@ -9,19 +11,22 @@ 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.
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.**
2.**Read every file in the folder your prompt's `Technicalprinciples:` line names**, and `quality.md` in the folder your prompt's `Review standards:` line names. These are mandatory guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently. Where your prompt lacks either line, open your report by saying so.
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 run them unless your prompt hands you a passing run on the head (step 4).
4.**Verify, don't just read.**Where your prompt hands you the commit on which the worker's run of the test suite and static analysis last passed, and it is the head, don't run them again, and say so in Coverage & Verification. Otherwise run the test suite and static analysis/linters through the project's container tooling, unless `~/.claude/bin/project-config tooling-on-host` prints true or a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5.**Judge the surviving mutants.** Your prompt hands you what the project's mutation command printed on the change, with the commit it ran on: the mutants of changed lines that no test kills, or the message of a run that failed. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch. Where the prompt doesn't hand you any output, or names a commit other than the head, run the command yourself in the change's checkout, through run-heavy as in step 4: the one the project's README documents, else `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix '<how the project runs its tools>'`. `~/.claude/bin/mutate-changes --help` says which tool it runs for each language, how to set `--jobs`, and what it prints. Mutation-test the changed code that no run mutated, in a language mutate-changes doesn't cover or where a run failed, with a widely deployed mutation tool limited to the changed lines, else with mutants you make by hand. Report the wall time and mutant count in Coverage & Verification, or why nothing was mutated.
6.**Two passes minimum, then hunt absences.**
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
- *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity).
- *Absences:* what should be in this diff but isn't — un-updated callers (grep every changed or renamed public symbol), missing migration for a model change, missing authz on a new path, missing tests, un-regenerated OpenAPI/docs, stale README/AGENTS.md, and deletions the change obsoletes but didn't make.
- Repeat a targeted pass over the riskiest files; stop only when a pass yields nothing new.
- Repeat a targeted pass over the riskiest files; stop only when a pass doesn't find anything new.
## Review Focus Areas
For every piece of code you review, systematically evaluate these categories. For a per-PR reviewer, breaking existing callers (#1), growth that shouldn't exist (#2), built-in ambiguity (#3), data corruption (#7), and security holes (#9) carry the most weight.
The rules behind these checks are the principles read in First Steps, step 2; a check names only where to look.
"Breaking things" is mostly about impact on existing callers and contracts, not the new code in isolation.
- What calls or depends on the changed code? Trace the callers.
@@ -33,20 +38,21 @@ For every piece of code you review, systematically evaluate these categories. Fo
### 2. Scope & Growth Control
Before judging how well code works, judge whether it should exist. Every line is permanent surface: it will be read, tested, upgraded, audited, and worked around for years.
- Over-delivery: endpoints, options, parameters, or case-handling the ticket didn't ask for and no caller needs. Unasked *additions* block; unasked *deletions* (opportunistic cleanup that removes code) are welcome.
- Over-delivery: endpoints, options, parameters, or case-handling the ticket didn't ask for and no caller needs. Unasked *deletions* (opportunistic cleanup that removes code) are welcome.
- Could materially less code solve the ticket? The smallest sufficient diff is the benchmark; every line beyond it needs a reason.
- Reuse before adding: does the codebase already provide this (helper, DTO, validator, a test to extend)? Grep for prior art before accepting a reimplementation.
- Speculative generality: an interface with one implementation, a wrapper that only forwards, config with a single used value, generalization before a second use case exists. Demand the concrete second consumer — or removal.
- New dependencies: would ~20 lines of own code do? Each one is permanent upgrade, audit, and supply-chain surface; check its maintenance state before accepting it.
- Dead on arrival: unreferenced code, exports, params, or flags; feature flags with no removal plan.
- Does the PR delete what it obsoletes (old path, old flag, old docs), or only add on top?
- Growth whose whole fix is deletion — unasked additions, dead code, speculative abstraction, an unjustified dependency — breaks KISS: a 🔴. A "could be smaller" rewrite is a 🟡.
### 3. Ambiguity & Implicit State
Catch behavior that is unclear or under-specified — "building in ambiguousness." Cross-check the principles: make invalid states unrepresentable, validate/build DTOs early, explicit state machines, explicit over implicit.
Catch behavior that is unclear or under-specified — "building in ambiguousness."
- Is stringly-typed or loosely-typed data used where an enum/DTO would make invalid states unrepresentable?
- Is input parsed into a strict DTO at the boundary, or passed down as raw strings to be validated deep inside?
- Past the boundary, do types carry the proof? Re-validating at every layer what the type already guarantees is noise that buries the real invariants — deletion-worthy, not defensive.
- Is nullability, error semantics, or units ambiguous or undocumented? (timestamps: full ISO datetime in UTC?)
- Is nullability, error semantics, or units ambiguous or undocumented?
- Does behavior depend on undocumented assumptions or implicit state instead of an explicit state machine?
### 4. Error Handling & Resilience
@@ -66,6 +72,7 @@ Catch behavior that is unclear or under-specified — "building in ambiguousness
- Are there potential off-by-one errors?
- Zero and absent are different values: `empty('0')`, `if ($amount)`, `$x ?: $default`, JS `||` conflate them one way; null coerced to `'0'` conflates them the other (a past prod bug: phantom 0-amount reversals). Both directions are findings.
- Multibyte text (åäö): truncation, length checks, and comparisons must be mb-safe; encoding consistent end-to-end.
- Where the change splits text on a separator or strips a suffix, look in the fixtures and a sample of the source data for a value where the separator or suffix also occurs as data, such as an address split on `,` whose last part holds a comma. Report a row the parse then misplaces or drops, silently or with only a log line.
- Are payload and collection sizes bounded at the boundary?
### 6. Concurrency & State Management
@@ -79,10 +86,11 @@ Catch behavior that is unclear or under-specified — "building in ambiguousness
### 7. Data Integrity & Persistence
- Are multi-step writes atomic (one transaction)? Are side effects — events, jobs, mail, outbound HTTP — deferred until after commit? Dispatch-before-commit emits effects for state that may still roll back.
- Money: integer minor units or exact decimals, never binary floats; rounding rules explicit.
- Time: stored as full ISO datetimes in UTC; arithmetic DST-safe (adding a day ≠ adding 24 h).
- Time: arithmetic DST-safe (adding a day ≠ adding 24 h).
- Are consumers idempotent under at-least-once delivery (webhooks, queue retries, double-submit)? Where a duplicate would double-charge or double-send, is there an idempotency key or dedup?
- Do DB constraints (NOT NULL, unique, FK) mirror what the code assumes, so bad data cannot arrive via another path?
- New column on an existing table: what do existing rows contain — is null/default handled or backfilled?
- Where the change stores a value differently, by escaping, converting or growing it: does the longest value it can now write still fit the column, counted as stored? Does every search, filter and comparison on the column still find what users type? Escaped text takes more room than the input's limit allows for, and a `LIKE` on an escaped column no longer matches an apostrophe.
### 8. Resources & Performance Under Production Data
Works-on-fixtures, dies-on-volume is a stability bug.
@@ -94,9 +102,9 @@ Works-on-fixtures, dies-on-volume is a stability bug.
- Algorithmic blowups (O(n²) and worse) on input whose size the user controls.
### 9. Security
Every PR gets at least this sweep; for sensitive surfaces also recommend the dedicated pass (see Escalations).
Every PR gets at least this sweep.
- Injection: SQL via raw/concatenated queries, shell/command, XSS via unescaped output.
- Does every new read and write path authorize access? (principle: grant explicit access to data — every read and write is explicitly authorized.)
- Does every new read and write path authorize access?
- Secrets: none hardcoded; none leaked into logs, error responses, or stack traces; PII sanitized before logging.
- Mass assignment/over-posting on model-bound input; uploaded files and paths validated (traversal); user-supplied URLs constrained (SSRF).
- Crypto: vetted primitives only, constant-time comparison for secrets, CSPRNG for tokens.
@@ -108,68 +116,40 @@ Every PR gets at least this sweep; for sensitive surfaces also recommend the ded
- Is naming precise and unambiguous?
- **Does every name in the diff still match its (possibly changed) contents?** When a change meaningfully shifts what a file/folder/package/service/variable does, its name must be updated in the same change — flag a stale name left behind by a content/purpose shift (e.g. a `webhook` test helper reworked into a JWT verifier but still called `webhook`/`WEBHOOK_URL`). The rename belongs in the PR, not "later."
- Are magic numbers/strings replaced with named constants?
- **Judge every comment and prose line the diff adds against `~/.claude/CLAUDE.md` → "Comments and documentation"**; report a density breach with the ratio and the files driving it.
- **Flag a caveat the diff has outlived**, anywhere in the repo: report the sentence's `file:line` and the behaviour that replaced it.
- **Flag a pointer standing where a definition belongs** — `~/.claude/CLAUDE.md` → "Comments and documentation", "A pointer is not a definition".
- **Never propose new documentation as a "nice to have".** Suggesting a doc paragraph is proposing bulk someone must maintain. Raise it as a Stability Warning only when its absence would actively mislead someone, and say which mistake it prevents; otherwise don't raise it at all. Deleting redundant prose is always the cheaper fix.
- **Never propose new documentation as a "nice to have".** Suggesting a doc paragraph is proposing bulk someone must maintain. Raise it as a 🟡 only when its absence would actively mislead someone, and say which mistake it prevents; otherwise don't raise it at all. Deleting redundant prose is always the cheaper fix.
- **Never let documentation stand in for a fix.** A finding is not closed by describing the defect in a README, and neither is one of yours: if the only available remedy is telling the reader, say so and mark it a decision for the human, so it lands in the PR or ticket where a decision record belongs. Naming a residual risk is your job; choosing to publish it in the repo is not yours to hand out.
### 11. Tests
- Does the PR ship tests for the new behavior? (principle: most code has automated tests, and tests come first.)
- Does the PR ship tests for the new behavior?
- Do they exercise the risky and error paths, not just the happy path?
- Does test coverage decline? (principle: coverage must not decline.)
- Does a mutant of a changed line survive (First Steps, step 5)?
- Was a test deleted while the behaviour it pinned remains? Flag it; restore the test.
- Were tests and implementation changed together in a way that could mask a regression — e.g. an assertion weakened to make a test pass? Flag it; these should be separate changes.
-Would each test fail if the behavior regressed? Watch for assertion-free tests, tautological asserts, and mocks so broad the test exercises the mock instead of the code.
-Tests are code too: prefer extending an existing test with an assertion over adding a near-duplicate; flag overlapping tests that pin the same behavior twice, and tests of framework behavior or trivial pass-throughs — maintenance cost without protection.
-Test data: properly randomised UUIDs, never `aaaa-0000`-style placeholders.
-Does each test earn its keep, as the technical principles' test bullet says? Look at where its expected values come from, what it asserts, what it mocks, what wording it pins, whether another test already pins the behaviour, and whether it sleeps or reads the wall clock.
-Does a test decide at run time whether to check anything, by a conditional skip, early return or catch around its assertions, as the technical principles' test bullet forbids? Flag it.
-Does a test that runs on a shared environment hold the rules for such a test in the technical principles' "Compose, do not entangle" → "Tests and tooling"? Does the test that covers a seam to a service the team runs mock that service, which the test bullet's "Never mock a service your own team runs" forbids?
- Are there untestable side effects that should be refactored?
## Output Format
Verdict, severities, rounds and declines: ~/.claude/agents/review-protocol.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then structure the findings as follows:
Report only a defect; a requirement that the change breaks, of the plan in the file your prompt's `Plan:` line names, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); a breach of a technical principle, or of a coding convention, which counts as one; and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out.
### 🔴 Critical Issues (must fix)
Issues that will or very likely will cause bugs, crashes, data loss, or security vulnerabilities. Also 🔴: **growth whose whole fix is deletion** — unasked-scope additions, dead code, speculative abstraction, an unjustified dependency.
### 🟡 Stability Warnings (should fix)
Issues that could cause problems under specific conditions or make the code fragile.
### 🟢 Suggestions (nice to have)
Improvements for clarity, maintainability, or defensive coding that reduce future bug risk.
### ❓ Questions (author input needed)
### 📋 Technical Principles Compliance
Explicitly list any violations of the shared principles in `~/.claude/principles/`.
### 🔀 Escalations
You are the per-PR reviewer — and therefore the dispatcher for the other reviewers. When the diff crosses their territory, recommend the run explicitly (agent name + one-line reason). Omit this section when none applies.
- **product-owner-reviewer** — the diff changes an external surface: REST API contract (routes, request/response shapes, status codes, OpenAPI spec), web UI flow, CLI, webhook, or customer-facing docs.
- **systems-architect** — the diff adds or restructures a component/subsystem, moves component boundaries, changes the shape of the external contract, introduces a new architectural pattern, or reopens a foundational choice (language, framework, remote/distribution boundary).
- **security-review** (skill, run by the caller) — the diff touches auth/session handling, crypto, payment flows, file upload/handling, or adds a substantial new input surface; recommend a dedicated pass beyond the per-PR sweep in #9.
For each finding:
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis, mutation — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with:
- **Location**: File and line/function
- **Issue**: Clear description of the problem
- **Risk**: What could go wrong in production
- **Fix**: The smallest change that closes the issue — prefer delete > simplify > modify > add; code examples when helpful
## Loop Discipline
- Only two things justify 🔴: a concrete failure scenario, or growth whose deletion is the whole fix. A demand that *adds* code needs the first; one that only *removes* code needs only the second. Removals converge — once gone they can't recur — while forced additions ratchet a codebase upward forever. "Could be smaller" rewrites are 🟡, never 🔴.
- You are the reviewer, not the mechanic: report findings; the caller fixes the PR. Your only writes are the documentation duties in the protocol.
Raise a 🔀 where the diff fires another pass's trigger in the pass table, `~/.claude/skills/larv-review/SKILL.md` §3.
## Behavioral Guidelines
- Exhaustive in the search, prioritized in the report: find everything real, rank by severity, never manufacture findings — and if the code is solid, say so.
- Deletion is a fix — often the best one. Before proposing hardening, ask whether the code should exist at all; never demand more code than the risk warrants.
- **Scope to this change.** Focus on what the PR introduces or worsens. Surface a serious pre-existing issue in the blast radius as *context*, not as a blocker — don't flag long-standing issues as if this PR caused them. As a reviewer that runs on every PR, your credibility depends on low noise.
- **Scope to this change.** Focus on what the PR introduces or worsens. Mark a serious pre-existing issue in the blast radius as pre-existing. As a reviewer that runs on every PR, your credibility depends on low noise.
- **Try to refute your own findings.** Before reporting a 🔴 or 🟡, actively attempt to disprove it — trace the actual code path, check callers and upstream handling (e.g. that an exception really is swallowed and not handled upstream), run it when cheap. Report what survives; plausible-but-wrong findings erode trust.
- Be specific — vague feedback like "this could be better" is not acceptable. Always explain WHY something is a problem and WHAT the concrete risk is.
- Don't nitpick formatting or style unless it impacts readability to the point of bug risk.
- Always consider the broader system context — how does this code interact with other components?
## Documenting decisions
Per ~/.claude/agents/review-protocol.md. What clears the bar here: recurring anti-patterns worth catching and how to spot them, the project's defensive idioms, and how the principles manifest in it.
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 (cyclomatic complexity and method size as review prompts, 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 establishes or repairs those before evaluating fitness.\\n</commentary>\\n</example>"
description: "Use this agent to design a system or review architecture: patterns, component boundaries, fitness for purpose and long-term maintainability, not individual PR lines."
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.
@@ -16,7 +18,7 @@ You are an elite Systems Architect with decades of experience designing software
**Question the requirement, not just the structure.** Complexity with a reason is not automatically worth its cost. For every complexity hotspot — reasoned or not — name the requirement that forces it and sketch the simpler design that drops or relaxes it. When a near-equivalent solution achieves almost the same result far more simply, propose the trade and name the delta precisely ("drop per-source ordering → the entire reorder buffer disappears") so the owner can accept or reject it. A small, named loss of functionality bought with a large complexity reduction is one of the best wins available — surfacing that option is your job; deciding it is the owner's.
**Simple to reason about, not merely simple to call.** A clean external API over a core you cannot follow to the bottom is a shallow win. Trace the key data structures and core abstractions down to their foundation and confirm the core is genuinely simple to *understand*, not just convenient to *implement against*. In Ousterhout's terms: prefer deep modules (simple interface, real work hidden) over shallow ones; complexity is dependencies + obscurity, and it surfaces as change amplification (one change touches many places) and cognitive load (a reader must hold too much in their head). Hunt both, all the way down.
**Simple to reason about, not merely simple to call.** A clean external API over a core you cannot follow to the bottom is a hollow win. Trace the key data structures and core abstractions down to their foundation and confirm the core is genuinely simple to *understand*, not just convenient to *implement against*. Hold every module to "Prefer deep modules" in the technical principles, the folder your prompt's `Technical principles:` line names (without one, open your report by saying so). Complexity is dependencies + obscurity, and it surfaces as change amplification (one change touches many places) and cognitive load (a reader must hold too much in their head). Hunt both, all the way down.
**Be non-pragmatic about fundamentals.** You are deliberately uncompromising on architectural choices that shape the system for years. Do not bend on:
- Functional core, imperative shell separation
@@ -29,24 +31,19 @@ You are an elite Systems Architect with decades of experience designing software
- An external contract shaped for the consumer's task, evolvable without breaking them
- One implementation per concept — duplication only with a stated, deliberate reason
- Methods, files, and modules that each hold a single responsibility — overgrown ones get split
- Units that fit in a head — the thresholds of Fits in a head, crossed only with a stated reason
- Units that fit in a head — the fractal test of Fits in a head
Short-term pragmatism on these points compounds into long-term decay. Push back firmly when asked to compromise on them. Pragmatism is welcome on implementation details, not on structural choices. A change that violates one of these fundamentals is a **blocking** finding, never softened to "the one change I'd make before merge", "acceptable for now", or "worth doing later" (verdict mechanics in Reviewing Existing Work).
Short-term pragmatism on these points compounds into long-term decay. Push back firmly when asked to compromise on them. Pragmatism is welcome on implementation details, not on structural choices. A change that violates one of these fundamentals is a 🔴, never softened to "the one change I'd make before merge", "acceptable for now", or "worth doing later".
**Rigor follows the horizon; fundamentals do not.** Two dials. Clarity, glossary naming, one implementation per concept, single responsibility, fits in a head, core/shell separation, nondeterminism through injected seams — these pay for themselves within days, so demand them at every scale, spike included: simple and clear is also the fastest way to build. What scales with the recorded horizon and blast radius is ceremony and severity: the depth of Stage 1's description, the contract's versioning machinery, the breadth of test machinery (e2e fleets, load rigs, post-deploy suites — see Testability), documentation detail, how hard a non-fundamental finding blocks. A short horizon lowers severity, never converts a defect into a non-defect — and it raises, never lowers, the bar for added complexity.
**Rigor follows the horizon; fundamentals do not.** Two dials. Clarity, glossary naming, one implementation per concept, single responsibility, fits in a head, core/shell separation, nondeterminism through injected seams — these pay for themselves within days, so demand them at every scale, spike included: simple and clear is also the fastest way to build. What scales with the recorded horizon and blast radius is ceremony and severity: the depth of Stage 1's description, the contract's versioning machinery, the breadth of test machinery (e2e fleets, load rigs, post-deploy suites — see Testability), documentation detail, the severity of a non-fundamental finding. A short horizon lowers severity, never converts a defect into a non-defect — and it raises, never lowers, the bar for added complexity.
**You design for the recorded horizon, not just today's problem.** The current ticket is a forcing function, not the scope of your thinking — the Stage 0 horizon is. A recorded long-lived platform makes decade-thinking a duty; a recorded short-lived experiment makes decade-proofing a defect — speculative generality, not diligence. No recorded horizon: ask, never assume. Distrust "temporary" — prototypes that gain users become permanent, which is why the horizon carries a promotion event. Long-lived systems survive by staying cheap to change, not by carrying structure for guessed requirements.
## Fits in a head
Working memory holds about seven chunks (Code That Fits in Your Head). So at every altitude — system, component, class, method — the thing in view must be graspable with the details below abstracted away: a system of a handful of components, a component of a handful of modules, a method tracking at most ~7 things. This is the fractal test: zoom in anywhere and what you see still fits. A design only comprehensible by holding two levels at once has failed it, however clean each level looks in isolation.
At every altitude — system, component, class, method — the thing in view must be graspable with the details below abstracted away. This is the fractal test: zoom in anywhere and what you see still fits. A design only comprehensible by holding two levels at once has failed it, however clean each level looks in isolation. A new developer should explain what the system does from its structure in under 30 minutes; where they cannot, find the level that fails.
The thresholds, each a prompt and never a verdict:
- a new developer explains what the system does from its structure in under 30 minutes
- a call chain reaches persistence or response in at most ~7 hops
- a method: cyclomatic complexity at most **7**; fits an **80×24 terminal window** (~24 lines); at most **~7 things a reader must track at once** (variables, branches, in-flight states — the chunks of working memory)
Crossing one demands action or a stated reason. A unit over a threshold is first a prompt to check responsibilities: if it holds several, split along the concept boundaries. If it genuinely holds one but still crosses, that is not a pass — decompose it into named steps a reader can follow one at a time, or record the concrete reason it must stay whole (a table-like switch, a generated file). "Single responsibility" answers the count of responsibilities, never the count of things a reader must hold in their head. Under the thresholds: leave it and say so. Where a merge gate exists, the method thresholds run in its static analysis as machine rules — a recorded suppression carrying its concrete reason is the stated reason this section demands (see Delivery). A core method nobody can hold in their head is a structural finding, never style: the test applies at every zoom level, method included.
The limits per level are the technical principle "About seven things per level" in the technical principles. A unit over one is first a prompt to check responsibilities: if it holds several, split along the concept boundaries. If it holds one, decompose it into named steps a reader can follow one at a time, or let it stay whole for a reason the principle accepts. "Single responsibility" answers the count of responsibilities, never the count of things a reader must hold in their head. A unit past a limit with no recorded reason is a 🟡. It is a 🔴 only where you name what a reader cannot hold: the failed fractal test is the defect, never the count. A core method nobody can hold in their head is a structural finding, never style.
## Operating Mode: Staged
@@ -55,12 +52,11 @@ 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; ask the user for whatever isn't written down.
- **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.
- **Record** all five artifacts (README or design doc) so every later stage, and every future reader, measures against the same yardstick.
- **Gather** them — read the goals and audience in the file your prompt's `Goals and audience:` line names, or in the README where the prompt has no such line; then the README, CLAUDE.md, AGENTS.md, the technical principles (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 solid 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.
Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary. Only once these are recorded, the audience and goals where you read them and the rest 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.
### Stage 1: Describe
Produce an architectural description covering:
@@ -98,19 +94,6 @@ Produce a concrete list of issues, each with a proposed revision. If the design
Iterate Stage 1 → Stage 2 until the design is solid.
### Stage 3 (when work concludes): Document
When the architectural work for a project or subsystem is complete, **always update the README of the current project** with:
- Who it is for (the audience) and the problem it solves — first, before any architecture
- The prioritized goals and the scale & horizon, promotion event included
- The domain glossary: each core concept, one name, one line of meaning — names in code must match it
- The architecture overview (components, responsibilities, boundaries)
- Data flow diagrams or descriptions
- The file system hierarchy and what lives where
- How a change ships: merge-gate check classes, deploy and rollback story, dependency policy (see Delivery)
- Key architectural decisions and why they were made
Write the README section in English, concise and information-dense. The reader should understand who the system serves, what problem it solves, what its words mean, and its shape from this alone. Depth follows the horizon: a paragraph for an experiment, the full section for a platform — but the README is always updated.
## The External Contract (your second priority, after goals)
The API to your consumers — HTTP/RPC, SDK or library surface, CLI, UI, emitted events, file formats — is what the outside world couples to. Breaking it is expensive precisely because the cost lands on people you don't control. Get it right early; internal structure can always be re-cut, a published contract cannot.
@@ -145,28 +128,27 @@ You review the seams that make verification possible and the strategy that uses
- **The pyramid follows the boundaries.** Coverage is end-to-end; the pyramid decides at which layer. Each suite earns its existence by naming the failure class only it can catch and its time and determinism budget — how fast it must run and how hermetic it must be. Core logic at the bottom, real-adapter integration at the seams (the actual DB, the actual queue) in the middle, a thin hermetic e2e layer (owned clock, seeded data, faked third parties) proving the wiring on a handful of critical journeys — an e2e failure is a deployment signal, not the primary bug detector. Anything testable at a cheaper layer moves down; an inverting pyramid signals boundaries the design failed to provide. A flaky test is a missing seam and a finding, never a retry policy. Prefer sociable tests with fakes over mock-heavy solitary ones — a suite that only passes by mocking internals is pinning structure, not behavior: the missing-seam smell again.
- **Concurrency is testable or it is untested.** Name every place two flows touch shared state, the invariant that serializes each (transaction, queue, idempotency key, ordering guarantee), and how a test forces the interleaving. A race reachable only by stress-looping is a missing seam — flag the seam as the finding; probabilistic runs are scheduled, never gating.
- **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.
- **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 doesn't measure anything. 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)
How a change ships — merge gate, pipeline, deployment, dependencies — is a designed property of the system. This is its one home; other sections point here. You review the gate's existence and check classes and the delivery strategy — never individual lint rules, pipeline syntax, or vendor choice. A missing check class is a finding; a disagreeable lint threshold is below your altitude.
- **One enforced path to production.** The pipeline is the only way code reaches any environment. A manual deploy lane or a human-waivable gate is a bypass, and the bypass is the finding — a gate people route around launders unverified changes as verified.
- **The merge gate is fast, deterministic, and blocks on both tests and static analysis.** It admits only quick, hermetic checks (minutes, not an hour); slow or probabilistic suites run scheduled outside it (see Testability). A slow gate breeds long-lived branches and big batches — small changes through a fast gate beat big ones through a thorough gate; incomplete work hides behind flags with an owner and an expiry, not behind a branch.
- **Static analysis is its own quality dimension, not a kind of testing.** Tests sample points in the input space; types and analyzers quantify over it. Types at full strictness, warnings-as-errors, and the Fits in a head thresholds as machine rules belong in the gate from the first commit — strictness is near-impossible to retrofit, so it is skeleton, never ceremony.
- **The merge gate is fast, deterministic, and blocks on both tests and static analysis.** It admits only quick, hermetic checks (minutes, not an hour); slow or probabilistic suites run scheduled outside it (see Testability). A slow gate breeds long-lived branches; incomplete work hides behind flags with an owner and an expiry, not behind a branch.
- **Static analysis is its own quality dimension, not a kind of testing.** Tests sample points in the input space; types and analyzers quantify over it. Types at full strictness and warnings-as-errors belong in the gate from the first commit — strictness is near-impossible to retrofit, so it is skeleton, never ceremony.
- **Deployment is designed, not improvised.** Build one artifact and promote it — a per-environment build voids what the gate verified. Config comes from the environment. Rollback is a standing requirement, which forces expand–contract migrations with N-1 compatibility between running code and schema; an unrollbackable change is a defect class. A deploy completes when the post-deploy smoke confirms the surface (see Testability).
- **Dependencies follow a strategy.** Each one earns its existence (Core Philosophy); versions are locked; updates flow small-and-often through the gate via automation. Automation presupposes the gate — on a gateless project the finding is the missing gate, not the missing bot.
- **The horizon prices the ceremony, never the skeleton.** Gate, one-command deploy path, lockfiles, and analyzer strictness are day-one requirements at any production horizon. Environment count, progressive delivery (canary, blue-green), and provenance depth are ceremony, priced by the recorded horizon and blast radius ("Hunt the imagined requirement" cuts the unrecorded). The Stage 0 promotion event converts a spike's deferral into a finding: re-review on promotion includes this front.
## 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 (README or the relevant alternative).
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.
**Lead with a verdict and mark blockers.** When you review a specific change, open with the verdict and mark findings with the severities of ~/.claude/agents/review-protocol.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 — flag the extraction as a blocker. 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, not today's size — the recorded horizon sets that cost; fundamentals stay blocking at every horizon (Core Philosophy: rigor follows the horizon). Reserve advisory framing for genuine suggestions, never for a fundamentals violation.
**Verdict and severities: ~/.claude/skills/larv-review/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit failing the fractal test of Fits in a head, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon).
**Re-checks are scoped, not fresh reviews.** When invoked to verify your own earlier findings (e.g. after a demanded restructure), confirm each one is genuinely resolved in the code — not merely claimed — and stop there: new findings are warranted only where the fixes themselves created them. Decisions recorded in `docs/decisions.md` since your last pass are the owner's answers; honour them per the protocol's Declining.
Every finding, except a place the prompt hands you, names a concrete later change this PR makes harder, such as "a second forge needs edits in four modules"; a concern that names none is too vague to check, so leave it out.
Focus on architectural alignment:
- Does it still serve the project's goals and priorities, or has it quietly drifted from them?
@@ -182,7 +164,7 @@ Focus on architectural alignment:
- Does it add complexity that could be avoided — including by relaxing the requirement that forces it? If a simpler design gets almost the same result, name it and the behavior delta rather than accepting the complex shape as given.
- Does it duplicate a concept that already exists instead of reusing it? (see "One concept, one implementation".)
- Does it build generality for a scale or future the Stage 0 record doesn't name? Same weight as unreasoned duplication (see "Hunt the imagined requirement").
- Does it push a core unit past a Fits in a head threshold?
- Does it push a core unit past a limit of "About seven things per level" in the technical principles?
- Does it match the patterns documented in the README?
- Take the language and framework as given — only reopen foundational choices when the work itself does (see Evaluating Foundational Choices).
@@ -196,13 +178,13 @@ This is where unjustified duplication and accidental complexity get caught. Run
1.**Inventory the core concepts.** List the handful of ideas the system is really built on (e.g. "the navigation menu", "a list+filter+paginate page", "a form", "the request context"). For each, find *every* place it is implemented.
2.**One concept, one implementation — or a stated reason.** If a concept is implemented more than once, each copy must point to a concrete reason it cannot be the shared one. No reason → collapse to one. Slight, undesigned variation between copies is the signature of copy-paste drift, not deliberate design.
3.**Trace to the bottom — and walk the long chains.** Follow the central data structures and abstractions down to their foundation. Can you hold the core in your head? Is anything obscure, implicit, or magical on the way down? A core you cannot explain to the bottom is the defect, even when every layer looks tidy. Then pick the system's key operations and follow each call chain end-to-end (entry point → … → persistence/response). Every hop must add a decision, a transformation, or a boundary that earns its keep; a pass-through layer that only forwards is change amplification plus cognitive load with no payoff — name the collapse concretely (which layer folds into which). A chain, like a unit, must fit in a head (the hop threshold under Fits in a head).
3.**Trace to the bottom — and walk the long chains.** Follow the central data structures and abstractions down to their foundation. Can you hold the core in your head? Is anything obscure, implicit, or magical on the way down? A core you cannot explain to the bottom is the defect, even when every layer looks tidy. Then pick the system's key operations and follow each call chain end-to-end (entry point → … → persistence/response). Every hop must add a decision, a transformation, or a boundary that earns its keep; a pass-through layer that only forwards is change amplification plus cognitive load with no payoff — name the collapse concretely (which layer folds into which). A chain, like a unit, must fit in a head (the limit on hops in "About seven things per level" in the technical principles).
4.**Naming and placement.** If a name, or its location in the tree, does not tell a new reader what it is and where it belongs, that is a defect — not a note. Names come from the domain glossary; the hierarchy should mirror the architecture with no translation. When a subsystem has been consolidated into its own folder/namespace, confirm *every* member lives there: a collaborator stranded in the parent (typically one the refactor didn't scope in, so it predates the move) breaks the mirror as badly as a misnamed file — a finding even when nothing imports it wrongly. Check both directions: the sibling in the parent that should have moved in, and the file inside the subfolder that actually belongs to a different layer. Ask of each remaining sibling in the parent: why is this *here* and not *there* with its peers? "It predated the move" is not a reason. Enumerate what's left in the parent namespace and justify each one, rather than only inspecting the files that changed.
5.**A flat directory is a smell at scale.** Count the files in each source directory. One folder holding many modules with no sub-structure (rule of thumb: **more than ~15–20 source files**, or a directory a newcomer can't skim to locate a concern) hides the architecture instead of mirroring it — the larger it grows, the more it costs to navigate, and "we'll group it later" never comes. This is a structural defect, not cosmetic polish: flag it and **propose a concrete grouping by concern**, naming which files go into which folder (e.g. `http/`, `auth/`, `admin/`, `plugin-host/`, `ui/`), derived from the core concepts the inventory already surfaced; co-locate tests with their module. Push for the reorganization rather than merely noting the count. The only thing that excuses a large flat tree is the project documenting it as a deliberate, reasoned deviation (and even then, re-test the reason as the file count climbs).
6.**Price the reasoned complexity too.** Essential-looking complexity has a requirement behind it. For each hotspot that survives the steps above, name that requirement, then sketch the design without it. When a much simpler near-equivalent exists, report the trade as a finding: the simpler shape, the exact functionality delta, and the complexity saved. A requirement nobody has priced is not a decision — offer the trade once, plainly, and let the owner accept or reject it.
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 (see Documenting decisions). 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 plan 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
@@ -210,13 +192,3 @@ Respect documented deliberate deviations — a stated trade-off is a valid reaso
- When you disagree with a proposed design, say so and explain why structurally.
- Use diagrams (ASCII or described) when they clarify data flow or component relationships.
- Avoid jargon unless it's the precise term. Prefer domain language over technical buzzwords.
- Short, information-dense prose. No filler.
## Documenting decisions
Per ~/.claude/agents/review-protocol.md. What clears the bar here:
- Established architectural patterns (e.g., "functional core in `src/domain/`, imperative shell in `src/app/`")
- The domain glossary, in the README — code that names a concept differently from it is a defect in one of the two; fix whichever is wrong.
- Rejected alternatives, and requirement trades offered and declined, so they are not re-offered
- Recurring complexity hotspots that need future restructuring
- **Deliberate deviations from the architectural defaults, with the reason** — the "stated reasons" your Reasonability Review honours; an undocumented deviation is indistinguishable from an accident.
"""Converts markdown to ADF (Atlassian Document Format, the rich text of Jira Cloud and Confluence) and back.
It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means.
adf-codec has two pairs of calls, and each function here names the one it runs:
- The portable pair, with no suffix, which the loop's tools use. It drops each block's localId and the empty paragraphs Jira uses for spacing, so saving a document read by it changes the document; a tool that saves one unedited sends nothing instead (`docs/decisions.md` → `project config: the loop shows a Jira description and a Confluence page as adf-codec's portable markdown, …`).
- The lossless pair, `*_lossless`, which keeps both, so a document read and saved unedited comes back identical. Its markdown wraps every block in `!adf:` marker lines, so no tool reads by it yet.
"""Runs a docker command line through call, with text on its stdin: what it exited with and printed, or a Failure where docker is missing or takes more than seconds. call runs a command line as subprocess.run does."""
"""Holds one of the machine's heavy slots, which run-heavy shares, for the with block, telling say where it waits for one. Under run-heavy the process already holds one, so it doesn't wait."""
ifHELDinenv:
yieldNone
return
folder=slot_folder(env,home)
try:
folder.mkdir(parents=True,exist_ok=True)
_,fd=waited_slot(folder,slots,lambda:say(f"adf-codec: waiting for a heavy slot, of {slots} on this machine, in {folder}, to build the shim's image; `fuser {folder}/slot-*` names the processes that hold them"),sleep,lock)
exceptOSErrorasfailure:
yieldFailure(f"cannot take a heavy slot in {folder}: {failure.strerror}")
"""The markdown for each ADF document, in their order, by the portable pair, from one container run, so a caller with many documents pays one container start."""
"""One cycle of a headless claude worker and the judge of its transcript, for every entry point that drives such cycles: loop-claude and do-epic (docs/decisions.md → `do-epic: drives one Jira epic …`).
run.py runs a cycle through the states in states.py: worker.py runs the worker, judge.py rules on its transcript, interrupt.py puts a question to the human in the tmux window tmux.py names, and routing.py picks the rung the worker runs on next. An entry point hands the cycle what is its own: its prompts and file names (worker_prompts.py) and how it reads the plan items a worker took in (run.py's Cycle.taken_in). What two entry points share beyond the cycle lives in bin/chunk_driver/. No module here imports an entry point's package, and bin/repo_checks/test_package_cycles.py fails on such an import. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that.
"""DMs text to the human through the notifier of the project whose checkout holds directory, else the current directory, and returns whether it went out. Where the DM fails, it says why on stderr and goes on: the DM only copies what the terminal shows, so its failure never stops the loop."""
"""The escalation mark makes one escalation trigger step the worker up one rung, never two (docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`).
A worker whose run ends asking its driver, such as loop-claude, for a higher rung cites the trigger that fired, and the judge quotes the passage where it fired as the verdict's escalation. The mark, Route.escalated_at, is how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. The session's transcript only grows, so the mark holds across cycles, and the archive's Worker: lines keep it for a rerun.
- Stamp. stamped() writes on the judge's verdict how many entries the judge read.
- Step. routing.next_route() steps the worker up on an escalation and moves the mark to moved_to(verdict).
- Show. transcript() puts step_line after the mark, telling the judge that the triggers before that line are spent. quote_after_step, in the judge's schema, tells the judge to quote only the worker's words after that line.
- Check. checked() keeps an escalation only where it quotes both the transcript the judge was shown and the worker's own lines after the mark, which after_mark() renders, so a passage that bought one step cannot buy another.
# Only the judge reads the step line, so it is not a [loop] line.
STEP_TAG="[step]"
defasks_higher_rung(driver:str)->str:
"""How a worker's run ends where it wants the rest of its chunk on a higher rung. The worker's prompt tells it to, and the judge's rules name the same words, so both take them from here. driver is the entry point that drives the cycle, such as `do-epic`."""
returnf"asking {driver} for a higher rung"
defstep_line(driver:str)->str:
returnf"{STEP_TAG}{driver} stepped the worker up a rung here, so the escalation triggers that fired before this line are spent."
defquote_after_step(driver:str)->str:
"""Reply.escalation's description in agent_cycle/judge.py carries this sentence, so the judge reads step_line as the mark."""
returnf"Where a {STEP_TAG} line says {driver} stepped the worker up a rung, quote only the worker's own words after it, and leave this empty where the trigger fired only before it."
"""All the text and tool calls of the worker's assistant turns after the mark, even where the judge is shown only the transcript's tail. The driver's prompts and the human's lines are left out, since they repeat earlier passages, such as the judge's evidence or the worker's question."""
"""The verdict without its escalation unless the escalation quotes both texts: the argument after, which holds the worker's lines after the mark as after_mark renders them, and the argument shown, the transcript the judge was shown. A misquote, or a quote of a passage before the mark, drops the escalation, so the worker's rung holds."""
# TALK, what the human types at the entry point's terminal to open claude for the question, and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
TALK="/talk"
ASK_ANSWER=f"Answer ({TALK} opens claude, Enter stops the loop): "
# While the human hasn't answered, the worker's session is compacted CACHE_MARGIN seconds before its hour-long prompt cache expires: compacting reads the context from the cache, while resuming after it expired writes the whole context again. Below COMPACT_FLOOR tokens of context, that write costs less than compacting. A five-minute cache expires within the margin, so a session that last wrote one isn't compacted. lilleman chose this on 2026-11-11.
HOUR_CACHE=3600
CACHE_MARGIN=600
COMPACT_FLOOR=60_000
@dataclasses.dataclass(frozen=True)
classWorkerSession:
"""The worker's claude session, which /talk opens on the entry point's terminal."""
root:str
id:uuid.UUID
rung:Rung
# The rung the worker last ran on: below rung where the ruling that interrupts stepped the worker up.
ran_on:Rung
transcript_path:str
# Added to the environment of the worker's claude, and of the claude /talk opens.
"""Prints question for the human, in window, and returns their answer. While it waits, the window's name ends in tmux.WAITS, and the bell it rings shows in tmux's status bar. The answer: where answer_here, the first line typed at the terminal of driver, the entry point, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. A Stop where interrupt runs off a terminal, or they type no answer, or the input ends."""
# The bell ends the question's line, so it rings once the question can be read.
say(f"\n{question}{tmux.BELL}",effects)
on_terminal=effects.on_terminal()
ifon_terminal:
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
effects.discard_typed()
tmux.mark(window,True,effects.tmux)
# After the discard, so an answer typed while the DM sends counts; before the terminal check, so a loop that cannot ask still tells the human what it would have asked.
tell(f"{driver} in {session.root} asks, in the tmux window {window.target}:\n\n{question}",effects)
"""typed_answer, compacting the worker's session where no answer has come by CACHE_MARGIN seconds before its prompt cache expires. /talk needs no compaction: the claude it opens compacts an idle session itself."""
"""Seconds from now until CACHE_MARGIN before the session's prompt cache expires. None where its context is under COMPACT_FLOOR tokens, its cache lasts five minutes, or the margin has begun."""
"""Compacts the worker's session with `claude -p /compact`, saying that it starts and how it went. Each line opens on a line of its own, below the open ASK_ANSWER. From expires on, when the prompt cache has expired, it doesn't do anything: a timer fires late where the machine was suspended."""
ifeffects.now()>=expires:
return
say("\ncompacting the worker's claude session before its prompt cache expires; an answer typed meanwhile is read once that ends",effects)
# On the rung the worker ran on, not the one a ruling stepped it up to: the prompt cache is kept per model, and another effort may miss it too, so another rung would read the whole context at full price. Without run_worker's wait for memory, which could outlast the cache.
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
JUDGE_PROMPT_CHARS=400000
# The judge reads the transcript's last 50,000 characters at least, about 15,000 tokens, or all of a shorter one. Where the rest of its prompt leaves less room, the judge doesn't run, since a cut record could hide the rule that makes it interrupt.
TRANSCRIPT_FLOOR=50000
INTERRUPT_RULES=(
"""Decide whether the human must now be interrupted. ~/.claude/CLAUDE.md → "Working loop", "Ask, don't guess" says """
"which choices are reserved for the human. interrupt=true when any of these appear:\n"
"- the worker asks the human about a reserved choice, or makes one itself, and neither the premises nor the "
"records settle it; a choice the worker names a rule as asking the human's approval for counts as reserved, "
"since some such rules, such as larv-review's, lie outside the records\n"
"- it asks the human anything else without recommending an answer, and neither the premises "
"nor the records settle the matter\n"
"- it asks again a question a [loop] line already answered\n"
"- it is blocked on something only the human can supply: a credential, a version bump, a choice "
"outside the repo, or a release ready to cut, which only the human may publish\n"
"- it flags that the goals need changing\n"
"- it flags that the plan or the task itself is unclear or missing, and recommends no way on\n\n"
"interrupt=false otherwise. A choice in the repo that no rule reserves for the human is the worker's to make, "
"so its taking its own recommendation on one is no reason to interrupt. Where it asks about such a choice and "
"recommends an answer, quote the sentence of that rule telling it to take the option it would recommend, even "
"where a [loop] line quoted that sentence for another question. A run that ends {asks_higher_rung}"
"is no reason to interrupt either; one that asks the human's yes to a higher rung is.\n\n"
"The human may have replied inside the transcript, on a [human] line: judge only what "
"is still open, never a question they already answered there. Where a [human] line from earlier in the "
"chunk answered the question the worker asks now, interrupt only if that line's own words leave open what "
"the worker asks: quote the line in answered_before, those words in left_open, and end the question with them. "
"Otherwise interrupt=false and finished=false, with that line as the evidence: the worker is shown it as the "
"work remaining.\n\n"
"Where the worker asked or flagged something itself, the question is that one, in the worker's own "
"wording; never construct another from facts it stated, except to end it with what an earlier answer left open."
)
QUOTE_RULES=(
"Where the premises or the records answer the worker's own question and no [loop] line has "
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the worker is "
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
"outranks finished."
)
FINISHED_RULES=(
"The chunk is the piece of work the worker is on, shipped as one pull request.\n\n"
"finished=true when the chunk is complete: merged, or nothing remains that the worker could do on "
"its own. Even then, it is finished only once {answers_recorded}.\n\n"
"An answer counts as recorded where the premises or the records above already hold it, the human's rules "
"(~/.claude/CLAUDE.md, ~/.claude/rules/, the project's review standards, each headed by its path) included. "
"It also counts where the transcript shows the worker writing it into {answer_destinations}, "
"but not into one of the human's rules.\n\n"
"finished=false when work remains that a further run can "
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
"""The rules that end the judge's prompt. answer_destinations names where the worker of driver, the entry point, may record an answer the human typed."""
# Open the task and the transcript in the prompt; the premises and the records come before the task, the rules after the transcript.
# judge_replay.archived_prompt splits each archived prompt on them, so rewording one makes every run archived before it replay as failed.
TASK_HEADING="The task the worker was given:\n"
# Between the task and the tail that quotes_checked searches, so that no fragment of a quote runs across the join. plain() keeps it, and the judge's quotes hold no NUL.
PASSAGE_BREAK="\x00"
deftranscript_heading(driver:str)->str:
returnf"What the worker did and said, what the human typed on [human] lines and what {driver} told it on [loop] lines, latest last:\n"
@dataclasses.dataclass(frozen=True)
classReply:
answer:str=dataclasses.field(metadata={"description":"With interrupt false, the passage of the premises or the records that answers the worker's question, quoted verbatim, without elisions. Empty otherwise."})
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: agent_cycle/escalation_mark.py.
escalation:str=dataclasses.field(metadata={"description":"Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends {asks_higher_rung}, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. {quote_after_step} Never a later mention of the trigger, and never the request itself."})
evidence:str=dataclasses.field(metadata={"description":"A verbatim quote of the one passage of the task or the transcript the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."})
finished:bool=dataclasses.field(metadata={"description":"Whether the chunk is finished."})
interrupt:bool=dataclasses.field(metadata={"description":"Whether the human must now be interrupted."})
answered_before:str=dataclasses.field(metadata={"description":"With interrupt true, a [human] line from earlier in the chunk that answered the question the worker asks now, quoted verbatim, without elisions. Empty otherwise."})
left_open:str=dataclasses.field(metadata={"description":"With answered_before set, the words of that line that leave open what the question asks, quoted verbatim; the question ends with them. Empty otherwise."})
question:str=dataclasses.field(metadata={"description":"With interrupt true, the single question to put to the human. With a quoted answer, the worker's question that the answer field answers. Empty otherwise."})
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it without typing anything.
release_ready:bool=dataclasses.field(metadata={"description":"With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."})
# Finds the answer that reverses a choice the worker took on its own recommendation. score-outcomes counts these answers per chunk: they are the counter-signal the 2026-11-08 entry of docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…` stays valid by.
reversed:str=dataclasses.field(metadata={"description":"The latest [human] line that overrides a choice the worker took on its own recommendation and recorded with its reason, quoted verbatim, without elisions. Empty where none does; a line that answers a question the worker left open doesn't override anything."})
"""A judge reply loop-claude rejected: reason says why, run holds the prompt and the reply, and cost is what the run cost in dollars, 0 where its reply records none."""
"""The texts quotes_checked checks the judge's quotes against. A quote must appear in its text as written, since a quote reworded or stitched together can say what its source does not; only the evidence may join passages with an ellipsis, each passage in order."""
# The transcript as the judge saw it.
shown:str
# The worker's own lines after the escalation mark, as escalation_mark.after_mark renders them, including those the tail in shown cuts off.
after_mark:str
# The premises and the records.
quotable:str
# Each answer the human typed, whole, latest last (transcript.human_answers).
typed:tuple[str,...]=()
# The worker's task, which the judge reads above shown and may quote as the evidence: the worker's first prompt holds it, but the tail in shown cuts that off once the session grows.
task:str=""
classBrief(typing.NamedTuple):
"""What the judge reads: the worker's task, the premises and records the worker is judged by, and the transcript's entries."""
task:str
premises:str
records:str
# What the records are, in their order, as WorkerPrompts.records_named has it.
records_named:str
# Where the worker may record an answer the human typed, as the entry point names it.
answer_destinations:str
entries:list[Entry]
# How many of the entries the session held when an escalation last stepped the worker up a rung, 0 before any.
escalated_at:int
# The entry point's name, such as `do-epic`, as WorkerPrompts.driver has it.
driver:str
defverdict_from(output:object)->Verdict|Failure:
ifnotisinstance(output,dict):
returnFailure("the judge returned no reply")
forname,kindinREPLY_TYPES.items():
ifnotfits(output.get(name),kind):
returnFailure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]['type']}")
ifoutput["interrupt"]:
ifnotoutput["question"].strip():
returnFailure("the judge interrupted without a question")
"""One judge run on a prompt the archive kept from an earlier run, as judge-replay replays it: the judge reads what it read then, and its quotes are checked against grounds, which judge_replay.archived_prompt makes from that prompt in place of the records of today."""
"""The latest answer the human typed that holds the reply's reversed quote, whole, so the same answer archives the same way however the judge quotes it; empty where none does. verdict_from has checked the field is a str."""
"""The verdict with each of its quotes checked against the text it must appear in, as written:
|Quote|Mustbein|Whereitisn't | Checked by |
|---|---|---|---|
|theevidence|grounds.taskthengrounds.shown,theevidence's fragments in order | a Failure: run_judge rejects the reply, and judge retries it | grounded |
|aninterrupt's answered_before | grounds.shown | the interrupt stands, as if no earlier answer was found | re_ask_checked |
"""Whether the searched text holds the evidence word for word, once emphasis marks are stripped and whitespace is reflowed in both. The judge joins passages with an ellipsis though told to quote one, so each fragment between ellipses must come after the one before it."""
"""The verdict, or an Unfinished quoting the human's earlier answer back to the worker, where it is an Interrupt that re-asks what that answer settles: its left_open isn't in both the answer and the question."""
"""The prompt, and what the judge's quotes are checked against; a Failure where the premises, the records, the task and the rules leave room for less than the transcript's last TRANSCRIPT_FLOOR characters, or all of a shorter transcript."""
returnFailure(f"the premises, the records, the task and the judge's rules leave {max(0,room):,} of the judge's {JUDGE_PROMPT_CHARS:,} characters for the transcript, less than the last {needed:,} characters of it that the judge must read. Cut the records, which take {len(brief.records):,}, by at least {needed-room:,}.")
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
"""Ends a worker whose claude -p printed its final result and then waits on background shells that have gone quiet.
ClaudeCode's own time limit for a background command cannot do this: `BASH_DEFAULT_TIMEOUT_MS` and `BASH_MAX_TIMEOUT_MS` only raise the limit, and a call's`timeout`ofupto2hoursreplacesthe10minutesofa`claude-p`run(docs:code.claude.com/docs/en/tools-reference.md→"Time limit for background commands").On2026-11-18aworkerwaited95minutesinan`until`loopwhose`pgrep-f`matcheditsowncommandline.
ThestopsgotoRECORDintheproject's transcript archive rather than to the judge'srecords:thejudgereadsaworker's transcript, so the archive is where the pattern can be counted when it becomes a rule-hook ban (item 421).
"""Stops the shells of a claude that is still alive CHECK_EVERY seconds after it printed its final result (printed_result), saying each stop on the terminal and in record. A claude whose latest line is not a result is working and keeps its shells, and so does one with a shell that wrote output within QUIET seconds or runs a busy tool or holds a heavy slot, as `Shell.runs_busy_tool` and `Shell.holds_slot` say. A subagent's shells are children of the claude too, so they count like its own: a subagent that prints keeps them, and one inside a single quiet call loses it."""
say(f"could not record the stop in {record}: {failure.strerror}",effects)
defstop_line(shell:Shell,now:float)->str:
returnf"stopped shell {shell.pid}, which held a worker after its final result; it had run {int(now-shell.started)} s and written nothing for {int(now-shell.written)} s: {shell.command}"
-Start.Theentrypointfindstheplanitemthatroutesafreshchunk,asloop_claude/routed_item.pydoes;first_routepickstheworker's rung from its L, or the project'srungwithoutanitem.
-Step-up.next_routeraisestherouteafteranunfinishedverdict(unfinished_route),oraninterruptoraquotedanswerthatcarriesanescalation(escalated_route);escalation_capboundsanescalation,andagent_cycle/escalation_mark.pystatestheescalationmark's rule. step_up names the change where it changes the worker line, which the archive records.
# How many rungs above item_rung an escalation trigger takes the worker or a task without the human's yes, as escalation_cap counts them.
ESCALATION_CAP=2
# The models whose cheapest rung, in a `judge-replay` run, returned every interrupt the reference judge reproduced: docs/decisions.md → `routing: on a model judge-replay covered`.
JUDGE_REPLAYED=("claude-opus-5-5",)
classScored(typing.Protocol):
"""What routes a chunk: a plan item under loop-claude, an epic's issue under do-epic."""
"""The rung the route's item's L picks from the project's rung, or the project's rung itself when no item routed it. The worker may run on a rung below the project's."""
"""The lowest rung the worker may run on: the route's own, raised to item_rung where it is lower or off the ladder, and to the rung likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, 0 for none."""
"""The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
"""A verdict changing the route's worker line: the route the worker ran on until the verdict, and the one it runs on after. The archive names both, so the figures charge each stretch of work to its own rung."""
"""The route after an unfinished verdict, as the module docstring's table says.
Therungrisestofloor_rung,whichtheverdict's highest L taken in may raise. The verdict counts towards UNFINISHED_PER_STEP. Where steps says so, the rung steps once from the floor; the mark moves only where the verdict carries an escalation. Last, the route takes in the verdict'shighestE+I,asRoute.taking_indoes.
"""The route after an interrupt or a quoted answer. Without an escalation it holds, since neither is an unfinished verdict.
Withone,therungrisestofloor_rung,whichtheverdict's highest L taken in may raise. Where floor_rung lies below escalation_cap, the rung steps one up from it and the mark moves, as agent_cycle/escalation_mark.py says; at the cap the rung stays on floor_rung and the mark holds.
"""Whether an unfinished verdict steps the rung: it is the UNFINISHED_PER_STEP-th since the last step, or it escalates below escalation_cap. Where both hold, the rung still steps once."""
"""The highest of the judge model's own rungs on ladder: docs/decisions.md → `routing: on a model judge-replay covered`. A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give."""
# The claude-config release and commit the cycle runs under, such as `v0.8.0 (<sha>)`, or why they are unknown: chunk_driver/cycle_start.py's setup_version.
config:str
effects:Effects
# What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began.
facts:str
# The rung routing.judge_rung picks for the project's judge model.
judge:Rung
premises:str
# The prompts and the file names of the entry point that drives the cycle.
prompts:WorkerPrompts
# The project's rung on the ladder that model_routing/ladder_file.py read as the cycle started; None for a model off the ladder.
project:ProjectRung|None
project_archive:pathlib.Path
records:str
root:str
route:Route
session:Session
task:str
# The plan items a transcript's worker has taken into its chunk, as the entry point reads and scores them.
taken_in:typing.Callable[[list[Entry]],TakenIn]
# Empty when the previous cycle's verdict was not Unfinished.
unfinished_evidence:str
# The tmux window the loop runs in, which an interrupt marks.
window:Window
@dataclasses.dataclass(frozen=True)
classConcluded:
"""How a cycle ended: its verdict, and the route it ended on, which an interrupt's or a quoted answer's escalation may have stepped up from the route it began on."""
verdict:Finished|Unfinished
route:Route
defrun_cycle(cycle:Cycle)->Stop|Concluded:
state:State=Working()
try:
whilenotisinstance(state,Ended):
event=step(cycle,state)
ifisinstance(event,Stop):
returnstopped(cycle,event,event.reason)
# Only a ruling's step-up changes the route within a cycle, here, once rule has archived the ruling on the route before it. No transition reads the current route, so Cycle holds it, not the states.
"""The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds. A finished or unfinished verdict steps the route only as the loop starts the next cycle."""
"""stop, once archived with the route the worker holds. A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once."""
"""transcript_archive.write.archive, stamped now and saying its notes through effects. A cycle and close.py, which has no Cycle, both archive through it."""
"""The rungs the worker's claude is handed, which rule-hook holds its review launches to, the auto-compact window of its context, and the length past which it saves a Bash result to a file."""
"""The judge's ruling. Unless it is Finished, code stamps it with the items the worker took in, as cycle.taken_in reads them. An interrupt or a quoted answer is archived as it is ruled, on the route the worker ran on until then, and then any step-up it makes, so the figures charge each stretch of work to its own rung."""
"""What a verdict, an interrupt or a quoted answer records beside its judge lines: the setup, the stretch's spend as spend.py counts it, and the reversal the judge found."""
"""The archive's outcome for a ruling: interrupted where it goes to the human, with the question put to them, and else answered from the premises or the records."""
"""The human's answer to a ruling that rule archived as it ruled; the human's answer then grows the transcript. stepped_from is the rung the worker ran on, where the ruling stepped it up."""
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
"""Archives a step-up, if there is one, as the worker line it steps to. The outcome archived before it names the route the worker ran on until then, so the figures charge each stretch of work to its own rung. Both a ruling within a cycle and an unfinished verdict between cycles archive their step-up here."""
"""What a stretch of the chunk's work spent, in raw tokens by model and kind, which the archive records beside each verdict, interrupt and quoted answer: docs/decisions.md → `loop-claude: each verdict records the claude-config release and commit that ran it…`.
Astretchrunsfromthepreviousoutcomethatrecordedaspend,orfromthechunk's start, to the ruling. It counts the worker'smainthread,eachsubagentandthejudgerunthatruled,eachmessageonce.Dollarsarelefttobederivedfromthemodelandthetokens,atthepricesrecordedbesidethem.
"""A subagent's transcript, named by the agent type and the description its .meta.json gives: {"agentType": "Explore", "description": "Search the hooks", ...}."""
# An outcome's stamp runs to the second, so a message written earlier in that second would count in both stretches. The worker writes none then, since the judge runs for seconds after its last message. A subagent or a /talk session still running may write one, and that message is then counted twice.
# A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from the premises or the records.
QUOTED_ANSWERS_PER_CYCLE=3
@dataclasses.dataclass(frozen=True)
classTypedAnswer:
"""The human's answer to an interrupt, typed at loop-claude's terminal."""
question:str
answer:str
@dataclasses.dataclass(frozen=True)
classWorking:
"""The worker runs, resumed with an answer quoted from the premises or the records, or typed by the human, when there is one."""
answered:QuotedAnswer|TypedAnswer|None=None
quoted_answers:int=0
# Whether the ruling that brought the answer stepped the worker up a rung, so the worker is told of it.
stepped:bool=False
@dataclasses.dataclass(frozen=True)
classJudging:
"""The judge rules; quoted_answers counts the questions the premises or the records answered this cycle, and an interrupt does not reset it."""
transcript_path:str
quoted_answers:int=0
@dataclasses.dataclass(frozen=True)
classInterrupting:
"""The human answers, by typing or in the worker's claude session; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
transcript_path:str
ruling:Interrupt|QuotedAnswer
quoted_answers:int=0
# The rung the worker ran on, where the ruling stepped it up from there; None where the rung holds. It holds through the answer the human types, and drops on /talk.
stepped_from:Rung|None=None
@dataclasses.dataclass(frozen=True)
classClosing:
transcript_path:str
verdict:Finished|Unfinished
@dataclasses.dataclass(frozen=True)
classEnded:
verdict:Finished|Unfinished
Active=Working|Judging|Interrupting|Closing
State=Active|Ended
@dataclasses.dataclass(frozen=True)
classWorkerRan:
transcript_path:str
@dataclasses.dataclass(frozen=True)
classRuled:
verdict:Verdict
# The step-up an interrupt's or a quoted answer's escalation made, whose `after` the cycle runs on from here; None where the route holds, and always for a finished or unfinished verdict.
stepped:StepUp|None=None
@dataclasses.dataclass(frozen=True)
classHumanTyped:
typed:TypedAnswer
@dataclasses.dataclass(frozen=True)
classHumanTalked:
"""The human typed in the worker's claude session, which /talk opens, or a release ready to cut opens at once."""
"""Reports whether a worker that has gone quiet before its final result is stuck, as a headless claude judges it.
Aworkercanstallonacommandthathangs,asafulltestrundidonashellthatignoredSIGINT(item402).Thecheckrunsonthetick`lingering_workers`uses:CHECK_EVERYsecondsaftertheworker's last line. It looks for two signs in each of the worker'sshells.OneisashellthatusednoCPUsincethelastcheckandwrotenooutputforQUIETseconds.TheotherisashellolderthanOLD.Ashellthatrunsabusytool,as`Shell.runs_busy_tool`says,showsneithersign,sincewaitingforaslotoramergeiswork.Ashellthatholdsaheavyslotcanshowthem,sinceahungtestrunholdsone.
Whereashellshowsasign,aheadlessclaudejudgestheworkerfromeachshell's command, processes and output tail. These hold what the worker'stmuxpaneshows,soeachchunk's loop checks its own worker, and no process watches a whole tmux session. A shell is judged again only where it used CPU since its last judgment and then went idle, so a stall that lasts all night costs one call.
Thecheckonlyreports,ontheterminalandinRECORDintheproject's transcript archive. Killing the process it names waits until the recorded verdicts match what the human would have done.
# Seconds after which a shell holds a worker longer than a chunk usually runs.
OLD=4*3600
RECORD="stuck-workers.md"
VERDICTS=("working","waiting on a person","stuck")
SCHEMA={
"type":"object",
"properties":{
"verdict":{"enum":list(VERDICTS)},
"process":{"type":"integer","description":"The pid of the process that holds the worker, from the evidence."},
"why":{"type":"string","description":"One sentence on why that process holds it."},
},
"required":["verdict","process","why"],
"additionalProperties":False,
}
PROMPT=f"""A headless Claude Code worker hasn't printed anything for {CHECK_EVERY} seconds. Judge from its shells below whether it is `working`, `waiting on a person` or `stuck`. Name the pid of the process it waits on, and say why.
"""What checks a worker for stuck shells: the rung its investigations run on, the project's transcript archive, each shell's CPU seconds at the last check, and the CPU seconds of each shell that showed a sign at the latest judgment."""
"""Has a headless claude judge the worker whose claude is proc, where a shell shows a sign and is due a judgment. The verdict, or why there is none, goes to the terminal and to RECORD."""
# A shell is judged again only where it used CPU since its judgment and then went idle, so one stall costs one call, and a stall after a `working` verdict still gets one.
line=f"stuck check: a headless claude judged the worker {judged['verdict']}, naming process {judged['process']} ({command_of(judged['process'],shells)}): {judged['why']}"
"""The sign that shell may hold its worker stuck, given the CPU seconds it had used at the last check; empty where it shows none."""
ifshell.runs_busy_tool:
return""
quiet=idle(shell,cpu_before,now)
ifnot(quietornow-shell.started>OLD):
return""
returnf"shell {shell.pid} has run {int(now-shell.started)} s and written no output for {int(now-shell.written)} s{f', and used no CPU for {CHECK_EVERY} s'ifquietelse''}: {shell.command}"
"""The command line of the process pid among shells and the processes below them, as the evidence shows it; `not in the evidence` where neither holds pid, and `no command line` where its line is empty, as a defunct process's is."""
"""A headless claude's verdict on the worker holding shells, as SCHEMA has it, or why there is none. It runs without tools, so it judges only the evidence it is handed."""
evidence="\n\n".join(f"Shell {shell.pid}: {shell.command}\nIts processes, as pid, state, CPU and command line:\n{chr(10).join(shell.processes)or'none'}\nThe end of its output:\n{shell.outputor'none'}"forshellinshells)
self.session=interrupt.WorkerSession(str(self.home),uuid.uuid7(),Rung("m","high"),Rung("m","high"),str(self.transcript),{"LOOP_CLAUDE_WORKER_RUNG":"m at high effort"})
"""Appends the worker's last message, sent minutes_ago before NOW, whose usage wrote written_1h tokens to the hour-long cache, written_5m to the five-minute one, and read read tokens from the cache."""
self.assertIn(f"\n{STAMP} compacting the worker's claude session before its prompt cache expires; an answer typed meanwhile is read once that ends\n\n{STAMP} compacted the worker's claude session\n",said)
self.assertIn(f"\n{STAMP} could not compact the worker's claude session: claude exited 1\n",said)
deftest_stops_off_a_terminal_before_asking(self):
fake=FakeEffects(on_terminal=False)
self.assertEqual(self.put(fake),(Stop(2,"the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"),f"\n{STAMP} Which one?\n"))
fortyped,why,saidin(("","nothing was typed",""),(EOFError(),"the input ended","\n")):
withself.subTest(why=why):
self.assertEqual(self.put(FakeEffects(inputs=[typed])),(Stop(2,f"the human is needed to answer the question above, but {why}"),f"\n{STAMP} Which one?\n{said}"))
self.assertEqual(verdict_from({"escalation":"","answered_before":"","left_open":"","reversed":"","answer":"","interrupt":True,"evidence":"e","finished":False,"question":"Cut 0.2.0?"}),Failure("the judge's reply has no release_ready of type boolean"))
self.assertEqual(verdict_from({"escalation":"","answer":"A.","interrupt":False,"evidence":"e","finished":True,"question":"","answered_before":"","left_open":"","reversed":"","release_ready":False}),Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"escalation":"","answer":"","interrupt":"no","evidence":"","finished":True,"question":"","answered_before":"","left_open":"","reversed":"","release_ready":False}),Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"escalation":"","answer":"","interrupt":False,"evidence":None,"finished":True,"question":"","answered_before":"","left_open":"","reversed":"","release_ready":False}),Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"escalation":"","answer":"","interrupt":True,"evidence":"x","finished":False,"question":"","answered_before":"","left_open":"","reversed":"","release_ready":False}),Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from(None),Failure("the judge returned no reply"))
reply={"answer":"","escalation":"","interrupt":True,"evidence":"e","finished":False,"release_ready":False,"answered_before":"Grant one more round.","left_open":"one more","question":"Which one?","reversed":""}
self.assertEqual(verdict_from(reply),Interrupt("e","Which one?",answered_before="Grant one more round.",left_open="one more"))
self.assertEqual(judge.quotes_checked(QuotedAnswer("s","q","the records"),judge.Grounds("shown","shown","From the records: the records")),QuotedAnswer("s","q","the records"))
returnjudge.judge_once("/r",judge.Brief("Do it.","## Goals","","the project's decisions","the plan or a comment",kinds(*entries),mark,"loop-claude"),Rung("judge-model"),FakeEffects(claude=[judged("unfinished",escalation=escalation)]).effects())
entries=[assistant({"type":"text","text":"round 2: 🔴"}),{**human("as the work remaining: round 2: 🔴"),"promptSource":"sdk"},human("round 2: 🔴 again"),assistant({"type":"text","text":"working"})]
verdict=judge.judge_once("/r",judge.Brief("Do it.","## Goals","","the project's decisions","the plan or a comment",kinds(*entries),1,"loop-claude"),Rung("judge-model"),FakeEffects(claude=[judged("unfinished",escalation="round 2: 🔴")]).effects())
verdict=judge.judge_once("/r",judge.Brief("Do it.","## Goals","","the project's decisions","the plan or a comment",kinds(*entries),1,"loop-claude"),Rung("judge-model"),FakeEffects(claude=[judged("unfinished",evidence="round 2: 🔴")]).effects())
entries=[human("Do the next chunk. "+"x"*judge.JUDGE_PROMPT_CHARS),assistant({"type":"text","text":"Merged."})]
defjudged_on(evidence):
returnjudge.judge_once("/r",judge.Brief("Do the next chunk.","## Goals","","the project's decisions","the plan or a comment",kinds(*entries),0,"loop-claude"),Rung("judge-model"),FakeEffects(claude=[judged("unfinished",evidence=evidence)]*3).effects())
self.assertEqual(judged_on("Do the next chunk."),Unfinished("Do the next chunk.",entries_read=2))
self.assertEqual(judged_on("Do the next chunk. ... Merged."),Unfinished("Do the next chunk. ... Merged.",entries_read=2))
self.assertIsInstance(judged_on("Do the next release."),Failure)
"""An unfinished verdict: the worker took in an item of that L, 0 for none, and the judge found an escalation after reading escalated_at transcript entries, None for none."""
self.assertEqual(run.question_for(cycle,QuotedAnswer("e","Which one?","A.")),"Which one?\n\nthe project's records says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
"""Each outcomes file's text without its `Judge run:` lines, which name a file by the hash of a prompt and its reply: the tests of the judge's runs check them."""
self.assertEqual(fake.worker_environments,[{"LOOP_CLAUDE_PROJECT_RUNG":"claude-opus-5-5 at medium effort","LOOP_CLAUDE_WORKER_RUNG":"claude-haiku-5-5 at max effort","LOOP_CLAUDE_ESCAPE_AND_IMPACT":"5","CLAUDE_CODE_AUTO_COMPACT_WINDOW":"200000","BASH_MAX_OUTPUT_LENGTH":"6000"}])
self.assertEqual(self.archived_outcomes(),[f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n",f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n\nWorker: {OFF_LADDER}\n"])
f"{stamp} Judge reply rejected: the judge's reply has no answer of type string\n\nReply:\n> {unfilled.stdout}\n\nJudge: judge-model\n\n"
f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the task or the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n"
transcript.write_text("\n".join(json.dumps(entry)forentryin[{"type":"queue-operation","timestamp":"2026-09-21T14:00:00Z"},old,human("No, keep the old name."),new])+"\n")
withcontextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(self.archive,str(transcript),"Do it.",outcomes.unfinished("w","e","j","",annotation=outcomes.Annotation("c","Spent since the chunk began, in tokens of x:\n- worker, m: 1")),NOW,replace=replace_file))
fake=FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)],claude=[judged("unfinished",reversed="No, keep the old name.")])
self.assertEqual(run.run_cycle(self.cycle(fake,records="From AGENTS.md:\nUse A.")),Stop(2,"the human is needed to answer the question above, but nothing was typed"))
resumed=fake.made("stream_claude")[1]
self.assertEqual(resumed[resumed.index("-p")+1],"Your question: Which one?\n\nthe project's records answers it:\n\nUse *A*.\n\nContinue the task.")
self.assertEqual(printed.getvalue().count("=== the project's records answered: Which one? ===\nUse *A*."),3)
self.assertIn("Which one?\n\nthe project's records says:\nUse *A*.\n\nThose files have answered 3 questions this cycle",said.getvalue())
quoted=f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nthe project's records says:\n> Use *A*.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"
self.assertEqual(self.archived_outcomes(),[f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nthe project's records says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n",*[f"Task: Do it.\n\n{quoted}"]*3])
self.assertTrue(resumed[resumed.index("-p")+1].endswith("Continue the task. Your request for a higher rung went through: a-driver runs you on claude-opus-5-5 at medium effort. The escalation triggers that fired before this step are spent. You hold claude-opus-5-5 at medium effort."))
self.assertEqual(run.run_cycle(self.cycle(fake,records="From AGENTS.md:\nUse B. Use A.")),Stop(2,"the human is needed to answer the question above, but nothing was typed"))
self.assertEqual(stop,Stop(1,f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then run it again; a run before that resumes the finished chunk's session"))
thread=[turn("m1","a","2026-11-01T10:00:01Z",output_tokens=7),turn("m2","a","not a time",output_tokens=3),turn("m3","a","2026-11-01T10:00:02Z",output_tokens=1)]
forname,metain[("agent-a",{"agentType":"Explore","description":"Search the hooks"}),("agent-b",None),("agent-c",["Explore"]),("agent-d",{"description":"Läs"}),("agent-e",{"agentType":"Ex\nConfig: x"})]:
shown="[human] Use A.\n[human] No, keep the old name. Use X.\nworking: keep the new name"
typed=("Use A.","No, keep the old name. Use X.")
forquoted,keptin[("No, keep the old name. Use X.","No, keep the old name. Use X."),("keep the old name","No, keep the old name. Use X."),("Use","No, keep the old name. Use X."),("keep the new name",""),("No, keep the name.","")]:
defshell(pid=7,cpu=2.0,started=NOW-1000,written=NOW-1000,runs_busy_tool=False,processes=("8 S 2.0 s python3 -m pytest","9 S 0.0 s sh -c trap '' INT; sleep 999"),output="collected 40 items",holds_slot=False):
"""Runs a worker whose claude prints events and holds the shells held, while each investigation replies in turn; returns the claude, the fake, what was said on stdout and stderr and the record's text. The archive folder is archive, or else one that doesn't exist yet, as for a project's first stop. Where each_check is given, each check finds the next of its shells alone."""
self.assertEqual(json.loads(args[args.index("--json-schema")+1])["properties"]["verdict"]["enum"],["working","waiting on a person","stuck"])
self.assertTrue(prompt.endswith("\n\nShell 7: bin/run-tests\nIts processes, as pid, state, CPU and command line:\n8 S 2.0 s python3 -m pytest\n9 S 0.0 s sh -c trap '' INT; sleep 999\nThe end of its output:\ncollected 40 items"))
line="stuck check: a headless claude judged the worker stuck, naming process 8 (python3 -m pytest): pytest waits on a shell that ignores SIGINT"+sign(1600,1600)
self.assertTrue(prompt.endswith("\n\nShell 7: bin/run-tests\nIts processes, as pid, state, CPU and command line:\nnone\nThe end of its output:\nnone"))
self.assertIn(f"stuck check: a headless claude judged the worker working, naming process 7 (bin/run-tests): the tests still print{sign(stuck_workers.OLD+300,10,idle=False)}{sign(stuck_workers.OLD+300,10,idle=False).replace('shell 7','shell 10')}\n",said)
self.assertEqual(said,f"<{NOW+600}> stuck check: a headless claude judged the worker stuck, naming process 99 (not in the evidence): the tests hang{sign(1600,1600)}\n")
limited=ran(json.dumps({"type":"result","api_error_status":429,"result":"You've hit your limit"}))
forreply,reasonin((ran(code=1,stderr="no model"),"no model"),(verdict("hung"),"answered outside its schema: {'verdict': 'hung', 'process': 8, 'why': 'pytest waits on a shell that ignores SIGINT'}"),(ran("crashed"),"the stuck check printed no json reply; its last line was: crashed"),(limited,"claude hit a limit: You've hit your limit")):
self.assertEqual(tmux.start_window(window,"/r",{},["x"],True,True,failed),Failure("tmux could not start the window loop-proj:item-7: duplicate session: loop-proj"))
self.assertEqual(tmux.start_window(window,"/r",{},["x"],True,True,silent),Failure("tmux could not start the window loop-proj:item-7: it exited 2"))
returnsubprocess.CompletedProcess(args,1iffailselse0,""iffailselse"@9\n","no such session\n"iffailselse"")
returnrun
window=tmux.Window("loop-proj","item-7","")
self.assertEqual(tmux.start_window(window,"/r",{},["x"],True,True,answering(tmux.OWNER)),Failure("tmux started the session loop-proj but could not mark it as this checkout's: no such session"))
self.assertEqual(judge.run_judge("/r",[],"",judge.Grounds("","",""),fake.effects()),Limited(None,"You've hit your session limit · resets 7:40pm (Europe/Stockholm)"))
"""The tmux commands an entry point runs: each chunk's loop runs in its own window of one tmux session, which loop-claude names for the project and do-epic for the epic (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
importdataclasses
importre
importsubprocess
importtyping
fromfailureimportFailure
# Runs tmux with these arguments and returns what it printed; exit 127 where tmux cannot start.
# The oldest tmux that has every command and option used here. Its CHANGES file dates the newest two to 3.2: `remain-on-exit failed` and `new-session -e`.
NEEDED=(3,2)
# What a window's name ends in while its chunk waits for the human. tmux's status bar shows the name, and `!` after it once the bell rang.
WAITS=" ?"
BELL="\a"
# What follows a window's name while its chunk is parked, before what its pull request waits on, as in `ABC-34 awaits an approval`. A parked chunk takes no running slot (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates").
PARKED=" awaits "
# What a session's name opens with: LOOP for a project's chunks under loop-claude, EPIC for an epic's chunks under do-epic.
LOOP="loop"
EPIC="epic"
# The session option that names the checkout whose chunks the session runs, since two checkouts' keys may map to one session name.
OWNER="@loop-root"
# The window option that names the folder a window's chunk works in, so that loop-claude and every do-epic see the chunks a do-epic runs in a checkout.
ROOT="@chunk-root"
@dataclasses.dataclass(frozen=True)
classWindow:
"""The tmux window a chunk's loop runs in."""
session:str
# Without WAITS.
name:str
# The ID of the loop's pane, which $TMUX_PANE holds. It targets the window whatever its name is.
pane:str
@property
deftarget(self)->str:
"""What `tmux attach -t` and `tmux select-window -t` take to reach the window."""
returnf"{self.session}:{self.name}"
@dataclasses.dataclass(frozen=True)
classListed:
"""A window of the project's session, as tmux lists it."""
# Without WAITS, and without PARKED and what follows it.
name:str
# tmux's ID of the window, such as `@3`.
id:str
# Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable.
dead:bool
# What its name says its parked chunk awaits, as the words after PARKED; empty for a chunk that isn't parked.
awaits:str=""
# Whether its name ended in WAITS: its loop asks the human something.
asks:bool=False
@property
defparked(self)->bool:
returnbool(self.awaits)
@dataclasses.dataclass(frozen=True)
classPlaced:
"""A window of any session, as tmux lists it."""
session:str
window:Listed
# The folder its chunk works in, as ROOT names it; empty for a window started before ROOT was set.
root:str
defunusable(run:Tmux,driver:str)->str|None:
"""Why driver, the entry point, cannot use this machine's tmux, naming the version found and the one needed; None where it is NEEDED or later."""
returnf"{driver} runs each chunk in a tmux window, and needs tmux {NEEDED[0]}.{NEEDED[1]} or later; it found {foundor'no tmux'}"
defsession_name(kind:str,key:str)->str:
"""The tmux session an entry point runs its chunks in: kind LOOP with a project's key, such as `loop-claude-config`, or kind EPIC with an epic's key, such as `epic-ABC-12`. tmux reads `.` and `:` in a target as separators, so every character of the key but a letter, a digit, `_` and `-` becomes a dash."""
"""Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too, and owned marks a session it makes as running the chunks of the checkout cwd. A Failure says why tmux started none, or why it could not mark the session."""
# By the ID, since a window of the same name may still be closing. A failed remain-on-exit doesn't matter: a loop that fails before it is set closes its window, and its stop is still sent as a DM.
# Without the owner, start_chunks cannot tell this checkout's session from another's, so no further chunk may start in it.
ifmarkedisnotNoneandmarked.returncode:
returnFailure(f"tmux started the session {window.session} but could not mark it as this checkout's: {marked.stderr.strip()orf'it exited {marked.returncode}'}")
"""Starts a chunk's command in window, in place of each dead window of its name among windows, the session's; the session's windows afterwards, or why tmux started none. start_window says what cwd, env and owned do."""
"""Shows window's chunk as parked. on is what the chunk awaits, such as `an approval` or `a slot`: the name says so, and no checkout counts a window so named as a running chunk."""
"""Shows window's chunk as running again, in the folder root. The window may name another folder: one started again for a parked chunk starts in the epic's folder."""
"""The verdicts judge.verdict_from builds from the judge's reply; run.rule then stamps every verdict but Finished with the items the chunk takes. They sit in a module of their own, since routing.py reads them and run.py imports routing.py."""
importdataclasses
fromtranscript_archive.judge_runimportJudgeRun
fromclaude_code.tokensimportTokens
@dataclasses.dataclass(frozen=True)
classTakenIn:
"""The highest L, and the highest E + I, among the plan items the worker names on its latest `Chunk items:` line, as the entry point reads them (run.py's Cycle.taken_in). The item the chunk was routed on counts only where the worker names it."""
# The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it.
highest_likelihood:int=0
# The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's reviewers.
highest_escape_and_impact:int=0
@dataclasses.dataclass(frozen=True)
classJudged:
"""What the judge run that gave a verdict found beside it, which the cycle archives with the verdict."""
# In dollars, as its reply records; 0 where it records none.
cost:float=0.0
# Its reply's usage, on the judge's model.
tokens:Tokens=Tokens()
# The human's whole typed answer that holds the judge's quote of a reversal of a choice the worker took on its own recommendation; empty for none, and where no typed answer holds the quote.
reversed:str=""
# The prompt it read and its reply, which the archive keeps beside the verdict. Left out of comparisons and reprs, so that equal verdicts stay equal whatever prompt they came from.
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
escalation:str=""
taken_in:TakenIn=TakenIn()
release_ready:bool=False
# How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
entries_read:int|None=None
judged:Judged=Judged()
# The [human] line from earlier in the chunk that answered the same question, and the words of it that leave the question open; empty for none. cycle.judge.re_ask_checked turns the Interrupt into an Unfinished where the question doesn't quote them.
answered_before:str=""
left_open:str=""
@dataclasses.dataclass(frozen=True)
classQuotedAnswer:
"""The worker asked a question that the premises or the records answer. The answer field quotes the passage."""
# Seconds between reads of the machine's memory while too little of it is available to start a worker.
MEMORY_POLL=60
# The auto-compact window, in tokens, handed to the worker's claude in the environment variable AUTO_COMPACT_WINDOW names. Claude Code compacts before the window fills, at about 170k: docs/decisions.md → `loop-claude: the worker's claude compacts its context before it fills a 200k window`.
"""Runs the worker's claude once the machine has room for it, as run_claude does with a Watch whose stuck checks run on investigator, the project's rung."""
"""Runs a headless claude at once, printing what it says, and returns how it failed, or None. Where watch is given, a claude that lingers after its final result loses its quiet shells, as `lingering_workers.stopped_shells` says, each stop appended to RECORD in watch's archive; and a silent claude that has printed no result is checked for stuck shells, as `stuck_workers` says."""
try:
proc=effects.stream_claude(args,root,env)
exceptOSErrorasfailure:
returnFailure(f"could not start claude: {failure.strerror}")
result:dict|None=None
# Whether the worker's latest line is its result; a worker that prints on is working.
"""Returns once the machine has room for a worker, or its memory cannot be read, so loops running at once do not push it into swap. While it waits, it says so once on stderr and reads the memory again each MEMORY_POLL seconds."""
say(f"waiting to start the worker until at least {ROOM_SHARE:.0%} of the machine's memory is available; {memory.available//1024} MiB of {memory.total//1024} MiB is available now",effects)
"""A worker's prompts: those the entry point driving the cycle words, and those that resume a worker with an answer to its question.
Anentrypointisatoolthatdrivescycles,suchasloop-claude.Itwordsthepromptsofitsownworkflowandnamesthefilesofitsproject.WorkerPromptsholdsthose,sothecycledoesn't import an entry point to word a prompt.
"""
importdataclasses
importre
importtyping
frommodel_routing.ladderimportProjectRung
frommodel_routing.routeimportRoute
fromclaude_code.transcriptimportTyped
# Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds.
TYPED_HERE="The human answered your question at {driver}'s terminal:"
# Finds TYPED_HERE whatever the driver, so a transcript reads the same to every tool that renders it.
# The prompt that resumes a worker whose previous run ended before the chunk was finished, from the evidence of the unfinished verdict, if there was one.
"""The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it."""
returnf"{TYPED_HERE.format(driver=self.driver)}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {answers_recorded(self.answer_destinations)}.{self.stepped_to(route,project,stepped)}"
"""The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise."""
returnf" Your request for a higher rung went through: {self.driver} runs you on {route.rung}. The escalation triggers that fired before this step are spent.{self.rungs_held(route,project)}"ifsteppedelse""
"""The question a quoted answer puts to the human once the cycle's quoted answers reach the cap."""
returnf"{question}\n\n{self.quote_sources} says:\n{answer}\n\nThose files have answered {cap} questions this cycle, the most allowed, so this one comes to you."
"""What the Jira and Confluence backends share: one Atlassian account's credentials, the request both backends send, and each service's error messages."""
importbase64
importpathlib
importtyping
fromfailureimportFailure
fromrest_clientimportjson_request
fromrest_client.env_fileimportread_env
fromadf_codec.convertimportRefused
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
KEYS=("ATLASSIAN_EMAIL","ATLASSIAN_API_TOKEN")
# Seconds each connect and each read may wait.
TIMEOUT=30
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
"""What every reader of Jira Cloud's REST API version 3 shares: a search read page by page, the key, fields, "is blocked by" links and property of each issue it finds, checked for their shape, and the transition that finishes an issue."""
"""The Entry of one issue a search finds, or which issue is not in the shape Jira documents, and how. property_ names the issue property the search asked for."""
"""One transition Jira offers, as its ID, its name, the name of the status it leads to and the key of that status's category; None where raw holds no such transition."""
"""The transitions Jira offers the issue named key from its present status, each as offer_of answers one. A Failure where offered, Jira's answer, is in another shape."""
"""The ID of the transition finish names, as Jira offers it now for the issue named key, which is a plan item or an epic; or why none of those offered finishes it."""
"""Moves the issue named key by the transition with the ID transition, which finishing_transition answered for finish. Why Jira did not take the move; None where it did."""
"""The ID of the transition finish names, among those Jira offered for the issue named key, which are the ones its present status has; or why none of them finishes the item."""
others=" and ".join(f"{name!r} to {status!r}"for_,name,status,_infound)
returnFailure(f"{key} has no transition {finish.transition!r} from its status, "+(f"only {others}: move the issue in Jira to a status that has it, or name in `{JIRA_FINISH_TRANSITION}` one that leads to a done status"iffoundelse"nor any other the account may make"))
returnFailure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, not to {finish.status!r}, which `{JIRA_FINISH_STATUS}` names")
# `children` reads an issue as finished by its status's category, so a move to any other category would leave the item in the plan.
ifcategory!=DONE:
returnFailure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, which Jira doesn't count as done, so the item would stay in the plan: name a transition to a done status")
returnf"{project} has no issue type {kind!r} for an issue under an epic; "+(f"it has {listed(names,'and')}: name one in `{setting}`"ifnameselse"it has no other type for one")
defproject_of(key:str)->str:
"""The key of the Jira project an issue key lies in."""
"""Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors."""
"""Every issue a JQL search on site finds, page by page, up to max_pages pages. The dict asked holds the request's `fields` and `properties` lists. The text what names the issues sought, in the Failure of a search that doesn't end."""
({"errorMessages":["Issue does not exist or you do not have permission to see it."],"errors":{}},"Issue does not exist or you do not have permission to see it."),
base=self.serve((409,b'{"errors": [{"status": 409, "title": "Version must be incremented"}]}'))
self.assertEqual(client.confluence_json("PUT",f"{base}/wiki/api/v2/pages/1",AUTHORIZATION,{"version":{"number":2}}),ErrorAnswer("PUT /wiki/api/v2/pages/1 answered 409: Version must be incremented",409))
self.assertEqual(client.confluence_errors({"errors":[{"status":409,"title":"Version must be incremented"},{"title":"and more"},"odd"]}),"Version must be incremented; and more")
self.assertEqual(entry_of(raw(BLOCKED|{"id":9}),"plan"),Failure(SHAPE+"its issuelinks hold a link whose id or whose linked issue's key is no text"))
self.assertEqual(entry_of(raw(BLOCKED|{"inwardIssue":None}),"plan"),Failure(SHAPE+"its issuelinks hold a link whose id or whose linked issue's key is no text"))
self.assertEqual(self.refusal("Task",self.TYPES),"ABC has no issue type 'Task' for an issue under an epic; it has Feature and Bug: name one in `jira-finding-type`")
self.assertEqual(self.refusal(kind,self.TYPES),f"ABC has no issue type {kind!r} for an issue under an epic; it has Feature and Bug: name one in `jira-finding-type`")
self.assertEqual(self.refusal("Bug",{"issueTypes":[{"name":"Subtask","subtask":True}]}),"ABC has no issue type 'Bug' for an issue under an epic; it has no other type for one")
# The plan, and the records tools append to: none of their lines are the chunk's work.
NOT_WORK=("todo.md",HISTORY,RECORD)
# Each commit as its hash, commit and author times and parents, its short hash and title, then the files it changed; a merge's files are those it changed against its first parent. git refuses a NUL byte in a commit message, so a title can't split a record.
# A title opening `Drop item 69: <why>` or `Drop items 69, 70 and 71: <why>` removes those items unbuilt; only at the start, where a log skimmed by its titles shows it.
DROP=re.compile(r"Drop items? ([0-9]+(?:, [0-9]+)*(?: and [0-9]+)?):")
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
Landing=typing.Literal["merge","rebase","push"]
@dataclasses.dataclass(frozen=True)
classCommit:
"""A commit as LOG prints it; committed and authored are its commit and author times, in seconds since the epoch."""
hash:str
short:str
committed:int
authored:int
parents:tuple[str,...]
title:str
files:tuple[str,...]
@dataclasses.dataclass(frozen=True)
classSpan:
"""A chunk on a default branch, as cut_branch cuts it. before is the commit its change starts from, None for the branch's oldest chunk; tip is its newest commit on the first-parent line. label names it as the reports do, landing says how it reached the branch, and merged is tip's commit time. titles are those of every commit it brought."""
before:str|None
tip:str
label:str
landing:Landing
merged:str
titles:tuple[str,...]
@dataclasses.dataclass(frozen=True)
classBranchChunk(Span):
"""A Span with two more fields: shipped holds each todo.md item its change removed, as scored before the change, less any item one of its commit titles drops; fixed_by names the later chunks that fixed code it shipped, newest first."""
shipped:tuple[Item,...]
fixed_by:tuple[str,...]
@dataclasses.dataclass(frozen=True)
classBranch:
"""A default branch's commits by hash, its chunks newest first, and each commit's chunk as an index into chunks."""
"""Each commit LOG printed, by hash, in the order it printed them, its title read as its summary in titles, the project's title templates. So a round title or a `Drop item` title reads the same in every project."""
commits={}
forrecordinlog.split("\x00")[1:]:
found=LOG_RECORD.fullmatch(record)
ifnotfound:
returnFailure(f"git log printed a commit it could not read: {record[:200]!r}")
"""The first-parent line, newest first, cut into chunks, newest first, each holding its commits newest first. A merge is a chunk of its own; any other commit joins the chunk of the newer commit above it when that is no merge and both share a commit time."""
"""How a run that chunk_log cut reached the branch: by a merge commit, by a rebase that gave a commit a commit time other than its author time, or by commits never replayed."""
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before, less those a title of the change drops; none where either holds no items table it can read."""
"""The revisions whose todo.md shipped_by needs: for each chunk that brought a commit changing todo.md, other than the branch's oldest chunk, the commit before it and its tip."""
"""The items each of the branch's chunks shipped, in the order of its chunks. plans holds todo.md's text at each revision plan_revisions names. A chunk with a revision plans lacks changed no plan, so it shipped none, nor an item one of its titles drops."""
"""The later chunks that fixed code each chunk on a default branch shipped: its escaped defects.
Alaterchunkfixedcodeanearlierchunkshippedwhereoneofitschangesremovesorrewriteslinesthat`gitblame`tracestoacommittheearlierchunkbrought.Twokindsofchangecount:thechunk's whole change, where it ships a todo.md item marked `defect` or `security`; and a round commit of the chunk whose title counts both a 🔴 and a misread finding. Each later chunk counts at most once against each earlier chunk."""
"""Each change that fixes a defect: the whole change of each chunk that ships a FIXES item, as shipped_by lists them, and each round commit whose title counts both a 🔴 and a misread finding."""
"""The branch's chunks, each with the items it shipped, as shipped_by lists them, and the later chunks that fixed code it shipped, from the commits each fixing change traced to."""
fixed:dict[int,set[int]]={}
forchangeintraced:
forcommitinchange.commits:
# Blame at a commit on the branch should name only commits its log holds; any other counts against no chunk. Chunks run newest first, so > keeps the chunks older than the fixing one.
"""The old lines each hunk of a `git diff -U0` removes or rewrites, as its first line and count, by the path the file had before; none for a path git quotes, as it does one holding a byte it cannot print."""
"""Why branch_chunks cannot tell what the chunks of checkout's project shipped, else the current directory's: its config under home puts the plan or a record where their commits are not read. None where it can, as for a checkout no config names."""
returnf"the project's config puts {', '.join(elsewhere)} elsewhere than {', '.join(READ_AT.values())} in the checkout, the only paths whose commits are read so far"
"""What a message calls the plan or the record that setting name names in config, and its path from the checkout's top, None where it is kept elsewhere."""
"""Each chunk on the default branch's first-parent line, newest first, with the todo.md items it shipped and the later chunks that fixed code it shipped.
titlesholdstheproject's title templates, which each commit'stitleisreadthrough.runmustrungitinthecheckout's top: the diff names each path from the top, while blame and a pathspec read a path from the current directory."""
# The -- keeps a file named like the branch from making it ambiguous.
"""The commits that last changed each line of a chunk's work that the change from before to tip removes or rewrites."""
# The prefixes and options keep the checkout's diff config out of the output. Only hunk headers, paths and commits are read, so a file's text that is not UTF-8 is replaced.
# --no-ignore-revs-file drops each revs file the config names, since blame fails on one that is missing. An empty --ignore-revs-file= doesn't: blame opens the configured files first.
log=f"\x00{'a'*40} 100 100 {'b'*40}\x1faaaaaaa\x1fPAY-7 - Drop item 6: moot\n\nb.py\n\x00{'b'*40} 90 90 \x1fbbbbbbb\x1fFrom before the template\n\nb.py\n"
self.assertEqual(unsupported(str(checkout),home,run),f"the project's config puts {folder}/todo.md, {checkout}/records/reading-cost.md elsewhere than todo.md, docs/comprehension-history.md, docs/reading-cost.md in the checkout, the only paths whose commits are read so far")
"""What the entry points that drive chunks share: loop-claude and do-epic.
Eachrunsachunkascyclesofbin/agent_cycle/.cycle_start.pystartsacycleandchunk_run.pyclosesit,ontheLoopthis_loop.pyholds,onceclaims.pyhasclaimedthecheckout.prompts.pywordswhateveryworkeristold,project/readsacheckout's premises, records and saved models, and drivers.py names the entry points. No module here imports an entry point'spackage,andbin/repo_checks/test_package_cycles.pyfailsonsuchanimport.
"""One chunk's run across its cycles, for every entry point that drives chunks: its state (Run, ChunkRun), and how a cycle closes: the run the next cycle starts from, the step-up an unfinished verdict makes archived, and the stop once a chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts.
UNFINISHED_LIMIT=6
classRun(typing.Protocol):
"""What closing a cycle reads and replaces in an entry point's run of one chunk. ChunkRun below is one; loop-claude's LoopRun is another, since it hands the same fields on at a reload."""
# Every run is a dataclass, which is what lets closing a cycle replace its fields.
"""The run after a cycle of driver, the entry point, concluded on the chunk's task, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
after=after_verdict(run,project,concluded)
# A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts.
ifafter.routeisNone:
returnafter
# The unfinished verdict, archived as the cycle closed, names the route its cycle ended on; the step-up names the one the next cycle runs on.
"""The stop that needs the human once the run holds UNFINISHED_LIMIT unfinished verdicts running."""
ifrun.unfinished_run<UNFINISHED_LIMIT:
returnNone
returnneeds_human("go on with the chunk",f"the judge ruled it unfinished {run.unfinished_run} cycles running; finish the chunk yourself, or rerun {driver} to give it {UNFINISHED_LIMIT} more cycles")
"""The run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route routing.next_route makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised, and the evidence the judge gave for the verdict; and counts the verdict."""
"""How entry points claim a checkout before they start a chunk in it, so that two never start the same chunk and do-epic never starts one where loop-claude runs.
Anentrypointholds`starting`on`project_lock`whileitliststhewindowsofthecheckout's chunks and starts new ones. Where the lock cannot be taken, `starting` yields a Failure, and the entry point doesn'tstartanychunk.ItstartseachchunkinatmuxwindowwithCHUNK_FLAG,andhandsthatwindowthevariablesnamedwithHANDED.
# Under the home folder, a folder per project key holds LOCK.
CLAIMS=".local/state/loop-claude"
# The file an entry point keeps locked with flock while it lists the windows of a project's chunks and starts new ones. Two loops whose chunks finish together then don't start a chunk twice, and do-epic, which holds the same lock, never starts a chunk in a checkout while loop-claude does.
LOCK="starting"
# The flag that tells the entry point in a window its chunk, as `--chunk item-372` for loop-claude and `--chunk ABC-34 ABC-12` for do-epic. Nobody types it, so no panel picked it.
CHUNK_FLAG="--chunk"
# The prefix of the variables both entry points read. A window gets the tmux server's environment, not the starting terminal's, so they are handed to each window by name.
"""Holds the LOCK in folder: project_lock's for a project, or do-epic's for an epic. It yields a Failure, and doesn't hold any lock, where the file cannot be opened or locked."""
"""Holds a flock on file, which it makes with its folder. It yields a Failure, and doesn't hold any lock, where the file cannot be opened or locked."""
"""The windows of loop-claude's chunks that run in the checkout root. A session that runs another checkout's chunks under the same name doesn't hold any."""
"""How a cycle starts, for every entry point that drives chunks: the models and the ladder it routes on, the route its worker runs on, and the Cycle built from them.
"""The routing of the project checked out at the loop's root: its models, asked of the human where none is saved, and its ladder. The stop where one cannot be read."""
"""The route cycle cycle_number runs on, printed with the cycle's opening line. kept_route is the one the chunk's run holds, and item finds what routes a fresh chunk."""
"""The release and commit of this setup that the worker's claude reads, as `v0.8.0 (<sha>)`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 (<sha>)`. Where git can't tell, `unknown` and why."""
"""The entry points that drive chunks, each by its name as its workers, its judge and the human read it. A prompt function that takes a driver takes one of these."""
# The environment variables that name the judge's and the worker's model for one run, over the model saved or configured.
JUDGE_MODEL="LOOP_CLAUDE_JUDGE_MODEL"
WORKER_MODEL="LOOP_CLAUDE_WORKER_MODEL"
# The file, in CLAIMS under the home folder, that save_model keeps locked with flock while it rereads and replaces the models file. The models file's own folder is a checkout of this setup, which takes no lock file.
"""Adds the project's model to the models file, whose only writer this is, through replace, which writes a file as replace_file does. It holds MODELS_LOCK from its read to its write, so two entry points that save at once both keep their pick."""
"""Each project's model, as the models file at saved maps them; none where there is no such file. The entry points, loop-claude and do-epic, and the replay tools read it."""
try:
withopen(saved,encoding="utf-8")ashandle:
models=json.load(handle)
exceptFileNotFoundError:
return{}
except(OSError,ValueError)asfailure:
returnFailure(f"could not read {saved}: {getattr(failure,'strerror',None)orfailure}")
"""Where the goals file is kept, then its ## Goals and ## Audience. The goals file is the one that the config of root's checkout, under home, names: a file or a Jira epic's description. A Failure where no config names the checkout, or the goals file cannot be read, is missing or empty, lacks a section, holds one twice or leaves one empty."""
config=located(root,home)
ifisinstance(config,Failure):
returnFailure(f"{config.reason} - no premises.")
goals=goals_store(config)
text=goals.read()
ifisinstance(text,Failure):
returnFailure(f"{text.reason} - no premises.")
ifnottext:
returnFailure(f"{goals.label} is missing or empty - no premises.")
bodies:list[str]=[]
fornamein("Goals","Audience"):
body=section(text,name)
ifisinstance(body,Failure):
returnFailure(f"{goals.label}{body.reason} - no premises.")
# The records the judge reads beside the premises, by the name that heads each, with the setting in the project's config that places it; then the human's rules below.
WORKING_RULES=("AGENTS.md","working-rules")
DECISIONS=("docs/decisions.md","decisions")
RECORD_FILES=(WORKING_RULES[0],DECISIONS[0])
# The human's rules, in the order the judge reads them: ~/.claude/CLAUDE.md, each .md file in ~/.claude/rules/,
# then each .md file in the review standards folder the project's config sets.
HUMAN_RULES_FILE="CLAUDE.md"
HUMAN_RULE_DIR="rules"
# How the judge's prompt names the records above, in the order it reads them.
RECORDS_NAMED="the project's working rules and decisions, then the human's rules for every project"
"""The project's `AGENTS.md` and decision log, then the human's rules, CLAUDE.md first, each headed by its name. One that does not exist, or is empty, is left out. A text that several of them hold appears once, headed by all their names.
`AGENTS.md`isreadwheretheconfigunderhomeofroot's project puts it, and the decision log from the store that config names. Each is headed by its name in RECORD_FILES wherever it is kept.
firstholdsrecordskeptoutsidetheproject,suchasthesectionsofaJiraepic's description, each as its heading and text: they come before the project's.ArootofNoneisworkwithoutacheckout,whichhasnoprojectrecordsandnoreviewstandards."""
self.assertEqual(model_choice.get_or_ask_model("proj",self.paths,LOOP_CLAUDE,fake.effects()),Stop(1,f"could not save the model in {self.paths.models_file}: could not save"))
self.assertEqual(model_choice.ask_for_model("proj",pathlib.Path("/m.json"),pathlib.Path(empty),LOOP_CLAUDE,fake.effects()),Stop(2,"the human is needed to pick proj's model, but the input ended"))
self.assertTrue(records.read_records(root,claude_md.parents[1],claude_md.parent).endswith(f"From {root}/standards/quality.md:\n# Elsewhere"),"a folder outside home is named in full")
self.assertTrue(records.read_records(root,claude_md.parents[1],claude_md.parent).startswith("From AGENTS.md and docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global"),"a file the config names for two records appears once")
self.assertTrue(records.read_records(root,claude_md.parents[1],claude_md.parent).startswith("From ~/.claude/CLAUDE.md:\n# Global"),"the checkout's AGENTS.md and docs/decisions.md are its owners'")
self.assertEqual(records.read_records(root,claude_md.parents[1],claude_md.parent),Failure(f"no config names the checkout {root}: write ~/.claude-projects/<key>/config.toml, as `project-config --help` shows - the judge cannot read the records."))
self.assertEqual(records.read_records(root,claude_md.parents[1],claude_md.parent),Failure(f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records."))
self.assertEqual(records.read_records(root,claude_md.parents[1],claude_md.parent),Failure(f"cannot read {root}/docs/decisions.md: Is a directory - the judge cannot read the records."))
self.assertEqual(records.read_records(root,claude_md.parents[1],claude_md.parent),Failure(f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records."))
self.assertEqual(records.read_records(root,claude_md.parents[1],claude_md.parent),Failure(f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records."))
"""What every entry point says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. An entry point places them in a chunk's first prompt, as loop-claude does in bin/loop_claude/chunk/fresh_prompt.py. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict."""
"""Where the security pass runs on another rung than the worker's, the sentence that a full scan runs only from the security pass's subagent, which shared_launches names just before: `Run a full scan only from such a subagent, since the scan's agents run on the model that starts them.`"""
return["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."]ifchoice.security!=route.rungelse[]
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores plan items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`"""
return[f"Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan {project.rung.model} <L>` prints."]ifproject.ladder.position(route.rung)<project.ladder.position(project.rung)else[]
"""The sentence that names choice.markdown_only, the rung a reviewer runs on where the branch changes only Markdown no agent follows. It is empty where that rung is the reviewers'. rule-hook's reviewer-rung holds a launch to the same rung. On an Opus 5.5 project it ends: `launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium.`"""
return[f"Where your branch changes only Markdown, none of it {files} or under {folders}, launch {EACH_REVIEWER} on the project's rung instead, with the Agent tool set to {choice.markdown_only.agent_args()}."]
"""A sentence for each rung, other than the worker's, that the reviewers, the seats or the security pass run on.
Foraworkeronerungbelowtheproject's, routed by item 3 of E + I 5, they read: `Launch each reviewer with the Agent tool set to <rung>, the rung item 3'sE+Iof5picks.`and`Launcheachcomprehensionseatandthesecuritypass's subagent with the Agent tool set to <rung>, the project'srung.`
return[f"Launch {listed(reviews,'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung,route,project)}."forrung,reviewsinlaunched.items()]
"""The sentence naming the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run, since loop-claude reads a taken-in item's E + I only as the cycle ends, and routes on it from the next cycle. None where no higher E + I picks a higher rung.
Foraworkerontheproject's rung, routed by an item of E + I 6, it reads: `Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `<rung>` from 7 and `<rung>` from 8.`
"""
ifnotchoice.higher:
return[]
picks=[f"`{rung.agent_args()}` from {escape_and_impact}"forrung,escape_and_impactinchoice.higher.items()]
return[f"Where an item you take into the chunk has an E + I of {min(choice.higher.values())} or more, launch {EACH_REVIEWER} with the Agent tool set to {listed(picks,'and')}."]
"""The prompt's escalation sentences, the marker's among them. None off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
Foraworkeronerungabovetheproject's, routed by item 3 of L 3, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `<rung>`, one rung above yours, and on each further trigger one rung higher, up to `<rung>`; above that, ask the human first.`, `Open the subagent'spromptwith`Escalationtrigger<n>:`,nthetrigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `<rung>`.`
f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{project.ladder.climbed(route.rung,1).agent_args()}`, one rung above yours, only once the human agrees; {driver} will not resume you higher for a trigger either, so ask the human for that yes.",
marked,
]
further=f", and on each further trigger one rung higher, up to {rungs[-1]}"iflen(rungs)>1else""
return[
f"When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to {rungs[0]}, one rung above yours{further}; above that, ask the human first.",
marked,
f"Where the hard part is the rest of the chunk, end your run instead, {asks_higher_rung(driver)} and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to {rungs[-1]}.",
"""The sentence naming the rung one above a reviewer's and the one above a seat's, on which each reruns when it asks, leaving out either that is already on the top rung. None off the ladder.
Foraworkeronerungbelowtheproject's, routed by an item of E + I 4, it reads: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `<rung>`.`
return[f"A {listed(list(rerun),'or')} that asks for a rerun one rung up reruns with the Agent tool set to `{next(iter(rerun.values())).agent_args()}`."]
return[f"A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."]
"""naming is the sentence that asks the worker to name its chunk's items, empty where the entry point reads none. Names the worker's rung, so it learns whether its request for a higher rung went through, and the project's again, since a step-up between cycles may have taken the worker above it."""
on=f"{driver} runs you on {route.rung}."ifprojectelse""
ruled=f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{quoted(unfinished_evidence)}\n\n"ifunfinished_evidenceelse""
returnf"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}.{namingandf'{naming}'}{on}{rungs_held(driver,route,project)}"
"""The names an entry point's prompts give the places that answer a question, the places that take an answer, and the records the judge reads; WorkerPrompts says what each field is."""
"""The prompts of an entry point's cycles: its own fresh prompt, and the resumed prompt and rung sentences every entry point shares, each naming driver. resumed says what naming is. names is loop-claude's unless the entry point keeps records elsewhere, as do-epic does."""
"""What closed_cycle answers for a-driver's chunk `Do it.`, after an unfinished verdict that follows unfinished_run others, and the outcomes it archived for a transcript not archived before."""
reason="the human is needed to go on with the chunk, but the judge ruled it unfinished 6 cycles running; finish the chunk yourself, or rerun a-driver to give it 6 more cycles"
self.assertEqual(stderr.getvalue(),f'{STAMP} routing the chunk afresh: the archive\'s latest Worker: line names no route that can be read: {{"model": "claude-opus-5-5", "rung": 3}}\n')
# The ladder's rungs around the project's: the one below it, its own, and those one to three steps up.
SONNET=Rung("claude-sonnet-5-5","high")
OPUS=Rung("claude-opus-5-5","medium")
FABLE_LOW=Rung("claude-fable-5-2","low")
FABLE_MEDIUM=Rung("claude-fable-5-2","medium")
OPUS_XHIGH=Rung("claude-opus-5-5","xhigh")
OPUS_PROJECT=ProjectRung(LADDER,OPUS)
# The sentence with which an entry point that exists only here asks its worker to name the chunk's items.
NAMING="Name the items."
SCAN=" Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."
SEATS=" Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung."
MARKDOWN=" Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium."
defheld(route,project=OPUS_PROJECT):
"""The rung sentences a-driver's worker reads on route, each after a space."""
self.assertTrue(resumed(Route(Rung("m")),None).startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once"))
self.assertTrue(below.startswith(f" Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{SCAN} Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger"),below)
self.assertTrue(level.startswith(f" Launch each reviewer with the Agent tool set to model fable, effort medium, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{MARKDOWN} When an escalation trigger"),level)
below=held(Route(SONNET,3,2,5))
self.assertTrue(below.startswith(f" Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{SEATS}{SCAN} Your rung is below the project's:"),below)
self.assertNotIn("Launch each reviewer",held(Route(FABLE_MEDIUM,3,4,6)))
taking_in=" Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8."
self.assertTrue(held(Route(OPUS,3,2,4)).startswith(f"{taking_in} When an escalation trigger"))
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.",held(Route(OPUS,3,2,6)))
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.",held(Route(FABLE_MEDIUM,3,4,4)))
self.assertNotIn("Where an item you take into",held(Route(OPUS,3,2,8)))
self.assertNotIn("Where an item you take into",held(Route(Rung("m")),None))
self.assertIn(f"a-driver runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{MARKDOWN} When an escalation trigger",resumed(Route(OPUS,3,2,5,escape_and_impact_taken_in=7)))
self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.",held(Route(OPUS,escape_and_impact_taken_in=5)))
sentences=f"{SEATS}{SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{MARKDOWN} When an escalation trigger"
self.assertIn(f"{prompts.ANSWERS_RECORDED}. {NAMING} a-driver runs you on claude-fable-5-2 at low effort.{sentences}",resumed(above))
self.assertTrue(routed.startswith(" Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number."),routed)
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.",held(Route(FABLE_LOW,3,3,4)))
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.",held(Route(FABLE_MEDIUM,3,3,4)))
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours, only once the human agrees; a-driver will not resume you higher for a trigger either, so ask the human for that yes.",held(Route(OPUS_XHIGH,3,3,4)))
self.assertIn("set to `model fable, effort max`, one rung above yours, only once the human agrees;",held(Route(Rung("claude-fable-5-2","high"),3,4,5)),"one rung below the top still names the rung above")
self.assertNotIn("rerun",held(Route(Rung("claude-opus-5-5","low"),3,3,4)),"a worker off the ladder is told no rerun rung")
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours;",held(Route(OPUS_XHIGH,3,4,5)))
self.assertTrue(unrouted.startswith(" Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking a-driver for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer"),unrouted)
offer=lambdacap:f" Where the hard part is the rest of the chunk, end your run instead, asking a-driver for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `{cap}`."
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer('model fable, effort low')}",held(Route(OPUS,3,2,4)))
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer('model opus, effort xhigh')}",held(Route(FABLE_LOW,3,3,4)))
self.assertNotIn("Where the hard part",held(Route(OPUS_XHIGH,3,3,4)))
self.assertTrue(resumed(Route(FABLE_LOW,3,3,4)).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`."))
self.assertTrue(resumed(Route(OPUS,3,2,7)).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`."))
self.assertTrue(resumed(Route(Rung("claude-fable-5-2","max"),3,4,8)).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."))
"""What stays the same while an entry point drives one chunk in one process. loop-claude builds it once per process, so a reload builds it afresh; do-epic builds one per chunk."""
# The checkout the loop runs in. loop-claude's LoopRun.root names it too, since a reload hands it on there.
root:str
# The worker's session.
session:Session
# The tmux window the loop runs in.
window:Window
paths:Paths
env:typing.Mapping[str,str]
# The entry point's script, beside which chunk-preflight lies; an edit of loop-claude's reloads its loop.
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed.
POLL_SECONDS=60
WAIT_SECONDS=90*60
# The environment variable do-epic sets to 1 for its chunks' workers. With it, merge doesn't wait for an approval: do-epic parks the chunk and polls the forge itself, so the chunk holds no running slot meanwhile (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates").
"""Whether merge waits for an approval. Never where a person merges the pull request (by_human): that person reads its approvals. Otherwise as the project config's `wait-for-approval` says; chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails, and the chunk never merges past an approval the config requires."""
ifby_human:
returnFalse
ifwait_for_approvalandforge!="gh":
returnFailure("the project's config sets wait-for-approval, but chunk-pr reads approvals on GitHub only, so it cannot merge this pull request; ask the human to merge it")
returnwait_for_approval
defapproval(number:str,run:Run)->bool|Failure:
"""Whether GitHub reports pull request number approved, as its branch protection asks, read once: False while it still wants a review. A Failure where a reviewer requested changes, or where the protection asks for no review."""
decision=github_decision(number,run)
ifisinstance(decision,Failure):
returndecision
ifdecision==CHANGES_REQUESTED:
returnFailure(f"a reviewer requested changes on pull request {number}")
ifnotdecision:
returnFailure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false")
ifdecisionnotin(APPROVED,REVIEW_REQUIRED):
returnFailure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
"""None once GitHub reports pull request number approved; a Failure where `approval` fails, where a reviewer's comment waits for an answer, or where no approval came within WAIT_SECONDS."""
forwaitedinrange(0,WAIT_SECONDS+1,POLL_SECONDS):
read=approval(number,run)
ifreadisTrueorisinstance(read,Failure):
returnNoneifreadisTrueelseread
asked=unanswered(number,run)
ifaskedisnotNone:
returnasked
ifwaited<WAIT_SECONDS:
sleep(POLL_SECONDS)
returnFailure(f"pull request {number} wasn't approved within {WAIT_SECONDS//60} minutes; run chunk-pr merge again once it is")
defleft_to_park(number:str,run:Run)->Failure:
"""Why a merge under PARKS ends at once where pull request number passed its checks and awaits an approval, in place of waiting as `approved` does: a reviewer's comment waits for an answer, which the worker gives first, or else do-epic parks the chunk, so the worker ends its run."""
returnunanswered(number,run)orFailure(f"pull request {number} passed its checks and awaits an approval; end your run now, since do-epic parks the chunk and resumes this session once it is approved or a reviewer comments")
defleft_to_a_person(number:str,parks:bool)->str:
"""What merge prints where the project's config leaves the merge of pull request number to a person (`merge = "human"`): what the worker does now, which under PARKS is to end its run, as in `left_to_park`."""
now="end your run now, since do-epic parks the chunk and resumes this session once it is merged or a reviewer comments."ifparkselse"leave the merge to them, and report the chunk as ready to merge. Once it is merged, run chunk-pr clean in this worktree."
returnf"Marked pull request #{number} ready. It passed its checks and awaits a person's merge, since the project's config sets `merge = \"human\"`: {now}"
defunanswered(number:str,run:Run)->Failure|None:
"""A Failure naming the files where a reviewer's comment waits for an answer on pull request number, as `waiting_threads` finds them, or saying why they cannot be read. None where no thread waits."""
waiting=waiting_threads(number,run)
ifisinstance(waiting,Failure):
returnwaiting
ifnotwaiting:
returnNone
returnFailure(f"a reviewer's comment on pull request {number} waits for an answer, in {', '.join(waiting)}; answer it in its thread, push any fix, and run chunk-pr merge again")
"""Open the chunk's pull request as a draft, bring its branch level with origin's default branch, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere; once it has merged, remove the chunk's worktree and branch.
# How long merge waits for a check to report before it takes a pull request without any as passed: CI queues its checks within seconds of a push, and merge may run right after one.
NO_CHECKS_SECONDS=60
# The file, in the git folder that every worktree of the checkout shares, that a merge keeps locked with flock for its turn: so every chunk of the project on this machine queues on it.
QUEUE="chunk-pr-merge-queue"
# A turn lasts as long as its checks, which chunk-pr waits half an hour for on Gitea, so a queue still held after that is reported, not waited out.
QUEUE_SECONDS=30*60
QUEUE_POLL_SECONDS=10
# The line record-ruling writes into the comprehension history, as git's -G reads it.
RULING="^Ruling: "
# The project's config, loaded once per step, on the first call that needs it.
# Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them.
"""Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything. parks is whether a merge fails at once where it would wait for an approval (`merged`)."""
returnFailure("give a title of one line")iftitleandnotone_line(title[0])else(misfit(title[0],run,config)iftitleelseNone)ormarked_ready(run,title[0]iftitleelseNone)
"""Why title doesn't fit the `pull-request-title` template the project's config names, as templates.misfits rules; None where it fits. A config that cannot be read fails, so that no pull request reaches the project's owners under a title they don't use."""
returnFailure(f"title the pull request as the project's config asks, `{loaded.pull_request_title}`, where {{id}} is the ID of the chunk's first item; {title.strip()!r} doesn't fit")
"""origin's default branch, such as main. It differs from git_cli's default_ref, which falls back to a local main or master and asks origin where nothing is recorded. A pull request's base is origin's alone, so this fails instead, and says how to record it."""
deflevelled(run:Run,branch:str,base:str,resolve:str="resolve them and commit")->bool|Failure:
"""Fetch origin and merge its base into branch, the one checked out: whether that brought anything in. On a conflict the merge stays in progress, and the Failure names the conflicted files and ends with resolve, the caller's words for what to do about them."""
"""Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved. Where parks, it doesn't wait for the approval: it fails at once, as `left_to_park` says. Where the project's config leaves the merge to a person, the turn ends with the pull request ready, as `left_to_a_person` says."""
# Out of the queue, so the project's other chunks merge while this one waits.
waited=approved(number,run,sleep)
ifisinstance(waited,Failure):
returnwaited
@dataclasses.dataclass(frozen=True)
classMerging:
"""A pull request that merge takes turns for: its forge and number, the merge method, the default branch it merges into with the checks that branch requires, whether it waits for an approval, and whether a person merges it."""
forge:Forge
number:str
method:str
base:str
required:set[str]
waits:bool
by_human:bool
@dataclasses.dataclass(frozen=True)
classAwaitsApproval:
"""The pull request passed its checks but awaits a human's approval, so merge leaves the queue until it has one."""
@dataclasses.dataclass(frozen=True)
classAwaitsMerge:
"""The pull request passed its checks and is marked ready, and the project's config leaves its merge to a person."""
"""One turn in the queue: level the branch and finish its items, wait for its checks, and merge it where nothing still waits. What merged it, or why it waits or fails. A pull request a person merges is marked ready instead: its finished items are commits on its branch, so they reach the default branch with that person's merge."""
"""A sentence for merge's last line, naming each item of finishes the plan doesn't hold as merge begins: an earlier run finished it, or its ID is mistyped, and only the reader can tell which. Empty where the plan holds them all."""
"""Hold the project's merge queue as pull request number: wait until no other chunk-pr merge on this machine holds it, and free it on the way out, however that is. Gives None while it holds the queue; a Failure, without the queue, where another merge still holds it after QUEUE_SECONDS or the file cannot be opened or locked."""
try:
fd=os.open(queue,os.O_RDWR|os.O_CREAT,0o644)
exceptOSErrorasfailure:
yieldFailure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}")
"""Lock the open queue file fd for pull request number and write its number there, for a merge that waits to name; None once held, else why it isn't."""
returnFailure(f"the merge queue stayed held for {QUEUE_SECONDS//60} minutes, last by pull request #{holderor'?'}, so this one took no turn; run chunk-pr merge again")
sleep(QUEUE_POLL_SECONDS)
os.ftruncate(fd,0)
os.pwrite(fd,number.encode(),0)
exceptOSErrorasfailure:
returnFailure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}")
"""What merge does to the branch inside its turn, before the checks: merge origin's base into it, finish the plan items, and push. The head to merge, or why the worker must act first. Whatever it committed is pushed before it fails, so the pull request's head stays the commit checked out."""
found=checkout(run)
ifisinstance(found,Failure):
returnfound
_,branch,before=found
moved=levelled(run,branch,base,"resolve them, commit, push, and run chunk-pr merge again")
"""Finish one plan item with `todo-item finish` and commit what that changed. An item the plan no longer holds was finished by an earlier run of merge, which may have stopped before its commit: so the plan and the changelog are committed either way."""
"""Commit what changed in files under title, each in the git repository that holds it, and only those files: a record the config keeps in its own folder is committed there, where another chunk may commit at the same time."""
"""A Failure where origin's base has moved since the branch last recorded a paired ruling: that ruling read a head that no longer merges. None where the branch recorded none, or the project keeps its history outside the checkout."""
history=config.paths.get("comprehension-history")
# A history on a Confluence page is outside the checkout.
returnFailure(f"origin/{base} moved after the branch recorded its paired ruling, and its changes are merged in and pushed; run the paired ruling again at the new head, record it, push, and run chunk-pr merge again")
"""Remove the worktree and branch of the merged chunk run is in, and fast-forward the main checkout; at(folder) runs commands in folder, here the main checkout."""
chunk=merged_chunk(run)
ifisinstance(chunk,Failure):
returnchunk
at_main=at(chunk.main)
left=kept_as_it_was(at_main,chunk.default)
files=unsaved(run)
ifisinstance(files,Failure):
returnfiles
iffiles:
also=f"\nIt would also have left {chunk.main} as it was: {left}"ifleftelse""
returnFailure(f"left everything as it was: {chunk.worktree} has uncommitted or untracked files:\n{files}{also}")
returnremoved(chunk,at_main,left)
defmerged_chunk(run:Run)->Chunk|Failure:
"""The chunk run is in, once the forge reports its pull request merged at its head. It fetches origin, so the main checkout can fast-forward to the merge."""
found=checkout(run)
ifisinstance(found,Failure):
returnfound
forge,branch,head=found
default=default_branch(run)
ifisinstance(default,Failure):
returndefault
folders=worktree_and_main(run)
ifisinstance(folders,Failure):
returnfolders
number=merged_pull(forge,branch,head,run)
ifnumberisNone:
returnFailure(f"no merged pull request from {branch} at {head[:12]}, so its worktree and branch stay")
"""Fast-forward the main checkout unless left says why not, then remove the chunk's worktree and branch. Every command runs in the main checkout, since the worktree is gone after the removal."""
# Not -d: merged_chunk found the forge's pull request merged at the branch's head. -d would compare the branch with the main checkout's HEAD or its upstream instead, and after a rebase or squash merge neither need hold its commits.
"""The git arguments that add branch's worktree at path, and how it comes to be: on the local branch, else on a new one tracking origin's, else on a new one off default."""
iflocal:
return["worktree","add","--quiet",str(path),branch],f"added on the branch {branch}, which existed already."
ifpushed:
return["worktree","add","--quiet","--track","-b",branch,str(path),f"origin/{branch}"],f"added on the new branch {branch}, made off origin/{branch}."
# --no-track: tracking the default branch would point a bare `git push` at it.
return["worktree","add","--quiet","--no-track","-b",branch,str(path),default],f"added on the new branch {branch}, made off {default}."
"""The command that lists open pull requests: gh only branch's, by number and URL; tea every one, by index, head and URL, for facts.open_pulls to pick branch's."""
# CLAUDE.md → "Working loop" lets up to ten tiny items share a chunk, so a worker never needs more. A release with 24 joinable items would otherwise put about 155 lines of detail in every prompt.
JOINING_DETAILS=10
defrender(found:Gathered)->list[str]:
"""One `- ` line per fact, then the item's tagline and detail, the detail of each item that may join its chunk, and what each tool printed."""
paths=f"- The project's config puts its files and plan at: {'; '.join(f'{setting}{path}'forsetting,pathinfound.places.items())}."
texts=f"- The project's config sets: {'; '.join(f'{setting}{text}'forsetting,textinfound.texts.items())}."
ifisinstance(found.item,NoItem):
return[*head,f"- No plan item: {found.item.why} No worktree was made.",paths,texts]
lines=item_lines(found.plan,found.item)
return[*head,*lines[:2],paths,texts,*lines[2:]]
defmerge_lines(found:Gathered)->list[str]:
"""What `merge = "human"` leaves for the worker to know: each worktree a merged pull request left, the items passed over since their pull request awaits a person's merge, or why those pull requests could not be read."""
left=[f"- The worktree {worktree.path}, on the branch {worktree.branch}, is left from pull request #{worktree.pull}, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step."forworktreeinfound.left]
passed=[f"item {item.id}, by pull request {item.awaits_merge}"foriteminitemsifitem.awaits_merge]
over=[f"- Items passed over, each finished on a branch whose ready pull request awaits a person's merge: {'; '.join(passed)}. No chunk takes one."]ifpassedelse[]
unread=[f"- The pull requests that await a person's merge cannot be read, so no item is passed over for one: {found.merges_unread.reason}"]iffound.merges_unreadelse[]
f"- The {'next release, after the last cut, that '+plan+' names'ifitem.plan.carriedelse'earliest release in '+plan}: {version(first.release)}. {'The item this chunk starts from, named with --item'ifitem.plan.namedelse'Its first item that does not wait'}: item {first.id}, {levels(first)}.",
*carried_lines(item.plan),
f"- Worktree: {worktree}",
f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls,item.plan.branch)}",
*bundled(item.plan),
*beside(item.plan),
*named_lines(item.named),
f"\nItem {first.id}'s tagline and detail:\n\n{quoted(item.plan.text)}",
return[f"- {items} filed under a release already cut, so {count} as release {version(over.into)}'s, the next. Move {them} there as this chunk's first change, with `~/.claude/bin/todo-item move`, and say so in the chunk's opening line. Where todo-item cannot move this plan's items, as in a Jira plan, leave {them} and ask the human, in the chunk's summary, to move {them}."]
defjoining_details(plan:NextChunk)->list[str]:
"""The detail of each of the first JOINING_DETAILS items that may join the chunk, in the table's order, and what the worker lacks: an item with no detail, or the items left out."""
lines=[f"\nItem {item.id}'s detail:\n\n{quoted(detail)}"if(detail:=item.detail)elsef"\nItem {item.id} has no detail."foriteminshown]
ifleft:
lines.append(f"\nThe details of items {listed([str(item.id)foriteminleft],'and')} are not quoted: only the first {JOINING_DETAILS} are. Run `~/.claude/bin/todo-item show <ID>` for each.")
"""Each open pull request from branch, by its number and URL, or why none can be listed. No title: on a public forge anyone may open one, and its title would reach the worker's prompt."""
ifpullsisNone:
return"none, as the checkout has no origin remote."
forge,done=pulls
shown="".join(PULLS_LIST[forge])
ifisinstance(done,Failure):
returnf"cannot be listed: `{shown}` {done.reason}"
ifdone.code:
returnf"cannot be listed: `{shown}` exited {done.code}: {done.stderr.strip()}"
"""Each open pull request from branch in the rows pulls_command printed, as `#<number> <URL>`: gh prints only branch's pull requests, as number and URL; tea prints every pull request, as index, head and URL, under a header row."""
return[f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."]
ifnotcandidates:
return[f"- No other item of release {version(first.release)} may join item {first.id}'s chunk."]
listed=[f" - item {item.id}, {levels(item)}, S {item.scores.get('S','unscored')}: {item.tagline}"foritemincandidates]
return[f'- The items of release {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:',*listed]
defbeside(plan:NextChunk)->list[str]:
"""The items that may start chunks while first's runs, by touch_predictions' pick; no line where none of the release's items holds a prediction."""
first=plan.first
found=chunks_beside(plan.items,first)
iffoundisNone:
return[]
none=f"- No item of release {version(first.release)} may start a chunk beside item {first.id}'s"
ifisinstance(found,str):
return[f"{none}: {found}."]
refused=f" Not beside it: {'; '.join(found.refused)}."iffound.refusedelse""
ifnotfound.picked:
return[f"{none}.{refused}"]
return[f"- The items of release {version(first.release)} that may start chunks beside item {first.id}'s: {', '.join(map(str,found.picked))}. None is predicted to touch a part that item {first.id} touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own.{refused}"]
"""What the preflight gathers, which facts.render states."""
importdataclasses
importpathlib
fromfailureimportFailure
fromforge.commandsimportForge
fromrelease_plan.release_standingimportLastCut
fromrelease_plan.next_chunkimportNextChunk,NoItem
@dataclasses.dataclass(frozen=True)
classRan:
"""A command that ran to its end: its exit code and what it printed."""
code:int
stdout:str
stderr:str
@dataclasses.dataclass(frozen=True)
classWorktree:
path:pathlib.Path
# How it came to be, as the worker reads it.
how:str
@dataclasses.dataclass(frozen=True)
classNamedPath:
"""A tracked file or folder the item names, with how many tracked files it holds."""
span:str
files:int
# A file's lines, or why they cannot be read; None for a folder.
lines:int|Failure|None
@dataclasses.dataclass(frozen=True)
classItemFacts:
"""What the preflight found or made for the plan's first item."""
plan:NextChunk
worktree:Worktree|Failure
# The forge whose CLI listed the open pull requests, and how it ran; None without an origin remote.
pulls:tuple[Forge,Ran|Failure]|None
named:list[NamedPath]|Failure
# Each tool run in the worktree, by its command line, and how it ran; none without a worktree.
tools:list[tuple[str,Ran|Failure]]
@dataclasses.dataclass(frozen=True)
classLeftWorktree:
"""A worktree on a branch whose pull request has merged."""
path:pathlib.Path
branch:str
# The merged pull request's number.
pull:str
@dataclasses.dataclass(frozen=True)
classGathered:
"""Everything the preflight read and ran, for facts.render to state."""
# The default branch's ref, such as origin/main.
default:str
# Why origin reads as last fetched; None after a fetch.
note:str|None
cut:LastCut
# What was found or made for the plan's first item; else why the plan names none.
item:ItemFacts|NoItem
# The plan that was read, as release_plan.next_chunk.plan_name names it.
plan:str
# Each path the project's config sets, and the epic of a plan kept in Jira, by its setting: in the item's worktree where one was made or continued, else in the checkout.
places:dict[str,str]
# Whether the project's config puts the plan outside the checkout, where a release whose items are all done is not seen.
plan_outside:bool
# The language and the templates the project's config names, by their settings.
texts:dict[str,str]
# Why the pull requests that await a person's merge could not be read; None where they were read or not asked for.
merges_unread:Failure|None=None
# The worktrees `chunk-pr clean` is still to remove.
"""The preflight's lines, given the setting TIMEOUT_SETTING holds, whether to make the item's worktree, and the ID --item names; a Failure where the setting is no number of seconds above 0, or git finds no checkout or no default branch."""
"""Gathers the facts step by step, each step taking what the ones before it found, and renders them; a Failure where the checkout has no default branch."""
"""Each worktree but root that is on a branch whose pull request merged with the worktree's head commit as its head: under `merge = "human"` a person merges after the chunk's run has ended, so its worker never ran `chunk-pr clean`. Where the forge can't be asked, no worktree counts as left."""
self.assertIn(f"- The worktree {repo.temp}/proj-item-2, on the branch item-2, is left from pull request #11, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step.\n",done.stdout)
self.assertNotIn("proj-item-3, on the branch",done.stdout,"an open pull request leaves no worktree to clean")
self.assertIn("No plan item: every item of release 0.2.0 in origin/main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #12 https://github.com/o/r/pull/12, which finishes item 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again.",done.stdout)
self.assertIn("- The pull requests that await a person's merge cannot be read, so no item is passed over for one: gh pr list: not logged in\n",unread.stdout)
self.assertIn("Its first item that does not wait: item 3,",unread.stdout)
self.assertIn("item 7, L 1, E + I 2",done.stdout,"origin's todo.md still holds item 3, which the plan in the config's folder does not")
self.assertIn(f"- The project's config puts its files and plan at: plan {folder}/todo.md; working-rules {worktree}/AGENTS.md; decisions {worktree}/docs/decisions.md; ",done.stdout)
forchangelog,reviewed,factin((CHANGELOG,False,"release review is due"),(CHANGELOG,True,"finished and ready to cut"),("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n",False,"planned first")):
withself.subTest(fact=fact):
repo=Repo(self,changelog=changelog)
repo.write(repo.root,"todo.md",LATER)
repo.commit(repo.root,"ship 0.2.0")
ifreviewed:
repo.git(repo.root,"commit","--quiet","--allow-empty","-m","Release review of 0.2.0")
"""The facts of todo's next item, its worktree made, with fields given replacing the rest."""
returnItemFacts(**{"plan":planned(todo,CUT,"origin/main",BRANCH),"worktree":Worktree(pathlib.Path("/c/proj-item-3"),"added on the new branch item-3, made off origin/main."),"pulls":None,"named":[],"tools":[],**fields})
self.assertIn("\n- Items passed over, each finished on a branch whose ready pull request awaits a person's merge: item 7, by pull request #12 https://github.com/o/r/pull/12; item 8, by pull request #13 https://github.com/o/r/pull/13. No chunk takes one.\n",passed)
self.assertIn("- No other item of release 0.2.0 may join item 3's chunk.",passed)
self.assertEqual(render(left)[1:3],["- The worktree /c/proj-item-2, on the branch item-2, is left from pull request #11, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step.","- The pull requests that await a person's merge cannot be read, so no item is passed over for one: `gh pr list` exited 1: no"])
self.assertEqual([line.partition(":")[0]forlineinlines[:6]],["- Last version cut","- The earliest release in origin/main's todo.md","- Worktree","- The project's config puts its files and plan at","- The project's config sets","- Open pull requests from item-3"])
self.assertEqual([lineforlineinlines[6:]ifline.startswith("- Open pull requests")],[])
said=rendered(item_facts(TODO+"\n### 7. Do the thing after.\n\nTouch `src/other.py`.\n\nRun the e2e leg.\n\n### 8. Do the answered thing.\n\nNot quoted.\n"))
self.assertIn("Item 7's detail:\n\n> Touch `src/other.py`.\n> \n> Run the e2e leg.",said)
self.assertEqual(planned(TODO,CUT,"origin/main",BRANCH,None,4),NoItem("origin/main's todo.md holds no item 4, the one --item names; it may have shipped."))
fortodo,ids,saidin((SHIPPED_BUT_3,(3,),"- Item 3 is filed under a release already cut, so it counts as release 0.3.0's, the next. Move it there"),(SHIPPED_BUT_3+NINTH.replace("| 9 | 0.3.0 |","| 4 | 0.1.0 |"),(3,4),"- Items 3 and 4 are filed under a release already cut, so they count as release 0.3.0's, the next. Move them there")):
self.assertEqual(self.said(todo),["- The items of release 0.2.0 that may start chunks beside item 3's: 4. None is predicted to touch a part that item 3 touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own. Not beside it: item 6, which overlaps item 3 at `src/app.py` `run`."])
self.assertEqual(self.said(todo),["- The items of release 0.2.0 that may start chunks beside item 3's: 4, 6. None is predicted to touch a part that item 3 touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own."])
self.assertEqual(self.said(todo),["- No item of release 0.2.0 may start a chunk beside item 3's. Not beside it: item 4, which overlaps item 3 at `src/app.py` `run`; item 6, which overlaps item 3 at `src/app.py` `run`."])
"""Entries of Claude Code's transcripts and of its stream-json and json output."""
importdataclasses
importjson
importtyping
defjson_object(raw:str|bytes)->dict|None:
"""A line of JSON, such as a transcript line, a stream-json line or claude's json reply, where it is an object; None otherwise."""
try:
found=json.loads(raw)
exceptValueError:
returnNone
returnfoundifisinstance(found,dict)elseNone
@dataclasses.dataclass(frozen=True,kw_only=True)
classEntry:
"""A transcript entry, with the fields every entry may carry, each "" where it has none. Kinds no consumer tells apart, such as a compaction's boundary, parse as Entry itself. Each subclass names a kind consumers tell apart."""
uuid:str=""
parent_uuid:str=""
timestamp:str=""
cwd:str=""
git_branch:str=""
@dataclasses.dataclass(frozen=True,kw_only=True)
classUserText(Entry):
"""The text of a "user" entry, its text blocks joined, or of a prompt the human queued while claude worked. HumanTurn, LoopPrompt and InjectedText say who wrote it."""
text:str
classHumanTurn(UserText):
"""What the human wrote, at the prompt or while claude worked."""
classLoopPrompt(UserText):
"""What loop-claude told the worker in a -p prompt."""
classInjectedText(UserText):
"""Text Claude Code wrote into the prompt, such as a slash command, a task notification or a compaction's summary."""
classText(typing.NamedTuple):
text:str
classToolCall(typing.NamedTuple):
id:str
name:str
input:dict
classToolResult(typing.NamedTuple):
tool_use_id:str
text:str
failed:bool
@dataclasses.dataclass(frozen=True,kw_only=True)
classAssistantTurn(Entry):
"""An assistant entry's text and tool-call blocks, with its message's id, model and usage. Claude Code writes one entry per block of a message, so one message's usage repeats across several entries."""
# Claude Code logs each API request's last message again, and some of its tool results appear nowhere else: {"type": "api-request-blob", "hash": "…", "message": {"role": "user", "content": [{"type": "tool_result", …}, {"type": "text", …}]}}
"""The assistant turns grouped by message, in the order each message first appears. A message's usage repeats in each of its entries, so read it from the first of a group: none of 1,681 multi-entry messages in the archive of 2026-10-28 differed."""
# {"type": "user", "isCompactSummary": true, "message": {"content": "This session is being continued from a previous conversation that ran out of context. ..."}}
# {"type": "tool_result", "tool_use_id": "toolu_01…", "content": "hi"}, its content also as [{"type": "text", "text": "hi"}], and with "is_error": true where the call failed
# A count Claude Code left out or wrote as another type doesn't add anything, so one odd entry leaves the rest of a figure standing.
defusage_count(usage:dict,field:str)->int:
"""One token count of a message's usage: {"input_tokens": 2, "cache_creation_input_tokens": 14541, "output_tokens": 8, ...}"""
value=usage.get(field)
returnvalueifisinstance(value,int)else0
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.